xref: /linux/drivers/md/dm-integrity.c (revision e5e03918fbec31f0c896f4f43c2bd2aadf35d43d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2016-2017 Red Hat, Inc. All rights reserved.
4  * Copyright (C) 2016-2017 Milan Broz
5  * Copyright (C) 2016-2017 Mikulas Patocka
6  *
7  * This file is released under the GPL.
8  */
9 
10 #include "dm-bio-record.h"
11 
12 #include <linux/compiler.h>
13 #include <linux/module.h>
14 #include <linux/device-mapper.h>
15 #include <linux/dm-io.h>
16 #include <linux/vmalloc.h>
17 #include <linux/sort.h>
18 #include <linux/rbtree.h>
19 #include <linux/delay.h>
20 #include <linux/hex.h>
21 #include <linux/random.h>
22 #include <linux/reboot.h>
23 #include <crypto/hash.h>
24 #include <crypto/skcipher.h>
25 #include <crypto/utils.h>
26 #include <linux/async_tx.h>
27 #include <linux/dm-bufio.h>
28 
29 #include "dm-audit.h"
30 
31 #define DM_MSG_PREFIX "integrity"
32 
33 #define DEFAULT_INTERLEAVE_SECTORS	32768
34 #define DEFAULT_JOURNAL_SIZE_FACTOR	7
35 #define DEFAULT_SECTORS_PER_BITMAP_BIT	32768
36 #define DEFAULT_BUFFER_SECTORS		128
37 #define DEFAULT_JOURNAL_WATERMARK	50
38 #define DEFAULT_SYNC_MSEC		10000
39 #define DEFAULT_MAX_JOURNAL_SECTORS	(IS_ENABLED(CONFIG_64BIT) ? 131072 : 8192)
40 #define MIN_LOG2_INTERLEAVE_SECTORS	3
41 #define MAX_LOG2_INTERLEAVE_SECTORS	31
42 #define METADATA_WORKQUEUE_MAX_ACTIVE	16
43 #define RECALC_SECTORS			(IS_ENABLED(CONFIG_64BIT) ? 32768 : 2048)
44 #define RECALC_WRITE_SUPER		16
45 #define BITMAP_BLOCK_SIZE		4096	/* don't change it */
46 #define BITMAP_FLUSH_INTERVAL		(10 * HZ)
47 #define DISCARD_FILLER			0xf6
48 #define SALT_SIZE			16
49 #define RECHECK_POOL_SIZE		256
50 
51 /*
52  * Warning - DEBUG_PRINT prints security-sensitive data to the log,
53  * so it should not be enabled in the official kernel
54  */
55 //#define DEBUG_PRINT
56 //#define INTERNAL_VERIFY
57 
58 /*
59  * On disk structures
60  */
61 
62 #define SB_MAGIC			"integrt"
63 #define SB_VERSION_1			1
64 #define SB_VERSION_2			2
65 #define SB_VERSION_3			3
66 #define SB_VERSION_4			4
67 #define SB_VERSION_5			5
68 #define SB_VERSION_6			6
69 #define SB_VERSION_7			7
70 #define SB_SECTORS			8
71 #define MAX_SECTORS_PER_BLOCK		8
72 
73 struct superblock {
74 	__u8 magic[8];
75 	__u8 version;
76 	__u8 log2_interleave_sectors;
77 	__le16 integrity_tag_size;
78 	__le32 journal_sections;
79 	__le64 provided_data_sectors;	/* userspace uses this value */
80 	__le32 flags;
81 	__u8 log2_sectors_per_block;
82 	__u8 log2_blocks_per_bitmap_bit;
83 	__u8 pad[2];
84 	__le64 recalc_sector;
85 	__u8 pad2[8];
86 	__u8 salt[SALT_SIZE];
87 };
88 
89 #define SB_FLAG_HAVE_JOURNAL_MAC	0x1
90 #define SB_FLAG_RECALCULATING		0x2
91 #define SB_FLAG_DIRTY_BITMAP		0x4
92 #define SB_FLAG_FIXED_PADDING		0x8
93 #define SB_FLAG_FIXED_HMAC		0x10
94 #define SB_FLAG_INLINE			0x20
95 #define SB_FLAG_DISCARD_KEYED		0x40
96 
97 #define	JOURNAL_ENTRY_ROUNDUP		8
98 
99 typedef __le64 commit_id_t;
100 #define JOURNAL_MAC_PER_SECTOR		8
101 
102 struct journal_entry {
103 	union {
104 		struct {
105 			__le32 sector_lo;
106 			__le32 sector_hi;
107 		} s;
108 		__le64 sector;
109 	} u;
110 	commit_id_t last_bytes[];
111 	/* __u8 tag[0]; */
112 };
113 
114 #define journal_entry_tag(ic, je)		((__u8 *)&(je)->last_bytes[(ic)->sectors_per_block])
115 
116 #if BITS_PER_LONG == 64
117 #define journal_entry_set_sector(je, x)		do { smp_wmb(); WRITE_ONCE((je)->u.sector, cpu_to_le64(x)); } while (0)
118 #else
119 #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)
120 #endif
121 #define journal_entry_get_sector(je)		le64_to_cpu((je)->u.sector)
122 #define journal_entry_is_unused(je)		((je)->u.s.sector_hi == cpu_to_le32(-1))
123 #define journal_entry_set_unused(je)		((je)->u.s.sector_hi = cpu_to_le32(-1))
124 #define journal_entry_is_inprogress(je)		((je)->u.s.sector_hi == cpu_to_le32(-2))
125 #define journal_entry_set_inprogress(je)	((je)->u.s.sector_hi = cpu_to_le32(-2))
126 
127 #define JOURNAL_BLOCK_SECTORS		8
128 #define JOURNAL_SECTOR_DATA		((1 << SECTOR_SHIFT) - sizeof(commit_id_t))
129 #define JOURNAL_MAC_SIZE		(JOURNAL_MAC_PER_SECTOR * JOURNAL_BLOCK_SECTORS)
130 
131 struct journal_sector {
132 	struct_group(sectors,
133 		__u8 entries[JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR];
134 		__u8 mac[JOURNAL_MAC_PER_SECTOR];
135 	);
136 	commit_id_t commit_id;
137 };
138 
139 #define MAX_TAG_SIZE			255
140 
141 #define METADATA_PADDING_SECTORS	8
142 
143 #define N_COMMIT_IDS			4
144 
145 static unsigned char prev_commit_seq(unsigned char seq)
146 {
147 	return (seq + N_COMMIT_IDS - 1) % N_COMMIT_IDS;
148 }
149 
150 static unsigned char next_commit_seq(unsigned char seq)
151 {
152 	return (seq + 1) % N_COMMIT_IDS;
153 }
154 
155 /*
156  * In-memory structures
157  */
158 
159 struct journal_node {
160 	struct rb_node node;
161 	sector_t sector;
162 };
163 
164 struct alg_spec {
165 	char *alg_string;
166 	char *key_string;
167 	__u8 *key;
168 	unsigned int key_size;
169 };
170 
171 struct dm_integrity_c {
172 	struct dm_dev *dev;
173 	struct dm_dev *meta_dev;
174 	unsigned int tag_size;
175 	__s8 log2_tag_size;
176 	unsigned int tuple_size;
177 	sector_t start;
178 	mempool_t journal_io_mempool;
179 	struct dm_io_client *io;
180 	struct dm_bufio_client *bufio;
181 	struct workqueue_struct *metadata_wq;
182 	struct superblock *sb;
183 	struct superblock *sb_copy;
184 	unsigned int journal_pages;
185 	unsigned int n_bitmap_blocks;
186 
187 	struct page_list *journal;
188 	struct page_list *journal_io;
189 	struct page_list *journal_xor;
190 	struct page_list *recalc_bitmap;
191 	struct page_list *may_write_bitmap;
192 	struct bitmap_block_status *bbs;
193 	unsigned int bitmap_flush_interval;
194 	int synchronous_mode;
195 	struct bio_list synchronous_bios;
196 	struct delayed_work bitmap_flush_work;
197 
198 	struct crypto_skcipher *journal_crypt;
199 	struct scatterlist **journal_scatterlist;
200 	struct scatterlist **journal_io_scatterlist;
201 	struct skcipher_request **sk_requests;
202 
203 	struct crypto_shash *journal_mac;
204 
205 	struct journal_node *journal_tree;
206 	struct rb_root journal_tree_root;
207 
208 	sector_t provided_data_sectors;
209 
210 	unsigned short journal_entry_size;
211 	unsigned char journal_entries_per_sector;
212 	unsigned char journal_section_entries;
213 	unsigned short journal_section_sectors;
214 	unsigned int journal_sections;
215 	unsigned int journal_entries;
216 	sector_t data_device_sectors;
217 	sector_t meta_device_sectors;
218 	unsigned int initial_sectors;
219 	unsigned int metadata_run;
220 	__s8 log2_metadata_run;
221 	__u8 log2_buffer_sectors;
222 	__u8 sectors_per_block;
223 	__u8 log2_blocks_per_bitmap_bit;
224 
225 	unsigned char mode;
226 	bool internal_hash;
227 
228 	int failed;
229 
230 	struct crypto_shash *internal_shash;
231 	struct crypto_ahash *internal_ahash;
232 	unsigned int internal_hash_digestsize;
233 
234 	struct dm_target *ti;
235 
236 	/* these variables are locked with endio_wait.lock */
237 	struct rb_root in_progress;
238 	struct list_head wait_list;
239 	wait_queue_head_t endio_wait;
240 	struct workqueue_struct *wait_wq;
241 	struct workqueue_struct *offload_wq;
242 
243 	unsigned char commit_seq;
244 	commit_id_t commit_ids[N_COMMIT_IDS];
245 
246 	unsigned int committed_section;
247 	unsigned int n_committed_sections;
248 
249 	unsigned int uncommitted_section;
250 	unsigned int n_uncommitted_sections;
251 
252 	unsigned int free_section;
253 	unsigned char free_section_entry;
254 	unsigned int free_sectors;
255 
256 	unsigned int free_sectors_threshold;
257 
258 	struct workqueue_struct *commit_wq;
259 	struct work_struct commit_work;
260 
261 	struct workqueue_struct *writer_wq;
262 	struct work_struct writer_work;
263 
264 	struct workqueue_struct *recalc_wq;
265 	struct work_struct recalc_work;
266 
267 	struct bio_list flush_bio_list;
268 
269 	unsigned long autocommit_jiffies;
270 	struct timer_list autocommit_timer;
271 	unsigned int autocommit_msec;
272 
273 	wait_queue_head_t copy_to_journal_wait;
274 
275 	struct completion crypto_backoff;
276 
277 	bool wrote_to_journal;
278 	bool journal_uptodate;
279 	bool just_formatted;
280 	bool recalculate_flag;
281 	bool reset_recalculate_flag;
282 	bool discard;
283 	bool discard_keyed;
284 	bool fix_padding;
285 	bool fix_hmac;
286 	bool legacy_recalculate;
287 
288 	mempool_t ahash_req_pool;
289 	struct ahash_request *journal_ahash_req;
290 
291 	struct alg_spec internal_hash_alg;
292 	struct alg_spec journal_crypt_alg;
293 	struct alg_spec journal_mac_alg;
294 
295 	atomic64_t number_of_mismatches;
296 
297 	mempool_t recheck_pool;
298 	struct bio_set recheck_bios;
299 	struct bio_set recalc_bios;
300 
301 	struct notifier_block reboot_notifier;
302 };
303 
304 struct dm_integrity_range {
305 	sector_t logical_sector;
306 	sector_t n_sectors;
307 	bool waiting;
308 	union {
309 		struct rb_node node;
310 		struct {
311 			struct task_struct *task;
312 			struct list_head wait_entry;
313 		};
314 	};
315 };
316 
317 struct dm_integrity_io {
318 	struct work_struct work;
319 
320 	struct dm_integrity_c *ic;
321 	enum req_op op;
322 	bool fua;
323 
324 	struct dm_integrity_range range;
325 
326 	sector_t metadata_block;
327 	unsigned int metadata_offset;
328 
329 	atomic_t in_flight;
330 	blk_status_t bi_status;
331 
332 	struct completion *completion;
333 
334 	struct dm_bio_details bio_details;
335 
336 	char *integrity_payload;
337 	unsigned payload_len;
338 	bool integrity_payload_from_mempool;
339 	bool integrity_range_locked;
340 
341 	struct ahash_request *ahash_req;
342 };
343 
344 struct journal_completion {
345 	struct dm_integrity_c *ic;
346 	atomic_t in_flight;
347 	struct completion comp;
348 };
349 
350 struct journal_io {
351 	struct dm_integrity_range range;
352 	struct journal_completion *comp;
353 };
354 
355 struct bitmap_block_status {
356 	struct work_struct work;
357 	struct dm_integrity_c *ic;
358 	unsigned int idx;
359 	unsigned long *bitmap;
360 	struct bio_list bio_queue;
361 	spinlock_t bio_queue_lock;
362 
363 };
364 
365 static struct kmem_cache *journal_io_cache;
366 
367 #define JOURNAL_IO_MEMPOOL	32
368 #define AHASH_MEMPOOL		32
369 
370 #ifdef DEBUG_PRINT
371 #define DEBUG_print(x, ...)			printk(KERN_DEBUG x, ##__VA_ARGS__)
372 #define DEBUG_bytes(bytes, len, msg, ...)	printk(KERN_DEBUG msg "%s%*ph\n", ##__VA_ARGS__, \
373 						       len ? ": " : "", len, bytes)
374 #else
375 #define DEBUG_print(x, ...)			do { } while (0)
376 #define DEBUG_bytes(bytes, len, msg, ...)	do { } while (0)
377 #endif
378 
379 static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map);
380 static int dm_integrity_map_inline(struct dm_integrity_io *dio, bool from_map);
381 static void integrity_bio_wait(struct work_struct *w);
382 static void dm_integrity_dtr(struct dm_target *ti);
383 
384 static void dm_integrity_io_error(struct dm_integrity_c *ic, const char *msg, int err)
385 {
386 	if (err == -EILSEQ)
387 		atomic64_inc(&ic->number_of_mismatches);
388 	if (!cmpxchg(&ic->failed, 0, err))
389 		DMERR("Error on %s: %d", msg, err);
390 }
391 
392 static int dm_integrity_failed(struct dm_integrity_c *ic)
393 {
394 	return READ_ONCE(ic->failed);
395 }
396 
397 static bool dm_integrity_disable_recalculate(struct dm_integrity_c *ic)
398 {
399 	if (ic->legacy_recalculate)
400 		return false;
401 	if (!(ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) ?
402 	    ic->internal_hash_alg.key || ic->journal_mac_alg.key :
403 	    ic->internal_hash_alg.key && !ic->journal_mac_alg.key)
404 		return true;
405 	return false;
406 }
407 
408 static commit_id_t dm_integrity_commit_id(struct dm_integrity_c *ic, unsigned int i,
409 					  unsigned int j, unsigned char seq)
410 {
411 	/*
412 	 * Xor the number with section and sector, so that if a piece of
413 	 * journal is written at wrong place, it is detected.
414 	 */
415 	return ic->commit_ids[seq] ^ cpu_to_le64(((__u64)i << 32) ^ j);
416 }
417 
418 static void get_area_and_offset(struct dm_integrity_c *ic, sector_t data_sector,
419 				sector_t *area, sector_t *offset)
420 {
421 	if (!ic->meta_dev) {
422 		__u8 log2_interleave_sectors = ic->sb->log2_interleave_sectors;
423 		*area = data_sector >> log2_interleave_sectors;
424 		*offset = (unsigned int)data_sector & ((1U << log2_interleave_sectors) - 1);
425 	} else {
426 		*area = 0;
427 		*offset = data_sector;
428 	}
429 }
430 
431 #define sector_to_block(ic, n)						\
432 do {									\
433 	BUG_ON((n) & (unsigned int)((ic)->sectors_per_block - 1));		\
434 	(n) >>= (ic)->sb->log2_sectors_per_block;			\
435 } while (0)
436 
437 static __u64 get_metadata_sector_and_offset(struct dm_integrity_c *ic, sector_t area,
438 					    sector_t offset, unsigned int *metadata_offset)
439 {
440 	__u64 ms;
441 	unsigned int mo;
442 
443 	ms = area << ic->sb->log2_interleave_sectors;
444 	if (likely(ic->log2_metadata_run >= 0))
445 		ms += area << ic->log2_metadata_run;
446 	else
447 		ms += area * ic->metadata_run;
448 	ms >>= ic->log2_buffer_sectors;
449 
450 	sector_to_block(ic, offset);
451 
452 	if (likely(ic->log2_tag_size >= 0)) {
453 		ms += offset >> (SECTOR_SHIFT + ic->log2_buffer_sectors - ic->log2_tag_size);
454 		mo = (offset << ic->log2_tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
455 	} else {
456 		ms += (__u64)offset * ic->tag_size >> (SECTOR_SHIFT + ic->log2_buffer_sectors);
457 		mo = (offset * ic->tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
458 	}
459 	*metadata_offset = mo;
460 	return ms;
461 }
462 
463 static sector_t get_data_sector(struct dm_integrity_c *ic, sector_t area, sector_t offset)
464 {
465 	sector_t result;
466 
467 	if (ic->meta_dev)
468 		return offset;
469 
470 	result = area << ic->sb->log2_interleave_sectors;
471 	if (likely(ic->log2_metadata_run >= 0))
472 		result += (area + 1) << ic->log2_metadata_run;
473 	else
474 		result += (area + 1) * ic->metadata_run;
475 
476 	result += (sector_t)ic->initial_sectors + offset;
477 	result += ic->start;
478 
479 	return result;
480 }
481 
482 static void wraparound_section(struct dm_integrity_c *ic, unsigned int *sec_ptr)
483 {
484 	if (unlikely(*sec_ptr >= ic->journal_sections))
485 		*sec_ptr -= ic->journal_sections;
486 }
487 
488 static void sb_set_version(struct dm_integrity_c *ic)
489 {
490 	if (ic->sb->flags & cpu_to_le32(SB_FLAG_DISCARD_KEYED))
491 		ic->sb->version = SB_VERSION_7;
492 	else if (ic->sb->flags & cpu_to_le32(SB_FLAG_INLINE))
493 		ic->sb->version = SB_VERSION_6;
494 	else if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC))
495 		ic->sb->version = SB_VERSION_5;
496 	else if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING))
497 		ic->sb->version = SB_VERSION_4;
498 	else if (ic->mode == 'B' || ic->sb->flags & cpu_to_le32(SB_FLAG_DIRTY_BITMAP))
499 		ic->sb->version = SB_VERSION_3;
500 	else if (ic->meta_dev || ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
501 		ic->sb->version = SB_VERSION_2;
502 	else
503 		ic->sb->version = SB_VERSION_1;
504 }
505 
506 static int sb_mac(struct dm_integrity_c *ic, bool wr)
507 {
508 	SHASH_DESC_ON_STACK(desc, ic->journal_mac);
509 	int r;
510 	unsigned int mac_size = crypto_shash_digestsize(ic->journal_mac);
511 	__u8 *sb = (__u8 *)ic->sb;
512 	__u8 *mac = sb + (1 << SECTOR_SHIFT) - mac_size;
513 
514 	if (sizeof(struct superblock) + mac_size > 1 << SECTOR_SHIFT ||
515 	    mac_size > HASH_MAX_DIGESTSIZE) {
516 		dm_integrity_io_error(ic, "digest is too long", -EINVAL);
517 		return -EINVAL;
518 	}
519 
520 	desc->tfm = ic->journal_mac;
521 
522 	if (likely(wr)) {
523 		r = crypto_shash_digest(desc, sb, mac - sb, mac);
524 		if (unlikely(r < 0)) {
525 			dm_integrity_io_error(ic, "crypto_shash_digest", r);
526 			return r;
527 		}
528 	} else {
529 		__u8 actual_mac[HASH_MAX_DIGESTSIZE];
530 
531 		r = crypto_shash_digest(desc, sb, mac - sb, actual_mac);
532 		if (unlikely(r < 0)) {
533 			dm_integrity_io_error(ic, "crypto_shash_digest", r);
534 			return r;
535 		}
536 		if (crypto_memneq(mac, actual_mac, mac_size)) {
537 			dm_integrity_io_error(ic, "superblock mac", -EILSEQ);
538 			dm_audit_log_target(DM_MSG_PREFIX, "mac-superblock", ic->ti, 0);
539 			return -EILSEQ;
540 		}
541 	}
542 
543 	return 0;
544 }
545 
546 static int sync_rw_sb(struct dm_integrity_c *ic, blk_opf_t opf)
547 {
548 	struct dm_io_request io_req;
549 	struct dm_io_region io_loc;
550 	const enum req_op op = opf & REQ_OP_MASK;
551 	int r;
552 
553 	io_req.bi_opf = opf;
554 	io_req.mem.type = DM_IO_KMEM;
555 	io_req.mem.ptr.addr = ic->sb;
556 	io_req.notify.fn = NULL;
557 	io_req.client = ic->io;
558 	io_loc.bdev = ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev;
559 	io_loc.sector = ic->start;
560 	io_loc.count = SB_SECTORS;
561 
562 	if (op == REQ_OP_WRITE) {
563 		sb_set_version(ic);
564 		if (ic->journal_mac && ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
565 			r = sb_mac(ic, true);
566 			if (unlikely(r))
567 				return r;
568 		}
569 	}
570 
571 	r = dm_io(&io_req, 1, &io_loc, NULL, NULL, IOPRIO_DEFAULT);
572 	if (unlikely(r))
573 		return r;
574 
575 	if (op == REQ_OP_READ) {
576 		if (ic->mode != 'R' && ic->journal_mac && ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
577 			r = sb_mac(ic, false);
578 			if (unlikely(r))
579 				return r;
580 		}
581 	}
582 
583 	return 0;
584 }
585 
586 #define BITMAP_OP_TEST_ALL_SET		0
587 #define BITMAP_OP_TEST_ALL_CLEAR	1
588 #define BITMAP_OP_SET			2
589 #define BITMAP_OP_CLEAR			3
590 
591 static bool block_bitmap_op(struct dm_integrity_c *ic, struct page_list *bitmap,
592 			    sector_t sector, sector_t n_sectors, int mode)
593 {
594 	unsigned long bit, end_bit, this_end_bit, page, end_page;
595 	unsigned long *data;
596 
597 	if (unlikely(((sector | n_sectors) & ((1 << ic->sb->log2_sectors_per_block) - 1)) != 0)) {
598 		DMCRIT("invalid bitmap access (%llx,%llx,%d,%d,%d)",
599 			sector,
600 			n_sectors,
601 			ic->sb->log2_sectors_per_block,
602 			ic->log2_blocks_per_bitmap_bit,
603 			mode);
604 		BUG();
605 	}
606 
607 	if (unlikely(!n_sectors))
608 		return true;
609 
610 	bit = sector >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
611 	end_bit = (sector + n_sectors - 1) >>
612 		(ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
613 
614 	page = bit / (PAGE_SIZE * 8);
615 	bit %= PAGE_SIZE * 8;
616 
617 	end_page = end_bit / (PAGE_SIZE * 8);
618 	end_bit %= PAGE_SIZE * 8;
619 
620 repeat:
621 	if (page < end_page)
622 		this_end_bit = PAGE_SIZE * 8 - 1;
623 	else
624 		this_end_bit = end_bit;
625 
626 	data = lowmem_page_address(bitmap[page].page);
627 
628 	if (mode == BITMAP_OP_TEST_ALL_SET) {
629 		while (bit <= this_end_bit) {
630 			if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
631 				do {
632 					if (data[bit / BITS_PER_LONG] != -1)
633 						return false;
634 					bit += BITS_PER_LONG;
635 				} while (this_end_bit >= bit + BITS_PER_LONG - 1);
636 				continue;
637 			}
638 			if (!test_bit(bit, data))
639 				return false;
640 			bit++;
641 		}
642 	} else if (mode == BITMAP_OP_TEST_ALL_CLEAR) {
643 		while (bit <= this_end_bit) {
644 			if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
645 				do {
646 					if (data[bit / BITS_PER_LONG] != 0)
647 						return false;
648 					bit += BITS_PER_LONG;
649 				} while (this_end_bit >= bit + BITS_PER_LONG - 1);
650 				continue;
651 			}
652 			if (test_bit(bit, data))
653 				return false;
654 			bit++;
655 		}
656 	} else if (mode == BITMAP_OP_SET) {
657 		while (bit <= this_end_bit) {
658 			if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
659 				do {
660 					data[bit / BITS_PER_LONG] = -1;
661 					bit += BITS_PER_LONG;
662 				} while (this_end_bit >= bit + BITS_PER_LONG - 1);
663 				continue;
664 			}
665 			__set_bit(bit, data);
666 			bit++;
667 		}
668 	} else if (mode == BITMAP_OP_CLEAR) {
669 		if (!bit && this_end_bit == PAGE_SIZE * 8 - 1)
670 			clear_page(data);
671 		else {
672 			while (bit <= this_end_bit) {
673 				if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
674 					do {
675 						data[bit / BITS_PER_LONG] = 0;
676 						bit += BITS_PER_LONG;
677 					} while (this_end_bit >= bit + BITS_PER_LONG - 1);
678 					continue;
679 				}
680 				__clear_bit(bit, data);
681 				bit++;
682 			}
683 		}
684 	} else {
685 		BUG();
686 	}
687 
688 	if (unlikely(page < end_page)) {
689 		bit = 0;
690 		page++;
691 		goto repeat;
692 	}
693 
694 	return true;
695 }
696 
697 static void block_bitmap_copy(struct dm_integrity_c *ic, struct page_list *dst, struct page_list *src)
698 {
699 	unsigned int n_bitmap_pages = DIV_ROUND_UP(ic->n_bitmap_blocks, PAGE_SIZE / BITMAP_BLOCK_SIZE);
700 	unsigned int i;
701 
702 	for (i = 0; i < n_bitmap_pages; i++) {
703 		unsigned long *dst_data = lowmem_page_address(dst[i].page);
704 		unsigned long *src_data = lowmem_page_address(src[i].page);
705 
706 		copy_page(dst_data, src_data);
707 	}
708 }
709 
710 static struct bitmap_block_status *sector_to_bitmap_block(struct dm_integrity_c *ic, sector_t sector)
711 {
712 	unsigned int bit = sector >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
713 	unsigned int bitmap_block = bit / (BITMAP_BLOCK_SIZE * 8);
714 
715 	BUG_ON(bitmap_block >= ic->n_bitmap_blocks);
716 	return &ic->bbs[bitmap_block];
717 }
718 
719 static void access_journal_check(struct dm_integrity_c *ic, unsigned int section, unsigned int offset,
720 				 bool e, const char *function)
721 {
722 #if defined(CONFIG_DM_DEBUG) || defined(INTERNAL_VERIFY)
723 	unsigned int limit = e ? ic->journal_section_entries : ic->journal_section_sectors;
724 
725 	if (unlikely(section >= ic->journal_sections) ||
726 	    unlikely(offset >= limit)) {
727 		DMCRIT("%s: invalid access at (%u,%u), limit (%u,%u)",
728 		       function, section, offset, ic->journal_sections, limit);
729 		BUG();
730 	}
731 #endif
732 }
733 
734 static void page_list_location(struct dm_integrity_c *ic, unsigned int section, unsigned int offset,
735 			       unsigned int *pl_index, unsigned int *pl_offset)
736 {
737 	unsigned int sector;
738 
739 	access_journal_check(ic, section, offset, false, "page_list_location");
740 
741 	sector = section * ic->journal_section_sectors + offset;
742 
743 	*pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
744 	*pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
745 }
746 
747 static struct journal_sector *access_page_list(struct dm_integrity_c *ic, struct page_list *pl,
748 					       unsigned int section, unsigned int offset, unsigned int *n_sectors)
749 {
750 	unsigned int pl_index, pl_offset;
751 	char *va;
752 
753 	page_list_location(ic, section, offset, &pl_index, &pl_offset);
754 
755 	if (n_sectors)
756 		*n_sectors = (PAGE_SIZE - pl_offset) >> SECTOR_SHIFT;
757 
758 	va = lowmem_page_address(pl[pl_index].page);
759 
760 	return (struct journal_sector *)(va + pl_offset);
761 }
762 
763 static struct journal_sector *access_journal(struct dm_integrity_c *ic, unsigned int section, unsigned int offset)
764 {
765 	return access_page_list(ic, ic->journal, section, offset, NULL);
766 }
767 
768 static struct journal_entry *access_journal_entry(struct dm_integrity_c *ic, unsigned int section, unsigned int n)
769 {
770 	unsigned int rel_sector, offset;
771 	struct journal_sector *js;
772 
773 	access_journal_check(ic, section, n, true, "access_journal_entry");
774 
775 	rel_sector = n % JOURNAL_BLOCK_SECTORS;
776 	offset = n / JOURNAL_BLOCK_SECTORS;
777 
778 	js = access_journal(ic, section, rel_sector);
779 	return (struct journal_entry *)((char *)js + offset * ic->journal_entry_size);
780 }
781 
782 static struct journal_sector *access_journal_data(struct dm_integrity_c *ic, unsigned int section, unsigned int n)
783 {
784 	n <<= ic->sb->log2_sectors_per_block;
785 
786 	n += JOURNAL_BLOCK_SECTORS;
787 
788 	access_journal_check(ic, section, n, false, "access_journal_data");
789 
790 	return access_journal(ic, section, n);
791 }
792 
793 static void section_mac(struct dm_integrity_c *ic, unsigned int section, __u8 result[JOURNAL_MAC_SIZE])
794 {
795 	SHASH_DESC_ON_STACK(desc, ic->journal_mac);
796 	int r;
797 	unsigned int j, size;
798 
799 	desc->tfm = ic->journal_mac;
800 
801 	r = crypto_shash_init(desc);
802 	if (unlikely(r < 0)) {
803 		dm_integrity_io_error(ic, "crypto_shash_init", r);
804 		goto err;
805 	}
806 
807 	if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
808 		__le64 section_le;
809 
810 		r = crypto_shash_update(desc, (__u8 *)&ic->sb->salt, SALT_SIZE);
811 		if (unlikely(r < 0)) {
812 			dm_integrity_io_error(ic, "crypto_shash_update", r);
813 			goto err;
814 		}
815 
816 		section_le = cpu_to_le64(section);
817 		r = crypto_shash_update(desc, (__u8 *)&section_le, sizeof(section_le));
818 		if (unlikely(r < 0)) {
819 			dm_integrity_io_error(ic, "crypto_shash_update", r);
820 			goto err;
821 		}
822 	}
823 
824 	for (j = 0; j < ic->journal_section_entries; j++) {
825 		struct journal_entry *je = access_journal_entry(ic, section, j);
826 
827 		r = crypto_shash_update(desc, (__u8 *)&je->u.sector, sizeof(je->u.sector));
828 		if (unlikely(r < 0)) {
829 			dm_integrity_io_error(ic, "crypto_shash_update", r);
830 			goto err;
831 		}
832 	}
833 
834 	size = crypto_shash_digestsize(ic->journal_mac);
835 
836 	if (likely(size <= JOURNAL_MAC_SIZE)) {
837 		r = crypto_shash_final(desc, result);
838 		if (unlikely(r < 0)) {
839 			dm_integrity_io_error(ic, "crypto_shash_final", r);
840 			goto err;
841 		}
842 		memset(result + size, 0, JOURNAL_MAC_SIZE - size);
843 	} else {
844 		__u8 digest[HASH_MAX_DIGESTSIZE];
845 
846 		if (WARN_ON(size > sizeof(digest))) {
847 			dm_integrity_io_error(ic, "digest_size", -EINVAL);
848 			goto err;
849 		}
850 		r = crypto_shash_final(desc, digest);
851 		if (unlikely(r < 0)) {
852 			dm_integrity_io_error(ic, "crypto_shash_final", r);
853 			goto err;
854 		}
855 		memcpy(result, digest, JOURNAL_MAC_SIZE);
856 	}
857 
858 	return;
859 err:
860 	memset(result, 0, JOURNAL_MAC_SIZE);
861 }
862 
863 static void rw_section_mac(struct dm_integrity_c *ic, unsigned int section, bool wr)
864 {
865 	__u8 result[JOURNAL_MAC_SIZE];
866 	unsigned int j;
867 
868 	if (!ic->journal_mac)
869 		return;
870 
871 	section_mac(ic, section, result);
872 
873 	for (j = 0; j < JOURNAL_BLOCK_SECTORS; j++) {
874 		struct journal_sector *js = access_journal(ic, section, j);
875 
876 		if (likely(wr))
877 			memcpy(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR);
878 		else {
879 			if (crypto_memneq(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR)) {
880 				dm_integrity_io_error(ic, "journal mac", -EILSEQ);
881 				dm_audit_log_target(DM_MSG_PREFIX, "mac-journal", ic->ti, 0);
882 			}
883 		}
884 	}
885 }
886 
887 static void complete_journal_op(void *context)
888 {
889 	struct journal_completion *comp = context;
890 
891 	BUG_ON(!atomic_read(&comp->in_flight));
892 	if (likely(atomic_dec_and_test(&comp->in_flight)))
893 		complete(&comp->comp);
894 }
895 
896 static void xor_journal(struct dm_integrity_c *ic, bool encrypt, unsigned int section,
897 			unsigned int n_sections, struct journal_completion *comp)
898 {
899 	struct async_submit_ctl submit;
900 	size_t n_bytes = (size_t)(n_sections * ic->journal_section_sectors) << SECTOR_SHIFT;
901 	unsigned int pl_index, pl_offset, section_index;
902 	struct page_list *source_pl, *target_pl;
903 
904 	if (likely(encrypt)) {
905 		source_pl = ic->journal;
906 		target_pl = ic->journal_io;
907 	} else {
908 		source_pl = ic->journal_io;
909 		target_pl = ic->journal;
910 	}
911 
912 	page_list_location(ic, section, 0, &pl_index, &pl_offset);
913 
914 	atomic_add(roundup(pl_offset + n_bytes, PAGE_SIZE) >> PAGE_SHIFT, &comp->in_flight);
915 
916 	init_async_submit(&submit, ASYNC_TX_XOR_ZERO_DST, NULL, complete_journal_op, comp, NULL);
917 
918 	section_index = pl_index;
919 
920 	do {
921 		size_t this_step;
922 		struct page *src_pages[2];
923 		struct page *dst_page;
924 
925 		while (unlikely(pl_index == section_index)) {
926 			unsigned int dummy;
927 
928 			if (likely(encrypt))
929 				rw_section_mac(ic, section, true);
930 			section++;
931 			n_sections--;
932 			if (!n_sections)
933 				break;
934 			page_list_location(ic, section, 0, &section_index, &dummy);
935 		}
936 
937 		this_step = min(n_bytes, (size_t)PAGE_SIZE - pl_offset);
938 		dst_page = target_pl[pl_index].page;
939 		src_pages[0] = source_pl[pl_index].page;
940 		src_pages[1] = ic->journal_xor[pl_index].page;
941 
942 		async_xor(dst_page, src_pages, pl_offset, 2, this_step, &submit);
943 
944 		pl_index++;
945 		pl_offset = 0;
946 		n_bytes -= this_step;
947 	} while (n_bytes);
948 
949 	BUG_ON(n_sections);
950 
951 	async_tx_issue_pending_all();
952 }
953 
954 static void complete_journal_encrypt(void *data, int err)
955 {
956 	struct journal_completion *comp = data;
957 
958 	if (unlikely(err)) {
959 		if (likely(err == -EINPROGRESS)) {
960 			complete(&comp->ic->crypto_backoff);
961 			return;
962 		}
963 		dm_integrity_io_error(comp->ic, "asynchronous encrypt", err);
964 	}
965 	complete_journal_op(comp);
966 }
967 
968 static bool do_crypt(bool encrypt, struct skcipher_request *req, struct journal_completion *comp)
969 {
970 	int r;
971 
972 	skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
973 				      complete_journal_encrypt, comp);
974 	if (likely(encrypt))
975 		r = crypto_skcipher_encrypt(req);
976 	else
977 		r = crypto_skcipher_decrypt(req);
978 	if (likely(!r))
979 		return false;
980 	if (likely(r == -EINPROGRESS))
981 		return true;
982 	if (likely(r == -EBUSY)) {
983 		wait_for_completion(&comp->ic->crypto_backoff);
984 		reinit_completion(&comp->ic->crypto_backoff);
985 		return true;
986 	}
987 	dm_integrity_io_error(comp->ic, "encrypt", r);
988 	return false;
989 }
990 
991 static void crypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned int section,
992 			  unsigned int n_sections, struct journal_completion *comp)
993 {
994 	struct scatterlist **source_sg;
995 	struct scatterlist **target_sg;
996 
997 	atomic_add(2, &comp->in_flight);
998 
999 	if (likely(encrypt)) {
1000 		source_sg = ic->journal_scatterlist;
1001 		target_sg = ic->journal_io_scatterlist;
1002 	} else {
1003 		source_sg = ic->journal_io_scatterlist;
1004 		target_sg = ic->journal_scatterlist;
1005 	}
1006 
1007 	do {
1008 		struct skcipher_request *req;
1009 		unsigned int ivsize;
1010 		char *iv;
1011 
1012 		if (likely(encrypt))
1013 			rw_section_mac(ic, section, true);
1014 
1015 		req = ic->sk_requests[section];
1016 		ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
1017 		iv = req->iv;
1018 
1019 		memcpy(iv, iv + ivsize, ivsize);
1020 
1021 		req->src = source_sg[section];
1022 		req->dst = target_sg[section];
1023 
1024 		if (unlikely(do_crypt(encrypt, req, comp)))
1025 			atomic_inc(&comp->in_flight);
1026 
1027 		section++;
1028 		n_sections--;
1029 	} while (n_sections);
1030 
1031 	atomic_dec(&comp->in_flight);
1032 	complete_journal_op(comp);
1033 }
1034 
1035 static void encrypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned int section,
1036 			    unsigned int n_sections, struct journal_completion *comp)
1037 {
1038 	if (ic->journal_xor)
1039 		return xor_journal(ic, encrypt, section, n_sections, comp);
1040 	else
1041 		return crypt_journal(ic, encrypt, section, n_sections, comp);
1042 }
1043 
1044 static void complete_journal_io(unsigned long error, unsigned long unsup, void *context)
1045 {
1046 	struct journal_completion *comp = context;
1047 
1048 	if (unlikely(error != 0))
1049 		dm_integrity_io_error(comp->ic, "writing journal", -EIO);
1050 	else if (unlikely(unsup != 0))
1051 		dm_integrity_io_error(comp->ic, "writing journal", -EOPNOTSUPP);
1052 	complete_journal_op(comp);
1053 }
1054 
1055 static void rw_journal_sectors(struct dm_integrity_c *ic, blk_opf_t opf,
1056 			       unsigned int sector, unsigned int n_sectors,
1057 			       struct journal_completion *comp)
1058 {
1059 	struct dm_io_request io_req;
1060 	struct dm_io_region io_loc;
1061 	unsigned int pl_index, pl_offset;
1062 	int r;
1063 
1064 	if (unlikely(dm_integrity_failed(ic))) {
1065 		if (comp)
1066 			complete_journal_io(-1UL, -1UL, comp);
1067 		return;
1068 	}
1069 
1070 	pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
1071 	pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
1072 
1073 	io_req.bi_opf = opf;
1074 	io_req.mem.type = DM_IO_PAGE_LIST;
1075 	if (ic->journal_io)
1076 		io_req.mem.ptr.pl = &ic->journal_io[pl_index];
1077 	else
1078 		io_req.mem.ptr.pl = &ic->journal[pl_index];
1079 	io_req.mem.offset = pl_offset;
1080 	if (likely(comp != NULL)) {
1081 		io_req.notify.fn = complete_journal_io;
1082 		io_req.notify.context = comp;
1083 	} else {
1084 		io_req.notify.fn = NULL;
1085 	}
1086 	io_req.client = ic->io;
1087 	io_loc.bdev = ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev;
1088 	io_loc.sector = ic->start + SB_SECTORS + sector;
1089 	io_loc.count = n_sectors;
1090 
1091 	r = dm_io(&io_req, 1, &io_loc, NULL, NULL, IOPRIO_DEFAULT);
1092 	if (unlikely(r)) {
1093 		dm_integrity_io_error(ic, (opf & REQ_OP_MASK) == REQ_OP_READ ?
1094 				      "reading journal" : "writing journal", r);
1095 		if (comp) {
1096 			WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
1097 			complete_journal_io(-1UL, -1UL, comp);
1098 		}
1099 	}
1100 }
1101 
1102 static void rw_journal(struct dm_integrity_c *ic, blk_opf_t opf,
1103 		       unsigned int section, unsigned int n_sections,
1104 		       struct journal_completion *comp)
1105 {
1106 	unsigned int sector, n_sectors;
1107 
1108 	sector = section * ic->journal_section_sectors;
1109 	n_sectors = n_sections * ic->journal_section_sectors;
1110 
1111 	rw_journal_sectors(ic, opf, sector, n_sectors, comp);
1112 }
1113 
1114 static void write_journal(struct dm_integrity_c *ic, unsigned int commit_start, unsigned int commit_sections)
1115 {
1116 	struct journal_completion io_comp;
1117 	struct journal_completion crypt_comp_1;
1118 	struct journal_completion crypt_comp_2;
1119 	unsigned int i;
1120 
1121 	io_comp.ic = ic;
1122 	init_completion(&io_comp.comp);
1123 
1124 	if (commit_start + commit_sections <= ic->journal_sections) {
1125 		io_comp.in_flight = (atomic_t)ATOMIC_INIT(1);
1126 		if (ic->journal_io) {
1127 			crypt_comp_1.ic = ic;
1128 			init_completion(&crypt_comp_1.comp);
1129 			crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
1130 			encrypt_journal(ic, true, commit_start, commit_sections, &crypt_comp_1);
1131 			wait_for_completion_io(&crypt_comp_1.comp);
1132 		} else {
1133 			for (i = 0; i < commit_sections; i++)
1134 				rw_section_mac(ic, commit_start + i, true);
1135 		}
1136 		rw_journal(ic, REQ_OP_WRITE | REQ_FUA | REQ_SYNC, commit_start,
1137 			   commit_sections, &io_comp);
1138 	} else {
1139 		unsigned int to_end;
1140 
1141 		io_comp.in_flight = (atomic_t)ATOMIC_INIT(2);
1142 		to_end = ic->journal_sections - commit_start;
1143 		if (ic->journal_io) {
1144 			crypt_comp_1.ic = ic;
1145 			init_completion(&crypt_comp_1.comp);
1146 			crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
1147 			encrypt_journal(ic, true, commit_start, to_end, &crypt_comp_1);
1148 			if (try_wait_for_completion(&crypt_comp_1.comp)) {
1149 				rw_journal(ic, REQ_OP_WRITE | REQ_FUA,
1150 					   commit_start, to_end, &io_comp);
1151 				reinit_completion(&crypt_comp_1.comp);
1152 				crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
1153 				encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_1);
1154 				wait_for_completion_io(&crypt_comp_1.comp);
1155 			} else {
1156 				crypt_comp_2.ic = ic;
1157 				init_completion(&crypt_comp_2.comp);
1158 				crypt_comp_2.in_flight = (atomic_t)ATOMIC_INIT(0);
1159 				encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_2);
1160 				wait_for_completion_io(&crypt_comp_1.comp);
1161 				rw_journal(ic, REQ_OP_WRITE | REQ_FUA, commit_start, to_end, &io_comp);
1162 				wait_for_completion_io(&crypt_comp_2.comp);
1163 			}
1164 		} else {
1165 			for (i = 0; i < to_end; i++)
1166 				rw_section_mac(ic, commit_start + i, true);
1167 			rw_journal(ic, REQ_OP_WRITE | REQ_FUA, commit_start, to_end, &io_comp);
1168 			for (i = 0; i < commit_sections - to_end; i++)
1169 				rw_section_mac(ic, i, true);
1170 		}
1171 		rw_journal(ic, REQ_OP_WRITE | REQ_FUA, 0, commit_sections - to_end, &io_comp);
1172 	}
1173 
1174 	wait_for_completion_io(&io_comp.comp);
1175 }
1176 
1177 static void copy_from_journal(struct dm_integrity_c *ic, unsigned int section, unsigned int offset,
1178 			      unsigned int n_sectors, sector_t target, io_notify_fn fn, void *data)
1179 {
1180 	struct dm_io_request io_req;
1181 	struct dm_io_region io_loc;
1182 	int r;
1183 	unsigned int sector, pl_index, pl_offset;
1184 
1185 	BUG_ON((target | n_sectors | offset) & (unsigned int)(ic->sectors_per_block - 1));
1186 
1187 	if (unlikely(dm_integrity_failed(ic))) {
1188 		fn(-1UL, -1UL, data);
1189 		return;
1190 	}
1191 
1192 	sector = section * ic->journal_section_sectors + JOURNAL_BLOCK_SECTORS + offset;
1193 
1194 	pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
1195 	pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
1196 
1197 	io_req.bi_opf = REQ_OP_WRITE;
1198 	io_req.mem.type = DM_IO_PAGE_LIST;
1199 	io_req.mem.ptr.pl = &ic->journal[pl_index];
1200 	io_req.mem.offset = pl_offset;
1201 	io_req.notify.fn = fn;
1202 	io_req.notify.context = data;
1203 	io_req.client = ic->io;
1204 	io_loc.bdev = ic->dev->bdev;
1205 	io_loc.sector = target;
1206 	io_loc.count = n_sectors;
1207 
1208 	r = dm_io(&io_req, 1, &io_loc, NULL, NULL, IOPRIO_DEFAULT);
1209 	if (unlikely(r)) {
1210 		WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
1211 		fn(-1UL, -1UL, data);
1212 	}
1213 }
1214 
1215 static bool ranges_overlap(struct dm_integrity_range *range1, struct dm_integrity_range *range2)
1216 {
1217 	return range1->logical_sector < range2->logical_sector + range2->n_sectors &&
1218 	       range1->logical_sector + range1->n_sectors > range2->logical_sector;
1219 }
1220 
1221 static bool add_new_range(struct dm_integrity_c *ic, struct dm_integrity_range *new_range, bool check_waiting)
1222 {
1223 	struct rb_node **n = &ic->in_progress.rb_node;
1224 	struct rb_node *parent;
1225 
1226 	BUG_ON((new_range->logical_sector | new_range->n_sectors) & (unsigned int)(ic->sectors_per_block - 1));
1227 
1228 	if (likely(check_waiting)) {
1229 		struct dm_integrity_range *range;
1230 
1231 		list_for_each_entry(range, &ic->wait_list, wait_entry) {
1232 			if (unlikely(ranges_overlap(range, new_range)))
1233 				return false;
1234 		}
1235 	}
1236 
1237 	parent = NULL;
1238 
1239 	while (*n) {
1240 		struct dm_integrity_range *range = container_of(*n, struct dm_integrity_range, node);
1241 
1242 		parent = *n;
1243 		if (new_range->logical_sector + new_range->n_sectors <= range->logical_sector)
1244 			n = &range->node.rb_left;
1245 		else if (new_range->logical_sector >= range->logical_sector + range->n_sectors)
1246 			n = &range->node.rb_right;
1247 		else
1248 			return false;
1249 	}
1250 
1251 	rb_link_node(&new_range->node, parent, n);
1252 	rb_insert_color(&new_range->node, &ic->in_progress);
1253 
1254 	return true;
1255 }
1256 
1257 static void remove_range_unlocked(struct dm_integrity_c *ic, struct dm_integrity_range *range)
1258 {
1259 	rb_erase(&range->node, &ic->in_progress);
1260 	while (unlikely(!list_empty(&ic->wait_list))) {
1261 		struct dm_integrity_range *last_range =
1262 			list_first_entry(&ic->wait_list, struct dm_integrity_range, wait_entry);
1263 		struct task_struct *last_range_task;
1264 
1265 		last_range_task = last_range->task;
1266 		list_del(&last_range->wait_entry);
1267 		if (!add_new_range(ic, last_range, false)) {
1268 			last_range->task = last_range_task;
1269 			list_add(&last_range->wait_entry, &ic->wait_list);
1270 			break;
1271 		}
1272 		last_range->waiting = false;
1273 		wake_up_process(last_range_task);
1274 	}
1275 }
1276 
1277 static void remove_range(struct dm_integrity_c *ic, struct dm_integrity_range *range)
1278 {
1279 	unsigned long flags;
1280 
1281 	spin_lock_irqsave(&ic->endio_wait.lock, flags);
1282 	remove_range_unlocked(ic, range);
1283 	spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1284 }
1285 
1286 static void wait_and_add_new_range(struct dm_integrity_c *ic, struct dm_integrity_range *new_range)
1287 {
1288 	new_range->waiting = true;
1289 	list_add_tail(&new_range->wait_entry, &ic->wait_list);
1290 	new_range->task = current;
1291 	do {
1292 		__set_current_state(TASK_UNINTERRUPTIBLE);
1293 		spin_unlock_irq(&ic->endio_wait.lock);
1294 		io_schedule();
1295 		spin_lock_irq(&ic->endio_wait.lock);
1296 	} while (unlikely(new_range->waiting));
1297 }
1298 
1299 static void add_new_range_and_wait(struct dm_integrity_c *ic, struct dm_integrity_range *new_range)
1300 {
1301 	if (unlikely(!add_new_range(ic, new_range, true)))
1302 		wait_and_add_new_range(ic, new_range);
1303 }
1304 
1305 static void init_journal_node(struct journal_node *node)
1306 {
1307 	RB_CLEAR_NODE(&node->node);
1308 	node->sector = (sector_t)-1;
1309 }
1310 
1311 static void add_journal_node(struct dm_integrity_c *ic, struct journal_node *node, sector_t sector)
1312 {
1313 	struct rb_node **link;
1314 	struct rb_node *parent;
1315 
1316 	node->sector = sector;
1317 	BUG_ON(!RB_EMPTY_NODE(&node->node));
1318 
1319 	link = &ic->journal_tree_root.rb_node;
1320 	parent = NULL;
1321 
1322 	while (*link) {
1323 		struct journal_node *j;
1324 
1325 		parent = *link;
1326 		j = container_of(parent, struct journal_node, node);
1327 		if (sector < j->sector)
1328 			link = &j->node.rb_left;
1329 		else
1330 			link = &j->node.rb_right;
1331 	}
1332 
1333 	rb_link_node(&node->node, parent, link);
1334 	rb_insert_color(&node->node, &ic->journal_tree_root);
1335 }
1336 
1337 static void remove_journal_node(struct dm_integrity_c *ic, struct journal_node *node)
1338 {
1339 	BUG_ON(RB_EMPTY_NODE(&node->node));
1340 	rb_erase(&node->node, &ic->journal_tree_root);
1341 	init_journal_node(node);
1342 }
1343 
1344 #define NOT_FOUND	(-1U)
1345 
1346 static unsigned int find_journal_node(struct dm_integrity_c *ic, sector_t sector, sector_t *next_sector)
1347 {
1348 	struct rb_node *n = ic->journal_tree_root.rb_node;
1349 	unsigned int found = NOT_FOUND;
1350 
1351 	*next_sector = (sector_t)-1;
1352 	while (n) {
1353 		struct journal_node *j = container_of(n, struct journal_node, node);
1354 
1355 		if (sector == j->sector)
1356 			found = j - ic->journal_tree;
1357 
1358 		if (sector < j->sector) {
1359 			*next_sector = j->sector;
1360 			n = j->node.rb_left;
1361 		} else
1362 			n = j->node.rb_right;
1363 	}
1364 
1365 	return found;
1366 }
1367 
1368 static bool test_journal_node(struct dm_integrity_c *ic, unsigned int pos, sector_t sector)
1369 {
1370 	struct journal_node *node, *next_node;
1371 	struct rb_node *next;
1372 
1373 	if (unlikely(pos >= ic->journal_entries))
1374 		return false;
1375 	node = &ic->journal_tree[pos];
1376 	if (unlikely(RB_EMPTY_NODE(&node->node)))
1377 		return false;
1378 	if (unlikely(node->sector != sector))
1379 		return false;
1380 
1381 	next = rb_next(&node->node);
1382 	if (unlikely(!next))
1383 		return true;
1384 
1385 	next_node = container_of(next, struct journal_node, node);
1386 	return next_node->sector != sector;
1387 }
1388 
1389 static bool find_newer_committed_node(struct dm_integrity_c *ic, struct journal_node *node)
1390 {
1391 	struct rb_node *next;
1392 	struct journal_node *next_node;
1393 	unsigned int next_section;
1394 
1395 	BUG_ON(RB_EMPTY_NODE(&node->node));
1396 
1397 	next = rb_next(&node->node);
1398 	if (unlikely(!next))
1399 		return false;
1400 
1401 	next_node = container_of(next, struct journal_node, node);
1402 
1403 	if (next_node->sector != node->sector)
1404 		return false;
1405 
1406 	next_section = (unsigned int)(next_node - ic->journal_tree) / ic->journal_section_entries;
1407 	if (next_section >= ic->committed_section &&
1408 	    next_section < ic->committed_section + ic->n_committed_sections)
1409 		return true;
1410 	if (next_section + ic->journal_sections < ic->committed_section + ic->n_committed_sections)
1411 		return true;
1412 
1413 	return false;
1414 }
1415 
1416 #define TAG_READ	0
1417 #define TAG_WRITE	1
1418 #define TAG_CMP		2
1419 
1420 static int dm_integrity_rw_tag(struct dm_integrity_c *ic, unsigned char *tag, sector_t *metadata_block,
1421 			       unsigned int *metadata_offset, unsigned int total_size, int op)
1422 {
1423 	unsigned int hash_offset = 0;
1424 	unsigned char mismatch_hash = 0;
1425 	unsigned char mismatch_filler = !ic->discard || ic->discard_keyed;
1426 
1427 	do {
1428 		unsigned char *data, *dp;
1429 		struct dm_buffer *b;
1430 		unsigned int to_copy;
1431 		int r;
1432 
1433 		r = dm_integrity_failed(ic);
1434 		if (unlikely(r))
1435 			return r;
1436 
1437 		data = dm_bufio_read(ic->bufio, *metadata_block, &b);
1438 		if (IS_ERR(data))
1439 			return PTR_ERR(data);
1440 
1441 		to_copy = min((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - *metadata_offset, total_size);
1442 		dp = data + *metadata_offset;
1443 		if (op == TAG_READ) {
1444 			memcpy(tag, dp, to_copy);
1445 		} else if (op == TAG_WRITE) {
1446 			if (crypto_memneq(dp, tag, to_copy)) {
1447 				memcpy(dp, tag, to_copy);
1448 				dm_bufio_mark_partial_buffer_dirty(b, *metadata_offset, *metadata_offset + to_copy);
1449 			}
1450 		} else {
1451 			/* e.g.: op == TAG_CMP */
1452 
1453 			if (likely(is_power_of_2(ic->tag_size))) {
1454 				if (unlikely(crypto_memneq(dp, tag, to_copy)))
1455 					goto thorough_test;
1456 			} else {
1457 				unsigned int i, ts;
1458 thorough_test:
1459 				ts = total_size;
1460 
1461 				for (i = 0; i < to_copy; i++, ts--) {
1462 					/*
1463 					 * Warning: the control flow must not be
1464 					 * dependent on match/mismatch of
1465 					 * individual bytes.
1466 					 */
1467 					mismatch_hash |= dp[i] ^ tag[i];
1468 					mismatch_filler |= dp[i] ^ DISCARD_FILLER;
1469 					hash_offset++;
1470 					if (unlikely(hash_offset == ic->tag_size)) {
1471 						if (unlikely(mismatch_hash) && unlikely(mismatch_filler)) {
1472 							dm_bufio_release(b);
1473 							return ts;
1474 						}
1475 						hash_offset = 0;
1476 						mismatch_hash = 0;
1477 						mismatch_filler = !ic->discard || ic->discard_keyed;
1478 					}
1479 				}
1480 			}
1481 		}
1482 		dm_bufio_release(b);
1483 
1484 		tag += to_copy;
1485 		*metadata_offset += to_copy;
1486 		if (unlikely(*metadata_offset == 1U << SECTOR_SHIFT << ic->log2_buffer_sectors)) {
1487 			(*metadata_block)++;
1488 			*metadata_offset = 0;
1489 		}
1490 
1491 		total_size -= to_copy;
1492 	} while (unlikely(total_size));
1493 
1494 	return 0;
1495 }
1496 
1497 struct flush_request {
1498 	struct dm_io_request io_req;
1499 	struct dm_io_region io_reg;
1500 	struct dm_integrity_c *ic;
1501 	struct completion comp;
1502 };
1503 
1504 static void flush_notify(unsigned long error, unsigned long unsup, void *fr_)
1505 {
1506 	struct flush_request *fr = fr_;
1507 
1508 	if (unlikely(error != 0))
1509 		dm_integrity_io_error(fr->ic, "flushing disk cache", -EIO);
1510 	else if (unlikely(unsup != 0))
1511 		dm_integrity_io_error(fr->ic, "flushing disk cache", -EOPNOTSUPP);
1512 	complete(&fr->comp);
1513 }
1514 
1515 static void dm_integrity_flush_buffers(struct dm_integrity_c *ic, bool flush_data)
1516 {
1517 	int r;
1518 	struct flush_request fr;
1519 
1520 	if (!ic->meta_dev)
1521 		flush_data = false;
1522 	if (flush_data) {
1523 		fr.io_req.bi_opf = REQ_OP_WRITE | REQ_PREFLUSH | REQ_SYNC;
1524 		fr.io_req.mem.type = DM_IO_KMEM;
1525 		fr.io_req.mem.ptr.addr = NULL;
1526 		fr.io_req.notify.fn = flush_notify;
1527 		fr.io_req.notify.context = &fr;
1528 		fr.io_req.client = dm_bufio_get_dm_io_client(ic->bufio);
1529 		fr.io_reg.bdev = ic->dev->bdev;
1530 		fr.io_reg.sector = 0;
1531 		fr.io_reg.count = 0;
1532 		fr.ic = ic;
1533 		init_completion(&fr.comp);
1534 		r = dm_io(&fr.io_req, 1, &fr.io_reg, NULL, NULL, IOPRIO_DEFAULT);
1535 		BUG_ON(r);
1536 	}
1537 
1538 	r = dm_bufio_write_dirty_buffers(ic->bufio);
1539 	if (unlikely(r))
1540 		dm_integrity_io_error(ic, "writing tags", r);
1541 
1542 	if (flush_data)
1543 		wait_for_completion(&fr.comp);
1544 }
1545 
1546 static void sleep_on_endio_wait(struct dm_integrity_c *ic)
1547 {
1548 	DECLARE_WAITQUEUE(wait, current);
1549 
1550 	__add_wait_queue(&ic->endio_wait, &wait);
1551 	__set_current_state(TASK_UNINTERRUPTIBLE);
1552 	spin_unlock_irq(&ic->endio_wait.lock);
1553 	io_schedule();
1554 	spin_lock_irq(&ic->endio_wait.lock);
1555 	__remove_wait_queue(&ic->endio_wait, &wait);
1556 }
1557 
1558 static void autocommit_fn(struct timer_list *t)
1559 {
1560 	struct dm_integrity_c *ic = timer_container_of(ic, t,
1561 						       autocommit_timer);
1562 
1563 	if (likely(!dm_integrity_failed(ic)))
1564 		queue_work(ic->commit_wq, &ic->commit_work);
1565 }
1566 
1567 static void schedule_autocommit(struct dm_integrity_c *ic)
1568 {
1569 	if (!timer_pending(&ic->autocommit_timer))
1570 		mod_timer(&ic->autocommit_timer, jiffies + ic->autocommit_jiffies);
1571 }
1572 
1573 static void submit_flush_bio(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
1574 {
1575 	struct bio *bio;
1576 	unsigned long flags;
1577 
1578 	spin_lock_irqsave(&ic->endio_wait.lock, flags);
1579 	bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1580 	bio_list_add(&ic->flush_bio_list, bio);
1581 	spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1582 
1583 	queue_work(ic->commit_wq, &ic->commit_work);
1584 }
1585 
1586 static void do_endio(struct dm_integrity_c *ic, struct bio *bio)
1587 {
1588 	int r;
1589 
1590 	r = dm_integrity_failed(ic);
1591 	if (unlikely(r) && !bio->bi_status)
1592 		bio->bi_status = errno_to_blk_status(r);
1593 	if (unlikely(ic->synchronous_mode) && bio_op(bio) == REQ_OP_WRITE) {
1594 		unsigned long flags;
1595 
1596 		spin_lock_irqsave(&ic->endio_wait.lock, flags);
1597 		bio_list_add(&ic->synchronous_bios, bio);
1598 		queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
1599 		spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1600 		return;
1601 	}
1602 	bio_endio(bio);
1603 }
1604 
1605 static void do_endio_flush(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
1606 {
1607 	struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1608 
1609 	if (unlikely(dio->fua) && likely(!bio->bi_status) && likely(!dm_integrity_failed(ic)))
1610 		submit_flush_bio(ic, dio);
1611 	else
1612 		do_endio(ic, bio);
1613 }
1614 
1615 static void dec_in_flight(struct dm_integrity_io *dio)
1616 {
1617 	if (atomic_dec_and_test(&dio->in_flight)) {
1618 		struct dm_integrity_c *ic = dio->ic;
1619 		struct bio *bio;
1620 
1621 		remove_range(ic, &dio->range);
1622 
1623 		if (dio->op == REQ_OP_WRITE || unlikely(dio->op == REQ_OP_DISCARD))
1624 			schedule_autocommit(ic);
1625 
1626 		bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1627 		if (unlikely(dio->bi_status) && !bio->bi_status)
1628 			bio->bi_status = dio->bi_status;
1629 		if (likely(!bio->bi_status) && unlikely(bio_sectors(bio) != dio->range.n_sectors)) {
1630 			dio->range.logical_sector += dio->range.n_sectors;
1631 			bio_advance(bio, dio->range.n_sectors << SECTOR_SHIFT);
1632 			INIT_WORK(&dio->work, integrity_bio_wait);
1633 			queue_work(ic->offload_wq, &dio->work);
1634 			return;
1635 		}
1636 		do_endio_flush(ic, dio);
1637 	}
1638 }
1639 
1640 static void integrity_end_io(struct bio *bio)
1641 {
1642 	struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
1643 
1644 	dm_bio_restore(&dio->bio_details, bio);
1645 	if (bio->bi_integrity)
1646 		bio->bi_opf |= REQ_INTEGRITY;
1647 
1648 	if (dio->completion)
1649 		complete(dio->completion);
1650 
1651 	dec_in_flight(dio);
1652 }
1653 
1654 static void integrity_sector_checksum_shash(struct dm_integrity_c *ic, sector_t sector,
1655 					    const char *data, unsigned offset,
1656 					    unsigned int len, char *result)
1657 {
1658 	__le64 sector_le = cpu_to_le64(sector);
1659 	SHASH_DESC_ON_STACK(req, ic->internal_shash);
1660 	int r;
1661 	unsigned int digest_size;
1662 
1663 	req->tfm = ic->internal_shash;
1664 
1665 	r = crypto_shash_init(req);
1666 	if (unlikely(r < 0)) {
1667 		dm_integrity_io_error(ic, "crypto_shash_init", r);
1668 		goto failed;
1669 	}
1670 
1671 	if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
1672 		r = crypto_shash_update(req, (__u8 *)&ic->sb->salt, SALT_SIZE);
1673 		if (unlikely(r < 0)) {
1674 			dm_integrity_io_error(ic, "crypto_shash_update", r);
1675 			goto failed;
1676 		}
1677 	}
1678 
1679 	r = crypto_shash_update(req, (const __u8 *)&sector_le, sizeof(sector_le));
1680 	if (unlikely(r < 0)) {
1681 		dm_integrity_io_error(ic, "crypto_shash_update", r);
1682 		goto failed;
1683 	}
1684 
1685 	if (likely(len)) {
1686 		r = crypto_shash_update(req, data + offset, len);
1687 		if (unlikely(r < 0)) {
1688 			dm_integrity_io_error(ic, "crypto_shash_update", r);
1689 			goto failed;
1690 		}
1691 	}
1692 
1693 	r = crypto_shash_final(req, result);
1694 	if (unlikely(r < 0)) {
1695 		dm_integrity_io_error(ic, "crypto_shash_final", r);
1696 		goto failed;
1697 	}
1698 
1699 	digest_size = ic->internal_hash_digestsize;
1700 	if (unlikely(digest_size < ic->tag_size))
1701 		memset(result + digest_size, 0, ic->tag_size - digest_size);
1702 
1703 	return;
1704 
1705 failed:
1706 	/* this shouldn't happen anyway, the hash functions have no reason to fail */
1707 	get_random_bytes(result, ic->tag_size);
1708 }
1709 
1710 static void integrity_sector_checksum_ahash(struct dm_integrity_c *ic, struct ahash_request **ahash_req,
1711 					    sector_t sector, struct page *page, unsigned offset,
1712 					    unsigned int len, char *result)
1713 {
1714 	__le64 sector_le = cpu_to_le64(sector);
1715 	struct ahash_request *req;
1716 	DECLARE_CRYPTO_WAIT(wait);
1717 	struct scatterlist sg[3], *s = sg;
1718 	int r;
1719 	unsigned int digest_size;
1720 	unsigned int nbytes = 0;
1721 	unsigned int nents = 1 + (len ? 1 : 0);
1722 
1723 	might_sleep();
1724 
1725 	req = *ahash_req;
1726 	if (unlikely(!req)) {
1727 		req = mempool_alloc(&ic->ahash_req_pool, GFP_NOIO);
1728 		*ahash_req = req;
1729 	}
1730 
1731 	ahash_request_set_tfm(req, ic->internal_ahash);
1732 	ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP, crypto_req_done, &wait);
1733 
1734 	if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
1735 		sg_init_table(sg, nents + 1);
1736 		sg_set_buf(s, (const __u8 *)&ic->sb->salt, SALT_SIZE);
1737 		nbytes += SALT_SIZE;
1738 		s++;
1739 	} else {
1740 		sg_init_table(sg, nents);
1741 	}
1742 
1743 	if (likely(!is_vmalloc_addr(&sector_le))) {
1744 		sg_set_buf(s, &sector_le, sizeof(sector_le));
1745 	} else {
1746 		struct page *sec_page = vmalloc_to_page(&sector_le);
1747 		unsigned int sec_off = offset_in_page(&sector_le);
1748 		sg_set_page(s, sec_page, sizeof(sector_le), sec_off);
1749 	}
1750 	nbytes += sizeof(sector_le);
1751 	s++;
1752 
1753 	if (likely(len)) {
1754 		sg_set_page(s, page, len, offset);
1755 		nbytes += len;
1756 	}
1757 
1758 	ahash_request_set_crypt(req, sg, result, nbytes);
1759 
1760 	r = crypto_wait_req(crypto_ahash_digest(req), &wait);
1761 	if (unlikely(r)) {
1762 		dm_integrity_io_error(ic, "crypto_ahash_digest", r);
1763 		goto failed;
1764 	}
1765 
1766 	digest_size = ic->internal_hash_digestsize;
1767 	if (unlikely(digest_size < ic->tag_size))
1768 		memset(result + digest_size, 0, ic->tag_size - digest_size);
1769 
1770 	return;
1771 
1772 failed:
1773 	/* this shouldn't happen anyway, the hash functions have no reason to fail */
1774 	get_random_bytes(result, ic->tag_size);
1775 }
1776 
1777 static void integrity_sector_checksum(struct dm_integrity_c *ic, struct ahash_request **ahash_req,
1778 				      sector_t sector, const char *data, unsigned offset, char *result)
1779 {
1780 	unsigned int len = ic->sectors_per_block << SECTOR_SHIFT;
1781 
1782 	if (likely(ic->internal_shash != NULL))
1783 		integrity_sector_checksum_shash(ic, sector, data, offset, len, result);
1784 	else
1785 		integrity_sector_checksum_ahash(ic, ahash_req, sector, (struct page *)data,
1786 						 offset, len, result);
1787 }
1788 
1789 /*
1790  * Authenticated marker for a discarded block: HMAC_key(salt || sector), with
1791  * no data payload. Because a real data tag's input always covers a full
1792  * block, its length differs from this marker's, so the two can never
1793  * collide structurally, regardless of block content.
1794  */
1795 static void integrity_discard_checksum(struct dm_integrity_c *ic, struct ahash_request **ahash_req,
1796 				       sector_t sector, char *result)
1797 {
1798 	if (likely(ic->internal_shash != NULL))
1799 		integrity_sector_checksum_shash(ic, sector, NULL, 0, 0, result);
1800 	else
1801 		integrity_sector_checksum_ahash(ic, ahash_req, sector, NULL, 0, 0, result);
1802 }
1803 
1804 static void integrity_discard_fill_tags(struct dm_integrity_c *ic, struct ahash_request **ahash_req,
1805 					unsigned char *checksums, sector_t *sector,
1806 					unsigned int blocks)
1807 {
1808 	unsigned int i;
1809 
1810 	for (i = 0; i < blocks; i++) {
1811 		integrity_discard_checksum(ic, ahash_req, *sector, checksums + i * ic->tag_size);
1812 		*sector += ic->sectors_per_block;
1813 	}
1814 }
1815 
1816 static void *integrity_kmap(struct dm_integrity_c *ic, struct page *p)
1817 {
1818 	if (likely(ic->internal_shash != NULL))
1819 		return kmap_local_page(p);
1820 	else
1821 		return p;
1822 }
1823 
1824 static void integrity_kunmap(struct dm_integrity_c *ic, const void *ptr)
1825 {
1826 	if (likely(ic->internal_shash != NULL))
1827 		kunmap_local(ptr);
1828 }
1829 
1830 static void *integrity_identity(struct dm_integrity_c *ic, void *data)
1831 {
1832 #ifdef CONFIG_DEBUG_SG
1833 	BUG_ON(offset_in_page(data));
1834 	BUG_ON(!virt_addr_valid(data));
1835 #endif
1836 	if (likely(ic->internal_shash != NULL))
1837 		return data;
1838 	else
1839 		return virt_to_page(data);
1840 }
1841 
1842 static int integrity_recheck_verify_tag(struct dm_integrity_io *dio, char *checksum,
1843 					char *on_disk_tag, sector_t logical_sector)
1844 {
1845 	struct dm_integrity_c *ic = dio->ic;
1846 	int r;
1847 
1848 	if (!ic->discard_keyed)
1849 		return dm_integrity_rw_tag(ic, checksum, &dio->metadata_block,
1850 					   &dio->metadata_offset, ic->tag_size, TAG_CMP);
1851 
1852 	r = dm_integrity_rw_tag(ic, on_disk_tag, &dio->metadata_block,
1853 				&dio->metadata_offset, ic->tag_size, TAG_READ);
1854 	if (unlikely(r))
1855 		return r;
1856 
1857 	r = crypto_memneq(on_disk_tag, checksum, ic->tag_size);
1858 	if (unlikely(r)) {
1859 		integrity_discard_checksum(ic, &dio->ahash_req, logical_sector, checksum);
1860 		r = crypto_memneq(on_disk_tag, checksum, ic->tag_size);
1861 	}
1862 	return r;
1863 }
1864 
1865 static noinline void integrity_recheck(struct dm_integrity_io *dio, char *checksum)
1866 {
1867 	struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1868 	struct dm_integrity_c *ic = dio->ic;
1869 	struct bvec_iter iter;
1870 	struct bio_vec bv;
1871 	sector_t sector, logical_sector, area, offset;
1872 	struct page *page;
1873 
1874 	get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
1875 	dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset,
1876 							     &dio->metadata_offset);
1877 	sector = get_data_sector(ic, area, offset);
1878 	logical_sector = dio->range.logical_sector;
1879 
1880 	page = mempool_alloc(&ic->recheck_pool, GFP_NOIO);
1881 
1882 	__bio_for_each_segment(bv, bio, iter, dio->bio_details.bi_iter) {
1883 		unsigned pos = 0;
1884 
1885 		do {
1886 			sector_t alignment;
1887 			char *mem;
1888 			char *buffer = page_to_virt(page);
1889 			unsigned int buffer_offset;
1890 			char on_disk_tag[MAX_T(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
1891 			int r;
1892 			struct dm_io_request io_req;
1893 			struct dm_io_region io_loc;
1894 			io_req.bi_opf = REQ_OP_READ;
1895 			io_req.mem.type = DM_IO_KMEM;
1896 			io_req.mem.ptr.addr = buffer;
1897 			io_req.notify.fn = NULL;
1898 			io_req.client = ic->io;
1899 			io_loc.bdev = ic->dev->bdev;
1900 			io_loc.sector = sector;
1901 			io_loc.count = ic->sectors_per_block;
1902 
1903 			/* Align the bio to logical block size */
1904 			alignment = dio->range.logical_sector | bio_sectors(bio) | (PAGE_SIZE >> SECTOR_SHIFT);
1905 			alignment &= -alignment;
1906 			io_loc.sector = round_down(io_loc.sector, alignment);
1907 			io_loc.count += sector - io_loc.sector;
1908 			buffer_offset = (sector - io_loc.sector) << SECTOR_SHIFT;
1909 			io_loc.count = round_up(io_loc.count, alignment);
1910 
1911 			r = dm_io(&io_req, 1, &io_loc, NULL, NULL, IOPRIO_DEFAULT);
1912 			if (unlikely(r)) {
1913 				dio->bi_status = errno_to_blk_status(r);
1914 				goto free_ret;
1915 			}
1916 
1917 			integrity_sector_checksum(ic, &dio->ahash_req, logical_sector, integrity_identity(ic, buffer), buffer_offset, checksum);
1918 			r = integrity_recheck_verify_tag(dio, checksum, on_disk_tag,
1919 							 logical_sector);
1920 			if (r) {
1921 				if (r > 0) {
1922 					DMERR_LIMIT("%pg: Checksum failed at sector 0x%llx",
1923 						    bio->bi_bdev, logical_sector);
1924 					atomic64_inc(&ic->number_of_mismatches);
1925 					dm_audit_log_bio(DM_MSG_PREFIX, "integrity-checksum",
1926 							 bio, logical_sector, 0);
1927 					r = -EILSEQ;
1928 				}
1929 				dio->bi_status = errno_to_blk_status(r);
1930 				goto free_ret;
1931 			}
1932 
1933 			mem = bvec_kmap_local(&bv);
1934 			memcpy(mem + pos, buffer + buffer_offset, ic->sectors_per_block << SECTOR_SHIFT);
1935 			kunmap_local(mem);
1936 
1937 			pos += ic->sectors_per_block << SECTOR_SHIFT;
1938 			sector += ic->sectors_per_block;
1939 			logical_sector += ic->sectors_per_block;
1940 		} while (pos < bv.bv_len);
1941 	}
1942 free_ret:
1943 	mempool_free(page, &ic->recheck_pool);
1944 }
1945 
1946 static void integrity_metadata(struct work_struct *w)
1947 {
1948 	struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
1949 	struct dm_integrity_c *ic = dio->ic;
1950 
1951 	int r;
1952 
1953 	if (ic->internal_hash) {
1954 		struct bvec_iter iter;
1955 		struct bio_vec bv;
1956 		unsigned int digest_size = ic->internal_hash_digestsize;
1957 		struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1958 		char *checksums;
1959 		unsigned int extra_space = unlikely(digest_size > ic->tag_size) ? digest_size - ic->tag_size : 0;
1960 		char checksums_onstack[MAX_T(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
1961 		sector_t sector;
1962 		unsigned int sectors_to_process;
1963 
1964 		if (unlikely(ic->mode == 'R'))
1965 			goto skip_io;
1966 
1967 		if (likely(dio->op != REQ_OP_DISCARD))
1968 			checksums = kmalloc((PAGE_SIZE >> SECTOR_SHIFT >> ic->sb->log2_sectors_per_block) * ic->tag_size + extra_space,
1969 					    GFP_NOIO | __GFP_NORETRY | __GFP_NOWARN);
1970 		else
1971 			checksums = kmalloc(PAGE_SIZE, GFP_NOIO | __GFP_NORETRY | __GFP_NOWARN);
1972 		if (!checksums) {
1973 			checksums = checksums_onstack;
1974 			if (WARN_ON(extra_space &&
1975 				    digest_size > sizeof(checksums_onstack))) {
1976 				r = -EINVAL;
1977 				goto error;
1978 			}
1979 		}
1980 
1981 		if (unlikely(dio->op == REQ_OP_DISCARD)) {
1982 			unsigned int bi_size = dio->bio_details.bi_iter.bi_size;
1983 			unsigned int max_size = likely(checksums != checksums_onstack) ? PAGE_SIZE : sizeof(checksums_onstack);
1984 			unsigned int max_blocks = (max_size - extra_space) / ic->tag_size;
1985 			sector_t sector = dio->range.logical_sector;
1986 
1987 			if (!ic->discard_keyed)
1988 				memset(checksums, DISCARD_FILLER, max_size);
1989 
1990 			while (bi_size) {
1991 				unsigned int this_step_blocks = bi_size >> (SECTOR_SHIFT + ic->sb->log2_sectors_per_block);
1992 
1993 				this_step_blocks = min(this_step_blocks, max_blocks);
1994 				if (ic->discard_keyed)
1995 					integrity_discard_fill_tags(ic, &dio->ahash_req, checksums,
1996 								    &sector, this_step_blocks);
1997 				r = dm_integrity_rw_tag(ic, checksums, &dio->metadata_block, &dio->metadata_offset,
1998 							this_step_blocks * ic->tag_size, TAG_WRITE);
1999 				if (unlikely(r)) {
2000 					if (likely(checksums != checksums_onstack))
2001 						kfree(checksums);
2002 					goto error;
2003 				}
2004 
2005 				bi_size -= this_step_blocks << (SECTOR_SHIFT + ic->sb->log2_sectors_per_block);
2006 			}
2007 
2008 			if (likely(checksums != checksums_onstack))
2009 				kfree(checksums);
2010 			goto skip_io;
2011 		}
2012 
2013 		sector = dio->range.logical_sector;
2014 		sectors_to_process = dio->range.n_sectors;
2015 
2016 		__bio_for_each_segment(bv, bio, iter, dio->bio_details.bi_iter) {
2017 			struct bio_vec bv_copy = bv;
2018 			unsigned int pos;
2019 			char *mem, *checksums_ptr;
2020 
2021 again:
2022 			mem = integrity_kmap(ic, bv_copy.bv_page);
2023 			pos = 0;
2024 			checksums_ptr = checksums;
2025 			do {
2026 				integrity_sector_checksum(ic, &dio->ahash_req, sector, mem, bv_copy.bv_offset + pos, checksums_ptr);
2027 				checksums_ptr += ic->tag_size;
2028 				sectors_to_process -= ic->sectors_per_block;
2029 				pos += ic->sectors_per_block << SECTOR_SHIFT;
2030 				sector += ic->sectors_per_block;
2031 			} while (pos < bv_copy.bv_len && sectors_to_process && checksums != checksums_onstack);
2032 			integrity_kunmap(ic, mem);
2033 
2034 			r = dm_integrity_rw_tag(ic, checksums, &dio->metadata_block, &dio->metadata_offset,
2035 						checksums_ptr - checksums, dio->op == REQ_OP_READ ? TAG_CMP : TAG_WRITE);
2036 			if (unlikely(r)) {
2037 				if (likely(checksums != checksums_onstack))
2038 					kfree(checksums);
2039 				if (r > 0) {
2040 					integrity_recheck(dio, checksums_onstack);
2041 					goto skip_io;
2042 				}
2043 				goto error;
2044 			}
2045 
2046 			if (!sectors_to_process)
2047 				break;
2048 
2049 			if (unlikely(pos < bv_copy.bv_len)) {
2050 				bv_copy.bv_offset += pos;
2051 				bv_copy.bv_len -= pos;
2052 				goto again;
2053 			}
2054 		}
2055 
2056 		if (likely(checksums != checksums_onstack))
2057 			kfree(checksums);
2058 	} else {
2059 		struct bio_integrity_payload *bip = dio->bio_details.bi_integrity;
2060 
2061 		if (bip) {
2062 			struct bio_vec biv;
2063 			struct bvec_iter iter;
2064 			unsigned int data_to_process = dio->range.n_sectors;
2065 
2066 			sector_to_block(ic, data_to_process);
2067 			data_to_process *= ic->tag_size;
2068 
2069 			bip_for_each_vec(biv, bip, iter) {
2070 				unsigned char *tag;
2071 				unsigned int this_len;
2072 
2073 				BUG_ON(PageHighMem(biv.bv_page));
2074 				tag = bvec_virt(&biv);
2075 				this_len = min(biv.bv_len, data_to_process);
2076 				r = dm_integrity_rw_tag(ic, tag, &dio->metadata_block, &dio->metadata_offset,
2077 							this_len, dio->op == REQ_OP_READ ? TAG_READ : TAG_WRITE);
2078 				if (unlikely(r))
2079 					goto error;
2080 				data_to_process -= this_len;
2081 				if (!data_to_process)
2082 					break;
2083 			}
2084 		}
2085 	}
2086 skip_io:
2087 	dec_in_flight(dio);
2088 	return;
2089 error:
2090 	dio->bi_status = errno_to_blk_status(r);
2091 	dec_in_flight(dio);
2092 }
2093 
2094 static inline bool dm_integrity_check_limits(struct dm_integrity_c *ic, sector_t logical_sector, struct bio *bio)
2095 {
2096 	if (unlikely(logical_sector + bio_sectors(bio) > ic->provided_data_sectors)) {
2097 		DMERR("Too big sector number: 0x%llx + 0x%x > 0x%llx",
2098 		      logical_sector, bio_sectors(bio),
2099 		      ic->provided_data_sectors);
2100 		return false;
2101 	}
2102 	if (unlikely((logical_sector | bio_sectors(bio)) & (unsigned int)(ic->sectors_per_block - 1))) {
2103 		DMERR("Bio not aligned on %u sectors: 0x%llx, 0x%x",
2104 		      ic->sectors_per_block,
2105 		      logical_sector, bio_sectors(bio));
2106 		return false;
2107 	}
2108 	if (ic->sectors_per_block > 1 && likely(bio_op(bio) != REQ_OP_DISCARD)) {
2109 		struct bvec_iter iter;
2110 		struct bio_vec bv;
2111 
2112 		bio_for_each_segment(bv, bio, iter) {
2113 			if (unlikely(bv.bv_len & ((ic->sectors_per_block << SECTOR_SHIFT) - 1))) {
2114 				DMERR("Bio vector (%u,%u) is not aligned on %u-sector boundary",
2115 					bv.bv_offset, bv.bv_len, ic->sectors_per_block);
2116 				return false;
2117 			}
2118 		}
2119 	}
2120 	return true;
2121 }
2122 
2123 static int dm_integrity_map(struct dm_target *ti, struct bio *bio)
2124 {
2125 	struct dm_integrity_c *ic = ti->private;
2126 	struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
2127 	struct bio_integrity_payload *bip;
2128 
2129 	sector_t area, offset;
2130 
2131 	dio->ic = ic;
2132 	dio->bi_status = 0;
2133 	dio->op = bio_op(bio);
2134 	dio->ahash_req = NULL;
2135 
2136 	if (ic->mode == 'I') {
2137 		bio->bi_iter.bi_sector = dm_target_offset(ic->ti, bio->bi_iter.bi_sector);
2138 		dio->integrity_payload = NULL;
2139 		dio->integrity_payload_from_mempool = false;
2140 		dio->integrity_range_locked = false;
2141 		return dm_integrity_map_inline(dio, true);
2142 	}
2143 
2144 	if (unlikely(dio->op == REQ_OP_DISCARD)) {
2145 		if (ti->max_io_len) {
2146 			sector_t sec = dm_target_offset(ti, bio->bi_iter.bi_sector);
2147 			unsigned int log2_max_io_len = __fls(ti->max_io_len);
2148 			sector_t start_boundary = sec >> log2_max_io_len;
2149 			sector_t end_boundary = (sec + bio_sectors(bio) - 1) >> log2_max_io_len;
2150 
2151 			if (start_boundary < end_boundary) {
2152 				sector_t len = ti->max_io_len - (sec & (ti->max_io_len - 1));
2153 
2154 				dm_accept_partial_bio(bio, len);
2155 			}
2156 		}
2157 	}
2158 
2159 	if (unlikely(bio->bi_opf & REQ_PREFLUSH)) {
2160 		submit_flush_bio(ic, dio);
2161 		return DM_MAPIO_SUBMITTED;
2162 	}
2163 
2164 	dio->range.logical_sector = dm_target_offset(ti, bio->bi_iter.bi_sector);
2165 	dio->fua = dio->op == REQ_OP_WRITE && bio->bi_opf & REQ_FUA;
2166 	if (unlikely(dio->fua)) {
2167 		/*
2168 		 * Don't pass down the FUA flag because we have to flush
2169 		 * disk cache anyway.
2170 		 */
2171 		bio->bi_opf &= ~REQ_FUA;
2172 	}
2173 	if (unlikely(!dm_integrity_check_limits(ic, dio->range.logical_sector, bio)))
2174 		return DM_MAPIO_KILL;
2175 
2176 	bip = bio_integrity(bio);
2177 	if (!ic->internal_hash) {
2178 		if (bip) {
2179 			unsigned int wanted_tag_size = bio_sectors(bio) >> ic->sb->log2_sectors_per_block;
2180 
2181 			if (ic->log2_tag_size >= 0)
2182 				wanted_tag_size <<= ic->log2_tag_size;
2183 			else
2184 				wanted_tag_size *= ic->tag_size;
2185 			if (unlikely(wanted_tag_size != bip->bip_iter.bi_size)) {
2186 				DMERR("Invalid integrity data size %u, expected %u",
2187 				      bip->bip_iter.bi_size, wanted_tag_size);
2188 				return DM_MAPIO_KILL;
2189 			}
2190 		}
2191 	} else {
2192 		if (unlikely(bip != NULL)) {
2193 			DMERR("Unexpected integrity data when using internal hash");
2194 			return DM_MAPIO_KILL;
2195 		}
2196 	}
2197 
2198 	if (unlikely(ic->mode == 'R') && unlikely(dio->op != REQ_OP_READ))
2199 		return DM_MAPIO_KILL;
2200 
2201 	get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
2202 	dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
2203 	bio->bi_iter.bi_sector = get_data_sector(ic, area, offset);
2204 
2205 	dm_integrity_map_continue(dio, true);
2206 	return DM_MAPIO_SUBMITTED;
2207 }
2208 
2209 static bool __journal_read_write(struct dm_integrity_io *dio, struct bio *bio,
2210 				 unsigned int journal_section, unsigned int journal_entry)
2211 {
2212 	struct dm_integrity_c *ic = dio->ic;
2213 	sector_t logical_sector;
2214 	unsigned int n_sectors;
2215 
2216 	logical_sector = dio->range.logical_sector;
2217 	n_sectors = dio->range.n_sectors;
2218 	do {
2219 		struct bio_vec bv = bio_iovec(bio);
2220 		char *mem;
2221 
2222 		if (unlikely(bv.bv_len >> SECTOR_SHIFT > n_sectors))
2223 			bv.bv_len = n_sectors << SECTOR_SHIFT;
2224 		n_sectors -= bv.bv_len >> SECTOR_SHIFT;
2225 		bio_advance_iter(bio, &bio->bi_iter, bv.bv_len);
2226 retry_kmap:
2227 		mem = kmap_local_page(bv.bv_page);
2228 		if (likely(dio->op == REQ_OP_WRITE))
2229 			flush_dcache_page(bv.bv_page);
2230 
2231 		do {
2232 			struct journal_entry *je = access_journal_entry(ic, journal_section, journal_entry);
2233 
2234 			if (unlikely(dio->op == REQ_OP_READ)) {
2235 				struct journal_sector *js;
2236 				char *mem_ptr;
2237 				unsigned int s;
2238 
2239 				if (unlikely(journal_entry_is_inprogress(je))) {
2240 					flush_dcache_page(bv.bv_page);
2241 					kunmap_local(mem);
2242 
2243 					__io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
2244 					goto retry_kmap;
2245 				}
2246 				smp_rmb();
2247 				BUG_ON(journal_entry_get_sector(je) != logical_sector);
2248 				js = access_journal_data(ic, journal_section, journal_entry);
2249 				mem_ptr = mem + bv.bv_offset;
2250 				s = 0;
2251 				do {
2252 					memcpy(mem_ptr, js, JOURNAL_SECTOR_DATA);
2253 					*(commit_id_t *)(mem_ptr + JOURNAL_SECTOR_DATA) = je->last_bytes[s];
2254 					js++;
2255 					mem_ptr += 1 << SECTOR_SHIFT;
2256 				} while (++s < ic->sectors_per_block);
2257 			}
2258 
2259 			if (!ic->internal_hash) {
2260 				struct bio_integrity_payload *bip = bio_integrity(bio);
2261 				unsigned int tag_todo = ic->tag_size;
2262 				char *tag_ptr = journal_entry_tag(ic, je);
2263 
2264 				if (bip) {
2265 					do {
2266 						struct bio_vec biv = bvec_iter_bvec(bip->bip_vec, bip->bip_iter);
2267 						unsigned int tag_now = min(biv.bv_len, tag_todo);
2268 						char *tag_addr;
2269 
2270 						BUG_ON(PageHighMem(biv.bv_page));
2271 						tag_addr = bvec_virt(&biv);
2272 						if (likely(dio->op == REQ_OP_WRITE))
2273 							memcpy(tag_ptr, tag_addr, tag_now);
2274 						else
2275 							memcpy(tag_addr, tag_ptr, tag_now);
2276 						bvec_iter_advance(bip->bip_vec, &bip->bip_iter, tag_now);
2277 						tag_ptr += tag_now;
2278 						tag_todo -= tag_now;
2279 					} while (unlikely(tag_todo));
2280 				} else if (likely(dio->op == REQ_OP_WRITE))
2281 					memset(tag_ptr, 0, tag_todo);
2282 			}
2283 
2284 			if (likely(dio->op == REQ_OP_WRITE)) {
2285 				struct journal_sector *js;
2286 				unsigned int s;
2287 
2288 				js = access_journal_data(ic, journal_section, journal_entry);
2289 				memcpy(js, mem + bv.bv_offset, ic->sectors_per_block << SECTOR_SHIFT);
2290 
2291 				s = 0;
2292 				do {
2293 					je->last_bytes[s] = js[s].commit_id;
2294 				} while (++s < ic->sectors_per_block);
2295 
2296 				if (ic->internal_hash) {
2297 					unsigned int digest_size = ic->internal_hash_digestsize;
2298 					void *js_page = integrity_identity(ic, (char *)js - offset_in_page(js));
2299 					unsigned js_offset = offset_in_page(js);
2300 
2301 					if (unlikely(digest_size > ic->tag_size)) {
2302 						char checksums_onstack[HASH_MAX_DIGESTSIZE];
2303 
2304 						integrity_sector_checksum(ic, &dio->ahash_req, logical_sector, js_page, js_offset, checksums_onstack);
2305 						memcpy(journal_entry_tag(ic, je), checksums_onstack, ic->tag_size);
2306 					} else
2307 						integrity_sector_checksum(ic, &dio->ahash_req, logical_sector, js_page, js_offset, journal_entry_tag(ic, je));
2308 				}
2309 
2310 				journal_entry_set_sector(je, logical_sector);
2311 			}
2312 			logical_sector += ic->sectors_per_block;
2313 
2314 			journal_entry++;
2315 			if (unlikely(journal_entry == ic->journal_section_entries)) {
2316 				journal_entry = 0;
2317 				journal_section++;
2318 				wraparound_section(ic, &journal_section);
2319 			}
2320 
2321 			bv.bv_offset += ic->sectors_per_block << SECTOR_SHIFT;
2322 		} while (bv.bv_len -= ic->sectors_per_block << SECTOR_SHIFT);
2323 
2324 		if (unlikely(dio->op == REQ_OP_READ))
2325 			flush_dcache_page(bv.bv_page);
2326 		kunmap_local(mem);
2327 	} while (n_sectors);
2328 
2329 	if (likely(dio->op == REQ_OP_WRITE)) {
2330 		smp_mb();
2331 		if (unlikely(waitqueue_active(&ic->copy_to_journal_wait)))
2332 			wake_up(&ic->copy_to_journal_wait);
2333 		if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold)
2334 			queue_work(ic->commit_wq, &ic->commit_work);
2335 		else
2336 			schedule_autocommit(ic);
2337 	} else
2338 		remove_range(ic, &dio->range);
2339 
2340 	if (unlikely(bio->bi_iter.bi_size)) {
2341 		sector_t area, offset;
2342 
2343 		dio->range.logical_sector = logical_sector;
2344 		get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
2345 		dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
2346 		return true;
2347 	}
2348 
2349 	return false;
2350 }
2351 
2352 static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map)
2353 {
2354 	struct dm_integrity_c *ic = dio->ic;
2355 	struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
2356 	unsigned int journal_section, journal_entry;
2357 	unsigned int journal_read_pos;
2358 	sector_t recalc_sector;
2359 	struct completion read_comp;
2360 	bool discard_retried = false;
2361 	bool need_sync_io = ic->internal_hash && dio->op == REQ_OP_READ;
2362 
2363 	if (unlikely(dio->op == REQ_OP_DISCARD) && ic->mode != 'D')
2364 		need_sync_io = true;
2365 
2366 	if (need_sync_io && from_map) {
2367 		INIT_WORK(&dio->work, integrity_bio_wait);
2368 		queue_work(ic->offload_wq, &dio->work);
2369 		return;
2370 	}
2371 
2372 lock_retry:
2373 	spin_lock_irq(&ic->endio_wait.lock);
2374 retry:
2375 	if (unlikely(dm_integrity_failed(ic))) {
2376 		spin_unlock_irq(&ic->endio_wait.lock);
2377 		do_endio(ic, bio);
2378 		return;
2379 	}
2380 	dio->range.n_sectors = bio_sectors(bio);
2381 	journal_read_pos = NOT_FOUND;
2382 	if (ic->mode == 'J' && likely(dio->op != REQ_OP_DISCARD)) {
2383 		if (dio->op == REQ_OP_WRITE) {
2384 			unsigned int next_entry, i, pos;
2385 			unsigned int ws, we, range_sectors;
2386 
2387 			dio->range.n_sectors = min(dio->range.n_sectors,
2388 						   (sector_t)ic->free_sectors << ic->sb->log2_sectors_per_block);
2389 			if (unlikely(!dio->range.n_sectors)) {
2390 				if (from_map)
2391 					goto offload_to_thread;
2392 				sleep_on_endio_wait(ic);
2393 				goto retry;
2394 			}
2395 			range_sectors = dio->range.n_sectors >> ic->sb->log2_sectors_per_block;
2396 			ic->free_sectors -= range_sectors;
2397 			journal_section = ic->free_section;
2398 			journal_entry = ic->free_section_entry;
2399 
2400 			next_entry = ic->free_section_entry + range_sectors;
2401 			ic->free_section_entry = next_entry % ic->journal_section_entries;
2402 			ic->free_section += next_entry / ic->journal_section_entries;
2403 			ic->n_uncommitted_sections += next_entry / ic->journal_section_entries;
2404 			wraparound_section(ic, &ic->free_section);
2405 
2406 			pos = journal_section * ic->journal_section_entries + journal_entry;
2407 			ws = journal_section;
2408 			we = journal_entry;
2409 			i = 0;
2410 			do {
2411 				struct journal_entry *je;
2412 
2413 				add_journal_node(ic, &ic->journal_tree[pos], dio->range.logical_sector + i);
2414 				pos++;
2415 				if (unlikely(pos >= ic->journal_entries))
2416 					pos = 0;
2417 
2418 				je = access_journal_entry(ic, ws, we);
2419 				BUG_ON(!journal_entry_is_unused(je));
2420 				journal_entry_set_inprogress(je);
2421 				we++;
2422 				if (unlikely(we == ic->journal_section_entries)) {
2423 					we = 0;
2424 					ws++;
2425 					wraparound_section(ic, &ws);
2426 				}
2427 			} while ((i += ic->sectors_per_block) < dio->range.n_sectors);
2428 
2429 			spin_unlock_irq(&ic->endio_wait.lock);
2430 			goto journal_read_write;
2431 		} else {
2432 			sector_t next_sector;
2433 
2434 			journal_read_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
2435 			if (likely(journal_read_pos == NOT_FOUND)) {
2436 				if (unlikely(dio->range.n_sectors > next_sector - dio->range.logical_sector))
2437 					dio->range.n_sectors = next_sector - dio->range.logical_sector;
2438 			} else {
2439 				unsigned int i;
2440 				unsigned int jp = journal_read_pos + 1;
2441 
2442 				for (i = ic->sectors_per_block; i < dio->range.n_sectors; i += ic->sectors_per_block, jp++) {
2443 					if (!test_journal_node(ic, jp, dio->range.logical_sector + i))
2444 						break;
2445 				}
2446 				dio->range.n_sectors = i;
2447 			}
2448 		}
2449 	}
2450 	if (unlikely(!add_new_range(ic, &dio->range, true))) {
2451 		/*
2452 		 * We must not sleep in the request routine because it could
2453 		 * stall bios on current->bio_list.
2454 		 * So, we offload the bio to a workqueue if we have to sleep.
2455 		 */
2456 		if (from_map) {
2457 offload_to_thread:
2458 			spin_unlock_irq(&ic->endio_wait.lock);
2459 			INIT_WORK(&dio->work, integrity_bio_wait);
2460 			queue_work(ic->wait_wq, &dio->work);
2461 			return;
2462 		}
2463 		if (journal_read_pos != NOT_FOUND)
2464 			dio->range.n_sectors = ic->sectors_per_block;
2465 		wait_and_add_new_range(ic, &dio->range);
2466 		/*
2467 		 * wait_and_add_new_range drops the spinlock, so the journal
2468 		 * may have been changed arbitrarily. We need to recheck.
2469 		 * To simplify the code, we restrict I/O size to just one block.
2470 		 */
2471 		if (journal_read_pos != NOT_FOUND) {
2472 			sector_t next_sector;
2473 			unsigned int new_pos;
2474 
2475 			new_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
2476 			if (unlikely(new_pos != journal_read_pos)) {
2477 				remove_range_unlocked(ic, &dio->range);
2478 				goto retry;
2479 			}
2480 		}
2481 	}
2482 	if (ic->mode == 'J' && likely(dio->op == REQ_OP_DISCARD) && !discard_retried) {
2483 		sector_t next_sector;
2484 		unsigned int new_pos;
2485 
2486 		new_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
2487 		if (unlikely(new_pos != NOT_FOUND) ||
2488 		    unlikely(next_sector < dio->range.logical_sector + dio->range.n_sectors)) {
2489 			remove_range_unlocked(ic, &dio->range);
2490 			spin_unlock_irq(&ic->endio_wait.lock);
2491 			queue_work(ic->commit_wq, &ic->commit_work);
2492 			flush_workqueue(ic->commit_wq);
2493 			queue_work(ic->writer_wq, &ic->writer_work);
2494 			flush_workqueue(ic->writer_wq);
2495 			discard_retried = true;
2496 			goto lock_retry;
2497 		}
2498 	}
2499 	recalc_sector = le64_to_cpu(ic->sb->recalc_sector);
2500 	spin_unlock_irq(&ic->endio_wait.lock);
2501 
2502 	if (unlikely(journal_read_pos != NOT_FOUND)) {
2503 		journal_section = journal_read_pos / ic->journal_section_entries;
2504 		journal_entry = journal_read_pos % ic->journal_section_entries;
2505 		goto journal_read_write;
2506 	}
2507 
2508 	if (ic->mode == 'B' && (dio->op == REQ_OP_WRITE || unlikely(dio->op == REQ_OP_DISCARD))) {
2509 		if (!block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
2510 				     dio->range.n_sectors, BITMAP_OP_TEST_ALL_SET)) {
2511 			struct bitmap_block_status *bbs;
2512 
2513 			bbs = sector_to_bitmap_block(ic, dio->range.logical_sector);
2514 			spin_lock(&bbs->bio_queue_lock);
2515 			bio_list_add(&bbs->bio_queue, bio);
2516 			spin_unlock(&bbs->bio_queue_lock);
2517 			queue_work(ic->writer_wq, &bbs->work);
2518 			return;
2519 		}
2520 	}
2521 
2522 	dio->in_flight = (atomic_t)ATOMIC_INIT(2);
2523 
2524 	if (need_sync_io) {
2525 		init_completion(&read_comp);
2526 		dio->completion = &read_comp;
2527 	} else
2528 		dio->completion = NULL;
2529 
2530 	dm_bio_record(&dio->bio_details, bio);
2531 	bio_set_dev(bio, ic->dev->bdev);
2532 	bio->bi_integrity = NULL;
2533 	bio->bi_opf &= ~REQ_INTEGRITY;
2534 	bio->bi_end_io = integrity_end_io;
2535 	bio->bi_iter.bi_size = dio->range.n_sectors << SECTOR_SHIFT;
2536 
2537 	if (unlikely(dio->op == REQ_OP_DISCARD) && likely(ic->mode != 'D')) {
2538 		integrity_metadata(&dio->work);
2539 		dm_integrity_flush_buffers(ic, false);
2540 
2541 		dio->in_flight = (atomic_t)ATOMIC_INIT(1);
2542 		dio->completion = NULL;
2543 
2544 		submit_bio_noacct(bio);
2545 
2546 		return;
2547 	}
2548 
2549 	submit_bio_noacct(bio);
2550 
2551 	if (need_sync_io) {
2552 		wait_for_completion_io(&read_comp);
2553 		if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
2554 		    dio->range.logical_sector + dio->range.n_sectors > recalc_sector)
2555 			goto skip_check;
2556 		if (ic->mode == 'B') {
2557 			if (!block_bitmap_op(ic, ic->recalc_bitmap, dio->range.logical_sector,
2558 					     dio->range.n_sectors, BITMAP_OP_TEST_ALL_CLEAR))
2559 				goto skip_check;
2560 		}
2561 
2562 		if (likely(!bio->bi_status))
2563 			integrity_metadata(&dio->work);
2564 		else
2565 skip_check:
2566 			dec_in_flight(dio);
2567 	} else {
2568 		INIT_WORK(&dio->work, integrity_metadata);
2569 		queue_work(ic->metadata_wq, &dio->work);
2570 	}
2571 
2572 	return;
2573 
2574 journal_read_write:
2575 	if (unlikely(__journal_read_write(dio, bio, journal_section, journal_entry)))
2576 		goto lock_retry;
2577 
2578 	do_endio_flush(ic, dio);
2579 }
2580 
2581 static int dm_integrity_map_inline(struct dm_integrity_io *dio, bool from_map)
2582 {
2583 	struct dm_integrity_c *ic = dio->ic;
2584 	struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
2585 	struct bio_integrity_payload *bip;
2586 	unsigned ret;
2587 	sector_t recalc_sector;
2588 
2589 	if (unlikely(bio_integrity(bio))) {
2590 		bio->bi_status = BLK_STS_NOTSUPP;
2591 		bio_endio(bio);
2592 		return DM_MAPIO_SUBMITTED;
2593 	}
2594 
2595 	bio_set_dev(bio, ic->dev->bdev);
2596 	if (unlikely((bio->bi_opf & REQ_PREFLUSH) != 0))
2597 		return DM_MAPIO_REMAPPED;
2598 
2599 	if (unlikely(!dm_integrity_check_limits(ic, bio->bi_iter.bi_sector, bio)))
2600 		return DM_MAPIO_KILL;
2601 
2602 retry:
2603 	if (!dio->integrity_payload) {
2604 		unsigned digest_size, extra_size;
2605 		dio->payload_len = ic->tuple_size * (bio_sectors(bio) >> ic->sb->log2_sectors_per_block);
2606 		digest_size = ic->internal_hash_digestsize;
2607 		extra_size = unlikely(digest_size > ic->tag_size) ? digest_size - ic->tag_size : 0;
2608 		dio->payload_len += extra_size;
2609 		dio->integrity_payload = kmalloc(dio->payload_len, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
2610 		if (unlikely(!dio->integrity_payload)) {
2611 			const unsigned x_size = PAGE_SIZE << 1;
2612 			if (dio->payload_len > x_size) {
2613 				unsigned sectors = ((x_size - extra_size) / ic->tuple_size) << ic->sb->log2_sectors_per_block;
2614 				if (WARN_ON(!sectors || sectors >= bio_sectors(bio))) {
2615 					bio->bi_status = BLK_STS_NOTSUPP;
2616 					bio_endio(bio);
2617 					return DM_MAPIO_SUBMITTED;
2618 				}
2619 				dm_accept_partial_bio(bio, sectors);
2620 				goto retry;
2621 			}
2622 		}
2623 	}
2624 
2625 	dio->range.logical_sector = bio->bi_iter.bi_sector;
2626 	dio->range.n_sectors = bio_sectors(bio);
2627 
2628 	if (!(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)))
2629 		goto skip_spinlock;
2630 #ifdef CONFIG_64BIT
2631 	/*
2632 	 * On 64-bit CPUs we can optimize the lock away (so that it won't cause
2633 	 * cache line bouncing) and use acquire/release barriers instead.
2634 	 *
2635 	 * Paired with smp_store_release in integrity_recalc_inline.
2636 	 */
2637 	recalc_sector = le64_to_cpu(smp_load_acquire(&ic->sb->recalc_sector));
2638 	if (likely(dio->range.logical_sector + dio->range.n_sectors <= recalc_sector))
2639 		goto skip_spinlock;
2640 #endif
2641 	spin_lock_irq(&ic->endio_wait.lock);
2642 	recalc_sector = le64_to_cpu(ic->sb->recalc_sector);
2643 	if (dio->range.logical_sector + dio->range.n_sectors <= recalc_sector)
2644 		goto skip_unlock;
2645 	if (unlikely(!add_new_range(ic, &dio->range, true))) {
2646 		if (from_map) {
2647 			spin_unlock_irq(&ic->endio_wait.lock);
2648 			INIT_WORK(&dio->work, integrity_bio_wait);
2649 			queue_work(ic->wait_wq, &dio->work);
2650 			return DM_MAPIO_SUBMITTED;
2651 		}
2652 		wait_and_add_new_range(ic, &dio->range);
2653 	}
2654 	dio->integrity_range_locked = true;
2655 skip_unlock:
2656 	spin_unlock_irq(&ic->endio_wait.lock);
2657 skip_spinlock:
2658 
2659 	if (unlikely(!dio->integrity_payload)) {
2660 		dio->integrity_payload = page_to_virt((struct page *)mempool_alloc(&ic->recheck_pool, GFP_NOIO));
2661 		dio->integrity_payload_from_mempool = true;
2662 	}
2663 
2664 	dio->bio_details.bi_iter = bio->bi_iter;
2665 
2666 	bio->bi_iter.bi_sector += ic->start + SB_SECTORS;
2667 
2668 	bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
2669 	if (IS_ERR(bip)) {
2670 		bio->bi_status = errno_to_blk_status(PTR_ERR(bip));
2671 		bio_endio(bio);
2672 		return DM_MAPIO_SUBMITTED;
2673 	}
2674 
2675 	if (dio->op == REQ_OP_WRITE) {
2676 		unsigned pos = 0;
2677 		while (dio->bio_details.bi_iter.bi_size) {
2678 			struct bio_vec bv = bio_iter_iovec(bio, dio->bio_details.bi_iter);
2679 			const char *mem = integrity_kmap(ic, bv.bv_page);
2680 			if (ic->tag_size < ic->tuple_size)
2681 				memset(dio->integrity_payload + pos + ic->tag_size, 0, ic->tuple_size - ic->tag_size);
2682 			integrity_sector_checksum(ic, &dio->ahash_req, dio->bio_details.bi_iter.bi_sector, mem, bv.bv_offset, dio->integrity_payload + pos);
2683 			integrity_kunmap(ic, mem);
2684 			pos += ic->tuple_size;
2685 			bio_advance_iter_single(bio, &dio->bio_details.bi_iter, ic->sectors_per_block << SECTOR_SHIFT);
2686 		}
2687 	}
2688 
2689 	ret = bio_integrity_add_page(bio, virt_to_page(dio->integrity_payload),
2690 					dio->payload_len, offset_in_page(dio->integrity_payload));
2691 	if (unlikely(ret != dio->payload_len)) {
2692 		bio->bi_status = BLK_STS_RESOURCE;
2693 		bio_endio(bio);
2694 		return DM_MAPIO_SUBMITTED;
2695 	}
2696 
2697 	return DM_MAPIO_REMAPPED;
2698 }
2699 
2700 static inline void dm_integrity_free_payload(struct dm_integrity_io *dio)
2701 {
2702 	struct dm_integrity_c *ic = dio->ic;
2703 	if (unlikely(dio->integrity_payload_from_mempool))
2704 		mempool_free(virt_to_page(dio->integrity_payload), &ic->recheck_pool);
2705 	else
2706 		kfree(dio->integrity_payload);
2707 	dio->integrity_payload = NULL;
2708 	dio->integrity_payload_from_mempool = false;
2709 }
2710 
2711 static void dm_integrity_inline_recheck(struct work_struct *w)
2712 {
2713 	struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
2714 	struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
2715 	struct dm_integrity_c *ic = dio->ic;
2716 	struct bio *outgoing_bio;
2717 	void *outgoing_data;
2718 
2719 	dio->integrity_payload = page_to_virt((struct page *)mempool_alloc(&ic->recheck_pool, GFP_NOIO));
2720 	dio->integrity_payload_from_mempool = true;
2721 
2722 	outgoing_data = dio->integrity_payload + PAGE_SIZE;
2723 
2724 	while (dio->bio_details.bi_iter.bi_size) {
2725 		char digest[MAX_T(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
2726 		int r;
2727 		struct bio_integrity_payload *bip;
2728 		struct bio_vec bv;
2729 		char *mem;
2730 
2731 		outgoing_bio = bio_alloc_bioset(ic->dev->bdev, 1, REQ_OP_READ, GFP_NOIO, &ic->recheck_bios);
2732 		bio_add_virt_nofail(outgoing_bio, outgoing_data,
2733 				ic->sectors_per_block << SECTOR_SHIFT);
2734 
2735 		bip = bio_integrity_alloc(outgoing_bio, GFP_NOIO, 1);
2736 		if (IS_ERR(bip)) {
2737 			bio_put(outgoing_bio);
2738 			bio->bi_status = errno_to_blk_status(PTR_ERR(bip));
2739 			bio_endio(bio);
2740 			return;
2741 		}
2742 
2743 		r = bio_integrity_add_page(outgoing_bio, virt_to_page(dio->integrity_payload), ic->tuple_size, 0);
2744 		if (unlikely(r != ic->tuple_size)) {
2745 			bio_put(outgoing_bio);
2746 			bio->bi_status = BLK_STS_RESOURCE;
2747 			bio_endio(bio);
2748 			return;
2749 		}
2750 
2751 		outgoing_bio->bi_iter.bi_sector = dio->bio_details.bi_iter.bi_sector + ic->start + SB_SECTORS;
2752 
2753 		r = submit_bio_wait(outgoing_bio);
2754 		if (unlikely(r != 0)) {
2755 			bio_put(outgoing_bio);
2756 			bio->bi_status = errno_to_blk_status(r);
2757 			bio_endio(bio);
2758 			return;
2759 		}
2760 		bio_put(outgoing_bio);
2761 
2762 		integrity_sector_checksum(ic, &dio->ahash_req, dio->bio_details.bi_iter.bi_sector, integrity_identity(ic, outgoing_data), 0, digest);
2763 		if (unlikely(crypto_memneq(digest, dio->integrity_payload, min(ic->internal_hash_digestsize, ic->tag_size)))) {
2764 			DMERR_LIMIT("%pg: Checksum failed at sector 0x%llx",
2765 				ic->dev->bdev, dio->bio_details.bi_iter.bi_sector);
2766 			atomic64_inc(&ic->number_of_mismatches);
2767 			dm_audit_log_bio(DM_MSG_PREFIX, "integrity-checksum",
2768 				bio, dio->bio_details.bi_iter.bi_sector, 0);
2769 
2770 			bio->bi_status = BLK_STS_PROTECTION;
2771 			bio_endio(bio);
2772 			return;
2773 		}
2774 
2775 		bv = bio_iter_iovec(bio, dio->bio_details.bi_iter);
2776 		mem = bvec_kmap_local(&bv);
2777 		memcpy(mem, outgoing_data, ic->sectors_per_block << SECTOR_SHIFT);
2778 		kunmap_local(mem);
2779 
2780 		bio_advance_iter_single(bio, &dio->bio_details.bi_iter, ic->sectors_per_block << SECTOR_SHIFT);
2781 	}
2782 
2783 	bio_endio(bio);
2784 }
2785 
2786 static inline bool dm_integrity_check(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
2787 {
2788 	struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
2789 	unsigned pos = 0;
2790 
2791 	while (dio->bio_details.bi_iter.bi_size) {
2792 		char digest[MAX_T(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
2793 		struct bio_vec bv = bio_iter_iovec(bio, dio->bio_details.bi_iter);
2794 		char *mem = integrity_kmap(ic, bv.bv_page);
2795 		integrity_sector_checksum(ic, &dio->ahash_req, dio->bio_details.bi_iter.bi_sector, mem, bv.bv_offset, digest);
2796 		if (unlikely(crypto_memneq(digest, dio->integrity_payload + pos,
2797 				min(ic->internal_hash_digestsize, ic->tag_size)))) {
2798 			integrity_kunmap(ic, mem);
2799 			dm_integrity_free_payload(dio);
2800 			INIT_WORK(&dio->work, dm_integrity_inline_recheck);
2801 			queue_work(ic->offload_wq, &dio->work);
2802 			return false;
2803 		}
2804 		integrity_kunmap(ic, mem);
2805 		pos += ic->tuple_size;
2806 		bio_advance_iter_single(bio, &dio->bio_details.bi_iter, ic->sectors_per_block << SECTOR_SHIFT);
2807 	}
2808 
2809 	return true;
2810 }
2811 
2812 static void dm_integrity_inline_async_check(struct work_struct *w)
2813 {
2814 	struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
2815 	struct dm_integrity_c *ic = dio->ic;
2816 	struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
2817 
2818 	if (likely(dm_integrity_check(ic, dio)))
2819 		bio_endio(bio);
2820 }
2821 
2822 static int dm_integrity_end_io(struct dm_target *ti, struct bio *bio, blk_status_t *status)
2823 {
2824 	struct dm_integrity_c *ic = ti->private;
2825 	struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
2826 	if (ic->mode == 'I') {
2827 		if (dio->op == REQ_OP_READ && likely(*status == BLK_STS_OK) && likely(dio->bio_details.bi_iter.bi_size != 0)) {
2828 			if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
2829 			    unlikely(dio->integrity_range_locked))
2830 			    	goto skip_check;
2831 			if (likely(ic->internal_shash != NULL)) {
2832 				if (unlikely(!dm_integrity_check(ic, dio)))
2833 					return DM_ENDIO_INCOMPLETE;
2834 			} else {
2835 				INIT_WORK(&dio->work, dm_integrity_inline_async_check);
2836 				queue_work(ic->offload_wq, &dio->work);
2837 				return DM_ENDIO_INCOMPLETE;
2838 			}
2839 		}
2840 skip_check:
2841 		dm_integrity_free_payload(dio);
2842 		if (unlikely(dio->integrity_range_locked))
2843 			remove_range(ic, &dio->range);
2844 	}
2845 	if (unlikely(dio->ahash_req))
2846 		mempool_free(dio->ahash_req, &ic->ahash_req_pool);
2847 	return DM_ENDIO_DONE;
2848 }
2849 
2850 static void integrity_bio_wait(struct work_struct *w)
2851 {
2852 	struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
2853 	struct dm_integrity_c *ic = dio->ic;
2854 
2855 	if (ic->mode == 'I') {
2856 		struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
2857 		int r = dm_integrity_map_inline(dio, false);
2858 		switch (r) {
2859 			case DM_MAPIO_KILL:
2860 				bio->bi_status = BLK_STS_IOERR;
2861 				bio_endio(bio);
2862 				return;
2863 			case DM_MAPIO_REMAPPED:
2864 				submit_bio_noacct(bio);
2865 				fallthrough;
2866 			case DM_MAPIO_SUBMITTED:
2867 				return;
2868 			default:
2869 				BUG();
2870 		}
2871 	} else {
2872 		dm_integrity_map_continue(dio, false);
2873 	}
2874 }
2875 
2876 static void pad_uncommitted(struct dm_integrity_c *ic)
2877 {
2878 	if (ic->free_section_entry) {
2879 		ic->free_sectors -= ic->journal_section_entries - ic->free_section_entry;
2880 		ic->free_section_entry = 0;
2881 		ic->free_section++;
2882 		wraparound_section(ic, &ic->free_section);
2883 		ic->n_uncommitted_sections++;
2884 	}
2885 	if (WARN_ON(ic->journal_sections * ic->journal_section_entries !=
2886 		    (ic->n_uncommitted_sections + ic->n_committed_sections) *
2887 		    ic->journal_section_entries + ic->free_sectors)) {
2888 		DMCRIT("journal_sections %u, journal_section_entries %u, "
2889 		       "n_uncommitted_sections %u, n_committed_sections %u, "
2890 		       "journal_section_entries %u, free_sectors %u",
2891 		       ic->journal_sections, ic->journal_section_entries,
2892 		       ic->n_uncommitted_sections, ic->n_committed_sections,
2893 		       ic->journal_section_entries, ic->free_sectors);
2894 	}
2895 }
2896 
2897 static void integrity_commit(struct work_struct *w)
2898 {
2899 	struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, commit_work);
2900 	unsigned int commit_start, commit_sections;
2901 	unsigned int i, j, n;
2902 	struct bio *flushes;
2903 
2904 	timer_delete(&ic->autocommit_timer);
2905 
2906 	if (ic->mode == 'I')
2907 		return;
2908 
2909 	spin_lock_irq(&ic->endio_wait.lock);
2910 	flushes = bio_list_get(&ic->flush_bio_list);
2911 	if (unlikely(dm_integrity_failed(ic))) {
2912 		wake_up_locked(&ic->endio_wait);
2913 		spin_unlock_irq(&ic->endio_wait.lock);
2914 		goto release_flush_bios;
2915 	}
2916 	if (unlikely(ic->mode != 'J')) {
2917 		spin_unlock_irq(&ic->endio_wait.lock);
2918 		dm_integrity_flush_buffers(ic, true);
2919 		goto release_flush_bios;
2920 	}
2921 
2922 	pad_uncommitted(ic);
2923 	commit_start = ic->uncommitted_section;
2924 	commit_sections = ic->n_uncommitted_sections;
2925 	spin_unlock_irq(&ic->endio_wait.lock);
2926 
2927 	if (!commit_sections)
2928 		goto release_flush_bios;
2929 
2930 	ic->wrote_to_journal = true;
2931 
2932 	i = commit_start;
2933 	for (n = 0; n < commit_sections; n++) {
2934 		for (j = 0; j < ic->journal_section_entries; j++) {
2935 			struct journal_entry *je;
2936 
2937 			je = access_journal_entry(ic, i, j);
2938 			io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
2939 		}
2940 		for (j = 0; j < ic->journal_section_sectors; j++) {
2941 			struct journal_sector *js;
2942 
2943 			js = access_journal(ic, i, j);
2944 			js->commit_id = dm_integrity_commit_id(ic, i, j, ic->commit_seq);
2945 		}
2946 		i++;
2947 		if (unlikely(i >= ic->journal_sections))
2948 			ic->commit_seq = next_commit_seq(ic->commit_seq);
2949 		wraparound_section(ic, &i);
2950 	}
2951 	smp_rmb();
2952 
2953 	write_journal(ic, commit_start, commit_sections);
2954 
2955 	spin_lock_irq(&ic->endio_wait.lock);
2956 	ic->uncommitted_section += commit_sections;
2957 	wraparound_section(ic, &ic->uncommitted_section);
2958 	ic->n_uncommitted_sections -= commit_sections;
2959 	ic->n_committed_sections += commit_sections;
2960 	spin_unlock_irq(&ic->endio_wait.lock);
2961 
2962 	if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold)
2963 		queue_work(ic->writer_wq, &ic->writer_work);
2964 
2965 release_flush_bios:
2966 	while (flushes) {
2967 		struct bio *next = flushes->bi_next;
2968 
2969 		flushes->bi_next = NULL;
2970 		do_endio(ic, flushes);
2971 		flushes = next;
2972 	}
2973 }
2974 
2975 static void complete_copy_from_journal(unsigned long error, unsigned long unsup, void *context)
2976 {
2977 	struct journal_io *io = context;
2978 	struct journal_completion *comp = io->comp;
2979 	struct dm_integrity_c *ic = comp->ic;
2980 
2981 	remove_range(ic, &io->range);
2982 	mempool_free(io, &ic->journal_io_mempool);
2983 	if (unlikely(error != 0))
2984 		dm_integrity_io_error(ic, "copying from journal", -EIO);
2985 	else if (unlikely(unsup != 0))
2986 		dm_integrity_io_error(ic, "copying from journal", -EOPNOTSUPP);
2987 	complete_journal_op(comp);
2988 }
2989 
2990 static void restore_last_bytes(struct dm_integrity_c *ic, struct journal_sector *js,
2991 			       struct journal_entry *je)
2992 {
2993 	unsigned int s = 0;
2994 
2995 	do {
2996 		js->commit_id = je->last_bytes[s];
2997 		js++;
2998 	} while (++s < ic->sectors_per_block);
2999 }
3000 
3001 static void do_journal_write(struct dm_integrity_c *ic, unsigned int write_start,
3002 			     unsigned int write_sections, bool from_replay)
3003 {
3004 	unsigned int i, j, n;
3005 	struct journal_completion comp;
3006 	struct blk_plug plug;
3007 
3008 	blk_start_plug(&plug);
3009 
3010 	comp.ic = ic;
3011 	comp.in_flight = (atomic_t)ATOMIC_INIT(1);
3012 	init_completion(&comp.comp);
3013 
3014 	i = write_start;
3015 	for (n = 0; n < write_sections; n++, i++, wraparound_section(ic, &i)) {
3016 #ifndef INTERNAL_VERIFY
3017 		if (unlikely(from_replay))
3018 #endif
3019 			rw_section_mac(ic, i, false);
3020 		for (j = 0; j < ic->journal_section_entries; j++) {
3021 			struct journal_entry *je = access_journal_entry(ic, i, j);
3022 			sector_t sec, area, offset;
3023 			unsigned int k, l, next_loop;
3024 			sector_t metadata_block;
3025 			unsigned int metadata_offset;
3026 			struct journal_io *io;
3027 
3028 			if (journal_entry_is_unused(je))
3029 				continue;
3030 			BUG_ON(unlikely(journal_entry_is_inprogress(je)) && !from_replay);
3031 			sec = journal_entry_get_sector(je);
3032 			if (unlikely(from_replay)) {
3033 				if (unlikely(sec & (unsigned int)(ic->sectors_per_block - 1))) {
3034 					dm_integrity_io_error(ic, "invalid sector in journal", -EIO);
3035 					sec &= ~(sector_t)(ic->sectors_per_block - 1);
3036 				}
3037 				if (unlikely(sec >= ic->provided_data_sectors)) {
3038 					journal_entry_set_unused(je);
3039 					continue;
3040 				}
3041 			}
3042 			get_area_and_offset(ic, sec, &area, &offset);
3043 			restore_last_bytes(ic, access_journal_data(ic, i, j), je);
3044 			for (k = j + 1; k < ic->journal_section_entries; k++) {
3045 				struct journal_entry *je2 = access_journal_entry(ic, i, k);
3046 				sector_t sec2, area2, offset2;
3047 
3048 				if (journal_entry_is_unused(je2))
3049 					break;
3050 				BUG_ON(unlikely(journal_entry_is_inprogress(je2)) && !from_replay);
3051 				sec2 = journal_entry_get_sector(je2);
3052 				if (unlikely(sec2 >= ic->provided_data_sectors))
3053 					break;
3054 				get_area_and_offset(ic, sec2, &area2, &offset2);
3055 				if (area2 != area || offset2 != offset + ((k - j) << ic->sb->log2_sectors_per_block))
3056 					break;
3057 				restore_last_bytes(ic, access_journal_data(ic, i, k), je2);
3058 			}
3059 			next_loop = k - 1;
3060 
3061 			io = mempool_alloc(&ic->journal_io_mempool, GFP_NOIO);
3062 			io->comp = &comp;
3063 			io->range.logical_sector = sec;
3064 			io->range.n_sectors = (k - j) << ic->sb->log2_sectors_per_block;
3065 
3066 			spin_lock_irq(&ic->endio_wait.lock);
3067 			add_new_range_and_wait(ic, &io->range);
3068 
3069 			if (likely(!from_replay)) {
3070 				struct journal_node *section_node = &ic->journal_tree[i * ic->journal_section_entries];
3071 
3072 				/* don't write if there is newer committed sector */
3073 				while (j < k && find_newer_committed_node(ic, &section_node[j])) {
3074 					struct journal_entry *je2 = access_journal_entry(ic, i, j);
3075 
3076 					journal_entry_set_unused(je2);
3077 					remove_journal_node(ic, &section_node[j]);
3078 					j++;
3079 					sec += ic->sectors_per_block;
3080 					offset += ic->sectors_per_block;
3081 				}
3082 				while (j < k && find_newer_committed_node(ic, &section_node[k - 1])) {
3083 					struct journal_entry *je2 = access_journal_entry(ic, i, k - 1);
3084 
3085 					journal_entry_set_unused(je2);
3086 					remove_journal_node(ic, &section_node[k - 1]);
3087 					k--;
3088 				}
3089 				if (j == k) {
3090 					remove_range_unlocked(ic, &io->range);
3091 					spin_unlock_irq(&ic->endio_wait.lock);
3092 					mempool_free(io, &ic->journal_io_mempool);
3093 					goto skip_io;
3094 				}
3095 				for (l = j; l < k; l++)
3096 					remove_journal_node(ic, &section_node[l]);
3097 			}
3098 			spin_unlock_irq(&ic->endio_wait.lock);
3099 
3100 			metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
3101 			for (l = j; l < k; l++) {
3102 				int r;
3103 				struct journal_entry *je2 = access_journal_entry(ic, i, l);
3104 
3105 				if (
3106 #ifndef INTERNAL_VERIFY
3107 				    unlikely(from_replay) &&
3108 #endif
3109 				    ic->internal_hash) {
3110 					char test_tag[MAX_T(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
3111 					struct journal_sector *js = access_journal_data(ic, i, l);
3112 					void *js_page = integrity_identity(ic, (char *)js - offset_in_page(js));
3113 					unsigned js_offset = offset_in_page(js);
3114 
3115 					integrity_sector_checksum(ic, &ic->journal_ahash_req, sec + ((l - j) << ic->sb->log2_sectors_per_block),
3116 								  js_page, js_offset, test_tag);
3117 					if (unlikely(crypto_memneq(test_tag, journal_entry_tag(ic, je2), ic->tag_size))) {
3118 						dm_integrity_io_error(ic, "tag mismatch when replaying journal", -EILSEQ);
3119 						dm_audit_log_target(DM_MSG_PREFIX, "integrity-replay-journal", ic->ti, 0);
3120 					}
3121 				}
3122 
3123 				journal_entry_set_unused(je2);
3124 				r = dm_integrity_rw_tag(ic, journal_entry_tag(ic, je2), &metadata_block, &metadata_offset,
3125 							ic->tag_size, TAG_WRITE);
3126 				if (unlikely(r))
3127 					dm_integrity_io_error(ic, "writing tags", r);
3128 			}
3129 
3130 			atomic_inc(&comp.in_flight);
3131 			copy_from_journal(ic, i, j << ic->sb->log2_sectors_per_block,
3132 					  (k - j) << ic->sb->log2_sectors_per_block,
3133 					  get_data_sector(ic, area, offset),
3134 					  complete_copy_from_journal, io);
3135 skip_io:
3136 			j = next_loop;
3137 		}
3138 	}
3139 
3140 	dm_bufio_write_dirty_buffers_async(ic->bufio);
3141 
3142 	blk_finish_plug(&plug);
3143 
3144 	complete_journal_op(&comp);
3145 	wait_for_completion_io(&comp.comp);
3146 
3147 	dm_integrity_flush_buffers(ic, true);
3148 }
3149 
3150 static void integrity_writer(struct work_struct *w)
3151 {
3152 	struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, writer_work);
3153 	unsigned int write_start, write_sections;
3154 	unsigned int prev_free_sectors;
3155 
3156 	spin_lock_irq(&ic->endio_wait.lock);
3157 	write_start = ic->committed_section;
3158 	write_sections = ic->n_committed_sections;
3159 	spin_unlock_irq(&ic->endio_wait.lock);
3160 
3161 	if (!write_sections)
3162 		return;
3163 
3164 	do_journal_write(ic, write_start, write_sections, false);
3165 
3166 	spin_lock_irq(&ic->endio_wait.lock);
3167 
3168 	ic->committed_section += write_sections;
3169 	wraparound_section(ic, &ic->committed_section);
3170 	ic->n_committed_sections -= write_sections;
3171 
3172 	prev_free_sectors = ic->free_sectors;
3173 	ic->free_sectors += write_sections * ic->journal_section_entries;
3174 	if (unlikely(!prev_free_sectors))
3175 		wake_up_locked(&ic->endio_wait);
3176 
3177 	spin_unlock_irq(&ic->endio_wait.lock);
3178 }
3179 
3180 static void recalc_write_super(struct dm_integrity_c *ic)
3181 {
3182 	int r;
3183 
3184 	dm_integrity_flush_buffers(ic, false);
3185 	if (dm_integrity_failed(ic))
3186 		return;
3187 
3188 	r = sync_rw_sb(ic, REQ_OP_WRITE);
3189 	if (unlikely(r))
3190 		dm_integrity_io_error(ic, "writing superblock", r);
3191 }
3192 
3193 static void integrity_recalc(struct work_struct *w)
3194 {
3195 	struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, recalc_work);
3196 	size_t recalc_tags_size;
3197 	u8 *recalc_buffer = NULL;
3198 	u8 *recalc_tags = NULL;
3199 	struct ahash_request *ahash_req = NULL;
3200 	struct dm_integrity_range range;
3201 	struct dm_io_request io_req;
3202 	struct dm_io_region io_loc;
3203 	sector_t area, offset;
3204 	sector_t metadata_block;
3205 	unsigned int metadata_offset;
3206 	sector_t logical_sector, n_sectors;
3207 	__u8 *t;
3208 	unsigned int i;
3209 	int r;
3210 	unsigned int super_counter = 0;
3211 	unsigned recalc_sectors = RECALC_SECTORS;
3212 
3213 retry:
3214 	recalc_buffer = kmalloc(recalc_sectors << SECTOR_SHIFT, GFP_NOIO | __GFP_NOWARN);
3215 	if (!recalc_buffer) {
3216 oom:
3217 		recalc_sectors >>= 1;
3218 		if (recalc_sectors >= 1U << ic->sb->log2_sectors_per_block)
3219 			goto retry;
3220 		DMCRIT("out of memory for recalculate buffer - recalculation disabled");
3221 		goto free_ret;
3222 	}
3223 	recalc_tags_size = (recalc_sectors >> ic->sb->log2_sectors_per_block) * ic->tag_size;
3224 	if (ic->internal_hash_digestsize > ic->tag_size)
3225 		recalc_tags_size += ic->internal_hash_digestsize - ic->tag_size;
3226 	recalc_tags = kvmalloc(recalc_tags_size, GFP_NOIO);
3227 	if (!recalc_tags) {
3228 		kfree(recalc_buffer);
3229 		recalc_buffer = NULL;
3230 		goto oom;
3231 	}
3232 
3233 	DEBUG_print("start recalculation... (position %llx)\n", le64_to_cpu(ic->sb->recalc_sector));
3234 
3235 	spin_lock_irq(&ic->endio_wait.lock);
3236 
3237 next_chunk:
3238 
3239 	if (unlikely(dm_post_suspending(ic->ti)))
3240 		goto unlock_ret;
3241 
3242 	range.logical_sector = le64_to_cpu(ic->sb->recalc_sector);
3243 	if (unlikely(range.logical_sector >= ic->provided_data_sectors)) {
3244 		if (ic->mode == 'B') {
3245 			block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
3246 			DEBUG_print("queue_delayed_work: bitmap_flush_work\n");
3247 			queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
3248 		}
3249 		goto unlock_ret;
3250 	}
3251 
3252 	get_area_and_offset(ic, range.logical_sector, &area, &offset);
3253 	range.n_sectors = min((sector_t)recalc_sectors, ic->provided_data_sectors - range.logical_sector);
3254 	if (!ic->meta_dev)
3255 		range.n_sectors = min(range.n_sectors, ((sector_t)1U << ic->sb->log2_interleave_sectors) - (unsigned int)offset);
3256 
3257 	add_new_range_and_wait(ic, &range);
3258 	spin_unlock_irq(&ic->endio_wait.lock);
3259 	logical_sector = range.logical_sector;
3260 	n_sectors = range.n_sectors;
3261 
3262 	if (ic->mode == 'B') {
3263 		if (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector, n_sectors, BITMAP_OP_TEST_ALL_CLEAR))
3264 			goto advance_and_next;
3265 
3266 		while (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector,
3267 				       ic->sectors_per_block, BITMAP_OP_TEST_ALL_CLEAR)) {
3268 			logical_sector += ic->sectors_per_block;
3269 			n_sectors -= ic->sectors_per_block;
3270 			cond_resched();
3271 		}
3272 		while (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector + n_sectors - ic->sectors_per_block,
3273 				       ic->sectors_per_block, BITMAP_OP_TEST_ALL_CLEAR)) {
3274 			n_sectors -= ic->sectors_per_block;
3275 			cond_resched();
3276 		}
3277 		get_area_and_offset(ic, logical_sector, &area, &offset);
3278 	}
3279 
3280 	DEBUG_print("recalculating: %llx, %llx\n", logical_sector, n_sectors);
3281 
3282 	if (unlikely(++super_counter == RECALC_WRITE_SUPER)) {
3283 		recalc_write_super(ic);
3284 		if (ic->mode == 'B')
3285 			queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, ic->bitmap_flush_interval);
3286 
3287 		super_counter = 0;
3288 	}
3289 
3290 	if (unlikely(dm_integrity_failed(ic)))
3291 		goto err;
3292 
3293 	io_req.bi_opf = REQ_OP_READ;
3294 	io_req.mem.type = DM_IO_KMEM;
3295 	io_req.mem.ptr.addr = recalc_buffer;
3296 	io_req.notify.fn = NULL;
3297 	io_req.client = ic->io;
3298 	io_loc.bdev = ic->dev->bdev;
3299 	io_loc.sector = get_data_sector(ic, area, offset);
3300 	io_loc.count = n_sectors;
3301 
3302 	r = dm_io(&io_req, 1, &io_loc, NULL, NULL, IOPRIO_DEFAULT);
3303 	if (unlikely(r)) {
3304 		dm_integrity_io_error(ic, "reading data", r);
3305 		goto err;
3306 	}
3307 
3308 	t = recalc_tags;
3309 	for (i = 0; i < n_sectors; i += ic->sectors_per_block) {
3310 		void *ptr = recalc_buffer + (i << SECTOR_SHIFT);
3311 		void *ptr_page = integrity_identity(ic, (char *)ptr - offset_in_page(ptr));
3312 		unsigned ptr_offset = offset_in_page(ptr);
3313 		integrity_sector_checksum(ic, &ahash_req, logical_sector + i, ptr_page, ptr_offset, t);
3314 		t += ic->tag_size;
3315 	}
3316 
3317 	metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
3318 
3319 	r = dm_integrity_rw_tag(ic, recalc_tags, &metadata_block, &metadata_offset, t - recalc_tags, TAG_WRITE);
3320 	if (unlikely(r)) {
3321 		dm_integrity_io_error(ic, "writing tags", r);
3322 		goto err;
3323 	}
3324 
3325 	if (ic->mode == 'B') {
3326 		sector_t start, end;
3327 
3328 		start = (range.logical_sector >>
3329 			 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit)) <<
3330 			(ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
3331 		end = ((range.logical_sector + range.n_sectors) >>
3332 		       (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit)) <<
3333 			(ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
3334 		block_bitmap_op(ic, ic->recalc_bitmap, start, end - start, BITMAP_OP_CLEAR);
3335 	}
3336 
3337 advance_and_next:
3338 	cond_resched();
3339 
3340 	spin_lock_irq(&ic->endio_wait.lock);
3341 	remove_range_unlocked(ic, &range);
3342 	ic->sb->recalc_sector = cpu_to_le64(range.logical_sector + range.n_sectors);
3343 	goto next_chunk;
3344 
3345 err:
3346 	remove_range(ic, &range);
3347 	goto free_ret;
3348 
3349 unlock_ret:
3350 	spin_unlock_irq(&ic->endio_wait.lock);
3351 
3352 	recalc_write_super(ic);
3353 
3354 free_ret:
3355 	kfree(recalc_buffer);
3356 	kvfree(recalc_tags);
3357 	mempool_free(ahash_req, &ic->ahash_req_pool);
3358 }
3359 
3360 static void integrity_recalc_inline(struct work_struct *w)
3361 {
3362 	struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, recalc_work);
3363 	size_t recalc_tags_size;
3364 	u8 *recalc_buffer = NULL;
3365 	u8 *recalc_tags = NULL;
3366 	struct ahash_request *ahash_req = NULL;
3367 	struct dm_integrity_range range;
3368 	struct bio *bio;
3369 	struct bio_integrity_payload *bip;
3370 	__u8 *t;
3371 	unsigned int i;
3372 	int r;
3373 	unsigned ret;
3374 	unsigned int super_counter = 0;
3375 	unsigned recalc_sectors = RECALC_SECTORS;
3376 
3377 retry:
3378 	recalc_buffer = kmalloc(recalc_sectors << SECTOR_SHIFT, GFP_NOIO | __GFP_NOWARN);
3379 	if (!recalc_buffer) {
3380 oom:
3381 		recalc_sectors >>= 1;
3382 		if (recalc_sectors >= 1U << ic->sb->log2_sectors_per_block)
3383 			goto retry;
3384 		DMCRIT("out of memory for recalculate buffer - recalculation disabled");
3385 		goto free_ret;
3386 	}
3387 
3388 	recalc_tags_size = (recalc_sectors >> ic->sb->log2_sectors_per_block) * ic->tuple_size;
3389 	if (ic->internal_hash_digestsize > ic->tuple_size)
3390 		recalc_tags_size += ic->internal_hash_digestsize - ic->tuple_size;
3391 	recalc_tags = kmalloc(recalc_tags_size, GFP_NOIO | __GFP_NOWARN);
3392 	if (!recalc_tags) {
3393 		kfree(recalc_buffer);
3394 		recalc_buffer = NULL;
3395 		goto oom;
3396 	}
3397 
3398 	spin_lock_irq(&ic->endio_wait.lock);
3399 
3400 next_chunk:
3401 	if (unlikely(dm_post_suspending(ic->ti)))
3402 		goto unlock_ret;
3403 
3404 	range.logical_sector = le64_to_cpu(ic->sb->recalc_sector);
3405 	if (unlikely(range.logical_sector >= ic->provided_data_sectors))
3406 		goto unlock_ret;
3407 	range.n_sectors = min((sector_t)recalc_sectors, ic->provided_data_sectors - range.logical_sector);
3408 
3409 	add_new_range_and_wait(ic, &range);
3410 	spin_unlock_irq(&ic->endio_wait.lock);
3411 
3412 	if (unlikely(++super_counter == RECALC_WRITE_SUPER)) {
3413 		recalc_write_super(ic);
3414 		super_counter = 0;
3415 	}
3416 
3417 	if (unlikely(dm_integrity_failed(ic)))
3418 		goto err;
3419 
3420 	DEBUG_print("recalculating: %llx - %llx\n", range.logical_sector, range.n_sectors);
3421 
3422 	bio = bio_alloc_bioset(ic->dev->bdev, 1, REQ_OP_READ, GFP_NOIO, &ic->recalc_bios);
3423 	bio->bi_iter.bi_sector = ic->start + SB_SECTORS + range.logical_sector;
3424 	bio_add_virt_nofail(bio, recalc_buffer,
3425 			range.n_sectors << SECTOR_SHIFT);
3426 	r = submit_bio_wait(bio);
3427 	bio_put(bio);
3428 	if (unlikely(r)) {
3429 		dm_integrity_io_error(ic, "reading data", r);
3430 		goto err;
3431 	}
3432 
3433 	t = recalc_tags;
3434 	for (i = 0; i < range.n_sectors; i += ic->sectors_per_block) {
3435 		void *ptr = recalc_buffer + (i << SECTOR_SHIFT);
3436 		void *ptr_page = integrity_identity(ic, (char *)ptr - offset_in_page(ptr));
3437 		unsigned ptr_offset = offset_in_page(ptr);
3438 		memset(t, 0, ic->tuple_size);
3439 		integrity_sector_checksum(ic, &ahash_req, range.logical_sector + i, ptr_page, ptr_offset, t);
3440 		t += ic->tuple_size;
3441 	}
3442 
3443 	bio = bio_alloc_bioset(ic->dev->bdev, 1, REQ_OP_WRITE, GFP_NOIO, &ic->recalc_bios);
3444 	bio->bi_iter.bi_sector = ic->start + SB_SECTORS + range.logical_sector;
3445 	bio_add_virt_nofail(bio, recalc_buffer,
3446 			range.n_sectors << SECTOR_SHIFT);
3447 
3448 	bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
3449 	if (unlikely(IS_ERR(bip))) {
3450 		bio_put(bio);
3451 		DMCRIT("out of memory for bio integrity payload - recalculation disabled");
3452 		goto err;
3453 	}
3454 	ret = bio_integrity_add_page(bio, virt_to_page(recalc_tags), t - recalc_tags, offset_in_page(recalc_tags));
3455 	if (unlikely(ret != t - recalc_tags)) {
3456 		bio_put(bio);
3457 		dm_integrity_io_error(ic, "attaching integrity tags", -ENOMEM);
3458 		goto err;
3459 	}
3460 
3461 	r = submit_bio_wait(bio);
3462 	bio_put(bio);
3463 	if (unlikely(r)) {
3464 		dm_integrity_io_error(ic, "writing data", r);
3465 		goto err;
3466 	}
3467 
3468 	cond_resched();
3469 	spin_lock_irq(&ic->endio_wait.lock);
3470 	remove_range_unlocked(ic, &range);
3471 #ifdef CONFIG_64BIT
3472 	/* Paired with smp_load_acquire in dm_integrity_map_inline. */
3473 	smp_store_release(&ic->sb->recalc_sector, cpu_to_le64(range.logical_sector + range.n_sectors));
3474 #else
3475 	ic->sb->recalc_sector = cpu_to_le64(range.logical_sector + range.n_sectors);
3476 #endif
3477 	goto next_chunk;
3478 
3479 err:
3480 	remove_range(ic, &range);
3481 	goto free_ret;
3482 
3483 unlock_ret:
3484 	spin_unlock_irq(&ic->endio_wait.lock);
3485 
3486 	recalc_write_super(ic);
3487 
3488 free_ret:
3489 	kfree(recalc_buffer);
3490 	kfree(recalc_tags);
3491 	mempool_free(ahash_req, &ic->ahash_req_pool);
3492 }
3493 
3494 static void bitmap_block_work(struct work_struct *w)
3495 {
3496 	struct bitmap_block_status *bbs = container_of(w, struct bitmap_block_status, work);
3497 	struct dm_integrity_c *ic = bbs->ic;
3498 	struct bio *bio;
3499 	struct bio_list bio_queue;
3500 	struct bio_list waiting;
3501 
3502 	bio_list_init(&waiting);
3503 
3504 	spin_lock(&bbs->bio_queue_lock);
3505 	bio_queue = bbs->bio_queue;
3506 	bio_list_init(&bbs->bio_queue);
3507 	spin_unlock(&bbs->bio_queue_lock);
3508 
3509 	while ((bio = bio_list_pop(&bio_queue))) {
3510 		struct dm_integrity_io *dio;
3511 
3512 		dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
3513 
3514 		if (block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
3515 				    dio->range.n_sectors, BITMAP_OP_TEST_ALL_SET)) {
3516 			remove_range(ic, &dio->range);
3517 			INIT_WORK(&dio->work, integrity_bio_wait);
3518 			queue_work(ic->offload_wq, &dio->work);
3519 		} else {
3520 			block_bitmap_op(ic, ic->journal, dio->range.logical_sector,
3521 					dio->range.n_sectors, BITMAP_OP_SET);
3522 			bio_list_add(&waiting, bio);
3523 		}
3524 	}
3525 
3526 	if (bio_list_empty(&waiting))
3527 		return;
3528 
3529 	rw_journal_sectors(ic, REQ_OP_WRITE | REQ_FUA | REQ_SYNC,
3530 			   bbs->idx * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT),
3531 			   BITMAP_BLOCK_SIZE >> SECTOR_SHIFT, NULL);
3532 
3533 	while ((bio = bio_list_pop(&waiting))) {
3534 		struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
3535 
3536 		block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
3537 				dio->range.n_sectors, BITMAP_OP_SET);
3538 
3539 		remove_range(ic, &dio->range);
3540 		INIT_WORK(&dio->work, integrity_bio_wait);
3541 		queue_work(ic->offload_wq, &dio->work);
3542 	}
3543 
3544 	queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, ic->bitmap_flush_interval);
3545 }
3546 
3547 static void bitmap_flush_work(struct work_struct *work)
3548 {
3549 	struct dm_integrity_c *ic = container_of(work, struct dm_integrity_c, bitmap_flush_work.work);
3550 	struct dm_integrity_range range;
3551 	unsigned long limit;
3552 	struct bio *bio;
3553 
3554 	dm_integrity_flush_buffers(ic, false);
3555 
3556 	range.logical_sector = 0;
3557 	range.n_sectors = ic->provided_data_sectors;
3558 
3559 	spin_lock_irq(&ic->endio_wait.lock);
3560 	add_new_range_and_wait(ic, &range);
3561 	spin_unlock_irq(&ic->endio_wait.lock);
3562 
3563 	dm_integrity_flush_buffers(ic, true);
3564 
3565 	limit = ic->provided_data_sectors;
3566 	if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
3567 		limit = le64_to_cpu(ic->sb->recalc_sector)
3568 			>> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit)
3569 			<< (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
3570 	}
3571 	/*DEBUG_print("zeroing journal\n");*/
3572 	block_bitmap_op(ic, ic->journal, 0, limit, BITMAP_OP_CLEAR);
3573 	block_bitmap_op(ic, ic->may_write_bitmap, 0, limit, BITMAP_OP_CLEAR);
3574 
3575 	rw_journal_sectors(ic, REQ_OP_WRITE | REQ_FUA | REQ_SYNC, 0,
3576 			   ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3577 
3578 	spin_lock_irq(&ic->endio_wait.lock);
3579 	remove_range_unlocked(ic, &range);
3580 	while (unlikely((bio = bio_list_pop(&ic->synchronous_bios)) != NULL)) {
3581 		bio_endio(bio);
3582 		spin_unlock_irq(&ic->endio_wait.lock);
3583 		spin_lock_irq(&ic->endio_wait.lock);
3584 	}
3585 	spin_unlock_irq(&ic->endio_wait.lock);
3586 }
3587 
3588 
3589 static void init_journal(struct dm_integrity_c *ic, unsigned int start_section,
3590 			 unsigned int n_sections, unsigned char commit_seq)
3591 {
3592 	unsigned int i, j, n;
3593 
3594 	if (!n_sections)
3595 		return;
3596 
3597 	for (n = 0; n < n_sections; n++) {
3598 		i = start_section + n;
3599 		wraparound_section(ic, &i);
3600 		for (j = 0; j < ic->journal_section_sectors; j++) {
3601 			struct journal_sector *js = access_journal(ic, i, j);
3602 
3603 			BUILD_BUG_ON(sizeof(js->sectors) != JOURNAL_SECTOR_DATA);
3604 			memset(&js->sectors, 0, sizeof(js->sectors));
3605 			js->commit_id = dm_integrity_commit_id(ic, i, j, commit_seq);
3606 		}
3607 		for (j = 0; j < ic->journal_section_entries; j++) {
3608 			struct journal_entry *je = access_journal_entry(ic, i, j);
3609 
3610 			journal_entry_set_unused(je);
3611 		}
3612 	}
3613 
3614 	write_journal(ic, start_section, n_sections);
3615 }
3616 
3617 static int find_commit_seq(struct dm_integrity_c *ic, unsigned int i, unsigned int j, commit_id_t id)
3618 {
3619 	unsigned char k;
3620 
3621 	for (k = 0; k < N_COMMIT_IDS; k++) {
3622 		if (dm_integrity_commit_id(ic, i, j, k) == id)
3623 			return k;
3624 	}
3625 	dm_integrity_io_error(ic, "journal commit id", -EIO);
3626 	return -EIO;
3627 }
3628 
3629 static void replay_journal(struct dm_integrity_c *ic)
3630 {
3631 	unsigned int i, j;
3632 	bool used_commit_ids[N_COMMIT_IDS];
3633 	unsigned int max_commit_id_sections[N_COMMIT_IDS];
3634 	unsigned int write_start, write_sections;
3635 	unsigned int continue_section;
3636 	bool journal_empty;
3637 	unsigned char unused, last_used, want_commit_seq;
3638 
3639 	if (ic->mode == 'R')
3640 		return;
3641 
3642 	if (ic->journal_uptodate)
3643 		return;
3644 
3645 	last_used = 0;
3646 	write_start = 0;
3647 
3648 	if (!ic->just_formatted) {
3649 		DEBUG_print("reading journal\n");
3650 		rw_journal(ic, REQ_OP_READ, 0, ic->journal_sections, NULL);
3651 		if (ic->journal_io)
3652 			DEBUG_bytes(lowmem_page_address(ic->journal_io[0].page), 64, "read journal");
3653 		if (ic->journal_io) {
3654 			struct journal_completion crypt_comp;
3655 
3656 			crypt_comp.ic = ic;
3657 			init_completion(&crypt_comp.comp);
3658 			crypt_comp.in_flight = (atomic_t)ATOMIC_INIT(0);
3659 			encrypt_journal(ic, false, 0, ic->journal_sections, &crypt_comp);
3660 			wait_for_completion(&crypt_comp.comp);
3661 		}
3662 		DEBUG_bytes(lowmem_page_address(ic->journal[0].page), 64, "decrypted journal");
3663 	}
3664 
3665 	if (dm_integrity_failed(ic))
3666 		goto clear_journal;
3667 
3668 	journal_empty = true;
3669 	memset(used_commit_ids, 0, sizeof(used_commit_ids));
3670 	memset(max_commit_id_sections, 0, sizeof(max_commit_id_sections));
3671 	for (i = 0; i < ic->journal_sections; i++) {
3672 		for (j = 0; j < ic->journal_section_sectors; j++) {
3673 			int k;
3674 			struct journal_sector *js = access_journal(ic, i, j);
3675 
3676 			k = find_commit_seq(ic, i, j, js->commit_id);
3677 			if (k < 0)
3678 				goto clear_journal;
3679 			used_commit_ids[k] = true;
3680 			max_commit_id_sections[k] = i;
3681 		}
3682 		if (journal_empty) {
3683 			for (j = 0; j < ic->journal_section_entries; j++) {
3684 				struct journal_entry *je = access_journal_entry(ic, i, j);
3685 
3686 				if (!journal_entry_is_unused(je)) {
3687 					journal_empty = false;
3688 					break;
3689 				}
3690 			}
3691 		}
3692 	}
3693 
3694 	if (!used_commit_ids[N_COMMIT_IDS - 1]) {
3695 		unused = N_COMMIT_IDS - 1;
3696 		while (unused && !used_commit_ids[unused - 1])
3697 			unused--;
3698 	} else {
3699 		for (unused = 0; unused < N_COMMIT_IDS; unused++)
3700 			if (!used_commit_ids[unused])
3701 				break;
3702 		if (unused == N_COMMIT_IDS) {
3703 			dm_integrity_io_error(ic, "journal commit ids", -EIO);
3704 			goto clear_journal;
3705 		}
3706 	}
3707 	DEBUG_print("first unused commit seq %d [%d,%d,%d,%d]\n",
3708 		    unused, used_commit_ids[0], used_commit_ids[1],
3709 		    used_commit_ids[2], used_commit_ids[3]);
3710 
3711 	last_used = prev_commit_seq(unused);
3712 	want_commit_seq = prev_commit_seq(last_used);
3713 
3714 	if (!used_commit_ids[want_commit_seq] && used_commit_ids[prev_commit_seq(want_commit_seq)])
3715 		journal_empty = true;
3716 
3717 	write_start = max_commit_id_sections[last_used] + 1;
3718 	if (unlikely(write_start >= ic->journal_sections))
3719 		want_commit_seq = next_commit_seq(want_commit_seq);
3720 	wraparound_section(ic, &write_start);
3721 
3722 	i = write_start;
3723 	for (write_sections = 0; write_sections < ic->journal_sections; write_sections++) {
3724 		for (j = 0; j < ic->journal_section_sectors; j++) {
3725 			struct journal_sector *js = access_journal(ic, i, j);
3726 
3727 			if (js->commit_id != dm_integrity_commit_id(ic, i, j, want_commit_seq)) {
3728 				/*
3729 				 * This could be caused by crash during writing.
3730 				 * We won't replay the inconsistent part of the
3731 				 * journal.
3732 				 */
3733 				DEBUG_print("commit id mismatch at position (%u, %u): %d != %d\n",
3734 					    i, j, find_commit_seq(ic, i, j, js->commit_id), want_commit_seq);
3735 				goto brk;
3736 			}
3737 		}
3738 		i++;
3739 		if (unlikely(i >= ic->journal_sections))
3740 			want_commit_seq = next_commit_seq(want_commit_seq);
3741 		wraparound_section(ic, &i);
3742 	}
3743 brk:
3744 
3745 	if (!journal_empty) {
3746 		DEBUG_print("replaying %u sections, starting at %u, commit seq %d\n",
3747 			    write_sections, write_start, want_commit_seq);
3748 		do_journal_write(ic, write_start, write_sections, true);
3749 	}
3750 
3751 	if (write_sections == ic->journal_sections && (ic->mode == 'J' || journal_empty)) {
3752 		continue_section = write_start;
3753 		ic->commit_seq = want_commit_seq;
3754 		DEBUG_print("continuing from section %u, commit seq %d\n", write_start, ic->commit_seq);
3755 	} else {
3756 		unsigned int s;
3757 		unsigned char erase_seq;
3758 
3759 clear_journal:
3760 		DEBUG_print("clearing journal\n");
3761 
3762 		erase_seq = prev_commit_seq(prev_commit_seq(last_used));
3763 		s = write_start;
3764 		init_journal(ic, s, 1, erase_seq);
3765 		s++;
3766 		wraparound_section(ic, &s);
3767 		if (ic->journal_sections >= 2) {
3768 			init_journal(ic, s, ic->journal_sections - 2, erase_seq);
3769 			s += ic->journal_sections - 2;
3770 			wraparound_section(ic, &s);
3771 			init_journal(ic, s, 1, erase_seq);
3772 		}
3773 
3774 		continue_section = 0;
3775 		ic->commit_seq = next_commit_seq(erase_seq);
3776 	}
3777 
3778 	ic->committed_section = continue_section;
3779 	ic->n_committed_sections = 0;
3780 
3781 	ic->uncommitted_section = continue_section;
3782 	ic->n_uncommitted_sections = 0;
3783 
3784 	ic->free_section = continue_section;
3785 	ic->free_section_entry = 0;
3786 	ic->free_sectors = ic->journal_entries;
3787 
3788 	ic->journal_tree_root = RB_ROOT;
3789 	for (i = 0; i < ic->journal_entries; i++)
3790 		init_journal_node(&ic->journal_tree[i]);
3791 }
3792 
3793 static void dm_integrity_enter_synchronous_mode(struct dm_integrity_c *ic)
3794 {
3795 	DEBUG_print("%s\n", __func__);
3796 
3797 	if (ic->mode == 'B') {
3798 		ic->bitmap_flush_interval = msecs_to_jiffies(10) + 1;
3799 		ic->synchronous_mode = 1;
3800 
3801 		cancel_delayed_work_sync(&ic->bitmap_flush_work);
3802 		queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
3803 		flush_workqueue(ic->commit_wq);
3804 	}
3805 }
3806 
3807 static int dm_integrity_reboot(struct notifier_block *n, unsigned long code, void *x)
3808 {
3809 	struct dm_integrity_c *ic = container_of(n, struct dm_integrity_c, reboot_notifier);
3810 
3811 	DEBUG_print("%s\n", __func__);
3812 
3813 	dm_integrity_enter_synchronous_mode(ic);
3814 
3815 	return NOTIFY_DONE;
3816 }
3817 
3818 static void dm_integrity_postsuspend(struct dm_target *ti)
3819 {
3820 	struct dm_integrity_c *ic = ti->private;
3821 	int r;
3822 
3823 	WARN_ON(unregister_reboot_notifier(&ic->reboot_notifier));
3824 
3825 	timer_delete_sync(&ic->autocommit_timer);
3826 
3827 	if (ic->recalc_wq)
3828 		drain_workqueue(ic->recalc_wq);
3829 
3830 	if (ic->mode == 'B')
3831 		cancel_delayed_work_sync(&ic->bitmap_flush_work);
3832 
3833 	queue_work(ic->commit_wq, &ic->commit_work);
3834 	drain_workqueue(ic->commit_wq);
3835 
3836 	if (ic->mode == 'J') {
3837 		queue_work(ic->writer_wq, &ic->writer_work);
3838 		drain_workqueue(ic->writer_wq);
3839 		dm_integrity_flush_buffers(ic, true);
3840 		if (ic->wrote_to_journal) {
3841 			init_journal(ic, ic->free_section,
3842 				     ic->journal_sections - ic->free_section, ic->commit_seq);
3843 			if (ic->free_section) {
3844 				init_journal(ic, 0, ic->free_section,
3845 					     next_commit_seq(ic->commit_seq));
3846 			}
3847 		}
3848 	}
3849 
3850 	if (ic->mode == 'B') {
3851 		dm_integrity_flush_buffers(ic, true);
3852 #if 1
3853 		/* set to 0 to test bitmap replay code */
3854 		init_journal(ic, 0, ic->journal_sections, 0);
3855 		ic->sb->flags &= ~cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
3856 		r = sync_rw_sb(ic, REQ_OP_WRITE | REQ_FUA);
3857 		if (unlikely(r))
3858 			dm_integrity_io_error(ic, "writing superblock", r);
3859 #endif
3860 	}
3861 
3862 	BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
3863 
3864 	ic->journal_uptodate = true;
3865 }
3866 
3867 /*
3868  * The superblock is re-read from the device on every resume, so that we pick
3869  * up the flags and the recalculate position. The geometry described by the
3870  * superblock must not change though - the in-memory structures (and the
3871  * journal in particular) were sized according to the superblock that was
3872  * validated in the constructor. Reject a superblock that was modified behind
3873  * our back.
3874  *
3875  * Only the fields that the driver never rewrites may be tested here. In
3876  * particular, "version" is recalculated by sb_set_version on every superblock
3877  * write and it depends on SB_FLAG_RECALCULATING and SB_FLAG_DIRTY_BITMAP, and
3878  * SB_FLAG_DISCARD_KEYED may be set by dm_integrity_resume itself.
3879  */
3880 static bool superblock_changed(struct dm_integrity_c *ic)
3881 {
3882 	const __le32 immutable_flags = cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC |
3883 						   SB_FLAG_FIXED_PADDING |
3884 						   SB_FLAG_FIXED_HMAC |
3885 						   SB_FLAG_INLINE);
3886 
3887 	return memcmp(ic->sb->magic, ic->sb_copy->magic, sizeof(ic->sb->magic)) != 0 ||
3888 	       ic->sb->log2_interleave_sectors != ic->sb_copy->log2_interleave_sectors ||
3889 	       ic->sb->integrity_tag_size != ic->sb_copy->integrity_tag_size ||
3890 	       ic->sb->journal_sections != ic->sb_copy->journal_sections ||
3891 	       ic->sb->log2_sectors_per_block != ic->sb_copy->log2_sectors_per_block ||
3892 	       ((ic->sb->flags ^ ic->sb_copy->flags) & immutable_flags) != 0 ||
3893 	       memcmp(ic->sb->salt, ic->sb_copy->salt, SALT_SIZE) != 0;
3894 }
3895 
3896 /*
3897  * The superblock is authenticated only if fix_hmac and journal_mac are used,
3898  * so SB_FLAG_DIRTY_BITMAP may have been set by someone who doesn't know the
3899  * key. Apply the policy that the constructor applies to SB_FLAG_RECALCULATING.
3900  */
3901 static bool dm_integrity_may_recalc_dirty_bitmap(struct dm_integrity_c *ic)
3902 {
3903 	if (!ic->internal_hash) {
3904 		DMERR("Dirty bitmap found, but internal_hash is not used");
3905 		return false;
3906 	}
3907 	if (dm_integrity_disable_recalculate(ic)) {
3908 		DMERR("Dirty bitmap found, but HMAC recalculation requires \"legacy_recalculate\"");
3909 		return false;
3910 	}
3911 	return true;
3912 }
3913 
3914 static void dm_integrity_resume(struct dm_target *ti)
3915 {
3916 	struct dm_integrity_c *ic = ti->private;
3917 	__u64 old_provided_data_sectors = le64_to_cpu(ic->sb->provided_data_sectors);
3918 	int r;
3919 	__le32 flags;
3920 
3921 	DEBUG_print("resume\n");
3922 
3923 	ic->wrote_to_journal = false;
3924 
3925 	flags = ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING);
3926 	if (ic->discard_keyed)
3927 		flags |= cpu_to_le32(SB_FLAG_DISCARD_KEYED);
3928 	r = sync_rw_sb(ic, REQ_OP_READ);
3929 	if (r)
3930 		dm_integrity_io_error(ic, "reading superblock", r);
3931 
3932 	if (unlikely(superblock_changed(ic))) {
3933 		/*
3934 		 * Restore the superblock that we validated in the constructor,
3935 		 * so that the rest of the driver doesn't operate on values
3936 		 * that don't match the in-memory structures.
3937 		 */
3938 		memcpy(ic->sb, ic->sb_copy, sizeof(struct superblock));
3939 		DMERR("The superblock was changed while the device was suspended");
3940 		dm_integrity_io_error(ic, "superblock check", -EINVAL);
3941 		goto skip_writes;
3942 	}
3943 
3944 	if (ic->mode == 'R')
3945 		goto skip_writes;
3946 
3947 	if ((ic->sb->flags & flags) != flags) {
3948 		ic->sb->flags |= flags;
3949 		r = sync_rw_sb(ic, REQ_OP_WRITE | REQ_FUA);
3950 		if (unlikely(r))
3951 			dm_integrity_io_error(ic, "writing superblock", r);
3952 	}
3953 
3954 	if (ic->provided_data_sectors != old_provided_data_sectors) {
3955 		if (ic->provided_data_sectors > old_provided_data_sectors &&
3956 		    ic->mode == 'B' &&
3957 		    ic->sb->flags & cpu_to_le32(SB_FLAG_DIRTY_BITMAP) &&
3958 		    ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit) {
3959 			rw_journal_sectors(ic, REQ_OP_READ, 0,
3960 					   ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3961 			block_bitmap_op(ic, ic->journal, old_provided_data_sectors,
3962 					ic->provided_data_sectors - old_provided_data_sectors, BITMAP_OP_SET);
3963 			rw_journal_sectors(ic, REQ_OP_WRITE | REQ_FUA | REQ_SYNC, 0,
3964 					   ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3965 		}
3966 
3967 		ic->sb->provided_data_sectors = cpu_to_le64(ic->provided_data_sectors);
3968 		r = sync_rw_sb(ic, REQ_OP_WRITE | REQ_FUA);
3969 		if (unlikely(r))
3970 			dm_integrity_io_error(ic, "writing superblock", r);
3971 	}
3972 
3973 	if (ic->sb->flags & cpu_to_le32(SB_FLAG_DIRTY_BITMAP)) {
3974 		DEBUG_print("resume dirty_bitmap\n");
3975 		rw_journal_sectors(ic, REQ_OP_READ, 0,
3976 				   ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3977 		if (ic->mode == 'B') {
3978 			if (ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit &&
3979 			    !ic->reset_recalculate_flag) {
3980 				block_bitmap_copy(ic, ic->recalc_bitmap, ic->journal);
3981 				block_bitmap_copy(ic, ic->may_write_bitmap, ic->journal);
3982 				if (!block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors,
3983 						     BITMAP_OP_TEST_ALL_CLEAR)) {
3984 					ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
3985 					ic->sb->recalc_sector = cpu_to_le64(0);
3986 				}
3987 			} else {
3988 				DEBUG_print("non-matching blocks_per_bitmap_bit: %u, %u\n",
3989 					    ic->sb->log2_blocks_per_bitmap_bit, ic->log2_blocks_per_bitmap_bit);
3990 				ic->sb->log2_blocks_per_bitmap_bit = ic->log2_blocks_per_bitmap_bit;
3991 				block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_SET);
3992 				block_bitmap_op(ic, ic->may_write_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_SET);
3993 				block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_SET);
3994 				rw_journal_sectors(ic, REQ_OP_WRITE | REQ_FUA | REQ_SYNC, 0,
3995 						   ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3996 				ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
3997 				ic->sb->recalc_sector = cpu_to_le64(0);
3998 			}
3999 		} else {
4000 			if (!(ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit &&
4001 			      block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_TEST_ALL_CLEAR)) ||
4002 			    ic->reset_recalculate_flag) {
4003 				if (dm_integrity_may_recalc_dirty_bitmap(ic)) {
4004 					ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
4005 					ic->sb->recalc_sector = cpu_to_le64(0);
4006 				}
4007 			}
4008 			init_journal(ic, 0, ic->journal_sections, 0);
4009 			replay_journal(ic);
4010 			ic->sb->flags &= ~cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
4011 		}
4012 		r = sync_rw_sb(ic, REQ_OP_WRITE | REQ_FUA);
4013 		if (unlikely(r))
4014 			dm_integrity_io_error(ic, "writing superblock", r);
4015 	} else {
4016 		replay_journal(ic);
4017 		if (ic->reset_recalculate_flag) {
4018 			ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
4019 			ic->sb->recalc_sector = cpu_to_le64(0);
4020 		}
4021 		if (ic->mode == 'B') {
4022 			ic->sb->flags |= cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
4023 			ic->sb->log2_blocks_per_bitmap_bit = ic->log2_blocks_per_bitmap_bit;
4024 			r = sync_rw_sb(ic, REQ_OP_WRITE | REQ_FUA);
4025 			if (unlikely(r))
4026 				dm_integrity_io_error(ic, "writing superblock", r);
4027 
4028 			block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
4029 			block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
4030 			block_bitmap_op(ic, ic->may_write_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
4031 			if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
4032 			    le64_to_cpu(ic->sb->recalc_sector) < ic->provided_data_sectors) {
4033 				block_bitmap_op(ic, ic->journal, le64_to_cpu(ic->sb->recalc_sector),
4034 						ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
4035 				block_bitmap_op(ic, ic->recalc_bitmap, le64_to_cpu(ic->sb->recalc_sector),
4036 						ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
4037 				block_bitmap_op(ic, ic->may_write_bitmap, le64_to_cpu(ic->sb->recalc_sector),
4038 						ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
4039 			}
4040 			rw_journal_sectors(ic, REQ_OP_WRITE | REQ_FUA | REQ_SYNC, 0,
4041 					   ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
4042 		}
4043 	}
4044 
4045 	DEBUG_print("testing recalc: %x\n", ic->sb->flags);
4046 	if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
4047 		__u64 recalc_pos = le64_to_cpu(ic->sb->recalc_sector);
4048 
4049 		DEBUG_print("recalc pos: %llx / %llx\n", recalc_pos, ic->provided_data_sectors);
4050 		if (recalc_pos < ic->provided_data_sectors) {
4051 			queue_work(ic->recalc_wq, &ic->recalc_work);
4052 		} else if (recalc_pos > ic->provided_data_sectors) {
4053 			ic->sb->recalc_sector = cpu_to_le64(ic->provided_data_sectors);
4054 			recalc_write_super(ic);
4055 		}
4056 	}
4057 
4058 skip_writes:
4059 	ic->reboot_notifier.notifier_call = dm_integrity_reboot;
4060 	ic->reboot_notifier.next = NULL;
4061 	ic->reboot_notifier.priority = INT_MAX - 1;	/* be notified after md and before hardware drivers */
4062 	WARN_ON(register_reboot_notifier(&ic->reboot_notifier));
4063 
4064 #if 0
4065 	/* set to 1 to stress test synchronous mode */
4066 	dm_integrity_enter_synchronous_mode(ic);
4067 #endif
4068 }
4069 
4070 static void dm_integrity_status(struct dm_target *ti, status_type_t type,
4071 				unsigned int status_flags, char *result, unsigned int maxlen)
4072 {
4073 	struct dm_integrity_c *ic = ti->private;
4074 	unsigned int arg_count;
4075 	size_t sz = 0;
4076 
4077 	switch (type) {
4078 	case STATUSTYPE_INFO:
4079 		DMEMIT("%llu %llu",
4080 			(unsigned long long)atomic64_read(&ic->number_of_mismatches),
4081 			ic->provided_data_sectors);
4082 		if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
4083 			DMEMIT(" %llu", le64_to_cpu(ic->sb->recalc_sector));
4084 		else
4085 			DMEMIT(" -");
4086 		break;
4087 
4088 	case STATUSTYPE_TABLE: {
4089 		arg_count = 1; /* buffer_sectors */
4090 		arg_count += !!ic->meta_dev;
4091 		arg_count += ic->sectors_per_block != 1;
4092 		arg_count += !!(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING));
4093 		arg_count += ic->reset_recalculate_flag;
4094 		arg_count += ic->discard && !ic->discard_keyed;
4095 		arg_count += ic->discard_keyed;
4096 		arg_count += ic->mode != 'I'; /* interleave_sectors */
4097 		arg_count += ic->mode == 'J'; /* journal_sectors */
4098 		arg_count += ic->mode == 'J'; /* journal_watermark */
4099 		arg_count += ic->mode == 'J'; /* commit_time */
4100 		arg_count += ic->mode == 'B'; /* sectors_per_bit */
4101 		arg_count += ic->mode == 'B'; /* bitmap_flush_interval */
4102 		arg_count += !!ic->internal_hash_alg.alg_string;
4103 		arg_count += !!ic->journal_crypt_alg.alg_string;
4104 		arg_count += !!ic->journal_mac_alg.alg_string;
4105 		arg_count += (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING)) != 0;
4106 		arg_count += (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) != 0;
4107 		arg_count += ic->legacy_recalculate;
4108 		DMEMIT("%s %llu %u %c %u", ic->dev->name, ic->start,
4109 		       ic->tag_size, ic->mode, arg_count);
4110 		if (ic->meta_dev)
4111 			DMEMIT(" meta_device:%s", ic->meta_dev->name);
4112 		if (ic->sectors_per_block != 1)
4113 			DMEMIT(" block_size:%u", ic->sectors_per_block << SECTOR_SHIFT);
4114 		if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
4115 			DMEMIT(" recalculate");
4116 		if (ic->reset_recalculate_flag)
4117 			DMEMIT(" reset_recalculate");
4118 		if (ic->discard && !ic->discard_keyed)
4119 			DMEMIT(" allow_discards");
4120 		if (ic->discard_keyed)
4121 			DMEMIT(" allow_discards_keyed");
4122 		if (ic->mode != 'I')
4123 			DMEMIT(" interleave_sectors:%u", 1U << ic->sb->log2_interleave_sectors);
4124 		DMEMIT(" buffer_sectors:%u", 1U << ic->log2_buffer_sectors);
4125 		if (ic->mode == 'J') {
4126 			__u64 watermark_percentage = (__u64)(ic->journal_entries - ic->free_sectors_threshold) * 100;
4127 
4128 			watermark_percentage += ic->journal_entries / 2;
4129 			do_div(watermark_percentage, ic->journal_entries);
4130 			DMEMIT(" journal_sectors:%u", ic->initial_sectors - SB_SECTORS);
4131 			DMEMIT(" journal_watermark:%u", (unsigned int)watermark_percentage);
4132 			DMEMIT(" commit_time:%u", ic->autocommit_msec);
4133 		}
4134 		if (ic->mode == 'B') {
4135 			DMEMIT(" sectors_per_bit:%llu", (sector_t)ic->sectors_per_block << ic->log2_blocks_per_bitmap_bit);
4136 			DMEMIT(" bitmap_flush_interval:%u", jiffies_to_msecs(ic->bitmap_flush_interval));
4137 		}
4138 		if ((ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING)) != 0)
4139 			DMEMIT(" fix_padding");
4140 		if ((ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) != 0)
4141 			DMEMIT(" fix_hmac");
4142 		if (ic->legacy_recalculate)
4143 			DMEMIT(" legacy_recalculate");
4144 
4145 #define EMIT_ALG(a, n)							\
4146 		do {							\
4147 			if (ic->a.alg_string) {				\
4148 				DMEMIT(" %s:%s", n, ic->a.alg_string);	\
4149 				if (ic->a.key_string)			\
4150 					DMEMIT(":%s", ic->a.key_string);\
4151 			}						\
4152 		} while (0)
4153 		EMIT_ALG(internal_hash_alg, "internal_hash");
4154 		EMIT_ALG(journal_crypt_alg, "journal_crypt");
4155 		EMIT_ALG(journal_mac_alg, "journal_mac");
4156 		break;
4157 	}
4158 	case STATUSTYPE_IMA:
4159 		DMEMIT_TARGET_NAME_VERSION(ti->type);
4160 		DMEMIT(",dev_name=%s,start=%llu,tag_size=%u,mode=%c",
4161 			ic->dev->name, ic->start, ic->tag_size, ic->mode);
4162 
4163 		if (ic->meta_dev)
4164 			DMEMIT(",meta_device=%s", ic->meta_dev->name);
4165 		if (ic->sectors_per_block != 1)
4166 			DMEMIT(",block_size=%u", ic->sectors_per_block << SECTOR_SHIFT);
4167 
4168 		DMEMIT(",recalculate=%c", (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) ?
4169 		       'y' : 'n');
4170 		DMEMIT(",allow_discards=%c", ic->discard ? 'y' : 'n');
4171 		DMEMIT(",allow_discards_keyed=%c", ic->discard_keyed ? 'y' : 'n');
4172 		DMEMIT(",fix_padding=%c",
4173 		       ((ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING)) != 0) ? 'y' : 'n');
4174 		DMEMIT(",fix_hmac=%c",
4175 		       ((ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) != 0) ? 'y' : 'n');
4176 		DMEMIT(",legacy_recalculate=%c", ic->legacy_recalculate ? 'y' : 'n');
4177 
4178 		DMEMIT(",journal_sectors=%u", ic->initial_sectors - SB_SECTORS);
4179 		DMEMIT(",interleave_sectors=%u", 1U << ic->sb->log2_interleave_sectors);
4180 		DMEMIT(",buffer_sectors=%u", 1U << ic->log2_buffer_sectors);
4181 		DMEMIT(";");
4182 		break;
4183 	}
4184 }
4185 
4186 static int dm_integrity_iterate_devices(struct dm_target *ti,
4187 					iterate_devices_callout_fn fn, void *data)
4188 {
4189 	struct dm_integrity_c *ic = ti->private;
4190 
4191 	if (!ic->meta_dev)
4192 		return fn(ti, ic->dev, ic->start + ic->initial_sectors + ic->metadata_run, ti->len, data);
4193 	else
4194 		return fn(ti, ic->dev, 0, ti->len, data);
4195 }
4196 
4197 static void dm_integrity_io_hints(struct dm_target *ti, struct queue_limits *limits)
4198 {
4199 	struct dm_integrity_c *ic = ti->private;
4200 
4201 	dm_stack_bs_limits(limits, ic->sectors_per_block << SECTOR_SHIFT);
4202 	limits->dma_alignment = limits->logical_block_size - 1;
4203 	limits->discard_granularity = ic->sectors_per_block << SECTOR_SHIFT;
4204 
4205 	if (ic->internal_hash &&
4206 	    (ic->mode == 'D' || ic->mode == 'B' || ic->mode == 'I'))
4207 		limits->features |= BLK_FEAT_STABLE_WRITES;
4208 
4209 	if (!ic->internal_hash) {
4210 		struct blk_integrity *bi = &limits->integrity;
4211 
4212 		memset(bi, 0, sizeof(*bi));
4213 		bi->metadata_size = ic->tag_size;
4214 		bi->tag_size = bi->metadata_size;
4215 		bi->interval_exp =
4216 			ic->sb->log2_sectors_per_block + SECTOR_SHIFT;
4217 	}
4218 
4219 	limits->max_integrity_segments = USHRT_MAX;
4220 }
4221 
4222 static void calculate_journal_section_size(struct dm_integrity_c *ic)
4223 {
4224 	unsigned int sector_space = JOURNAL_SECTOR_DATA;
4225 
4226 	ic->journal_sections = le32_to_cpu(ic->sb->journal_sections);
4227 	ic->journal_entry_size = roundup(offsetof(struct journal_entry, last_bytes[ic->sectors_per_block]) + ic->tag_size,
4228 					 JOURNAL_ENTRY_ROUNDUP);
4229 
4230 	if (ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC))
4231 		sector_space -= JOURNAL_MAC_PER_SECTOR;
4232 	ic->journal_entries_per_sector = sector_space / ic->journal_entry_size;
4233 	ic->journal_section_entries = ic->journal_entries_per_sector * JOURNAL_BLOCK_SECTORS;
4234 	ic->journal_section_sectors = (ic->journal_section_entries << ic->sb->log2_sectors_per_block) + JOURNAL_BLOCK_SECTORS;
4235 	ic->journal_entries = ic->journal_section_entries * ic->journal_sections;
4236 }
4237 
4238 static int calculate_device_limits(struct dm_integrity_c *ic)
4239 {
4240 	__u64 initial_sectors;
4241 
4242 	calculate_journal_section_size(ic);
4243 	initial_sectors = SB_SECTORS + (__u64)ic->journal_section_sectors * ic->journal_sections;
4244 	if (initial_sectors + METADATA_PADDING_SECTORS >= ic->meta_device_sectors || initial_sectors > UINT_MAX)
4245 		return -EINVAL;
4246 	ic->initial_sectors = initial_sectors;
4247 
4248 	if (ic->mode == 'I') {
4249 		if (ic->initial_sectors + ic->provided_data_sectors > ic->meta_device_sectors)
4250 			return -EINVAL;
4251 	} else if (!ic->meta_dev) {
4252 		sector_t last_sector, last_area, last_offset;
4253 
4254 		/* we have to maintain excessive padding for compatibility with existing volumes */
4255 		__u64 metadata_run_padding =
4256 			ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING) ?
4257 			(__u64)(METADATA_PADDING_SECTORS << SECTOR_SHIFT) :
4258 			(__u64)(1 << SECTOR_SHIFT << METADATA_PADDING_SECTORS);
4259 
4260 		ic->metadata_run = round_up((__u64)ic->tag_size << (ic->sb->log2_interleave_sectors - ic->sb->log2_sectors_per_block),
4261 					    metadata_run_padding) >> SECTOR_SHIFT;
4262 		if (!(ic->metadata_run & (ic->metadata_run - 1)))
4263 			ic->log2_metadata_run = __ffs(ic->metadata_run);
4264 		else
4265 			ic->log2_metadata_run = -1;
4266 
4267 		get_area_and_offset(ic, ic->provided_data_sectors - 1, &last_area, &last_offset);
4268 		last_sector = get_data_sector(ic, last_area, last_offset);
4269 		if (last_sector < ic->start || last_sector >= ic->meta_device_sectors)
4270 			return -EINVAL;
4271 	} else {
4272 		__u64 meta_size = (ic->provided_data_sectors >> ic->sb->log2_sectors_per_block) * ic->tag_size;
4273 
4274 		meta_size = (meta_size + ((1U << (ic->log2_buffer_sectors + SECTOR_SHIFT)) - 1))
4275 				>> (ic->log2_buffer_sectors + SECTOR_SHIFT);
4276 		meta_size <<= ic->log2_buffer_sectors;
4277 		if (ic->initial_sectors + meta_size < ic->initial_sectors ||
4278 		    ic->initial_sectors + meta_size > ic->meta_device_sectors)
4279 			return -EINVAL;
4280 		ic->metadata_run = 1;
4281 		ic->log2_metadata_run = 0;
4282 	}
4283 
4284 	return 0;
4285 }
4286 
4287 static void get_provided_data_sectors(struct dm_integrity_c *ic)
4288 {
4289 	if (!ic->meta_dev) {
4290 		int test_bit;
4291 
4292 		ic->provided_data_sectors = 0;
4293 		for (test_bit = fls64(ic->meta_device_sectors) - 1; test_bit >= 3; test_bit--) {
4294 			__u64 prev_data_sectors = ic->provided_data_sectors;
4295 
4296 			ic->provided_data_sectors |= (sector_t)1 << test_bit;
4297 			if (calculate_device_limits(ic))
4298 				ic->provided_data_sectors = prev_data_sectors;
4299 		}
4300 	} else {
4301 		ic->provided_data_sectors = ic->data_device_sectors;
4302 		ic->provided_data_sectors &= ~(sector_t)(ic->sectors_per_block - 1);
4303 	}
4304 }
4305 
4306 static int initialize_superblock(struct dm_integrity_c *ic,
4307 				 unsigned int journal_sectors, unsigned int interleave_sectors)
4308 {
4309 	unsigned int journal_sections;
4310 	int test_bit;
4311 
4312 	memset(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT);
4313 	memcpy(ic->sb->magic, SB_MAGIC, 8);
4314 	if (ic->mode == 'I')
4315 		ic->sb->flags |= cpu_to_le32(SB_FLAG_INLINE);
4316 	ic->sb->integrity_tag_size = cpu_to_le16(ic->tag_size);
4317 	ic->sb->log2_sectors_per_block = __ffs(ic->sectors_per_block);
4318 	if (ic->journal_mac_alg.alg_string)
4319 		ic->sb->flags |= cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC);
4320 
4321 	calculate_journal_section_size(ic);
4322 	journal_sections = journal_sectors / ic->journal_section_sectors;
4323 	if (!journal_sections)
4324 		journal_sections = 1;
4325 	if (ic->mode == 'I')
4326 		journal_sections = 0;
4327 
4328 	if (ic->fix_hmac && (ic->internal_hash_alg.alg_string || ic->journal_mac_alg.alg_string)) {
4329 		ic->sb->flags |= cpu_to_le32(SB_FLAG_FIXED_HMAC);
4330 		get_random_bytes(ic->sb->salt, SALT_SIZE);
4331 	}
4332 
4333 	if (ic->discard_keyed)
4334 		ic->sb->flags |= cpu_to_le32(SB_FLAG_DISCARD_KEYED);
4335 
4336 	if (!ic->meta_dev) {
4337 		if (ic->fix_padding)
4338 			ic->sb->flags |= cpu_to_le32(SB_FLAG_FIXED_PADDING);
4339 		ic->sb->journal_sections = cpu_to_le32(journal_sections);
4340 		if (!interleave_sectors)
4341 			interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
4342 		ic->sb->log2_interleave_sectors = __fls(interleave_sectors);
4343 		ic->sb->log2_interleave_sectors = max_t(__u8, MIN_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
4344 		ic->sb->log2_interleave_sectors = min_t(__u8, MAX_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
4345 
4346 		get_provided_data_sectors(ic);
4347 		if (!ic->provided_data_sectors)
4348 			return -EINVAL;
4349 	} else {
4350 		ic->sb->log2_interleave_sectors = 0;
4351 
4352 		get_provided_data_sectors(ic);
4353 		if (!ic->provided_data_sectors)
4354 			return -EINVAL;
4355 
4356 try_smaller_buffer:
4357 		ic->sb->journal_sections = cpu_to_le32(0);
4358 		for (test_bit = fls(journal_sections) - 1; test_bit >= 0; test_bit--) {
4359 			__u32 prev_journal_sections = le32_to_cpu(ic->sb->journal_sections);
4360 			__u32 test_journal_sections = prev_journal_sections | (1U << test_bit);
4361 
4362 			if (test_journal_sections > journal_sections)
4363 				continue;
4364 			ic->sb->journal_sections = cpu_to_le32(test_journal_sections);
4365 			if (calculate_device_limits(ic))
4366 				ic->sb->journal_sections = cpu_to_le32(prev_journal_sections);
4367 
4368 		}
4369 		if (!le32_to_cpu(ic->sb->journal_sections)) {
4370 			if (ic->log2_buffer_sectors > 3) {
4371 				ic->log2_buffer_sectors--;
4372 				goto try_smaller_buffer;
4373 			}
4374 			return -EINVAL;
4375 		}
4376 	}
4377 
4378 	ic->sb->provided_data_sectors = cpu_to_le64(ic->provided_data_sectors);
4379 
4380 	sb_set_version(ic);
4381 
4382 	return 0;
4383 }
4384 
4385 static void dm_integrity_free_page_list(struct page_list *pl)
4386 {
4387 	unsigned int i;
4388 
4389 	if (!pl)
4390 		return;
4391 	for (i = 0; pl[i].page; i++)
4392 		__free_page(pl[i].page);
4393 	kvfree(pl);
4394 }
4395 
4396 static struct page_list *dm_integrity_alloc_page_list(unsigned int n_pages)
4397 {
4398 	struct page_list *pl;
4399 	unsigned int i;
4400 
4401 	pl = kvmalloc_objs(struct page_list, n_pages + 1,
4402 			   GFP_KERNEL | __GFP_ZERO);
4403 	if (!pl)
4404 		return NULL;
4405 
4406 	for (i = 0; i < n_pages; i++) {
4407 		pl[i].page = alloc_page(GFP_KERNEL);
4408 		if (!pl[i].page) {
4409 			dm_integrity_free_page_list(pl);
4410 			return NULL;
4411 		}
4412 		if (i)
4413 			pl[i - 1].next = &pl[i];
4414 	}
4415 	pl[i].page = NULL;
4416 	pl[i].next = NULL;
4417 
4418 	return pl;
4419 }
4420 
4421 static void dm_integrity_free_journal_scatterlist(struct dm_integrity_c *ic, struct scatterlist **sl)
4422 {
4423 	unsigned int i;
4424 
4425 	for (i = 0; i < ic->journal_sections; i++)
4426 		kvfree(sl[i]);
4427 	kvfree(sl);
4428 }
4429 
4430 static struct scatterlist **dm_integrity_alloc_journal_scatterlist(struct dm_integrity_c *ic,
4431 								   struct page_list *pl)
4432 {
4433 	struct scatterlist **sl;
4434 	unsigned int i;
4435 
4436 	sl = kvmalloc_objs(struct scatterlist *, ic->journal_sections,
4437 			   GFP_KERNEL | __GFP_ZERO);
4438 	if (!sl)
4439 		return NULL;
4440 
4441 	for (i = 0; i < ic->journal_sections; i++) {
4442 		struct scatterlist *s;
4443 		unsigned int start_index, start_offset;
4444 		unsigned int end_index, end_offset;
4445 		unsigned int n_pages;
4446 		unsigned int idx;
4447 
4448 		page_list_location(ic, i, 0, &start_index, &start_offset);
4449 		page_list_location(ic, i, ic->journal_section_sectors - 1,
4450 				   &end_index, &end_offset);
4451 
4452 		n_pages = (end_index - start_index + 1);
4453 
4454 		s = kvmalloc_objs(struct scatterlist, n_pages);
4455 		if (!s) {
4456 			dm_integrity_free_journal_scatterlist(ic, sl);
4457 			return NULL;
4458 		}
4459 
4460 		sg_init_table(s, n_pages);
4461 		for (idx = start_index; idx <= end_index; idx++) {
4462 			char *va = lowmem_page_address(pl[idx].page);
4463 			unsigned int start = 0, end = PAGE_SIZE;
4464 
4465 			if (idx == start_index)
4466 				start = start_offset;
4467 			if (idx == end_index)
4468 				end = end_offset + (1 << SECTOR_SHIFT);
4469 			sg_set_buf(&s[idx - start_index], va + start, end - start);
4470 		}
4471 
4472 		sl[i] = s;
4473 	}
4474 
4475 	return sl;
4476 }
4477 
4478 static void free_alg(struct alg_spec *a)
4479 {
4480 	kfree_sensitive(a->alg_string);
4481 	kfree_sensitive(a->key);
4482 	memset(a, 0, sizeof(*a));
4483 }
4484 
4485 static int get_alg_and_key(const char *arg, struct alg_spec *a, char **error, char *error_inval)
4486 {
4487 	char *k;
4488 
4489 	free_alg(a);
4490 
4491 	a->alg_string = kstrdup(strchr(arg, ':') + 1, GFP_KERNEL);
4492 	if (!a->alg_string)
4493 		goto nomem;
4494 
4495 	k = strchr(a->alg_string, ':');
4496 	if (k) {
4497 		*k = 0;
4498 		a->key_string = k + 1;
4499 		if (strlen(a->key_string) & 1)
4500 			goto inval;
4501 
4502 		a->key_size = strlen(a->key_string) / 2;
4503 		a->key = kmalloc(a->key_size, GFP_KERNEL);
4504 		if (!a->key)
4505 			goto nomem;
4506 		if (hex2bin(a->key, a->key_string, a->key_size))
4507 			goto inval;
4508 	}
4509 
4510 	return 0;
4511 inval:
4512 	*error = error_inval;
4513 	return -EINVAL;
4514 nomem:
4515 	*error = "Out of memory for an argument";
4516 	return -ENOMEM;
4517 }
4518 
4519 static int get_mac(struct crypto_shash **shash, struct crypto_ahash **ahash,
4520 		   struct alg_spec *a, char **error, char *error_alg, char *error_key)
4521 {
4522 	int r;
4523 
4524 	if (a->alg_string) {
4525 		if (shash) {
4526 			*shash = crypto_alloc_shash(a->alg_string, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
4527 			if (IS_ERR(*shash)) {
4528 				*shash = NULL;
4529 				goto try_ahash;
4530 			}
4531 			if (a->key) {
4532 				r = crypto_shash_setkey(*shash, a->key, a->key_size);
4533 				if (r) {
4534 					*error = error_key;
4535 					return r;
4536 				}
4537 			} else if (crypto_shash_get_flags(*shash) & CRYPTO_TFM_NEED_KEY) {
4538 				*error = error_key;
4539 				return -ENOKEY;
4540 			}
4541 			return 0;
4542 		}
4543 try_ahash:
4544 		if (ahash) {
4545 			*ahash = crypto_alloc_ahash(a->alg_string, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
4546 			if (IS_ERR(*ahash)) {
4547 				*error = error_alg;
4548 				r = PTR_ERR(*ahash);
4549 				*ahash = NULL;
4550 				return r;
4551 			}
4552 			if (a->key) {
4553 				r = crypto_ahash_setkey(*ahash, a->key, a->key_size);
4554 				if (r) {
4555 					*error = error_key;
4556 					return r;
4557 				}
4558 			} else if (crypto_ahash_get_flags(*ahash) & CRYPTO_TFM_NEED_KEY) {
4559 				*error = error_key;
4560 				return -ENOKEY;
4561 			}
4562 			return 0;
4563 		}
4564 		*error = error_alg;
4565 		return -ENOENT;
4566 	}
4567 
4568 	return 0;
4569 }
4570 
4571 static int create_journal(struct dm_integrity_c *ic, char **error)
4572 {
4573 	int r = 0;
4574 	unsigned int i;
4575 	__u64 journal_pages, journal_desc_size, journal_tree_size;
4576 	unsigned char *crypt_data = NULL, *crypt_iv = NULL;
4577 	struct skcipher_request *req = NULL;
4578 
4579 	ic->commit_ids[0] = cpu_to_le64(0x1111111111111111ULL);
4580 	ic->commit_ids[1] = cpu_to_le64(0x2222222222222222ULL);
4581 	ic->commit_ids[2] = cpu_to_le64(0x3333333333333333ULL);
4582 	ic->commit_ids[3] = cpu_to_le64(0x4444444444444444ULL);
4583 
4584 	journal_pages = roundup((__u64)ic->journal_sections * ic->journal_section_sectors,
4585 				PAGE_SIZE >> SECTOR_SHIFT) >> (PAGE_SHIFT - SECTOR_SHIFT);
4586 	journal_desc_size = journal_pages * sizeof(struct page_list);
4587 	if (journal_pages >= totalram_pages() - totalhigh_pages() || journal_desc_size > ULONG_MAX) {
4588 		*error = "Journal doesn't fit into memory";
4589 		r = -ENOMEM;
4590 		goto bad;
4591 	}
4592 	ic->journal_pages = journal_pages;
4593 
4594 	ic->journal = dm_integrity_alloc_page_list(ic->journal_pages);
4595 	if (!ic->journal) {
4596 		*error = "Could not allocate memory for journal";
4597 		r = -ENOMEM;
4598 		goto bad;
4599 	}
4600 	if (ic->journal_crypt_alg.alg_string) {
4601 		unsigned int ivsize, blocksize;
4602 		struct journal_completion comp;
4603 
4604 		comp.ic = ic;
4605 		ic->journal_crypt = crypto_alloc_skcipher(ic->journal_crypt_alg.alg_string, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
4606 		if (IS_ERR(ic->journal_crypt)) {
4607 			*error = "Invalid journal cipher";
4608 			r = PTR_ERR(ic->journal_crypt);
4609 			ic->journal_crypt = NULL;
4610 			goto bad;
4611 		}
4612 		ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
4613 		blocksize = crypto_skcipher_blocksize(ic->journal_crypt);
4614 
4615 		if (ic->journal_crypt_alg.key) {
4616 			r = crypto_skcipher_setkey(ic->journal_crypt, ic->journal_crypt_alg.key,
4617 						   ic->journal_crypt_alg.key_size);
4618 			if (r) {
4619 				*error = "Error setting encryption key";
4620 				goto bad;
4621 			}
4622 		}
4623 		DEBUG_print("cipher %s, block size %u iv size %u\n",
4624 			    ic->journal_crypt_alg.alg_string, blocksize, ivsize);
4625 
4626 		ic->journal_io = dm_integrity_alloc_page_list(ic->journal_pages);
4627 		if (!ic->journal_io) {
4628 			*error = "Could not allocate memory for journal io";
4629 			r = -ENOMEM;
4630 			goto bad;
4631 		}
4632 
4633 		if (blocksize == 1) {
4634 			struct scatterlist *sg;
4635 
4636 			req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
4637 			if (!req) {
4638 				*error = "Could not allocate crypt request";
4639 				r = -ENOMEM;
4640 				goto bad;
4641 			}
4642 
4643 			crypt_iv = kzalloc(ivsize, GFP_KERNEL);
4644 			if (!crypt_iv) {
4645 				*error = "Could not allocate iv";
4646 				r = -ENOMEM;
4647 				goto bad;
4648 			}
4649 
4650 			ic->journal_xor = dm_integrity_alloc_page_list(ic->journal_pages);
4651 			if (!ic->journal_xor) {
4652 				*error = "Could not allocate memory for journal xor";
4653 				r = -ENOMEM;
4654 				goto bad;
4655 			}
4656 
4657 			sg = kvmalloc_objs(struct scatterlist,
4658 					   ic->journal_pages + 1);
4659 			if (!sg) {
4660 				*error = "Unable to allocate sg list";
4661 				r = -ENOMEM;
4662 				goto bad;
4663 			}
4664 			sg_init_table(sg, ic->journal_pages + 1);
4665 			for (i = 0; i < ic->journal_pages; i++) {
4666 				char *va = lowmem_page_address(ic->journal_xor[i].page);
4667 
4668 				clear_page(va);
4669 				sg_set_buf(&sg[i], va, PAGE_SIZE);
4670 			}
4671 			sg_set_buf(&sg[i], &ic->commit_ids, sizeof(ic->commit_ids));
4672 
4673 			skcipher_request_set_crypt(req, sg, sg,
4674 						   PAGE_SIZE * ic->journal_pages + sizeof(ic->commit_ids), crypt_iv);
4675 			init_completion(&comp.comp);
4676 			comp.in_flight = (atomic_t)ATOMIC_INIT(1);
4677 			if (do_crypt(true, req, &comp))
4678 				wait_for_completion(&comp.comp);
4679 			kvfree(sg);
4680 			r = dm_integrity_failed(ic);
4681 			if (r) {
4682 				*error = "Unable to encrypt journal";
4683 				goto bad;
4684 			}
4685 			DEBUG_bytes(lowmem_page_address(ic->journal_xor[0].page), 64, "xor data");
4686 
4687 			crypto_free_skcipher(ic->journal_crypt);
4688 			ic->journal_crypt = NULL;
4689 		} else {
4690 			unsigned int crypt_len = roundup(ivsize, blocksize);
4691 
4692 			req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
4693 			if (!req) {
4694 				*error = "Could not allocate crypt request";
4695 				r = -ENOMEM;
4696 				goto bad;
4697 			}
4698 
4699 			crypt_iv = kmalloc(ivsize, GFP_KERNEL);
4700 			if (!crypt_iv) {
4701 				*error = "Could not allocate iv";
4702 				r = -ENOMEM;
4703 				goto bad;
4704 			}
4705 
4706 			crypt_data = kmalloc(crypt_len, GFP_KERNEL);
4707 			if (!crypt_data) {
4708 				*error = "Unable to allocate crypt data";
4709 				r = -ENOMEM;
4710 				goto bad;
4711 			}
4712 
4713 			ic->journal_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal);
4714 			if (!ic->journal_scatterlist) {
4715 				*error = "Unable to allocate sg list";
4716 				r = -ENOMEM;
4717 				goto bad;
4718 			}
4719 			ic->journal_io_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal_io);
4720 			if (!ic->journal_io_scatterlist) {
4721 				*error = "Unable to allocate sg list";
4722 				r = -ENOMEM;
4723 				goto bad;
4724 			}
4725 			ic->sk_requests = kvmalloc_objs(struct skcipher_request *,
4726 							ic->journal_sections,
4727 							GFP_KERNEL | __GFP_ZERO);
4728 			if (!ic->sk_requests) {
4729 				*error = "Unable to allocate sk requests";
4730 				r = -ENOMEM;
4731 				goto bad;
4732 			}
4733 			for (i = 0; i < ic->journal_sections; i++) {
4734 				struct scatterlist sg;
4735 				struct skcipher_request *section_req;
4736 				__le32 section_le = cpu_to_le32(i);
4737 
4738 				memset(crypt_iv, 0x00, ivsize);
4739 				memset(crypt_data, 0x00, crypt_len);
4740 				memcpy(crypt_data, &section_le, min_t(size_t, crypt_len, sizeof(section_le)));
4741 
4742 				sg_init_one(&sg, crypt_data, crypt_len);
4743 				skcipher_request_set_crypt(req, &sg, &sg, crypt_len, crypt_iv);
4744 				init_completion(&comp.comp);
4745 				comp.in_flight = (atomic_t)ATOMIC_INIT(1);
4746 				if (do_crypt(true, req, &comp))
4747 					wait_for_completion(&comp.comp);
4748 
4749 				r = dm_integrity_failed(ic);
4750 				if (r) {
4751 					*error = "Unable to generate iv";
4752 					goto bad;
4753 				}
4754 
4755 				section_req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
4756 				if (!section_req) {
4757 					*error = "Unable to allocate crypt request";
4758 					r = -ENOMEM;
4759 					goto bad;
4760 				}
4761 				section_req->iv = kmalloc_array(ivsize, 2,
4762 								GFP_KERNEL);
4763 				if (!section_req->iv) {
4764 					skcipher_request_free(section_req);
4765 					*error = "Unable to allocate iv";
4766 					r = -ENOMEM;
4767 					goto bad;
4768 				}
4769 				memcpy(section_req->iv + ivsize, crypt_data, ivsize);
4770 				section_req->cryptlen = (size_t)ic->journal_section_sectors << SECTOR_SHIFT;
4771 				ic->sk_requests[i] = section_req;
4772 				DEBUG_bytes(crypt_data, ivsize, "iv(%u)", i);
4773 			}
4774 		}
4775 	}
4776 
4777 	for (i = 0; i < N_COMMIT_IDS; i++) {
4778 		unsigned int j;
4779 
4780 retest_commit_id:
4781 		for (j = 0; j < i; j++) {
4782 			if (ic->commit_ids[j] == ic->commit_ids[i]) {
4783 				ic->commit_ids[i] = cpu_to_le64(le64_to_cpu(ic->commit_ids[i]) + 1);
4784 				goto retest_commit_id;
4785 			}
4786 		}
4787 		DEBUG_print("commit id %u: %016llx\n", i, ic->commit_ids[i]);
4788 	}
4789 
4790 	journal_tree_size = (__u64)ic->journal_entries * sizeof(struct journal_node);
4791 	if (journal_tree_size > ULONG_MAX) {
4792 		*error = "Journal doesn't fit into memory";
4793 		r = -ENOMEM;
4794 		goto bad;
4795 	}
4796 	ic->journal_tree = kvmalloc(journal_tree_size, GFP_KERNEL);
4797 	if (!ic->journal_tree) {
4798 		*error = "Could not allocate memory for journal tree";
4799 		r = -ENOMEM;
4800 		goto bad;
4801 	}
4802 bad:
4803 	kfree(crypt_data);
4804 	kfree(crypt_iv);
4805 	skcipher_request_free(req);
4806 
4807 	return r;
4808 }
4809 
4810 /*
4811  * Construct a integrity mapping
4812  *
4813  * Arguments:
4814  *	device
4815  *	offset from the start of the device
4816  *	tag size
4817  *	D - direct writes, J - journal writes, B - bitmap mode, R - recovery mode
4818  *	number of optional arguments
4819  *	optional arguments:
4820  *		journal_sectors
4821  *		interleave_sectors
4822  *		buffer_sectors
4823  *		journal_watermark
4824  *		commit_time
4825  *		meta_device
4826  *		block_size
4827  *		sectors_per_bit
4828  *		bitmap_flush_interval
4829  *		internal_hash
4830  *		journal_crypt
4831  *		journal_mac
4832  *		recalculate
4833  */
4834 static int dm_integrity_ctr(struct dm_target *ti, unsigned int argc, char **argv)
4835 {
4836 	struct dm_integrity_c *ic;
4837 	char dummy;
4838 	int r;
4839 	unsigned int extra_args;
4840 	struct dm_arg_set as;
4841 	static const struct dm_arg _args[] = {
4842 		{0, 18, "Invalid number of feature args"},
4843 	};
4844 	unsigned int journal_sectors, interleave_sectors, buffer_sectors, journal_watermark, sync_msec;
4845 	bool should_write_sb;
4846 	__u64 threshold;
4847 	unsigned long long start;
4848 	__s8 log2_sectors_per_bitmap_bit = -1;
4849 	__s8 log2_blocks_per_bitmap_bit;
4850 	__u64 bits_in_journal;
4851 	__u64 n_bitmap_bits;
4852 
4853 #define DIRECT_ARGUMENTS	4
4854 
4855 	if (argc <= DIRECT_ARGUMENTS) {
4856 		ti->error = "Invalid argument count";
4857 		return -EINVAL;
4858 	}
4859 
4860 	ic = kzalloc_obj(struct dm_integrity_c);
4861 	if (!ic) {
4862 		ti->error = "Cannot allocate integrity context";
4863 		return -ENOMEM;
4864 	}
4865 	ti->private = ic;
4866 	ti->per_io_data_size = sizeof(struct dm_integrity_io);
4867 	ic->ti = ti;
4868 
4869 	ic->in_progress = RB_ROOT;
4870 	INIT_LIST_HEAD(&ic->wait_list);
4871 	init_waitqueue_head(&ic->endio_wait);
4872 	bio_list_init(&ic->flush_bio_list);
4873 	init_waitqueue_head(&ic->copy_to_journal_wait);
4874 	init_completion(&ic->crypto_backoff);
4875 	atomic64_set(&ic->number_of_mismatches, 0);
4876 	ic->bitmap_flush_interval = BITMAP_FLUSH_INTERVAL;
4877 
4878 	r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &ic->dev);
4879 	if (r) {
4880 		ti->error = "Device lookup failed";
4881 		goto bad;
4882 	}
4883 
4884 	if (sscanf(argv[1], "%llu%c", &start, &dummy) != 1 || start != (sector_t)start) {
4885 		ti->error = "Invalid starting offset";
4886 		r = -EINVAL;
4887 		goto bad;
4888 	}
4889 	ic->start = start;
4890 
4891 	if (strcmp(argv[2], "-")) {
4892 		if (sscanf(argv[2], "%u%c", &ic->tag_size, &dummy) != 1 || !ic->tag_size) {
4893 			ti->error = "Invalid tag size";
4894 			r = -EINVAL;
4895 			goto bad;
4896 		}
4897 	}
4898 
4899 	if (!strcmp(argv[3], "J") || !strcmp(argv[3], "B") ||
4900 	    !strcmp(argv[3], "D") || !strcmp(argv[3], "R") ||
4901 	    !strcmp(argv[3], "I")) {
4902 		ic->mode = argv[3][0];
4903 	} else {
4904 		ti->error = "Invalid mode (expecting J, B, D, R, I)";
4905 		r = -EINVAL;
4906 		goto bad;
4907 	}
4908 
4909 	journal_sectors = 0;
4910 	interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
4911 	buffer_sectors = DEFAULT_BUFFER_SECTORS;
4912 	journal_watermark = DEFAULT_JOURNAL_WATERMARK;
4913 	sync_msec = DEFAULT_SYNC_MSEC;
4914 	ic->sectors_per_block = 1;
4915 
4916 	as.argc = argc - DIRECT_ARGUMENTS;
4917 	as.argv = argv + DIRECT_ARGUMENTS;
4918 	r = dm_read_arg_group(_args, &as, &extra_args, &ti->error);
4919 	if (r)
4920 		goto bad;
4921 
4922 	while (extra_args--) {
4923 		const char *opt_string;
4924 		unsigned int val;
4925 		unsigned long long llval;
4926 
4927 		opt_string = dm_shift_arg(&as);
4928 		if (!opt_string) {
4929 			r = -EINVAL;
4930 			ti->error = "Not enough feature arguments";
4931 			goto bad;
4932 		}
4933 		if (sscanf(opt_string, "journal_sectors:%u%c", &val, &dummy) == 1)
4934 			journal_sectors = val ? val : 1;
4935 		else if (sscanf(opt_string, "interleave_sectors:%u%c", &val, &dummy) == 1)
4936 			interleave_sectors = val;
4937 		else if (sscanf(opt_string, "buffer_sectors:%u%c", &val, &dummy) == 1)
4938 			buffer_sectors = val;
4939 		else if (sscanf(opt_string, "journal_watermark:%u%c", &val, &dummy) == 1 && val <= 100)
4940 			journal_watermark = val;
4941 		else if (sscanf(opt_string, "commit_time:%u%c", &val, &dummy) == 1)
4942 			sync_msec = val;
4943 		else if (!strncmp(opt_string, "meta_device:", strlen("meta_device:"))) {
4944 			if (ic->meta_dev) {
4945 				dm_put_device(ti, ic->meta_dev);
4946 				ic->meta_dev = NULL;
4947 			}
4948 			r = dm_get_device(ti, strchr(opt_string, ':') + 1,
4949 					  dm_table_get_mode(ti->table), &ic->meta_dev);
4950 			if (r) {
4951 				ti->error = "Device lookup failed";
4952 				goto bad;
4953 			}
4954 		} else if (sscanf(opt_string, "block_size:%u%c", &val, &dummy) == 1) {
4955 			if (val < 1 << SECTOR_SHIFT ||
4956 			    val > MAX_SECTORS_PER_BLOCK << SECTOR_SHIFT ||
4957 			    (val & (val - 1))) {
4958 				r = -EINVAL;
4959 				ti->error = "Invalid block_size argument";
4960 				goto bad;
4961 			}
4962 			ic->sectors_per_block = val >> SECTOR_SHIFT;
4963 		} else if (sscanf(opt_string, "sectors_per_bit:%llu%c", &llval, &dummy) == 1) {
4964 			log2_sectors_per_bitmap_bit = !llval ? 0 : __ilog2_u64(llval);
4965 		} else if (sscanf(opt_string, "bitmap_flush_interval:%u%c", &val, &dummy) == 1) {
4966 			if ((uint64_t)val >= (uint64_t)UINT_MAX * 1000 / HZ) {
4967 				r = -EINVAL;
4968 				ti->error = "Invalid bitmap_flush_interval argument";
4969 				goto bad;
4970 			}
4971 			ic->bitmap_flush_interval = msecs_to_jiffies(val);
4972 		} else if (!strncmp(opt_string, "internal_hash:", strlen("internal_hash:"))) {
4973 			r = get_alg_and_key(opt_string, &ic->internal_hash_alg, &ti->error,
4974 					    "Invalid internal_hash argument");
4975 			if (r)
4976 				goto bad;
4977 		} else if (!strncmp(opt_string, "journal_crypt:", strlen("journal_crypt:"))) {
4978 			r = get_alg_and_key(opt_string, &ic->journal_crypt_alg, &ti->error,
4979 					    "Invalid journal_crypt argument");
4980 			if (r)
4981 				goto bad;
4982 		} else if (!strncmp(opt_string, "journal_mac:", strlen("journal_mac:"))) {
4983 			r = get_alg_and_key(opt_string, &ic->journal_mac_alg, &ti->error,
4984 					    "Invalid journal_mac argument");
4985 			if (r)
4986 				goto bad;
4987 		} else if (!strcmp(opt_string, "recalculate")) {
4988 			ic->recalculate_flag = true;
4989 		} else if (!strcmp(opt_string, "reset_recalculate")) {
4990 			ic->recalculate_flag = true;
4991 			ic->reset_recalculate_flag = true;
4992 		} else if (!strcmp(opt_string, "allow_discards")) {
4993 			ic->discard = true;
4994 		} else if (!strcmp(opt_string, "allow_discards_keyed")) {
4995 			ic->discard = true;
4996 			ic->discard_keyed = true;
4997 		} else if (!strcmp(opt_string, "fix_padding")) {
4998 			ic->fix_padding = true;
4999 		} else if (!strcmp(opt_string, "fix_hmac")) {
5000 			ic->fix_hmac = true;
5001 		} else if (!strcmp(opt_string, "legacy_recalculate")) {
5002 			ic->legacy_recalculate = true;
5003 		} else {
5004 			r = -EINVAL;
5005 			ti->error = "Invalid argument";
5006 			goto bad;
5007 		}
5008 	}
5009 
5010 	ic->data_device_sectors = bdev_nr_sectors(ic->dev->bdev);
5011 	if (!ic->meta_dev)
5012 		ic->meta_device_sectors = ic->data_device_sectors;
5013 	else
5014 		ic->meta_device_sectors = bdev_nr_sectors(ic->meta_dev->bdev);
5015 
5016 	if (!journal_sectors) {
5017 		journal_sectors = min((sector_t)DEFAULT_MAX_JOURNAL_SECTORS,
5018 				      ic->data_device_sectors >> DEFAULT_JOURNAL_SIZE_FACTOR);
5019 	}
5020 
5021 	if (!buffer_sectors)
5022 		buffer_sectors = 1;
5023 	ic->log2_buffer_sectors = min((int)__fls(buffer_sectors), 31 - SECTOR_SHIFT);
5024 
5025 	r = get_mac(&ic->internal_shash, &ic->internal_ahash, &ic->internal_hash_alg, &ti->error,
5026 		    "Invalid internal hash", "Error setting internal hash key");
5027 	if (r)
5028 		goto bad;
5029 	if (ic->internal_shash) {
5030 		ic->internal_hash = true;
5031 		ic->internal_hash_digestsize = crypto_shash_digestsize(ic->internal_shash);
5032 	}
5033 	if (ic->internal_ahash) {
5034 		ic->internal_hash = true;
5035 		ic->internal_hash_digestsize = crypto_ahash_digestsize(ic->internal_ahash);
5036 		r = mempool_init_kmalloc_pool(&ic->ahash_req_pool, AHASH_MEMPOOL,
5037 					      sizeof(struct ahash_request) + crypto_ahash_reqsize(ic->internal_ahash));
5038 		if (r) {
5039 			ti->error = "Cannot allocate mempool";
5040 			goto bad;
5041 		}
5042 	}
5043 
5044 	r = get_mac(&ic->journal_mac, NULL, &ic->journal_mac_alg, &ti->error,
5045 		    "Invalid journal mac", "Error setting journal mac key");
5046 	if (r)
5047 		goto bad;
5048 
5049 	if (!ic->tag_size) {
5050 		if (!ic->internal_hash) {
5051 			ti->error = "Unknown tag size";
5052 			r = -EINVAL;
5053 			goto bad;
5054 		}
5055 		ic->tag_size = ic->internal_hash_digestsize;
5056 	}
5057 	if (ic->tag_size > MAX_TAG_SIZE) {
5058 		ti->error = "Too big tag size";
5059 		r = -EINVAL;
5060 		goto bad;
5061 	}
5062 	if (!(ic->tag_size & (ic->tag_size - 1)))
5063 		ic->log2_tag_size = __ffs(ic->tag_size);
5064 	else
5065 		ic->log2_tag_size = -1;
5066 
5067 	if (ic->mode == 'I') {
5068 		struct blk_integrity *bi;
5069 		if (ic->meta_dev) {
5070 			r = -EINVAL;
5071 			ti->error = "Metadata device not supported in inline mode";
5072 			goto bad;
5073 		}
5074 		if (!ic->internal_hash_alg.alg_string) {
5075 			r = -EINVAL;
5076 			ti->error = "Internal hash not set in inline mode";
5077 			goto bad;
5078 		}
5079 		if (ic->journal_crypt_alg.alg_string || ic->journal_mac_alg.alg_string) {
5080 			r = -EINVAL;
5081 			ti->error = "Journal crypt not supported in inline mode";
5082 			goto bad;
5083 		}
5084 		if (ic->discard) {
5085 			r = -EINVAL;
5086 			ti->error = "Discards not supported in inline mode";
5087 			goto bad;
5088 		}
5089 		bi = blk_get_integrity(ic->dev->bdev->bd_disk);
5090 		if (!bi || bi->csum_type != BLK_INTEGRITY_CSUM_NONE) {
5091 			r = -EINVAL;
5092 			ti->error = "Integrity profile not supported";
5093 			goto bad;
5094 		}
5095 		/*printk("tag_size: %u, metadata_size: %u\n", bi->tag_size, bi->metadata_size);*/
5096 		if (bi->metadata_size < ic->tag_size) {
5097 			r = -EINVAL;
5098 			ti->error = "The integrity profile is smaller than tag size";
5099 			goto bad;
5100 		}
5101 		if ((unsigned long)bi->metadata_size > PAGE_SIZE / 2) {
5102 			r = -EINVAL;
5103 			ti->error = "Too big tuple size";
5104 			goto bad;
5105 		}
5106 		ic->tuple_size = bi->metadata_size;
5107 		if (1 << bi->interval_exp != ic->sectors_per_block << SECTOR_SHIFT) {
5108 			r = -EINVAL;
5109 			ti->error = "Integrity profile sector size mismatch";
5110 			goto bad;
5111 		}
5112 	}
5113 
5114 	if (ic->mode == 'B' && !ic->internal_hash) {
5115 		r = -EINVAL;
5116 		ti->error = "Bitmap mode can be only used with internal hash";
5117 		goto bad;
5118 	}
5119 
5120 	if (ic->discard && !ic->internal_hash) {
5121 		r = -EINVAL;
5122 		ti->error = "Discard can be only used with internal hash";
5123 		goto bad;
5124 	}
5125 	if (ic->discard_keyed && !ic->internal_hash_alg.key) {
5126 		r = -EINVAL;
5127 		ti->error = "Keyed discard can only be used with keyed internal hash";
5128 		goto bad;
5129 	}
5130 
5131 	ic->autocommit_jiffies = msecs_to_jiffies(sync_msec);
5132 	ic->autocommit_msec = sync_msec;
5133 	timer_setup(&ic->autocommit_timer, autocommit_fn, 0);
5134 
5135 	ic->io = dm_io_client_create();
5136 	if (IS_ERR(ic->io)) {
5137 		r = PTR_ERR(ic->io);
5138 		ic->io = NULL;
5139 		ti->error = "Cannot allocate dm io";
5140 		goto bad;
5141 	}
5142 
5143 	r = mempool_init_slab_pool(&ic->journal_io_mempool, JOURNAL_IO_MEMPOOL, journal_io_cache);
5144 	if (r) {
5145 		ti->error = "Cannot allocate mempool";
5146 		goto bad;
5147 	}
5148 
5149 	r = mempool_init_page_pool(&ic->recheck_pool, 1, ic->mode == 'I' ? 1 : 0);
5150 	if (r) {
5151 		ti->error = "Cannot allocate mempool";
5152 		goto bad;
5153 	}
5154 
5155 	if (ic->mode == 'I') {
5156 		r = bioset_init(&ic->recheck_bios, RECHECK_POOL_SIZE, 0, BIOSET_NEED_BVECS);
5157 		if (r) {
5158 			ti->error = "Cannot allocate bio set";
5159 			goto bad;
5160 		}
5161 		r = bioset_init(&ic->recalc_bios, 1, 0, BIOSET_NEED_BVECS);
5162 		if (r) {
5163 			ti->error = "Cannot allocate bio set";
5164 			goto bad;
5165 		}
5166 	}
5167 
5168 	ic->metadata_wq = alloc_workqueue("dm-integrity-metadata",
5169 					  WQ_MEM_RECLAIM | WQ_PERCPU,
5170 					  METADATA_WORKQUEUE_MAX_ACTIVE);
5171 	if (!ic->metadata_wq) {
5172 		ti->error = "Cannot allocate workqueue";
5173 		r = -ENOMEM;
5174 		goto bad;
5175 	}
5176 
5177 	/*
5178 	 * If this workqueue weren't ordered, it would cause bio reordering
5179 	 * and reduced performance.
5180 	 */
5181 	ic->wait_wq = alloc_ordered_workqueue("dm-integrity-wait", WQ_MEM_RECLAIM);
5182 	if (!ic->wait_wq) {
5183 		ti->error = "Cannot allocate workqueue";
5184 		r = -ENOMEM;
5185 		goto bad;
5186 	}
5187 
5188 	ic->offload_wq = alloc_workqueue("dm-integrity-offload",
5189 					  WQ_MEM_RECLAIM | WQ_PERCPU,
5190 					  METADATA_WORKQUEUE_MAX_ACTIVE);
5191 	if (!ic->offload_wq) {
5192 		ti->error = "Cannot allocate workqueue";
5193 		r = -ENOMEM;
5194 		goto bad;
5195 	}
5196 
5197 	ic->commit_wq = alloc_workqueue("dm-integrity-commit",
5198 					WQ_MEM_RECLAIM | WQ_PERCPU, 1);
5199 	if (!ic->commit_wq) {
5200 		ti->error = "Cannot allocate workqueue";
5201 		r = -ENOMEM;
5202 		goto bad;
5203 	}
5204 	INIT_WORK(&ic->commit_work, integrity_commit);
5205 
5206 	if (ic->mode == 'J' || ic->mode == 'B') {
5207 		ic->writer_wq = alloc_workqueue("dm-integrity-writer",
5208 						WQ_MEM_RECLAIM | WQ_PERCPU, 1);
5209 		if (!ic->writer_wq) {
5210 			ti->error = "Cannot allocate workqueue";
5211 			r = -ENOMEM;
5212 			goto bad;
5213 		}
5214 		INIT_WORK(&ic->writer_work, integrity_writer);
5215 	}
5216 
5217 	ic->sb = alloc_pages_exact(SB_SECTORS << SECTOR_SHIFT, GFP_KERNEL);
5218 	if (!ic->sb) {
5219 		r = -ENOMEM;
5220 		ti->error = "Cannot allocate superblock area";
5221 		goto bad;
5222 	}
5223 
5224 	r = sync_rw_sb(ic, REQ_OP_READ);
5225 	if (r) {
5226 		ti->error = "Error reading superblock";
5227 		goto bad;
5228 	}
5229 	should_write_sb = false;
5230 	if (memcmp(ic->sb->magic, SB_MAGIC, 8)) {
5231 		if (ic->mode != 'R') {
5232 			if (memchr_inv(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT)) {
5233 				r = -EINVAL;
5234 				ti->error = "The device is not initialized";
5235 				goto bad;
5236 			}
5237 		}
5238 
5239 		r = initialize_superblock(ic, journal_sectors, interleave_sectors);
5240 		if (r) {
5241 			ti->error = "Could not initialize superblock";
5242 			goto bad;
5243 		}
5244 		if (ic->mode != 'R')
5245 			should_write_sb = true;
5246 	}
5247 
5248 	if (!ic->sb->version || ic->sb->version > SB_VERSION_7) {
5249 		r = -EINVAL;
5250 		ti->error = "Unknown version";
5251 		goto bad;
5252 	}
5253 	if (!!(ic->sb->flags & cpu_to_le32(SB_FLAG_INLINE)) != (ic->mode == 'I')) {
5254 		r = -EINVAL;
5255 		ti->error = "Inline flag mismatch";
5256 		goto bad;
5257 	}
5258 	if (le16_to_cpu(ic->sb->integrity_tag_size) != ic->tag_size) {
5259 		r = -EINVAL;
5260 		ti->error = "Tag size doesn't match the information in superblock";
5261 		goto bad;
5262 	}
5263 	if (ic->sb->log2_sectors_per_block != __ffs(ic->sectors_per_block)) {
5264 		r = -EINVAL;
5265 		ti->error = "Block size doesn't match the information in superblock";
5266 		goto bad;
5267 	}
5268 	if (ic->mode != 'I') {
5269 		if (!le32_to_cpu(ic->sb->journal_sections)) {
5270 			r = -EINVAL;
5271 			ti->error = "Corrupted superblock, journal_sections is 0";
5272 			goto bad;
5273 		}
5274 	} else {
5275 		if (le32_to_cpu(ic->sb->journal_sections)) {
5276 			r = -EINVAL;
5277 			ti->error = "Corrupted superblock, journal_sections is not 0";
5278 			goto bad;
5279 		}
5280 	}
5281 	/* make sure that ti->max_io_len doesn't overflow */
5282 	if (!ic->meta_dev) {
5283 		if (ic->sb->log2_interleave_sectors < MIN_LOG2_INTERLEAVE_SECTORS ||
5284 		    ic->sb->log2_interleave_sectors > MAX_LOG2_INTERLEAVE_SECTORS) {
5285 			r = -EINVAL;
5286 			ti->error = "Invalid interleave_sectors in the superblock";
5287 			goto bad;
5288 		}
5289 	} else {
5290 		if (ic->sb->log2_interleave_sectors) {
5291 			r = -EINVAL;
5292 			ti->error = "Invalid interleave_sectors in the superblock";
5293 			goto bad;
5294 		}
5295 	}
5296 	if (!ic->discard_keyed && (ic->sb->flags & cpu_to_le32(SB_FLAG_DISCARD_KEYED))) {
5297 		r = -EINVAL;
5298 		ti->error = "Keyed discard cannot be disabled once enabled";
5299 		goto bad;
5300 	}
5301 	if (!!(ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC)) != !!ic->journal_mac_alg.alg_string) {
5302 		r = -EINVAL;
5303 		ti->error = "Journal mac mismatch";
5304 		goto bad;
5305 	}
5306 	if (ic->fix_hmac && !(ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) && ic->journal_mac_alg.key_string) {
5307 		/*
5308 		 * If this happens, it may be either because someone tampered
5309 		 * with the device or it may be due to a bug in the
5310 		 * integritysetup tool.
5311 		 *
5312 		 * In the latter case, upgrade to integritysetup 2.8.7 and use
5313 		 * the argument --integrity-legacy-hmac when using the open
5314 		 * command.
5315 		 */
5316 		r = -EINVAL;
5317 		ti->error = "fix_hmac is on the command line but not in the superblock";
5318 		goto bad;
5319 	}
5320 
5321 	get_provided_data_sectors(ic);
5322 	if (!ic->provided_data_sectors) {
5323 		r = -EINVAL;
5324 		ti->error = "The device is too small";
5325 		goto bad;
5326 	}
5327 
5328 try_smaller_buffer:
5329 	r = calculate_device_limits(ic);
5330 	if (r) {
5331 		if (ic->meta_dev) {
5332 			if (ic->log2_buffer_sectors > 3) {
5333 				ic->log2_buffer_sectors--;
5334 				goto try_smaller_buffer;
5335 			}
5336 		}
5337 		ti->error = "The device is too small";
5338 		goto bad;
5339 	}
5340 
5341 	if (log2_sectors_per_bitmap_bit < 0)
5342 		log2_sectors_per_bitmap_bit = __fls(DEFAULT_SECTORS_PER_BITMAP_BIT);
5343 	if (log2_sectors_per_bitmap_bit < ic->sb->log2_sectors_per_block)
5344 		log2_sectors_per_bitmap_bit = ic->sb->log2_sectors_per_block;
5345 
5346 	bits_in_journal = ((__u64)ic->journal_section_sectors * ic->journal_sections) << (SECTOR_SHIFT + 3);
5347 	if (bits_in_journal > UINT_MAX)
5348 		bits_in_journal = UINT_MAX;
5349 	if (bits_in_journal)
5350 		while (bits_in_journal < (ic->provided_data_sectors + ((sector_t)1 << log2_sectors_per_bitmap_bit) - 1) >> log2_sectors_per_bitmap_bit)
5351 			log2_sectors_per_bitmap_bit++;
5352 
5353 	log2_blocks_per_bitmap_bit = log2_sectors_per_bitmap_bit - ic->sb->log2_sectors_per_block;
5354 	ic->log2_blocks_per_bitmap_bit = log2_blocks_per_bitmap_bit;
5355 	if (should_write_sb)
5356 		ic->sb->log2_blocks_per_bitmap_bit = log2_blocks_per_bitmap_bit;
5357 
5358 	n_bitmap_bits = ((ic->provided_data_sectors >> ic->sb->log2_sectors_per_block)
5359 				+ (((sector_t)1 << log2_blocks_per_bitmap_bit) - 1)) >> log2_blocks_per_bitmap_bit;
5360 	ic->n_bitmap_blocks = DIV_ROUND_UP(n_bitmap_bits, BITMAP_BLOCK_SIZE * 8);
5361 
5362 	if (!ic->meta_dev)
5363 		ic->log2_buffer_sectors = min(ic->log2_buffer_sectors, (__u8)__ffs(ic->metadata_run));
5364 
5365 	if (ti->len > ic->provided_data_sectors) {
5366 		r = -EINVAL;
5367 		ti->error = "Not enough provided sectors for requested mapping size";
5368 		goto bad;
5369 	}
5370 
5371 	threshold = (__u64)ic->journal_entries * (100 - journal_watermark);
5372 	threshold += 50;
5373 	do_div(threshold, 100);
5374 	ic->free_sectors_threshold = threshold;
5375 
5376 	DEBUG_print("initialized:\n");
5377 	DEBUG_print("	integrity_tag_size %u\n", le16_to_cpu(ic->sb->integrity_tag_size));
5378 	DEBUG_print("	journal_entry_size %u\n", ic->journal_entry_size);
5379 	DEBUG_print("	journal_entries_per_sector %u\n", ic->journal_entries_per_sector);
5380 	DEBUG_print("	journal_section_entries %u\n", ic->journal_section_entries);
5381 	DEBUG_print("	journal_section_sectors %u\n", ic->journal_section_sectors);
5382 	DEBUG_print("	journal_sections %u\n", (unsigned int)le32_to_cpu(ic->sb->journal_sections));
5383 	DEBUG_print("	journal_entries %u\n", ic->journal_entries);
5384 	DEBUG_print("	log2_interleave_sectors %d\n", ic->sb->log2_interleave_sectors);
5385 	DEBUG_print("	data_device_sectors 0x%llx\n", bdev_nr_sectors(ic->dev->bdev));
5386 	DEBUG_print("	initial_sectors 0x%x\n", ic->initial_sectors);
5387 	DEBUG_print("	metadata_run 0x%x\n", ic->metadata_run);
5388 	DEBUG_print("	log2_metadata_run %d\n", ic->log2_metadata_run);
5389 	DEBUG_print("	provided_data_sectors 0x%llx (%llu)\n", ic->provided_data_sectors, ic->provided_data_sectors);
5390 	DEBUG_print("	log2_buffer_sectors %u\n", ic->log2_buffer_sectors);
5391 	DEBUG_print("	bits_in_journal %llu\n", bits_in_journal);
5392 
5393 	if (ic->recalculate_flag && !(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))) {
5394 		ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
5395 		ic->sb->recalc_sector = cpu_to_le64(0);
5396 	}
5397 
5398 	if (ic->internal_hash) {
5399 		ic->recalc_wq = alloc_workqueue("dm-integrity-recalc",
5400 						WQ_MEM_RECLAIM | WQ_PERCPU, 1);
5401 		if (!ic->recalc_wq) {
5402 			ti->error = "Cannot allocate workqueue";
5403 			r = -ENOMEM;
5404 			goto bad;
5405 		}
5406 		INIT_WORK(&ic->recalc_work, ic->mode == 'I' ? integrity_recalc_inline : integrity_recalc);
5407 	} else {
5408 		if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
5409 			ti->error = "Recalculate can only be specified with internal_hash";
5410 			r = -EINVAL;
5411 			goto bad;
5412 		}
5413 	}
5414 
5415 	if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
5416 	    le64_to_cpu(ic->sb->recalc_sector) < ic->provided_data_sectors &&
5417 	    dm_integrity_disable_recalculate(ic)) {
5418 		ti->error = "Recalculating with HMAC is disabled for security reasons - if you really need it, use the argument \"legacy_recalculate\"";
5419 		r = -EOPNOTSUPP;
5420 		goto bad;
5421 	}
5422 
5423 	ic->bufio = dm_bufio_client_create(ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev,
5424 			1U << (SECTOR_SHIFT + ic->log2_buffer_sectors), 1, 0, NULL, NULL, 0);
5425 	if (IS_ERR(ic->bufio)) {
5426 		r = PTR_ERR(ic->bufio);
5427 		ti->error = "Cannot initialize dm-bufio";
5428 		ic->bufio = NULL;
5429 		goto bad;
5430 	}
5431 	dm_bufio_set_sector_offset(ic->bufio, ic->start + ic->initial_sectors);
5432 
5433 	if (ic->mode != 'R' && ic->mode != 'I') {
5434 		r = create_journal(ic, &ti->error);
5435 		if (r)
5436 			goto bad;
5437 	}
5438 
5439 	if (ic->mode == 'B') {
5440 		unsigned int i;
5441 		unsigned int n_bitmap_pages = DIV_ROUND_UP(ic->n_bitmap_blocks, PAGE_SIZE / BITMAP_BLOCK_SIZE);
5442 
5443 		ic->recalc_bitmap = dm_integrity_alloc_page_list(n_bitmap_pages);
5444 		if (!ic->recalc_bitmap) {
5445 			ti->error = "Could not allocate memory for bitmap";
5446 			r = -ENOMEM;
5447 			goto bad;
5448 		}
5449 		ic->may_write_bitmap = dm_integrity_alloc_page_list(n_bitmap_pages);
5450 		if (!ic->may_write_bitmap) {
5451 			ti->error = "Could not allocate memory for bitmap";
5452 			r = -ENOMEM;
5453 			goto bad;
5454 		}
5455 		ic->bbs = kvmalloc_objs(struct bitmap_block_status,
5456 					ic->n_bitmap_blocks);
5457 		if (!ic->bbs) {
5458 			ti->error = "Could not allocate memory for bitmap";
5459 			r = -ENOMEM;
5460 			goto bad;
5461 		}
5462 		INIT_DELAYED_WORK(&ic->bitmap_flush_work, bitmap_flush_work);
5463 		for (i = 0; i < ic->n_bitmap_blocks; i++) {
5464 			struct bitmap_block_status *bbs = &ic->bbs[i];
5465 			unsigned int sector, pl_index, pl_offset;
5466 
5467 			INIT_WORK(&bbs->work, bitmap_block_work);
5468 			bbs->ic = ic;
5469 			bbs->idx = i;
5470 			bio_list_init(&bbs->bio_queue);
5471 			spin_lock_init(&bbs->bio_queue_lock);
5472 
5473 			sector = i * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT);
5474 			pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
5475 			pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
5476 
5477 			bbs->bitmap = lowmem_page_address(ic->journal[pl_index].page) + pl_offset;
5478 		}
5479 	}
5480 
5481 	if (should_write_sb) {
5482 		init_journal(ic, 0, ic->journal_sections, 0);
5483 		r = dm_integrity_failed(ic);
5484 		if (unlikely(r)) {
5485 			ti->error = "Error initializing journal";
5486 			goto bad;
5487 		}
5488 		r = sync_rw_sb(ic, REQ_OP_WRITE | REQ_FUA);
5489 		if (r) {
5490 			ti->error = "Error initializing superblock";
5491 			goto bad;
5492 		}
5493 		ic->just_formatted = true;
5494 	}
5495 
5496 	ic->sb_copy = kmemdup(ic->sb, sizeof(struct superblock), GFP_KERNEL);
5497 	if (!ic->sb_copy) {
5498 		ti->error = "Cannot allocate superblock copy";
5499 		r = -ENOMEM;
5500 		goto bad;
5501 	}
5502 
5503 	if (!ic->meta_dev && ic->mode != 'I') {
5504 		r = dm_set_target_max_io_len(ti, 1U << ic->sb->log2_interleave_sectors);
5505 		if (r)
5506 			goto bad;
5507 	}
5508 	if (ic->mode == 'B') {
5509 		unsigned int max_io_len;
5510 
5511 		max_io_len = ((sector_t)ic->sectors_per_block << ic->log2_blocks_per_bitmap_bit) * (BITMAP_BLOCK_SIZE * 8);
5512 		if (!max_io_len)
5513 			max_io_len = 1U << 31;
5514 		DEBUG_print("max_io_len: old %u, new %u\n", ti->max_io_len, max_io_len);
5515 		if (!ti->max_io_len || ti->max_io_len > max_io_len) {
5516 			r = dm_set_target_max_io_len(ti, max_io_len);
5517 			if (r)
5518 				goto bad;
5519 		}
5520 	}
5521 
5522 	ti->num_flush_bios = 1;
5523 	ti->flush_supported = true;
5524 	if (ic->discard)
5525 		ti->num_discard_bios = 1;
5526 
5527 	if (ic->mode == 'I')
5528 		ti->mempool_needs_integrity = true;
5529 
5530 	dm_audit_log_ctr(DM_MSG_PREFIX, ti, 1);
5531 	return 0;
5532 
5533 bad:
5534 	dm_audit_log_ctr(DM_MSG_PREFIX, ti, 0);
5535 	dm_integrity_dtr(ti);
5536 	return r;
5537 }
5538 
5539 static void dm_integrity_dtr(struct dm_target *ti)
5540 {
5541 	struct dm_integrity_c *ic = ti->private;
5542 
5543 	BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
5544 	BUG_ON(!list_empty(&ic->wait_list));
5545 
5546 	if (ic->mode == 'B' && ic->bitmap_flush_work.work.func)
5547 		cancel_delayed_work_sync(&ic->bitmap_flush_work);
5548 	if (ic->metadata_wq)
5549 		destroy_workqueue(ic->metadata_wq);
5550 	if (ic->wait_wq)
5551 		destroy_workqueue(ic->wait_wq);
5552 	if (ic->offload_wq)
5553 		destroy_workqueue(ic->offload_wq);
5554 	if (ic->commit_wq)
5555 		destroy_workqueue(ic->commit_wq);
5556 	if (ic->writer_wq)
5557 		destroy_workqueue(ic->writer_wq);
5558 	if (ic->recalc_wq)
5559 		destroy_workqueue(ic->recalc_wq);
5560 	kvfree(ic->bbs);
5561 	if (ic->bufio)
5562 		dm_bufio_client_destroy(ic->bufio);
5563 	mempool_free(ic->journal_ahash_req, &ic->ahash_req_pool);
5564 	mempool_exit(&ic->ahash_req_pool);
5565 	bioset_exit(&ic->recalc_bios);
5566 	bioset_exit(&ic->recheck_bios);
5567 	mempool_exit(&ic->recheck_pool);
5568 	mempool_exit(&ic->journal_io_mempool);
5569 	if (ic->io)
5570 		dm_io_client_destroy(ic->io);
5571 	if (ic->dev)
5572 		dm_put_device(ti, ic->dev);
5573 	if (ic->meta_dev)
5574 		dm_put_device(ti, ic->meta_dev);
5575 	dm_integrity_free_page_list(ic->journal);
5576 	dm_integrity_free_page_list(ic->journal_io);
5577 	dm_integrity_free_page_list(ic->journal_xor);
5578 	dm_integrity_free_page_list(ic->recalc_bitmap);
5579 	dm_integrity_free_page_list(ic->may_write_bitmap);
5580 	if (ic->journal_scatterlist)
5581 		dm_integrity_free_journal_scatterlist(ic, ic->journal_scatterlist);
5582 	if (ic->journal_io_scatterlist)
5583 		dm_integrity_free_journal_scatterlist(ic, ic->journal_io_scatterlist);
5584 	if (ic->sk_requests) {
5585 		unsigned int i;
5586 
5587 		for (i = 0; i < ic->journal_sections; i++) {
5588 			struct skcipher_request *req;
5589 
5590 			req = ic->sk_requests[i];
5591 			if (req) {
5592 				kfree_sensitive(req->iv);
5593 				skcipher_request_free(req);
5594 			}
5595 		}
5596 		kvfree(ic->sk_requests);
5597 	}
5598 	kvfree(ic->journal_tree);
5599 	if (ic->sb)
5600 		free_pages_exact(ic->sb, SB_SECTORS << SECTOR_SHIFT);
5601 	kfree(ic->sb_copy);
5602 
5603 	if (ic->internal_shash)
5604 		crypto_free_shash(ic->internal_shash);
5605 	if (ic->internal_ahash)
5606 		crypto_free_ahash(ic->internal_ahash);
5607 	free_alg(&ic->internal_hash_alg);
5608 
5609 	if (ic->journal_crypt)
5610 		crypto_free_skcipher(ic->journal_crypt);
5611 	free_alg(&ic->journal_crypt_alg);
5612 
5613 	if (ic->journal_mac)
5614 		crypto_free_shash(ic->journal_mac);
5615 	free_alg(&ic->journal_mac_alg);
5616 
5617 	kfree(ic);
5618 	dm_audit_log_dtr(DM_MSG_PREFIX, ti, 1);
5619 }
5620 
5621 static struct target_type integrity_target = {
5622 	.name			= "integrity",
5623 	.version		= {1, 15, 0},
5624 	.module			= THIS_MODULE,
5625 	.features		= DM_TARGET_SINGLETON | DM_TARGET_INTEGRITY,
5626 	.ctr			= dm_integrity_ctr,
5627 	.dtr			= dm_integrity_dtr,
5628 	.map			= dm_integrity_map,
5629 	.end_io			= dm_integrity_end_io,
5630 	.postsuspend		= dm_integrity_postsuspend,
5631 	.resume			= dm_integrity_resume,
5632 	.status			= dm_integrity_status,
5633 	.iterate_devices	= dm_integrity_iterate_devices,
5634 	.io_hints		= dm_integrity_io_hints,
5635 };
5636 
5637 static int __init dm_integrity_init(void)
5638 {
5639 	int r;
5640 
5641 	journal_io_cache = kmem_cache_create("integrity_journal_io",
5642 					     sizeof(struct journal_io), 0, 0, NULL);
5643 	if (!journal_io_cache) {
5644 		DMERR("can't allocate journal io cache");
5645 		return -ENOMEM;
5646 	}
5647 
5648 	r = dm_register_target(&integrity_target);
5649 	if (r < 0) {
5650 		kmem_cache_destroy(journal_io_cache);
5651 		return r;
5652 	}
5653 
5654 	return 0;
5655 }
5656 
5657 static void __exit dm_integrity_exit(void)
5658 {
5659 	dm_unregister_target(&integrity_target);
5660 	kmem_cache_destroy(journal_io_cache);
5661 }
5662 
5663 module_init(dm_integrity_init);
5664 module_exit(dm_integrity_exit);
5665 
5666 MODULE_AUTHOR("Milan Broz");
5667 MODULE_AUTHOR("Mikulas Patocka");
5668 MODULE_DESCRIPTION(DM_NAME " target for integrity tags extension");
5669 MODULE_LICENSE("GPL");
5670