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