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