xref: /openbmc/linux/drivers/md/dm-integrity.c (revision 752beb5e)
1 /*
2  * Copyright (C) 2016-2017 Red Hat, Inc. All rights reserved.
3  * Copyright (C) 2016-2017 Milan Broz
4  * Copyright (C) 2016-2017 Mikulas Patocka
5  *
6  * This file is released under the GPL.
7  */
8 
9 #include <linux/compiler.h>
10 #include <linux/module.h>
11 #include <linux/device-mapper.h>
12 #include <linux/dm-io.h>
13 #include <linux/vmalloc.h>
14 #include <linux/sort.h>
15 #include <linux/rbtree.h>
16 #include <linux/delay.h>
17 #include <linux/random.h>
18 #include <crypto/hash.h>
19 #include <crypto/skcipher.h>
20 #include <linux/async_tx.h>
21 #include <linux/dm-bufio.h>
22 
23 #define DM_MSG_PREFIX "integrity"
24 
25 #define DEFAULT_INTERLEAVE_SECTORS	32768
26 #define DEFAULT_JOURNAL_SIZE_FACTOR	7
27 #define DEFAULT_BUFFER_SECTORS		128
28 #define DEFAULT_JOURNAL_WATERMARK	50
29 #define DEFAULT_SYNC_MSEC		10000
30 #define DEFAULT_MAX_JOURNAL_SECTORS	131072
31 #define MIN_LOG2_INTERLEAVE_SECTORS	3
32 #define MAX_LOG2_INTERLEAVE_SECTORS	31
33 #define METADATA_WORKQUEUE_MAX_ACTIVE	16
34 #define RECALC_SECTORS			8192
35 #define RECALC_WRITE_SUPER		16
36 
37 /*
38  * Warning - DEBUG_PRINT prints security-sensitive data to the log,
39  * so it should not be enabled in the official kernel
40  */
41 //#define DEBUG_PRINT
42 //#define INTERNAL_VERIFY
43 
44 /*
45  * On disk structures
46  */
47 
48 #define SB_MAGIC			"integrt"
49 #define SB_VERSION_1			1
50 #define SB_VERSION_2			2
51 #define SB_SECTORS			8
52 #define MAX_SECTORS_PER_BLOCK		8
53 
54 struct superblock {
55 	__u8 magic[8];
56 	__u8 version;
57 	__u8 log2_interleave_sectors;
58 	__u16 integrity_tag_size;
59 	__u32 journal_sections;
60 	__u64 provided_data_sectors;	/* userspace uses this value */
61 	__u32 flags;
62 	__u8 log2_sectors_per_block;
63 	__u8 pad[3];
64 	__u64 recalc_sector;
65 };
66 
67 #define SB_FLAG_HAVE_JOURNAL_MAC	0x1
68 #define SB_FLAG_RECALCULATING		0x2
69 
70 #define	JOURNAL_ENTRY_ROUNDUP		8
71 
72 typedef __u64 commit_id_t;
73 #define JOURNAL_MAC_PER_SECTOR		8
74 
75 struct journal_entry {
76 	union {
77 		struct {
78 			__u32 sector_lo;
79 			__u32 sector_hi;
80 		} s;
81 		__u64 sector;
82 	} u;
83 	commit_id_t last_bytes[0];
84 	/* __u8 tag[0]; */
85 };
86 
87 #define journal_entry_tag(ic, je)		((__u8 *)&(je)->last_bytes[(ic)->sectors_per_block])
88 
89 #if BITS_PER_LONG == 64
90 #define journal_entry_set_sector(je, x)		do { smp_wmb(); WRITE_ONCE((je)->u.sector, cpu_to_le64(x)); } while (0)
91 #else
92 #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)
93 #endif
94 #define journal_entry_get_sector(je)		le64_to_cpu((je)->u.sector)
95 #define journal_entry_is_unused(je)		((je)->u.s.sector_hi == cpu_to_le32(-1))
96 #define journal_entry_set_unused(je)		do { ((je)->u.s.sector_hi = cpu_to_le32(-1)); } while (0)
97 #define journal_entry_is_inprogress(je)		((je)->u.s.sector_hi == cpu_to_le32(-2))
98 #define journal_entry_set_inprogress(je)	do { ((je)->u.s.sector_hi = cpu_to_le32(-2)); } while (0)
99 
100 #define JOURNAL_BLOCK_SECTORS		8
101 #define JOURNAL_SECTOR_DATA		((1 << SECTOR_SHIFT) - sizeof(commit_id_t))
102 #define JOURNAL_MAC_SIZE		(JOURNAL_MAC_PER_SECTOR * JOURNAL_BLOCK_SECTORS)
103 
104 struct journal_sector {
105 	__u8 entries[JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR];
106 	__u8 mac[JOURNAL_MAC_PER_SECTOR];
107 	commit_id_t commit_id;
108 };
109 
110 #define MAX_TAG_SIZE			(JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR - offsetof(struct journal_entry, last_bytes[MAX_SECTORS_PER_BLOCK]))
111 
112 #define METADATA_PADDING_SECTORS	8
113 
114 #define N_COMMIT_IDS			4
115 
116 static unsigned char prev_commit_seq(unsigned char seq)
117 {
118 	return (seq + N_COMMIT_IDS - 1) % N_COMMIT_IDS;
119 }
120 
121 static unsigned char next_commit_seq(unsigned char seq)
122 {
123 	return (seq + 1) % N_COMMIT_IDS;
124 }
125 
126 /*
127  * In-memory structures
128  */
129 
130 struct journal_node {
131 	struct rb_node node;
132 	sector_t sector;
133 };
134 
135 struct alg_spec {
136 	char *alg_string;
137 	char *key_string;
138 	__u8 *key;
139 	unsigned key_size;
140 };
141 
142 struct dm_integrity_c {
143 	struct dm_dev *dev;
144 	struct dm_dev *meta_dev;
145 	unsigned tag_size;
146 	__s8 log2_tag_size;
147 	sector_t start;
148 	mempool_t journal_io_mempool;
149 	struct dm_io_client *io;
150 	struct dm_bufio_client *bufio;
151 	struct workqueue_struct *metadata_wq;
152 	struct superblock *sb;
153 	unsigned journal_pages;
154 	struct page_list *journal;
155 	struct page_list *journal_io;
156 	struct page_list *journal_xor;
157 
158 	struct crypto_skcipher *journal_crypt;
159 	struct scatterlist **journal_scatterlist;
160 	struct scatterlist **journal_io_scatterlist;
161 	struct skcipher_request **sk_requests;
162 
163 	struct crypto_shash *journal_mac;
164 
165 	struct journal_node *journal_tree;
166 	struct rb_root journal_tree_root;
167 
168 	sector_t provided_data_sectors;
169 
170 	unsigned short journal_entry_size;
171 	unsigned char journal_entries_per_sector;
172 	unsigned char journal_section_entries;
173 	unsigned short journal_section_sectors;
174 	unsigned journal_sections;
175 	unsigned journal_entries;
176 	sector_t data_device_sectors;
177 	sector_t meta_device_sectors;
178 	unsigned initial_sectors;
179 	unsigned metadata_run;
180 	__s8 log2_metadata_run;
181 	__u8 log2_buffer_sectors;
182 	__u8 sectors_per_block;
183 
184 	unsigned char mode;
185 	int suspending;
186 
187 	int failed;
188 
189 	struct crypto_shash *internal_hash;
190 
191 	/* these variables are locked with endio_wait.lock */
192 	struct rb_root in_progress;
193 	struct list_head wait_list;
194 	wait_queue_head_t endio_wait;
195 	struct workqueue_struct *wait_wq;
196 
197 	unsigned char commit_seq;
198 	commit_id_t commit_ids[N_COMMIT_IDS];
199 
200 	unsigned committed_section;
201 	unsigned n_committed_sections;
202 
203 	unsigned uncommitted_section;
204 	unsigned n_uncommitted_sections;
205 
206 	unsigned free_section;
207 	unsigned char free_section_entry;
208 	unsigned free_sectors;
209 
210 	unsigned free_sectors_threshold;
211 
212 	struct workqueue_struct *commit_wq;
213 	struct work_struct commit_work;
214 
215 	struct workqueue_struct *writer_wq;
216 	struct work_struct writer_work;
217 
218 	struct workqueue_struct *recalc_wq;
219 	struct work_struct recalc_work;
220 	u8 *recalc_buffer;
221 	u8 *recalc_tags;
222 
223 	struct bio_list flush_bio_list;
224 
225 	unsigned long autocommit_jiffies;
226 	struct timer_list autocommit_timer;
227 	unsigned autocommit_msec;
228 
229 	wait_queue_head_t copy_to_journal_wait;
230 
231 	struct completion crypto_backoff;
232 
233 	bool journal_uptodate;
234 	bool just_formatted;
235 
236 	struct alg_spec internal_hash_alg;
237 	struct alg_spec journal_crypt_alg;
238 	struct alg_spec journal_mac_alg;
239 
240 	atomic64_t number_of_mismatches;
241 };
242 
243 struct dm_integrity_range {
244 	sector_t logical_sector;
245 	unsigned n_sectors;
246 	bool waiting;
247 	union {
248 		struct rb_node node;
249 		struct {
250 			struct task_struct *task;
251 			struct list_head wait_entry;
252 		};
253 	};
254 };
255 
256 struct dm_integrity_io {
257 	struct work_struct work;
258 
259 	struct dm_integrity_c *ic;
260 	bool write;
261 	bool fua;
262 
263 	struct dm_integrity_range range;
264 
265 	sector_t metadata_block;
266 	unsigned metadata_offset;
267 
268 	atomic_t in_flight;
269 	blk_status_t bi_status;
270 
271 	struct completion *completion;
272 
273 	struct gendisk *orig_bi_disk;
274 	u8 orig_bi_partno;
275 	bio_end_io_t *orig_bi_end_io;
276 	struct bio_integrity_payload *orig_bi_integrity;
277 	struct bvec_iter orig_bi_iter;
278 };
279 
280 struct journal_completion {
281 	struct dm_integrity_c *ic;
282 	atomic_t in_flight;
283 	struct completion comp;
284 };
285 
286 struct journal_io {
287 	struct dm_integrity_range range;
288 	struct journal_completion *comp;
289 };
290 
291 static struct kmem_cache *journal_io_cache;
292 
293 #define JOURNAL_IO_MEMPOOL	32
294 
295 #ifdef DEBUG_PRINT
296 #define DEBUG_print(x, ...)	printk(KERN_DEBUG x, ##__VA_ARGS__)
297 static void __DEBUG_bytes(__u8 *bytes, size_t len, const char *msg, ...)
298 {
299 	va_list args;
300 	va_start(args, msg);
301 	vprintk(msg, args);
302 	va_end(args);
303 	if (len)
304 		pr_cont(":");
305 	while (len) {
306 		pr_cont(" %02x", *bytes);
307 		bytes++;
308 		len--;
309 	}
310 	pr_cont("\n");
311 }
312 #define DEBUG_bytes(bytes, len, msg, ...)	__DEBUG_bytes(bytes, len, KERN_DEBUG msg, ##__VA_ARGS__)
313 #else
314 #define DEBUG_print(x, ...)			do { } while (0)
315 #define DEBUG_bytes(bytes, len, msg, ...)	do { } while (0)
316 #endif
317 
318 /*
319  * DM Integrity profile, protection is performed layer above (dm-crypt)
320  */
321 static const struct blk_integrity_profile dm_integrity_profile = {
322 	.name			= "DM-DIF-EXT-TAG",
323 	.generate_fn		= NULL,
324 	.verify_fn		= NULL,
325 };
326 
327 static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map);
328 static void integrity_bio_wait(struct work_struct *w);
329 static void dm_integrity_dtr(struct dm_target *ti);
330 
331 static void dm_integrity_io_error(struct dm_integrity_c *ic, const char *msg, int err)
332 {
333 	if (err == -EILSEQ)
334 		atomic64_inc(&ic->number_of_mismatches);
335 	if (!cmpxchg(&ic->failed, 0, err))
336 		DMERR("Error on %s: %d", msg, err);
337 }
338 
339 static int dm_integrity_failed(struct dm_integrity_c *ic)
340 {
341 	return READ_ONCE(ic->failed);
342 }
343 
344 static commit_id_t dm_integrity_commit_id(struct dm_integrity_c *ic, unsigned i,
345 					  unsigned j, unsigned char seq)
346 {
347 	/*
348 	 * Xor the number with section and sector, so that if a piece of
349 	 * journal is written at wrong place, it is detected.
350 	 */
351 	return ic->commit_ids[seq] ^ cpu_to_le64(((__u64)i << 32) ^ j);
352 }
353 
354 static void get_area_and_offset(struct dm_integrity_c *ic, sector_t data_sector,
355 				sector_t *area, sector_t *offset)
356 {
357 	if (!ic->meta_dev) {
358 		__u8 log2_interleave_sectors = ic->sb->log2_interleave_sectors;
359 		*area = data_sector >> log2_interleave_sectors;
360 		*offset = (unsigned)data_sector & ((1U << log2_interleave_sectors) - 1);
361 	} else {
362 		*area = 0;
363 		*offset = data_sector;
364 	}
365 }
366 
367 #define sector_to_block(ic, n)						\
368 do {									\
369 	BUG_ON((n) & (unsigned)((ic)->sectors_per_block - 1));		\
370 	(n) >>= (ic)->sb->log2_sectors_per_block;			\
371 } while (0)
372 
373 static __u64 get_metadata_sector_and_offset(struct dm_integrity_c *ic, sector_t area,
374 					    sector_t offset, unsigned *metadata_offset)
375 {
376 	__u64 ms;
377 	unsigned mo;
378 
379 	ms = area << ic->sb->log2_interleave_sectors;
380 	if (likely(ic->log2_metadata_run >= 0))
381 		ms += area << ic->log2_metadata_run;
382 	else
383 		ms += area * ic->metadata_run;
384 	ms >>= ic->log2_buffer_sectors;
385 
386 	sector_to_block(ic, offset);
387 
388 	if (likely(ic->log2_tag_size >= 0)) {
389 		ms += offset >> (SECTOR_SHIFT + ic->log2_buffer_sectors - ic->log2_tag_size);
390 		mo = (offset << ic->log2_tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
391 	} else {
392 		ms += (__u64)offset * ic->tag_size >> (SECTOR_SHIFT + ic->log2_buffer_sectors);
393 		mo = (offset * ic->tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
394 	}
395 	*metadata_offset = mo;
396 	return ms;
397 }
398 
399 static sector_t get_data_sector(struct dm_integrity_c *ic, sector_t area, sector_t offset)
400 {
401 	sector_t result;
402 
403 	if (ic->meta_dev)
404 		return offset;
405 
406 	result = area << ic->sb->log2_interleave_sectors;
407 	if (likely(ic->log2_metadata_run >= 0))
408 		result += (area + 1) << ic->log2_metadata_run;
409 	else
410 		result += (area + 1) * ic->metadata_run;
411 
412 	result += (sector_t)ic->initial_sectors + offset;
413 	result += ic->start;
414 
415 	return result;
416 }
417 
418 static void wraparound_section(struct dm_integrity_c *ic, unsigned *sec_ptr)
419 {
420 	if (unlikely(*sec_ptr >= ic->journal_sections))
421 		*sec_ptr -= ic->journal_sections;
422 }
423 
424 static void sb_set_version(struct dm_integrity_c *ic)
425 {
426 	if (ic->meta_dev || ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
427 		ic->sb->version = SB_VERSION_2;
428 	else
429 		ic->sb->version = SB_VERSION_1;
430 }
431 
432 static int sync_rw_sb(struct dm_integrity_c *ic, int op, int op_flags)
433 {
434 	struct dm_io_request io_req;
435 	struct dm_io_region io_loc;
436 
437 	io_req.bi_op = op;
438 	io_req.bi_op_flags = op_flags;
439 	io_req.mem.type = DM_IO_KMEM;
440 	io_req.mem.ptr.addr = ic->sb;
441 	io_req.notify.fn = NULL;
442 	io_req.client = ic->io;
443 	io_loc.bdev = ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev;
444 	io_loc.sector = ic->start;
445 	io_loc.count = SB_SECTORS;
446 
447 	return dm_io(&io_req, 1, &io_loc, NULL);
448 }
449 
450 static void access_journal_check(struct dm_integrity_c *ic, unsigned section, unsigned offset,
451 				 bool e, const char *function)
452 {
453 #if defined(CONFIG_DM_DEBUG) || defined(INTERNAL_VERIFY)
454 	unsigned limit = e ? ic->journal_section_entries : ic->journal_section_sectors;
455 
456 	if (unlikely(section >= ic->journal_sections) ||
457 	    unlikely(offset >= limit)) {
458 		printk(KERN_CRIT "%s: invalid access at (%u,%u), limit (%u,%u)\n",
459 			function, section, offset, ic->journal_sections, limit);
460 		BUG();
461 	}
462 #endif
463 }
464 
465 static void page_list_location(struct dm_integrity_c *ic, unsigned section, unsigned offset,
466 			       unsigned *pl_index, unsigned *pl_offset)
467 {
468 	unsigned sector;
469 
470 	access_journal_check(ic, section, offset, false, "page_list_location");
471 
472 	sector = section * ic->journal_section_sectors + offset;
473 
474 	*pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
475 	*pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
476 }
477 
478 static struct journal_sector *access_page_list(struct dm_integrity_c *ic, struct page_list *pl,
479 					       unsigned section, unsigned offset, unsigned *n_sectors)
480 {
481 	unsigned pl_index, pl_offset;
482 	char *va;
483 
484 	page_list_location(ic, section, offset, &pl_index, &pl_offset);
485 
486 	if (n_sectors)
487 		*n_sectors = (PAGE_SIZE - pl_offset) >> SECTOR_SHIFT;
488 
489 	va = lowmem_page_address(pl[pl_index].page);
490 
491 	return (struct journal_sector *)(va + pl_offset);
492 }
493 
494 static struct journal_sector *access_journal(struct dm_integrity_c *ic, unsigned section, unsigned offset)
495 {
496 	return access_page_list(ic, ic->journal, section, offset, NULL);
497 }
498 
499 static struct journal_entry *access_journal_entry(struct dm_integrity_c *ic, unsigned section, unsigned n)
500 {
501 	unsigned rel_sector, offset;
502 	struct journal_sector *js;
503 
504 	access_journal_check(ic, section, n, true, "access_journal_entry");
505 
506 	rel_sector = n % JOURNAL_BLOCK_SECTORS;
507 	offset = n / JOURNAL_BLOCK_SECTORS;
508 
509 	js = access_journal(ic, section, rel_sector);
510 	return (struct journal_entry *)((char *)js + offset * ic->journal_entry_size);
511 }
512 
513 static struct journal_sector *access_journal_data(struct dm_integrity_c *ic, unsigned section, unsigned n)
514 {
515 	n <<= ic->sb->log2_sectors_per_block;
516 
517 	n += JOURNAL_BLOCK_SECTORS;
518 
519 	access_journal_check(ic, section, n, false, "access_journal_data");
520 
521 	return access_journal(ic, section, n);
522 }
523 
524 static void section_mac(struct dm_integrity_c *ic, unsigned section, __u8 result[JOURNAL_MAC_SIZE])
525 {
526 	SHASH_DESC_ON_STACK(desc, ic->journal_mac);
527 	int r;
528 	unsigned j, size;
529 
530 	desc->tfm = ic->journal_mac;
531 
532 	r = crypto_shash_init(desc);
533 	if (unlikely(r)) {
534 		dm_integrity_io_error(ic, "crypto_shash_init", r);
535 		goto err;
536 	}
537 
538 	for (j = 0; j < ic->journal_section_entries; j++) {
539 		struct journal_entry *je = access_journal_entry(ic, section, j);
540 		r = crypto_shash_update(desc, (__u8 *)&je->u.sector, sizeof je->u.sector);
541 		if (unlikely(r)) {
542 			dm_integrity_io_error(ic, "crypto_shash_update", r);
543 			goto err;
544 		}
545 	}
546 
547 	size = crypto_shash_digestsize(ic->journal_mac);
548 
549 	if (likely(size <= JOURNAL_MAC_SIZE)) {
550 		r = crypto_shash_final(desc, result);
551 		if (unlikely(r)) {
552 			dm_integrity_io_error(ic, "crypto_shash_final", r);
553 			goto err;
554 		}
555 		memset(result + size, 0, JOURNAL_MAC_SIZE - size);
556 	} else {
557 		__u8 digest[HASH_MAX_DIGESTSIZE];
558 
559 		if (WARN_ON(size > sizeof(digest))) {
560 			dm_integrity_io_error(ic, "digest_size", -EINVAL);
561 			goto err;
562 		}
563 		r = crypto_shash_final(desc, digest);
564 		if (unlikely(r)) {
565 			dm_integrity_io_error(ic, "crypto_shash_final", r);
566 			goto err;
567 		}
568 		memcpy(result, digest, JOURNAL_MAC_SIZE);
569 	}
570 
571 	return;
572 err:
573 	memset(result, 0, JOURNAL_MAC_SIZE);
574 }
575 
576 static void rw_section_mac(struct dm_integrity_c *ic, unsigned section, bool wr)
577 {
578 	__u8 result[JOURNAL_MAC_SIZE];
579 	unsigned j;
580 
581 	if (!ic->journal_mac)
582 		return;
583 
584 	section_mac(ic, section, result);
585 
586 	for (j = 0; j < JOURNAL_BLOCK_SECTORS; j++) {
587 		struct journal_sector *js = access_journal(ic, section, j);
588 
589 		if (likely(wr))
590 			memcpy(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR);
591 		else {
592 			if (memcmp(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR))
593 				dm_integrity_io_error(ic, "journal mac", -EILSEQ);
594 		}
595 	}
596 }
597 
598 static void complete_journal_op(void *context)
599 {
600 	struct journal_completion *comp = context;
601 	BUG_ON(!atomic_read(&comp->in_flight));
602 	if (likely(atomic_dec_and_test(&comp->in_flight)))
603 		complete(&comp->comp);
604 }
605 
606 static void xor_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
607 			unsigned n_sections, struct journal_completion *comp)
608 {
609 	struct async_submit_ctl submit;
610 	size_t n_bytes = (size_t)(n_sections * ic->journal_section_sectors) << SECTOR_SHIFT;
611 	unsigned pl_index, pl_offset, section_index;
612 	struct page_list *source_pl, *target_pl;
613 
614 	if (likely(encrypt)) {
615 		source_pl = ic->journal;
616 		target_pl = ic->journal_io;
617 	} else {
618 		source_pl = ic->journal_io;
619 		target_pl = ic->journal;
620 	}
621 
622 	page_list_location(ic, section, 0, &pl_index, &pl_offset);
623 
624 	atomic_add(roundup(pl_offset + n_bytes, PAGE_SIZE) >> PAGE_SHIFT, &comp->in_flight);
625 
626 	init_async_submit(&submit, ASYNC_TX_XOR_ZERO_DST, NULL, complete_journal_op, comp, NULL);
627 
628 	section_index = pl_index;
629 
630 	do {
631 		size_t this_step;
632 		struct page *src_pages[2];
633 		struct page *dst_page;
634 
635 		while (unlikely(pl_index == section_index)) {
636 			unsigned dummy;
637 			if (likely(encrypt))
638 				rw_section_mac(ic, section, true);
639 			section++;
640 			n_sections--;
641 			if (!n_sections)
642 				break;
643 			page_list_location(ic, section, 0, &section_index, &dummy);
644 		}
645 
646 		this_step = min(n_bytes, (size_t)PAGE_SIZE - pl_offset);
647 		dst_page = target_pl[pl_index].page;
648 		src_pages[0] = source_pl[pl_index].page;
649 		src_pages[1] = ic->journal_xor[pl_index].page;
650 
651 		async_xor(dst_page, src_pages, pl_offset, 2, this_step, &submit);
652 
653 		pl_index++;
654 		pl_offset = 0;
655 		n_bytes -= this_step;
656 	} while (n_bytes);
657 
658 	BUG_ON(n_sections);
659 
660 	async_tx_issue_pending_all();
661 }
662 
663 static void complete_journal_encrypt(struct crypto_async_request *req, int err)
664 {
665 	struct journal_completion *comp = req->data;
666 	if (unlikely(err)) {
667 		if (likely(err == -EINPROGRESS)) {
668 			complete(&comp->ic->crypto_backoff);
669 			return;
670 		}
671 		dm_integrity_io_error(comp->ic, "asynchronous encrypt", err);
672 	}
673 	complete_journal_op(comp);
674 }
675 
676 static bool do_crypt(bool encrypt, struct skcipher_request *req, struct journal_completion *comp)
677 {
678 	int r;
679 	skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
680 				      complete_journal_encrypt, comp);
681 	if (likely(encrypt))
682 		r = crypto_skcipher_encrypt(req);
683 	else
684 		r = crypto_skcipher_decrypt(req);
685 	if (likely(!r))
686 		return false;
687 	if (likely(r == -EINPROGRESS))
688 		return true;
689 	if (likely(r == -EBUSY)) {
690 		wait_for_completion(&comp->ic->crypto_backoff);
691 		reinit_completion(&comp->ic->crypto_backoff);
692 		return true;
693 	}
694 	dm_integrity_io_error(comp->ic, "encrypt", r);
695 	return false;
696 }
697 
698 static void crypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
699 			  unsigned n_sections, struct journal_completion *comp)
700 {
701 	struct scatterlist **source_sg;
702 	struct scatterlist **target_sg;
703 
704 	atomic_add(2, &comp->in_flight);
705 
706 	if (likely(encrypt)) {
707 		source_sg = ic->journal_scatterlist;
708 		target_sg = ic->journal_io_scatterlist;
709 	} else {
710 		source_sg = ic->journal_io_scatterlist;
711 		target_sg = ic->journal_scatterlist;
712 	}
713 
714 	do {
715 		struct skcipher_request *req;
716 		unsigned ivsize;
717 		char *iv;
718 
719 		if (likely(encrypt))
720 			rw_section_mac(ic, section, true);
721 
722 		req = ic->sk_requests[section];
723 		ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
724 		iv = req->iv;
725 
726 		memcpy(iv, iv + ivsize, ivsize);
727 
728 		req->src = source_sg[section];
729 		req->dst = target_sg[section];
730 
731 		if (unlikely(do_crypt(encrypt, req, comp)))
732 			atomic_inc(&comp->in_flight);
733 
734 		section++;
735 		n_sections--;
736 	} while (n_sections);
737 
738 	atomic_dec(&comp->in_flight);
739 	complete_journal_op(comp);
740 }
741 
742 static void encrypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
743 			    unsigned n_sections, struct journal_completion *comp)
744 {
745 	if (ic->journal_xor)
746 		return xor_journal(ic, encrypt, section, n_sections, comp);
747 	else
748 		return crypt_journal(ic, encrypt, section, n_sections, comp);
749 }
750 
751 static void complete_journal_io(unsigned long error, void *context)
752 {
753 	struct journal_completion *comp = context;
754 	if (unlikely(error != 0))
755 		dm_integrity_io_error(comp->ic, "writing journal", -EIO);
756 	complete_journal_op(comp);
757 }
758 
759 static void rw_journal(struct dm_integrity_c *ic, int op, int op_flags, unsigned section,
760 		       unsigned n_sections, struct journal_completion *comp)
761 {
762 	struct dm_io_request io_req;
763 	struct dm_io_region io_loc;
764 	unsigned sector, n_sectors, pl_index, pl_offset;
765 	int r;
766 
767 	if (unlikely(dm_integrity_failed(ic))) {
768 		if (comp)
769 			complete_journal_io(-1UL, comp);
770 		return;
771 	}
772 
773 	sector = section * ic->journal_section_sectors;
774 	n_sectors = n_sections * ic->journal_section_sectors;
775 
776 	pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
777 	pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
778 
779 	io_req.bi_op = op;
780 	io_req.bi_op_flags = op_flags;
781 	io_req.mem.type = DM_IO_PAGE_LIST;
782 	if (ic->journal_io)
783 		io_req.mem.ptr.pl = &ic->journal_io[pl_index];
784 	else
785 		io_req.mem.ptr.pl = &ic->journal[pl_index];
786 	io_req.mem.offset = pl_offset;
787 	if (likely(comp != NULL)) {
788 		io_req.notify.fn = complete_journal_io;
789 		io_req.notify.context = comp;
790 	} else {
791 		io_req.notify.fn = NULL;
792 	}
793 	io_req.client = ic->io;
794 	io_loc.bdev = ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev;
795 	io_loc.sector = ic->start + SB_SECTORS + sector;
796 	io_loc.count = n_sectors;
797 
798 	r = dm_io(&io_req, 1, &io_loc, NULL);
799 	if (unlikely(r)) {
800 		dm_integrity_io_error(ic, op == REQ_OP_READ ? "reading journal" : "writing journal", r);
801 		if (comp) {
802 			WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
803 			complete_journal_io(-1UL, comp);
804 		}
805 	}
806 }
807 
808 static void write_journal(struct dm_integrity_c *ic, unsigned commit_start, unsigned commit_sections)
809 {
810 	struct journal_completion io_comp;
811 	struct journal_completion crypt_comp_1;
812 	struct journal_completion crypt_comp_2;
813 	unsigned i;
814 
815 	io_comp.ic = ic;
816 	init_completion(&io_comp.comp);
817 
818 	if (commit_start + commit_sections <= ic->journal_sections) {
819 		io_comp.in_flight = (atomic_t)ATOMIC_INIT(1);
820 		if (ic->journal_io) {
821 			crypt_comp_1.ic = ic;
822 			init_completion(&crypt_comp_1.comp);
823 			crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
824 			encrypt_journal(ic, true, commit_start, commit_sections, &crypt_comp_1);
825 			wait_for_completion_io(&crypt_comp_1.comp);
826 		} else {
827 			for (i = 0; i < commit_sections; i++)
828 				rw_section_mac(ic, commit_start + i, true);
829 		}
830 		rw_journal(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, commit_start,
831 			   commit_sections, &io_comp);
832 	} else {
833 		unsigned to_end;
834 		io_comp.in_flight = (atomic_t)ATOMIC_INIT(2);
835 		to_end = ic->journal_sections - commit_start;
836 		if (ic->journal_io) {
837 			crypt_comp_1.ic = ic;
838 			init_completion(&crypt_comp_1.comp);
839 			crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
840 			encrypt_journal(ic, true, commit_start, to_end, &crypt_comp_1);
841 			if (try_wait_for_completion(&crypt_comp_1.comp)) {
842 				rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
843 				reinit_completion(&crypt_comp_1.comp);
844 				crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
845 				encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_1);
846 				wait_for_completion_io(&crypt_comp_1.comp);
847 			} else {
848 				crypt_comp_2.ic = ic;
849 				init_completion(&crypt_comp_2.comp);
850 				crypt_comp_2.in_flight = (atomic_t)ATOMIC_INIT(0);
851 				encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_2);
852 				wait_for_completion_io(&crypt_comp_1.comp);
853 				rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
854 				wait_for_completion_io(&crypt_comp_2.comp);
855 			}
856 		} else {
857 			for (i = 0; i < to_end; i++)
858 				rw_section_mac(ic, commit_start + i, true);
859 			rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
860 			for (i = 0; i < commit_sections - to_end; i++)
861 				rw_section_mac(ic, i, true);
862 		}
863 		rw_journal(ic, REQ_OP_WRITE, REQ_FUA, 0, commit_sections - to_end, &io_comp);
864 	}
865 
866 	wait_for_completion_io(&io_comp.comp);
867 }
868 
869 static void copy_from_journal(struct dm_integrity_c *ic, unsigned section, unsigned offset,
870 			      unsigned n_sectors, sector_t target, io_notify_fn fn, void *data)
871 {
872 	struct dm_io_request io_req;
873 	struct dm_io_region io_loc;
874 	int r;
875 	unsigned sector, pl_index, pl_offset;
876 
877 	BUG_ON((target | n_sectors | offset) & (unsigned)(ic->sectors_per_block - 1));
878 
879 	if (unlikely(dm_integrity_failed(ic))) {
880 		fn(-1UL, data);
881 		return;
882 	}
883 
884 	sector = section * ic->journal_section_sectors + JOURNAL_BLOCK_SECTORS + offset;
885 
886 	pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
887 	pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
888 
889 	io_req.bi_op = REQ_OP_WRITE;
890 	io_req.bi_op_flags = 0;
891 	io_req.mem.type = DM_IO_PAGE_LIST;
892 	io_req.mem.ptr.pl = &ic->journal[pl_index];
893 	io_req.mem.offset = pl_offset;
894 	io_req.notify.fn = fn;
895 	io_req.notify.context = data;
896 	io_req.client = ic->io;
897 	io_loc.bdev = ic->dev->bdev;
898 	io_loc.sector = target;
899 	io_loc.count = n_sectors;
900 
901 	r = dm_io(&io_req, 1, &io_loc, NULL);
902 	if (unlikely(r)) {
903 		WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
904 		fn(-1UL, data);
905 	}
906 }
907 
908 static bool ranges_overlap(struct dm_integrity_range *range1, struct dm_integrity_range *range2)
909 {
910 	return range1->logical_sector < range2->logical_sector + range2->n_sectors &&
911 	       range1->logical_sector + range1->n_sectors > range2->logical_sector;
912 }
913 
914 static bool add_new_range(struct dm_integrity_c *ic, struct dm_integrity_range *new_range, bool check_waiting)
915 {
916 	struct rb_node **n = &ic->in_progress.rb_node;
917 	struct rb_node *parent;
918 
919 	BUG_ON((new_range->logical_sector | new_range->n_sectors) & (unsigned)(ic->sectors_per_block - 1));
920 
921 	if (likely(check_waiting)) {
922 		struct dm_integrity_range *range;
923 		list_for_each_entry(range, &ic->wait_list, wait_entry) {
924 			if (unlikely(ranges_overlap(range, new_range)))
925 				return false;
926 		}
927 	}
928 
929 	parent = NULL;
930 
931 	while (*n) {
932 		struct dm_integrity_range *range = container_of(*n, struct dm_integrity_range, node);
933 
934 		parent = *n;
935 		if (new_range->logical_sector + new_range->n_sectors <= range->logical_sector) {
936 			n = &range->node.rb_left;
937 		} else if (new_range->logical_sector >= range->logical_sector + range->n_sectors) {
938 			n = &range->node.rb_right;
939 		} else {
940 			return false;
941 		}
942 	}
943 
944 	rb_link_node(&new_range->node, parent, n);
945 	rb_insert_color(&new_range->node, &ic->in_progress);
946 
947 	return true;
948 }
949 
950 static void remove_range_unlocked(struct dm_integrity_c *ic, struct dm_integrity_range *range)
951 {
952 	rb_erase(&range->node, &ic->in_progress);
953 	while (unlikely(!list_empty(&ic->wait_list))) {
954 		struct dm_integrity_range *last_range =
955 			list_first_entry(&ic->wait_list, struct dm_integrity_range, wait_entry);
956 		struct task_struct *last_range_task;
957 		last_range_task = last_range->task;
958 		list_del(&last_range->wait_entry);
959 		if (!add_new_range(ic, last_range, false)) {
960 			last_range->task = last_range_task;
961 			list_add(&last_range->wait_entry, &ic->wait_list);
962 			break;
963 		}
964 		last_range->waiting = false;
965 		wake_up_process(last_range_task);
966 	}
967 }
968 
969 static void remove_range(struct dm_integrity_c *ic, struct dm_integrity_range *range)
970 {
971 	unsigned long flags;
972 
973 	spin_lock_irqsave(&ic->endio_wait.lock, flags);
974 	remove_range_unlocked(ic, range);
975 	spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
976 }
977 
978 static void wait_and_add_new_range(struct dm_integrity_c *ic, struct dm_integrity_range *new_range)
979 {
980 	new_range->waiting = true;
981 	list_add_tail(&new_range->wait_entry, &ic->wait_list);
982 	new_range->task = current;
983 	do {
984 		__set_current_state(TASK_UNINTERRUPTIBLE);
985 		spin_unlock_irq(&ic->endio_wait.lock);
986 		io_schedule();
987 		spin_lock_irq(&ic->endio_wait.lock);
988 	} while (unlikely(new_range->waiting));
989 }
990 
991 static void init_journal_node(struct journal_node *node)
992 {
993 	RB_CLEAR_NODE(&node->node);
994 	node->sector = (sector_t)-1;
995 }
996 
997 static void add_journal_node(struct dm_integrity_c *ic, struct journal_node *node, sector_t sector)
998 {
999 	struct rb_node **link;
1000 	struct rb_node *parent;
1001 
1002 	node->sector = sector;
1003 	BUG_ON(!RB_EMPTY_NODE(&node->node));
1004 
1005 	link = &ic->journal_tree_root.rb_node;
1006 	parent = NULL;
1007 
1008 	while (*link) {
1009 		struct journal_node *j;
1010 		parent = *link;
1011 		j = container_of(parent, struct journal_node, node);
1012 		if (sector < j->sector)
1013 			link = &j->node.rb_left;
1014 		else
1015 			link = &j->node.rb_right;
1016 	}
1017 
1018 	rb_link_node(&node->node, parent, link);
1019 	rb_insert_color(&node->node, &ic->journal_tree_root);
1020 }
1021 
1022 static void remove_journal_node(struct dm_integrity_c *ic, struct journal_node *node)
1023 {
1024 	BUG_ON(RB_EMPTY_NODE(&node->node));
1025 	rb_erase(&node->node, &ic->journal_tree_root);
1026 	init_journal_node(node);
1027 }
1028 
1029 #define NOT_FOUND	(-1U)
1030 
1031 static unsigned find_journal_node(struct dm_integrity_c *ic, sector_t sector, sector_t *next_sector)
1032 {
1033 	struct rb_node *n = ic->journal_tree_root.rb_node;
1034 	unsigned found = NOT_FOUND;
1035 	*next_sector = (sector_t)-1;
1036 	while (n) {
1037 		struct journal_node *j = container_of(n, struct journal_node, node);
1038 		if (sector == j->sector) {
1039 			found = j - ic->journal_tree;
1040 		}
1041 		if (sector < j->sector) {
1042 			*next_sector = j->sector;
1043 			n = j->node.rb_left;
1044 		} else {
1045 			n = j->node.rb_right;
1046 		}
1047 	}
1048 
1049 	return found;
1050 }
1051 
1052 static bool test_journal_node(struct dm_integrity_c *ic, unsigned pos, sector_t sector)
1053 {
1054 	struct journal_node *node, *next_node;
1055 	struct rb_node *next;
1056 
1057 	if (unlikely(pos >= ic->journal_entries))
1058 		return false;
1059 	node = &ic->journal_tree[pos];
1060 	if (unlikely(RB_EMPTY_NODE(&node->node)))
1061 		return false;
1062 	if (unlikely(node->sector != sector))
1063 		return false;
1064 
1065 	next = rb_next(&node->node);
1066 	if (unlikely(!next))
1067 		return true;
1068 
1069 	next_node = container_of(next, struct journal_node, node);
1070 	return next_node->sector != sector;
1071 }
1072 
1073 static bool find_newer_committed_node(struct dm_integrity_c *ic, struct journal_node *node)
1074 {
1075 	struct rb_node *next;
1076 	struct journal_node *next_node;
1077 	unsigned next_section;
1078 
1079 	BUG_ON(RB_EMPTY_NODE(&node->node));
1080 
1081 	next = rb_next(&node->node);
1082 	if (unlikely(!next))
1083 		return false;
1084 
1085 	next_node = container_of(next, struct journal_node, node);
1086 
1087 	if (next_node->sector != node->sector)
1088 		return false;
1089 
1090 	next_section = (unsigned)(next_node - ic->journal_tree) / ic->journal_section_entries;
1091 	if (next_section >= ic->committed_section &&
1092 	    next_section < ic->committed_section + ic->n_committed_sections)
1093 		return true;
1094 	if (next_section + ic->journal_sections < ic->committed_section + ic->n_committed_sections)
1095 		return true;
1096 
1097 	return false;
1098 }
1099 
1100 #define TAG_READ	0
1101 #define TAG_WRITE	1
1102 #define TAG_CMP		2
1103 
1104 static int dm_integrity_rw_tag(struct dm_integrity_c *ic, unsigned char *tag, sector_t *metadata_block,
1105 			       unsigned *metadata_offset, unsigned total_size, int op)
1106 {
1107 	do {
1108 		unsigned char *data, *dp;
1109 		struct dm_buffer *b;
1110 		unsigned to_copy;
1111 		int r;
1112 
1113 		r = dm_integrity_failed(ic);
1114 		if (unlikely(r))
1115 			return r;
1116 
1117 		data = dm_bufio_read(ic->bufio, *metadata_block, &b);
1118 		if (IS_ERR(data))
1119 			return PTR_ERR(data);
1120 
1121 		to_copy = min((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - *metadata_offset, total_size);
1122 		dp = data + *metadata_offset;
1123 		if (op == TAG_READ) {
1124 			memcpy(tag, dp, to_copy);
1125 		} else if (op == TAG_WRITE) {
1126 			memcpy(dp, tag, to_copy);
1127 			dm_bufio_mark_partial_buffer_dirty(b, *metadata_offset, *metadata_offset + to_copy);
1128 		} else  {
1129 			/* e.g.: op == TAG_CMP */
1130 			if (unlikely(memcmp(dp, tag, to_copy))) {
1131 				unsigned i;
1132 
1133 				for (i = 0; i < to_copy; i++) {
1134 					if (dp[i] != tag[i])
1135 						break;
1136 					total_size--;
1137 				}
1138 				dm_bufio_release(b);
1139 				return total_size;
1140 			}
1141 		}
1142 		dm_bufio_release(b);
1143 
1144 		tag += to_copy;
1145 		*metadata_offset += to_copy;
1146 		if (unlikely(*metadata_offset == 1U << SECTOR_SHIFT << ic->log2_buffer_sectors)) {
1147 			(*metadata_block)++;
1148 			*metadata_offset = 0;
1149 		}
1150 		total_size -= to_copy;
1151 	} while (unlikely(total_size));
1152 
1153 	return 0;
1154 }
1155 
1156 static void dm_integrity_flush_buffers(struct dm_integrity_c *ic)
1157 {
1158 	int r;
1159 	r = dm_bufio_write_dirty_buffers(ic->bufio);
1160 	if (unlikely(r))
1161 		dm_integrity_io_error(ic, "writing tags", r);
1162 }
1163 
1164 static void sleep_on_endio_wait(struct dm_integrity_c *ic)
1165 {
1166 	DECLARE_WAITQUEUE(wait, current);
1167 	__add_wait_queue(&ic->endio_wait, &wait);
1168 	__set_current_state(TASK_UNINTERRUPTIBLE);
1169 	spin_unlock_irq(&ic->endio_wait.lock);
1170 	io_schedule();
1171 	spin_lock_irq(&ic->endio_wait.lock);
1172 	__remove_wait_queue(&ic->endio_wait, &wait);
1173 }
1174 
1175 static void autocommit_fn(struct timer_list *t)
1176 {
1177 	struct dm_integrity_c *ic = from_timer(ic, t, autocommit_timer);
1178 
1179 	if (likely(!dm_integrity_failed(ic)))
1180 		queue_work(ic->commit_wq, &ic->commit_work);
1181 }
1182 
1183 static void schedule_autocommit(struct dm_integrity_c *ic)
1184 {
1185 	if (!timer_pending(&ic->autocommit_timer))
1186 		mod_timer(&ic->autocommit_timer, jiffies + ic->autocommit_jiffies);
1187 }
1188 
1189 static void submit_flush_bio(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
1190 {
1191 	struct bio *bio;
1192 	unsigned long flags;
1193 
1194 	spin_lock_irqsave(&ic->endio_wait.lock, flags);
1195 	bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1196 	bio_list_add(&ic->flush_bio_list, bio);
1197 	spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1198 
1199 	queue_work(ic->commit_wq, &ic->commit_work);
1200 }
1201 
1202 static void do_endio(struct dm_integrity_c *ic, struct bio *bio)
1203 {
1204 	int r = dm_integrity_failed(ic);
1205 	if (unlikely(r) && !bio->bi_status)
1206 		bio->bi_status = errno_to_blk_status(r);
1207 	bio_endio(bio);
1208 }
1209 
1210 static void do_endio_flush(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
1211 {
1212 	struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1213 
1214 	if (unlikely(dio->fua) && likely(!bio->bi_status) && likely(!dm_integrity_failed(ic)))
1215 		submit_flush_bio(ic, dio);
1216 	else
1217 		do_endio(ic, bio);
1218 }
1219 
1220 static void dec_in_flight(struct dm_integrity_io *dio)
1221 {
1222 	if (atomic_dec_and_test(&dio->in_flight)) {
1223 		struct dm_integrity_c *ic = dio->ic;
1224 		struct bio *bio;
1225 
1226 		remove_range(ic, &dio->range);
1227 
1228 		if (unlikely(dio->write))
1229 			schedule_autocommit(ic);
1230 
1231 		bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1232 
1233 		if (unlikely(dio->bi_status) && !bio->bi_status)
1234 			bio->bi_status = dio->bi_status;
1235 		if (likely(!bio->bi_status) && unlikely(bio_sectors(bio) != dio->range.n_sectors)) {
1236 			dio->range.logical_sector += dio->range.n_sectors;
1237 			bio_advance(bio, dio->range.n_sectors << SECTOR_SHIFT);
1238 			INIT_WORK(&dio->work, integrity_bio_wait);
1239 			queue_work(ic->wait_wq, &dio->work);
1240 			return;
1241 		}
1242 		do_endio_flush(ic, dio);
1243 	}
1244 }
1245 
1246 static void integrity_end_io(struct bio *bio)
1247 {
1248 	struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
1249 
1250 	bio->bi_iter = dio->orig_bi_iter;
1251 	bio->bi_disk = dio->orig_bi_disk;
1252 	bio->bi_partno = dio->orig_bi_partno;
1253 	if (dio->orig_bi_integrity) {
1254 		bio->bi_integrity = dio->orig_bi_integrity;
1255 		bio->bi_opf |= REQ_INTEGRITY;
1256 	}
1257 	bio->bi_end_io = dio->orig_bi_end_io;
1258 
1259 	if (dio->completion)
1260 		complete(dio->completion);
1261 
1262 	dec_in_flight(dio);
1263 }
1264 
1265 static void integrity_sector_checksum(struct dm_integrity_c *ic, sector_t sector,
1266 				      const char *data, char *result)
1267 {
1268 	__u64 sector_le = cpu_to_le64(sector);
1269 	SHASH_DESC_ON_STACK(req, ic->internal_hash);
1270 	int r;
1271 	unsigned digest_size;
1272 
1273 	req->tfm = ic->internal_hash;
1274 
1275 	r = crypto_shash_init(req);
1276 	if (unlikely(r < 0)) {
1277 		dm_integrity_io_error(ic, "crypto_shash_init", r);
1278 		goto failed;
1279 	}
1280 
1281 	r = crypto_shash_update(req, (const __u8 *)&sector_le, sizeof sector_le);
1282 	if (unlikely(r < 0)) {
1283 		dm_integrity_io_error(ic, "crypto_shash_update", r);
1284 		goto failed;
1285 	}
1286 
1287 	r = crypto_shash_update(req, data, ic->sectors_per_block << SECTOR_SHIFT);
1288 	if (unlikely(r < 0)) {
1289 		dm_integrity_io_error(ic, "crypto_shash_update", r);
1290 		goto failed;
1291 	}
1292 
1293 	r = crypto_shash_final(req, result);
1294 	if (unlikely(r < 0)) {
1295 		dm_integrity_io_error(ic, "crypto_shash_final", r);
1296 		goto failed;
1297 	}
1298 
1299 	digest_size = crypto_shash_digestsize(ic->internal_hash);
1300 	if (unlikely(digest_size < ic->tag_size))
1301 		memset(result + digest_size, 0, ic->tag_size - digest_size);
1302 
1303 	return;
1304 
1305 failed:
1306 	/* this shouldn't happen anyway, the hash functions have no reason to fail */
1307 	get_random_bytes(result, ic->tag_size);
1308 }
1309 
1310 static void integrity_metadata(struct work_struct *w)
1311 {
1312 	struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
1313 	struct dm_integrity_c *ic = dio->ic;
1314 
1315 	int r;
1316 
1317 	if (ic->internal_hash) {
1318 		struct bvec_iter iter;
1319 		struct bio_vec bv;
1320 		unsigned digest_size = crypto_shash_digestsize(ic->internal_hash);
1321 		struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1322 		char *checksums;
1323 		unsigned extra_space = unlikely(digest_size > ic->tag_size) ? digest_size - ic->tag_size : 0;
1324 		char checksums_onstack[HASH_MAX_DIGESTSIZE];
1325 		unsigned sectors_to_process = dio->range.n_sectors;
1326 		sector_t sector = dio->range.logical_sector;
1327 
1328 		if (unlikely(ic->mode == 'R'))
1329 			goto skip_io;
1330 
1331 		checksums = kmalloc((PAGE_SIZE >> SECTOR_SHIFT >> ic->sb->log2_sectors_per_block) * ic->tag_size + extra_space,
1332 				    GFP_NOIO | __GFP_NORETRY | __GFP_NOWARN);
1333 		if (!checksums) {
1334 			checksums = checksums_onstack;
1335 			if (WARN_ON(extra_space &&
1336 				    digest_size > sizeof(checksums_onstack))) {
1337 				r = -EINVAL;
1338 				goto error;
1339 			}
1340 		}
1341 
1342 		__bio_for_each_segment(bv, bio, iter, dio->orig_bi_iter) {
1343 			unsigned pos;
1344 			char *mem, *checksums_ptr;
1345 
1346 again:
1347 			mem = (char *)kmap_atomic(bv.bv_page) + bv.bv_offset;
1348 			pos = 0;
1349 			checksums_ptr = checksums;
1350 			do {
1351 				integrity_sector_checksum(ic, sector, mem + pos, checksums_ptr);
1352 				checksums_ptr += ic->tag_size;
1353 				sectors_to_process -= ic->sectors_per_block;
1354 				pos += ic->sectors_per_block << SECTOR_SHIFT;
1355 				sector += ic->sectors_per_block;
1356 			} while (pos < bv.bv_len && sectors_to_process && checksums != checksums_onstack);
1357 			kunmap_atomic(mem);
1358 
1359 			r = dm_integrity_rw_tag(ic, checksums, &dio->metadata_block, &dio->metadata_offset,
1360 						checksums_ptr - checksums, !dio->write ? TAG_CMP : TAG_WRITE);
1361 			if (unlikely(r)) {
1362 				if (r > 0) {
1363 					DMERR_LIMIT("Checksum failed at sector 0x%llx",
1364 						    (unsigned long long)(sector - ((r + ic->tag_size - 1) / ic->tag_size)));
1365 					r = -EILSEQ;
1366 					atomic64_inc(&ic->number_of_mismatches);
1367 				}
1368 				if (likely(checksums != checksums_onstack))
1369 					kfree(checksums);
1370 				goto error;
1371 			}
1372 
1373 			if (!sectors_to_process)
1374 				break;
1375 
1376 			if (unlikely(pos < bv.bv_len)) {
1377 				bv.bv_offset += pos;
1378 				bv.bv_len -= pos;
1379 				goto again;
1380 			}
1381 		}
1382 
1383 		if (likely(checksums != checksums_onstack))
1384 			kfree(checksums);
1385 	} else {
1386 		struct bio_integrity_payload *bip = dio->orig_bi_integrity;
1387 
1388 		if (bip) {
1389 			struct bio_vec biv;
1390 			struct bvec_iter iter;
1391 			unsigned data_to_process = dio->range.n_sectors;
1392 			sector_to_block(ic, data_to_process);
1393 			data_to_process *= ic->tag_size;
1394 
1395 			bip_for_each_vec(biv, bip, iter) {
1396 				unsigned char *tag;
1397 				unsigned this_len;
1398 
1399 				BUG_ON(PageHighMem(biv.bv_page));
1400 				tag = lowmem_page_address(biv.bv_page) + biv.bv_offset;
1401 				this_len = min(biv.bv_len, data_to_process);
1402 				r = dm_integrity_rw_tag(ic, tag, &dio->metadata_block, &dio->metadata_offset,
1403 							this_len, !dio->write ? TAG_READ : TAG_WRITE);
1404 				if (unlikely(r))
1405 					goto error;
1406 				data_to_process -= this_len;
1407 				if (!data_to_process)
1408 					break;
1409 			}
1410 		}
1411 	}
1412 skip_io:
1413 	dec_in_flight(dio);
1414 	return;
1415 error:
1416 	dio->bi_status = errno_to_blk_status(r);
1417 	dec_in_flight(dio);
1418 }
1419 
1420 static int dm_integrity_map(struct dm_target *ti, struct bio *bio)
1421 {
1422 	struct dm_integrity_c *ic = ti->private;
1423 	struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
1424 	struct bio_integrity_payload *bip;
1425 
1426 	sector_t area, offset;
1427 
1428 	dio->ic = ic;
1429 	dio->bi_status = 0;
1430 
1431 	if (unlikely(bio->bi_opf & REQ_PREFLUSH)) {
1432 		submit_flush_bio(ic, dio);
1433 		return DM_MAPIO_SUBMITTED;
1434 	}
1435 
1436 	dio->range.logical_sector = dm_target_offset(ti, bio->bi_iter.bi_sector);
1437 	dio->write = bio_op(bio) == REQ_OP_WRITE;
1438 	dio->fua = dio->write && bio->bi_opf & REQ_FUA;
1439 	if (unlikely(dio->fua)) {
1440 		/*
1441 		 * Don't pass down the FUA flag because we have to flush
1442 		 * disk cache anyway.
1443 		 */
1444 		bio->bi_opf &= ~REQ_FUA;
1445 	}
1446 	if (unlikely(dio->range.logical_sector + bio_sectors(bio) > ic->provided_data_sectors)) {
1447 		DMERR("Too big sector number: 0x%llx + 0x%x > 0x%llx",
1448 		      (unsigned long long)dio->range.logical_sector, bio_sectors(bio),
1449 		      (unsigned long long)ic->provided_data_sectors);
1450 		return DM_MAPIO_KILL;
1451 	}
1452 	if (unlikely((dio->range.logical_sector | bio_sectors(bio)) & (unsigned)(ic->sectors_per_block - 1))) {
1453 		DMERR("Bio not aligned on %u sectors: 0x%llx, 0x%x",
1454 		      ic->sectors_per_block,
1455 		      (unsigned long long)dio->range.logical_sector, bio_sectors(bio));
1456 		return DM_MAPIO_KILL;
1457 	}
1458 
1459 	if (ic->sectors_per_block > 1) {
1460 		struct bvec_iter iter;
1461 		struct bio_vec bv;
1462 		bio_for_each_segment(bv, bio, iter) {
1463 			if (unlikely(bv.bv_len & ((ic->sectors_per_block << SECTOR_SHIFT) - 1))) {
1464 				DMERR("Bio vector (%u,%u) is not aligned on %u-sector boundary",
1465 					bv.bv_offset, bv.bv_len, ic->sectors_per_block);
1466 				return DM_MAPIO_KILL;
1467 			}
1468 		}
1469 	}
1470 
1471 	bip = bio_integrity(bio);
1472 	if (!ic->internal_hash) {
1473 		if (bip) {
1474 			unsigned wanted_tag_size = bio_sectors(bio) >> ic->sb->log2_sectors_per_block;
1475 			if (ic->log2_tag_size >= 0)
1476 				wanted_tag_size <<= ic->log2_tag_size;
1477 			else
1478 				wanted_tag_size *= ic->tag_size;
1479 			if (unlikely(wanted_tag_size != bip->bip_iter.bi_size)) {
1480 				DMERR("Invalid integrity data size %u, expected %u", bip->bip_iter.bi_size, wanted_tag_size);
1481 				return DM_MAPIO_KILL;
1482 			}
1483 		}
1484 	} else {
1485 		if (unlikely(bip != NULL)) {
1486 			DMERR("Unexpected integrity data when using internal hash");
1487 			return DM_MAPIO_KILL;
1488 		}
1489 	}
1490 
1491 	if (unlikely(ic->mode == 'R') && unlikely(dio->write))
1492 		return DM_MAPIO_KILL;
1493 
1494 	get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
1495 	dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
1496 	bio->bi_iter.bi_sector = get_data_sector(ic, area, offset);
1497 
1498 	dm_integrity_map_continue(dio, true);
1499 	return DM_MAPIO_SUBMITTED;
1500 }
1501 
1502 static bool __journal_read_write(struct dm_integrity_io *dio, struct bio *bio,
1503 				 unsigned journal_section, unsigned journal_entry)
1504 {
1505 	struct dm_integrity_c *ic = dio->ic;
1506 	sector_t logical_sector;
1507 	unsigned n_sectors;
1508 
1509 	logical_sector = dio->range.logical_sector;
1510 	n_sectors = dio->range.n_sectors;
1511 	do {
1512 		struct bio_vec bv = bio_iovec(bio);
1513 		char *mem;
1514 
1515 		if (unlikely(bv.bv_len >> SECTOR_SHIFT > n_sectors))
1516 			bv.bv_len = n_sectors << SECTOR_SHIFT;
1517 		n_sectors -= bv.bv_len >> SECTOR_SHIFT;
1518 		bio_advance_iter(bio, &bio->bi_iter, bv.bv_len);
1519 retry_kmap:
1520 		mem = kmap_atomic(bv.bv_page);
1521 		if (likely(dio->write))
1522 			flush_dcache_page(bv.bv_page);
1523 
1524 		do {
1525 			struct journal_entry *je = access_journal_entry(ic, journal_section, journal_entry);
1526 
1527 			if (unlikely(!dio->write)) {
1528 				struct journal_sector *js;
1529 				char *mem_ptr;
1530 				unsigned s;
1531 
1532 				if (unlikely(journal_entry_is_inprogress(je))) {
1533 					flush_dcache_page(bv.bv_page);
1534 					kunmap_atomic(mem);
1535 
1536 					__io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
1537 					goto retry_kmap;
1538 				}
1539 				smp_rmb();
1540 				BUG_ON(journal_entry_get_sector(je) != logical_sector);
1541 				js = access_journal_data(ic, journal_section, journal_entry);
1542 				mem_ptr = mem + bv.bv_offset;
1543 				s = 0;
1544 				do {
1545 					memcpy(mem_ptr, js, JOURNAL_SECTOR_DATA);
1546 					*(commit_id_t *)(mem_ptr + JOURNAL_SECTOR_DATA) = je->last_bytes[s];
1547 					js++;
1548 					mem_ptr += 1 << SECTOR_SHIFT;
1549 				} while (++s < ic->sectors_per_block);
1550 #ifdef INTERNAL_VERIFY
1551 				if (ic->internal_hash) {
1552 					char checksums_onstack[max(HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
1553 
1554 					integrity_sector_checksum(ic, logical_sector, mem + bv.bv_offset, checksums_onstack);
1555 					if (unlikely(memcmp(checksums_onstack, journal_entry_tag(ic, je), ic->tag_size))) {
1556 						DMERR_LIMIT("Checksum failed when reading from journal, at sector 0x%llx",
1557 							    (unsigned long long)logical_sector);
1558 					}
1559 				}
1560 #endif
1561 			}
1562 
1563 			if (!ic->internal_hash) {
1564 				struct bio_integrity_payload *bip = bio_integrity(bio);
1565 				unsigned tag_todo = ic->tag_size;
1566 				char *tag_ptr = journal_entry_tag(ic, je);
1567 
1568 				if (bip) do {
1569 					struct bio_vec biv = bvec_iter_bvec(bip->bip_vec, bip->bip_iter);
1570 					unsigned tag_now = min(biv.bv_len, tag_todo);
1571 					char *tag_addr;
1572 					BUG_ON(PageHighMem(biv.bv_page));
1573 					tag_addr = lowmem_page_address(biv.bv_page) + biv.bv_offset;
1574 					if (likely(dio->write))
1575 						memcpy(tag_ptr, tag_addr, tag_now);
1576 					else
1577 						memcpy(tag_addr, tag_ptr, tag_now);
1578 					bvec_iter_advance(bip->bip_vec, &bip->bip_iter, tag_now);
1579 					tag_ptr += tag_now;
1580 					tag_todo -= tag_now;
1581 				} while (unlikely(tag_todo)); else {
1582 					if (likely(dio->write))
1583 						memset(tag_ptr, 0, tag_todo);
1584 				}
1585 			}
1586 
1587 			if (likely(dio->write)) {
1588 				struct journal_sector *js;
1589 				unsigned s;
1590 
1591 				js = access_journal_data(ic, journal_section, journal_entry);
1592 				memcpy(js, mem + bv.bv_offset, ic->sectors_per_block << SECTOR_SHIFT);
1593 
1594 				s = 0;
1595 				do {
1596 					je->last_bytes[s] = js[s].commit_id;
1597 				} while (++s < ic->sectors_per_block);
1598 
1599 				if (ic->internal_hash) {
1600 					unsigned digest_size = crypto_shash_digestsize(ic->internal_hash);
1601 					if (unlikely(digest_size > ic->tag_size)) {
1602 						char checksums_onstack[HASH_MAX_DIGESTSIZE];
1603 						integrity_sector_checksum(ic, logical_sector, (char *)js, checksums_onstack);
1604 						memcpy(journal_entry_tag(ic, je), checksums_onstack, ic->tag_size);
1605 					} else
1606 						integrity_sector_checksum(ic, logical_sector, (char *)js, journal_entry_tag(ic, je));
1607 				}
1608 
1609 				journal_entry_set_sector(je, logical_sector);
1610 			}
1611 			logical_sector += ic->sectors_per_block;
1612 
1613 			journal_entry++;
1614 			if (unlikely(journal_entry == ic->journal_section_entries)) {
1615 				journal_entry = 0;
1616 				journal_section++;
1617 				wraparound_section(ic, &journal_section);
1618 			}
1619 
1620 			bv.bv_offset += ic->sectors_per_block << SECTOR_SHIFT;
1621 		} while (bv.bv_len -= ic->sectors_per_block << SECTOR_SHIFT);
1622 
1623 		if (unlikely(!dio->write))
1624 			flush_dcache_page(bv.bv_page);
1625 		kunmap_atomic(mem);
1626 	} while (n_sectors);
1627 
1628 	if (likely(dio->write)) {
1629 		smp_mb();
1630 		if (unlikely(waitqueue_active(&ic->copy_to_journal_wait)))
1631 			wake_up(&ic->copy_to_journal_wait);
1632 		if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold) {
1633 			queue_work(ic->commit_wq, &ic->commit_work);
1634 		} else {
1635 			schedule_autocommit(ic);
1636 		}
1637 	} else {
1638 		remove_range(ic, &dio->range);
1639 	}
1640 
1641 	if (unlikely(bio->bi_iter.bi_size)) {
1642 		sector_t area, offset;
1643 
1644 		dio->range.logical_sector = logical_sector;
1645 		get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
1646 		dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
1647 		return true;
1648 	}
1649 
1650 	return false;
1651 }
1652 
1653 static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map)
1654 {
1655 	struct dm_integrity_c *ic = dio->ic;
1656 	struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1657 	unsigned journal_section, journal_entry;
1658 	unsigned journal_read_pos;
1659 	struct completion read_comp;
1660 	bool need_sync_io = ic->internal_hash && !dio->write;
1661 
1662 	if (need_sync_io && from_map) {
1663 		INIT_WORK(&dio->work, integrity_bio_wait);
1664 		queue_work(ic->metadata_wq, &dio->work);
1665 		return;
1666 	}
1667 
1668 lock_retry:
1669 	spin_lock_irq(&ic->endio_wait.lock);
1670 retry:
1671 	if (unlikely(dm_integrity_failed(ic))) {
1672 		spin_unlock_irq(&ic->endio_wait.lock);
1673 		do_endio(ic, bio);
1674 		return;
1675 	}
1676 	dio->range.n_sectors = bio_sectors(bio);
1677 	journal_read_pos = NOT_FOUND;
1678 	if (likely(ic->mode == 'J')) {
1679 		if (dio->write) {
1680 			unsigned next_entry, i, pos;
1681 			unsigned ws, we, range_sectors;
1682 
1683 			dio->range.n_sectors = min(dio->range.n_sectors,
1684 						   ic->free_sectors << ic->sb->log2_sectors_per_block);
1685 			if (unlikely(!dio->range.n_sectors)) {
1686 				if (from_map)
1687 					goto offload_to_thread;
1688 				sleep_on_endio_wait(ic);
1689 				goto retry;
1690 			}
1691 			range_sectors = dio->range.n_sectors >> ic->sb->log2_sectors_per_block;
1692 			ic->free_sectors -= range_sectors;
1693 			journal_section = ic->free_section;
1694 			journal_entry = ic->free_section_entry;
1695 
1696 			next_entry = ic->free_section_entry + range_sectors;
1697 			ic->free_section_entry = next_entry % ic->journal_section_entries;
1698 			ic->free_section += next_entry / ic->journal_section_entries;
1699 			ic->n_uncommitted_sections += next_entry / ic->journal_section_entries;
1700 			wraparound_section(ic, &ic->free_section);
1701 
1702 			pos = journal_section * ic->journal_section_entries + journal_entry;
1703 			ws = journal_section;
1704 			we = journal_entry;
1705 			i = 0;
1706 			do {
1707 				struct journal_entry *je;
1708 
1709 				add_journal_node(ic, &ic->journal_tree[pos], dio->range.logical_sector + i);
1710 				pos++;
1711 				if (unlikely(pos >= ic->journal_entries))
1712 					pos = 0;
1713 
1714 				je = access_journal_entry(ic, ws, we);
1715 				BUG_ON(!journal_entry_is_unused(je));
1716 				journal_entry_set_inprogress(je);
1717 				we++;
1718 				if (unlikely(we == ic->journal_section_entries)) {
1719 					we = 0;
1720 					ws++;
1721 					wraparound_section(ic, &ws);
1722 				}
1723 			} while ((i += ic->sectors_per_block) < dio->range.n_sectors);
1724 
1725 			spin_unlock_irq(&ic->endio_wait.lock);
1726 			goto journal_read_write;
1727 		} else {
1728 			sector_t next_sector;
1729 			journal_read_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
1730 			if (likely(journal_read_pos == NOT_FOUND)) {
1731 				if (unlikely(dio->range.n_sectors > next_sector - dio->range.logical_sector))
1732 					dio->range.n_sectors = next_sector - dio->range.logical_sector;
1733 			} else {
1734 				unsigned i;
1735 				unsigned jp = journal_read_pos + 1;
1736 				for (i = ic->sectors_per_block; i < dio->range.n_sectors; i += ic->sectors_per_block, jp++) {
1737 					if (!test_journal_node(ic, jp, dio->range.logical_sector + i))
1738 						break;
1739 				}
1740 				dio->range.n_sectors = i;
1741 			}
1742 		}
1743 	}
1744 	if (unlikely(!add_new_range(ic, &dio->range, true))) {
1745 		/*
1746 		 * We must not sleep in the request routine because it could
1747 		 * stall bios on current->bio_list.
1748 		 * So, we offload the bio to a workqueue if we have to sleep.
1749 		 */
1750 		if (from_map) {
1751 offload_to_thread:
1752 			spin_unlock_irq(&ic->endio_wait.lock);
1753 			INIT_WORK(&dio->work, integrity_bio_wait);
1754 			queue_work(ic->wait_wq, &dio->work);
1755 			return;
1756 		}
1757 		wait_and_add_new_range(ic, &dio->range);
1758 	}
1759 	spin_unlock_irq(&ic->endio_wait.lock);
1760 
1761 	if (unlikely(journal_read_pos != NOT_FOUND)) {
1762 		journal_section = journal_read_pos / ic->journal_section_entries;
1763 		journal_entry = journal_read_pos % ic->journal_section_entries;
1764 		goto journal_read_write;
1765 	}
1766 
1767 	dio->in_flight = (atomic_t)ATOMIC_INIT(2);
1768 
1769 	if (need_sync_io) {
1770 		init_completion(&read_comp);
1771 		dio->completion = &read_comp;
1772 	} else
1773 		dio->completion = NULL;
1774 
1775 	dio->orig_bi_iter = bio->bi_iter;
1776 
1777 	dio->orig_bi_disk = bio->bi_disk;
1778 	dio->orig_bi_partno = bio->bi_partno;
1779 	bio_set_dev(bio, ic->dev->bdev);
1780 
1781 	dio->orig_bi_integrity = bio_integrity(bio);
1782 	bio->bi_integrity = NULL;
1783 	bio->bi_opf &= ~REQ_INTEGRITY;
1784 
1785 	dio->orig_bi_end_io = bio->bi_end_io;
1786 	bio->bi_end_io = integrity_end_io;
1787 
1788 	bio->bi_iter.bi_size = dio->range.n_sectors << SECTOR_SHIFT;
1789 	generic_make_request(bio);
1790 
1791 	if (need_sync_io) {
1792 		wait_for_completion_io(&read_comp);
1793 		if (unlikely(ic->recalc_wq != NULL) &&
1794 		    ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
1795 		    dio->range.logical_sector + dio->range.n_sectors > le64_to_cpu(ic->sb->recalc_sector))
1796 			goto skip_check;
1797 		if (likely(!bio->bi_status))
1798 			integrity_metadata(&dio->work);
1799 		else
1800 skip_check:
1801 			dec_in_flight(dio);
1802 
1803 	} else {
1804 		INIT_WORK(&dio->work, integrity_metadata);
1805 		queue_work(ic->metadata_wq, &dio->work);
1806 	}
1807 
1808 	return;
1809 
1810 journal_read_write:
1811 	if (unlikely(__journal_read_write(dio, bio, journal_section, journal_entry)))
1812 		goto lock_retry;
1813 
1814 	do_endio_flush(ic, dio);
1815 }
1816 
1817 
1818 static void integrity_bio_wait(struct work_struct *w)
1819 {
1820 	struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
1821 
1822 	dm_integrity_map_continue(dio, false);
1823 }
1824 
1825 static void pad_uncommitted(struct dm_integrity_c *ic)
1826 {
1827 	if (ic->free_section_entry) {
1828 		ic->free_sectors -= ic->journal_section_entries - ic->free_section_entry;
1829 		ic->free_section_entry = 0;
1830 		ic->free_section++;
1831 		wraparound_section(ic, &ic->free_section);
1832 		ic->n_uncommitted_sections++;
1833 	}
1834 	WARN_ON(ic->journal_sections * ic->journal_section_entries !=
1835 		(ic->n_uncommitted_sections + ic->n_committed_sections) * ic->journal_section_entries + ic->free_sectors);
1836 }
1837 
1838 static void integrity_commit(struct work_struct *w)
1839 {
1840 	struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, commit_work);
1841 	unsigned commit_start, commit_sections;
1842 	unsigned i, j, n;
1843 	struct bio *flushes;
1844 
1845 	del_timer(&ic->autocommit_timer);
1846 
1847 	spin_lock_irq(&ic->endio_wait.lock);
1848 	flushes = bio_list_get(&ic->flush_bio_list);
1849 	if (unlikely(ic->mode != 'J')) {
1850 		spin_unlock_irq(&ic->endio_wait.lock);
1851 		dm_integrity_flush_buffers(ic);
1852 		goto release_flush_bios;
1853 	}
1854 
1855 	pad_uncommitted(ic);
1856 	commit_start = ic->uncommitted_section;
1857 	commit_sections = ic->n_uncommitted_sections;
1858 	spin_unlock_irq(&ic->endio_wait.lock);
1859 
1860 	if (!commit_sections)
1861 		goto release_flush_bios;
1862 
1863 	i = commit_start;
1864 	for (n = 0; n < commit_sections; n++) {
1865 		for (j = 0; j < ic->journal_section_entries; j++) {
1866 			struct journal_entry *je;
1867 			je = access_journal_entry(ic, i, j);
1868 			io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
1869 		}
1870 		for (j = 0; j < ic->journal_section_sectors; j++) {
1871 			struct journal_sector *js;
1872 			js = access_journal(ic, i, j);
1873 			js->commit_id = dm_integrity_commit_id(ic, i, j, ic->commit_seq);
1874 		}
1875 		i++;
1876 		if (unlikely(i >= ic->journal_sections))
1877 			ic->commit_seq = next_commit_seq(ic->commit_seq);
1878 		wraparound_section(ic, &i);
1879 	}
1880 	smp_rmb();
1881 
1882 	write_journal(ic, commit_start, commit_sections);
1883 
1884 	spin_lock_irq(&ic->endio_wait.lock);
1885 	ic->uncommitted_section += commit_sections;
1886 	wraparound_section(ic, &ic->uncommitted_section);
1887 	ic->n_uncommitted_sections -= commit_sections;
1888 	ic->n_committed_sections += commit_sections;
1889 	spin_unlock_irq(&ic->endio_wait.lock);
1890 
1891 	if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold)
1892 		queue_work(ic->writer_wq, &ic->writer_work);
1893 
1894 release_flush_bios:
1895 	while (flushes) {
1896 		struct bio *next = flushes->bi_next;
1897 		flushes->bi_next = NULL;
1898 		do_endio(ic, flushes);
1899 		flushes = next;
1900 	}
1901 }
1902 
1903 static void complete_copy_from_journal(unsigned long error, void *context)
1904 {
1905 	struct journal_io *io = context;
1906 	struct journal_completion *comp = io->comp;
1907 	struct dm_integrity_c *ic = comp->ic;
1908 	remove_range(ic, &io->range);
1909 	mempool_free(io, &ic->journal_io_mempool);
1910 	if (unlikely(error != 0))
1911 		dm_integrity_io_error(ic, "copying from journal", -EIO);
1912 	complete_journal_op(comp);
1913 }
1914 
1915 static void restore_last_bytes(struct dm_integrity_c *ic, struct journal_sector *js,
1916 			       struct journal_entry *je)
1917 {
1918 	unsigned s = 0;
1919 	do {
1920 		js->commit_id = je->last_bytes[s];
1921 		js++;
1922 	} while (++s < ic->sectors_per_block);
1923 }
1924 
1925 static void do_journal_write(struct dm_integrity_c *ic, unsigned write_start,
1926 			     unsigned write_sections, bool from_replay)
1927 {
1928 	unsigned i, j, n;
1929 	struct journal_completion comp;
1930 	struct blk_plug plug;
1931 
1932 	blk_start_plug(&plug);
1933 
1934 	comp.ic = ic;
1935 	comp.in_flight = (atomic_t)ATOMIC_INIT(1);
1936 	init_completion(&comp.comp);
1937 
1938 	i = write_start;
1939 	for (n = 0; n < write_sections; n++, i++, wraparound_section(ic, &i)) {
1940 #ifndef INTERNAL_VERIFY
1941 		if (unlikely(from_replay))
1942 #endif
1943 			rw_section_mac(ic, i, false);
1944 		for (j = 0; j < ic->journal_section_entries; j++) {
1945 			struct journal_entry *je = access_journal_entry(ic, i, j);
1946 			sector_t sec, area, offset;
1947 			unsigned k, l, next_loop;
1948 			sector_t metadata_block;
1949 			unsigned metadata_offset;
1950 			struct journal_io *io;
1951 
1952 			if (journal_entry_is_unused(je))
1953 				continue;
1954 			BUG_ON(unlikely(journal_entry_is_inprogress(je)) && !from_replay);
1955 			sec = journal_entry_get_sector(je);
1956 			if (unlikely(from_replay)) {
1957 				if (unlikely(sec & (unsigned)(ic->sectors_per_block - 1))) {
1958 					dm_integrity_io_error(ic, "invalid sector in journal", -EIO);
1959 					sec &= ~(sector_t)(ic->sectors_per_block - 1);
1960 				}
1961 			}
1962 			get_area_and_offset(ic, sec, &area, &offset);
1963 			restore_last_bytes(ic, access_journal_data(ic, i, j), je);
1964 			for (k = j + 1; k < ic->journal_section_entries; k++) {
1965 				struct journal_entry *je2 = access_journal_entry(ic, i, k);
1966 				sector_t sec2, area2, offset2;
1967 				if (journal_entry_is_unused(je2))
1968 					break;
1969 				BUG_ON(unlikely(journal_entry_is_inprogress(je2)) && !from_replay);
1970 				sec2 = journal_entry_get_sector(je2);
1971 				get_area_and_offset(ic, sec2, &area2, &offset2);
1972 				if (area2 != area || offset2 != offset + ((k - j) << ic->sb->log2_sectors_per_block))
1973 					break;
1974 				restore_last_bytes(ic, access_journal_data(ic, i, k), je2);
1975 			}
1976 			next_loop = k - 1;
1977 
1978 			io = mempool_alloc(&ic->journal_io_mempool, GFP_NOIO);
1979 			io->comp = &comp;
1980 			io->range.logical_sector = sec;
1981 			io->range.n_sectors = (k - j) << ic->sb->log2_sectors_per_block;
1982 
1983 			spin_lock_irq(&ic->endio_wait.lock);
1984 			if (unlikely(!add_new_range(ic, &io->range, true)))
1985 				wait_and_add_new_range(ic, &io->range);
1986 
1987 			if (likely(!from_replay)) {
1988 				struct journal_node *section_node = &ic->journal_tree[i * ic->journal_section_entries];
1989 
1990 				/* don't write if there is newer committed sector */
1991 				while (j < k && find_newer_committed_node(ic, &section_node[j])) {
1992 					struct journal_entry *je2 = access_journal_entry(ic, i, j);
1993 
1994 					journal_entry_set_unused(je2);
1995 					remove_journal_node(ic, &section_node[j]);
1996 					j++;
1997 					sec += ic->sectors_per_block;
1998 					offset += ic->sectors_per_block;
1999 				}
2000 				while (j < k && find_newer_committed_node(ic, &section_node[k - 1])) {
2001 					struct journal_entry *je2 = access_journal_entry(ic, i, k - 1);
2002 
2003 					journal_entry_set_unused(je2);
2004 					remove_journal_node(ic, &section_node[k - 1]);
2005 					k--;
2006 				}
2007 				if (j == k) {
2008 					remove_range_unlocked(ic, &io->range);
2009 					spin_unlock_irq(&ic->endio_wait.lock);
2010 					mempool_free(io, &ic->journal_io_mempool);
2011 					goto skip_io;
2012 				}
2013 				for (l = j; l < k; l++) {
2014 					remove_journal_node(ic, &section_node[l]);
2015 				}
2016 			}
2017 			spin_unlock_irq(&ic->endio_wait.lock);
2018 
2019 			metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
2020 			for (l = j; l < k; l++) {
2021 				int r;
2022 				struct journal_entry *je2 = access_journal_entry(ic, i, l);
2023 
2024 				if (
2025 #ifndef INTERNAL_VERIFY
2026 				    unlikely(from_replay) &&
2027 #endif
2028 				    ic->internal_hash) {
2029 					char test_tag[max_t(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
2030 
2031 					integrity_sector_checksum(ic, sec + ((l - j) << ic->sb->log2_sectors_per_block),
2032 								  (char *)access_journal_data(ic, i, l), test_tag);
2033 					if (unlikely(memcmp(test_tag, journal_entry_tag(ic, je2), ic->tag_size)))
2034 						dm_integrity_io_error(ic, "tag mismatch when replaying journal", -EILSEQ);
2035 				}
2036 
2037 				journal_entry_set_unused(je2);
2038 				r = dm_integrity_rw_tag(ic, journal_entry_tag(ic, je2), &metadata_block, &metadata_offset,
2039 							ic->tag_size, TAG_WRITE);
2040 				if (unlikely(r)) {
2041 					dm_integrity_io_error(ic, "reading tags", r);
2042 				}
2043 			}
2044 
2045 			atomic_inc(&comp.in_flight);
2046 			copy_from_journal(ic, i, j << ic->sb->log2_sectors_per_block,
2047 					  (k - j) << ic->sb->log2_sectors_per_block,
2048 					  get_data_sector(ic, area, offset),
2049 					  complete_copy_from_journal, io);
2050 skip_io:
2051 			j = next_loop;
2052 		}
2053 	}
2054 
2055 	dm_bufio_write_dirty_buffers_async(ic->bufio);
2056 
2057 	blk_finish_plug(&plug);
2058 
2059 	complete_journal_op(&comp);
2060 	wait_for_completion_io(&comp.comp);
2061 
2062 	dm_integrity_flush_buffers(ic);
2063 }
2064 
2065 static void integrity_writer(struct work_struct *w)
2066 {
2067 	struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, writer_work);
2068 	unsigned write_start, write_sections;
2069 
2070 	unsigned prev_free_sectors;
2071 
2072 	/* the following test is not needed, but it tests the replay code */
2073 	if (READ_ONCE(ic->suspending) && !ic->meta_dev)
2074 		return;
2075 
2076 	spin_lock_irq(&ic->endio_wait.lock);
2077 	write_start = ic->committed_section;
2078 	write_sections = ic->n_committed_sections;
2079 	spin_unlock_irq(&ic->endio_wait.lock);
2080 
2081 	if (!write_sections)
2082 		return;
2083 
2084 	do_journal_write(ic, write_start, write_sections, false);
2085 
2086 	spin_lock_irq(&ic->endio_wait.lock);
2087 
2088 	ic->committed_section += write_sections;
2089 	wraparound_section(ic, &ic->committed_section);
2090 	ic->n_committed_sections -= write_sections;
2091 
2092 	prev_free_sectors = ic->free_sectors;
2093 	ic->free_sectors += write_sections * ic->journal_section_entries;
2094 	if (unlikely(!prev_free_sectors))
2095 		wake_up_locked(&ic->endio_wait);
2096 
2097 	spin_unlock_irq(&ic->endio_wait.lock);
2098 }
2099 
2100 static void recalc_write_super(struct dm_integrity_c *ic)
2101 {
2102 	int r;
2103 
2104 	dm_integrity_flush_buffers(ic);
2105 	if (dm_integrity_failed(ic))
2106 		return;
2107 
2108 	sb_set_version(ic);
2109 	r = sync_rw_sb(ic, REQ_OP_WRITE, 0);
2110 	if (unlikely(r))
2111 		dm_integrity_io_error(ic, "writing superblock", r);
2112 }
2113 
2114 static void integrity_recalc(struct work_struct *w)
2115 {
2116 	struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, recalc_work);
2117 	struct dm_integrity_range range;
2118 	struct dm_io_request io_req;
2119 	struct dm_io_region io_loc;
2120 	sector_t area, offset;
2121 	sector_t metadata_block;
2122 	unsigned metadata_offset;
2123 	__u8 *t;
2124 	unsigned i;
2125 	int r;
2126 	unsigned super_counter = 0;
2127 
2128 	spin_lock_irq(&ic->endio_wait.lock);
2129 
2130 next_chunk:
2131 
2132 	if (unlikely(READ_ONCE(ic->suspending)))
2133 		goto unlock_ret;
2134 
2135 	range.logical_sector = le64_to_cpu(ic->sb->recalc_sector);
2136 	if (unlikely(range.logical_sector >= ic->provided_data_sectors))
2137 		goto unlock_ret;
2138 
2139 	get_area_and_offset(ic, range.logical_sector, &area, &offset);
2140 	range.n_sectors = min((sector_t)RECALC_SECTORS, ic->provided_data_sectors - range.logical_sector);
2141 	if (!ic->meta_dev)
2142 		range.n_sectors = min(range.n_sectors, (1U << ic->sb->log2_interleave_sectors) - (unsigned)offset);
2143 
2144 	if (unlikely(!add_new_range(ic, &range, true)))
2145 		wait_and_add_new_range(ic, &range);
2146 
2147 	spin_unlock_irq(&ic->endio_wait.lock);
2148 
2149 	if (unlikely(++super_counter == RECALC_WRITE_SUPER)) {
2150 		recalc_write_super(ic);
2151 		super_counter = 0;
2152 	}
2153 
2154 	if (unlikely(dm_integrity_failed(ic)))
2155 		goto err;
2156 
2157 	io_req.bi_op = REQ_OP_READ;
2158 	io_req.bi_op_flags = 0;
2159 	io_req.mem.type = DM_IO_VMA;
2160 	io_req.mem.ptr.addr = ic->recalc_buffer;
2161 	io_req.notify.fn = NULL;
2162 	io_req.client = ic->io;
2163 	io_loc.bdev = ic->dev->bdev;
2164 	io_loc.sector = get_data_sector(ic, area, offset);
2165 	io_loc.count = range.n_sectors;
2166 
2167 	r = dm_io(&io_req, 1, &io_loc, NULL);
2168 	if (unlikely(r)) {
2169 		dm_integrity_io_error(ic, "reading data", r);
2170 		goto err;
2171 	}
2172 
2173 	t = ic->recalc_tags;
2174 	for (i = 0; i < range.n_sectors; i += ic->sectors_per_block) {
2175 		integrity_sector_checksum(ic, range.logical_sector + i, ic->recalc_buffer + (i << SECTOR_SHIFT), t);
2176 		t += ic->tag_size;
2177 	}
2178 
2179 	metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
2180 
2181 	r = dm_integrity_rw_tag(ic, ic->recalc_tags, &metadata_block, &metadata_offset, t - ic->recalc_tags, TAG_WRITE);
2182 	if (unlikely(r)) {
2183 		dm_integrity_io_error(ic, "writing tags", r);
2184 		goto err;
2185 	}
2186 
2187 	spin_lock_irq(&ic->endio_wait.lock);
2188 	remove_range_unlocked(ic, &range);
2189 	ic->sb->recalc_sector = cpu_to_le64(range.logical_sector + range.n_sectors);
2190 	goto next_chunk;
2191 
2192 err:
2193 	remove_range(ic, &range);
2194 	return;
2195 
2196 unlock_ret:
2197 	spin_unlock_irq(&ic->endio_wait.lock);
2198 
2199 	recalc_write_super(ic);
2200 }
2201 
2202 static void init_journal(struct dm_integrity_c *ic, unsigned start_section,
2203 			 unsigned n_sections, unsigned char commit_seq)
2204 {
2205 	unsigned i, j, n;
2206 
2207 	if (!n_sections)
2208 		return;
2209 
2210 	for (n = 0; n < n_sections; n++) {
2211 		i = start_section + n;
2212 		wraparound_section(ic, &i);
2213 		for (j = 0; j < ic->journal_section_sectors; j++) {
2214 			struct journal_sector *js = access_journal(ic, i, j);
2215 			memset(&js->entries, 0, JOURNAL_SECTOR_DATA);
2216 			js->commit_id = dm_integrity_commit_id(ic, i, j, commit_seq);
2217 		}
2218 		for (j = 0; j < ic->journal_section_entries; j++) {
2219 			struct journal_entry *je = access_journal_entry(ic, i, j);
2220 			journal_entry_set_unused(je);
2221 		}
2222 	}
2223 
2224 	write_journal(ic, start_section, n_sections);
2225 }
2226 
2227 static int find_commit_seq(struct dm_integrity_c *ic, unsigned i, unsigned j, commit_id_t id)
2228 {
2229 	unsigned char k;
2230 	for (k = 0; k < N_COMMIT_IDS; k++) {
2231 		if (dm_integrity_commit_id(ic, i, j, k) == id)
2232 			return k;
2233 	}
2234 	dm_integrity_io_error(ic, "journal commit id", -EIO);
2235 	return -EIO;
2236 }
2237 
2238 static void replay_journal(struct dm_integrity_c *ic)
2239 {
2240 	unsigned i, j;
2241 	bool used_commit_ids[N_COMMIT_IDS];
2242 	unsigned max_commit_id_sections[N_COMMIT_IDS];
2243 	unsigned write_start, write_sections;
2244 	unsigned continue_section;
2245 	bool journal_empty;
2246 	unsigned char unused, last_used, want_commit_seq;
2247 
2248 	if (ic->mode == 'R')
2249 		return;
2250 
2251 	if (ic->journal_uptodate)
2252 		return;
2253 
2254 	last_used = 0;
2255 	write_start = 0;
2256 
2257 	if (!ic->just_formatted) {
2258 		DEBUG_print("reading journal\n");
2259 		rw_journal(ic, REQ_OP_READ, 0, 0, ic->journal_sections, NULL);
2260 		if (ic->journal_io)
2261 			DEBUG_bytes(lowmem_page_address(ic->journal_io[0].page), 64, "read journal");
2262 		if (ic->journal_io) {
2263 			struct journal_completion crypt_comp;
2264 			crypt_comp.ic = ic;
2265 			init_completion(&crypt_comp.comp);
2266 			crypt_comp.in_flight = (atomic_t)ATOMIC_INIT(0);
2267 			encrypt_journal(ic, false, 0, ic->journal_sections, &crypt_comp);
2268 			wait_for_completion(&crypt_comp.comp);
2269 		}
2270 		DEBUG_bytes(lowmem_page_address(ic->journal[0].page), 64, "decrypted journal");
2271 	}
2272 
2273 	if (dm_integrity_failed(ic))
2274 		goto clear_journal;
2275 
2276 	journal_empty = true;
2277 	memset(used_commit_ids, 0, sizeof used_commit_ids);
2278 	memset(max_commit_id_sections, 0, sizeof max_commit_id_sections);
2279 	for (i = 0; i < ic->journal_sections; i++) {
2280 		for (j = 0; j < ic->journal_section_sectors; j++) {
2281 			int k;
2282 			struct journal_sector *js = access_journal(ic, i, j);
2283 			k = find_commit_seq(ic, i, j, js->commit_id);
2284 			if (k < 0)
2285 				goto clear_journal;
2286 			used_commit_ids[k] = true;
2287 			max_commit_id_sections[k] = i;
2288 		}
2289 		if (journal_empty) {
2290 			for (j = 0; j < ic->journal_section_entries; j++) {
2291 				struct journal_entry *je = access_journal_entry(ic, i, j);
2292 				if (!journal_entry_is_unused(je)) {
2293 					journal_empty = false;
2294 					break;
2295 				}
2296 			}
2297 		}
2298 	}
2299 
2300 	if (!used_commit_ids[N_COMMIT_IDS - 1]) {
2301 		unused = N_COMMIT_IDS - 1;
2302 		while (unused && !used_commit_ids[unused - 1])
2303 			unused--;
2304 	} else {
2305 		for (unused = 0; unused < N_COMMIT_IDS; unused++)
2306 			if (!used_commit_ids[unused])
2307 				break;
2308 		if (unused == N_COMMIT_IDS) {
2309 			dm_integrity_io_error(ic, "journal commit ids", -EIO);
2310 			goto clear_journal;
2311 		}
2312 	}
2313 	DEBUG_print("first unused commit seq %d [%d,%d,%d,%d]\n",
2314 		    unused, used_commit_ids[0], used_commit_ids[1],
2315 		    used_commit_ids[2], used_commit_ids[3]);
2316 
2317 	last_used = prev_commit_seq(unused);
2318 	want_commit_seq = prev_commit_seq(last_used);
2319 
2320 	if (!used_commit_ids[want_commit_seq] && used_commit_ids[prev_commit_seq(want_commit_seq)])
2321 		journal_empty = true;
2322 
2323 	write_start = max_commit_id_sections[last_used] + 1;
2324 	if (unlikely(write_start >= ic->journal_sections))
2325 		want_commit_seq = next_commit_seq(want_commit_seq);
2326 	wraparound_section(ic, &write_start);
2327 
2328 	i = write_start;
2329 	for (write_sections = 0; write_sections < ic->journal_sections; write_sections++) {
2330 		for (j = 0; j < ic->journal_section_sectors; j++) {
2331 			struct journal_sector *js = access_journal(ic, i, j);
2332 
2333 			if (js->commit_id != dm_integrity_commit_id(ic, i, j, want_commit_seq)) {
2334 				/*
2335 				 * This could be caused by crash during writing.
2336 				 * We won't replay the inconsistent part of the
2337 				 * journal.
2338 				 */
2339 				DEBUG_print("commit id mismatch at position (%u, %u): %d != %d\n",
2340 					    i, j, find_commit_seq(ic, i, j, js->commit_id), want_commit_seq);
2341 				goto brk;
2342 			}
2343 		}
2344 		i++;
2345 		if (unlikely(i >= ic->journal_sections))
2346 			want_commit_seq = next_commit_seq(want_commit_seq);
2347 		wraparound_section(ic, &i);
2348 	}
2349 brk:
2350 
2351 	if (!journal_empty) {
2352 		DEBUG_print("replaying %u sections, starting at %u, commit seq %d\n",
2353 			    write_sections, write_start, want_commit_seq);
2354 		do_journal_write(ic, write_start, write_sections, true);
2355 	}
2356 
2357 	if (write_sections == ic->journal_sections && (ic->mode == 'J' || journal_empty)) {
2358 		continue_section = write_start;
2359 		ic->commit_seq = want_commit_seq;
2360 		DEBUG_print("continuing from section %u, commit seq %d\n", write_start, ic->commit_seq);
2361 	} else {
2362 		unsigned s;
2363 		unsigned char erase_seq;
2364 clear_journal:
2365 		DEBUG_print("clearing journal\n");
2366 
2367 		erase_seq = prev_commit_seq(prev_commit_seq(last_used));
2368 		s = write_start;
2369 		init_journal(ic, s, 1, erase_seq);
2370 		s++;
2371 		wraparound_section(ic, &s);
2372 		if (ic->journal_sections >= 2) {
2373 			init_journal(ic, s, ic->journal_sections - 2, erase_seq);
2374 			s += ic->journal_sections - 2;
2375 			wraparound_section(ic, &s);
2376 			init_journal(ic, s, 1, erase_seq);
2377 		}
2378 
2379 		continue_section = 0;
2380 		ic->commit_seq = next_commit_seq(erase_seq);
2381 	}
2382 
2383 	ic->committed_section = continue_section;
2384 	ic->n_committed_sections = 0;
2385 
2386 	ic->uncommitted_section = continue_section;
2387 	ic->n_uncommitted_sections = 0;
2388 
2389 	ic->free_section = continue_section;
2390 	ic->free_section_entry = 0;
2391 	ic->free_sectors = ic->journal_entries;
2392 
2393 	ic->journal_tree_root = RB_ROOT;
2394 	for (i = 0; i < ic->journal_entries; i++)
2395 		init_journal_node(&ic->journal_tree[i]);
2396 }
2397 
2398 static void dm_integrity_postsuspend(struct dm_target *ti)
2399 {
2400 	struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2401 
2402 	del_timer_sync(&ic->autocommit_timer);
2403 
2404 	WRITE_ONCE(ic->suspending, 1);
2405 
2406 	if (ic->recalc_wq)
2407 		drain_workqueue(ic->recalc_wq);
2408 
2409 	queue_work(ic->commit_wq, &ic->commit_work);
2410 	drain_workqueue(ic->commit_wq);
2411 
2412 	if (ic->mode == 'J') {
2413 		if (ic->meta_dev)
2414 			queue_work(ic->writer_wq, &ic->writer_work);
2415 		drain_workqueue(ic->writer_wq);
2416 		dm_integrity_flush_buffers(ic);
2417 	}
2418 
2419 	WRITE_ONCE(ic->suspending, 0);
2420 
2421 	BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
2422 
2423 	ic->journal_uptodate = true;
2424 }
2425 
2426 static void dm_integrity_resume(struct dm_target *ti)
2427 {
2428 	struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2429 
2430 	replay_journal(ic);
2431 
2432 	if (ic->recalc_wq && ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
2433 		__u64 recalc_pos = le64_to_cpu(ic->sb->recalc_sector);
2434 		if (recalc_pos < ic->provided_data_sectors) {
2435 			queue_work(ic->recalc_wq, &ic->recalc_work);
2436 		} else if (recalc_pos > ic->provided_data_sectors) {
2437 			ic->sb->recalc_sector = cpu_to_le64(ic->provided_data_sectors);
2438 			recalc_write_super(ic);
2439 		}
2440 	}
2441 }
2442 
2443 static void dm_integrity_status(struct dm_target *ti, status_type_t type,
2444 				unsigned status_flags, char *result, unsigned maxlen)
2445 {
2446 	struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2447 	unsigned arg_count;
2448 	size_t sz = 0;
2449 
2450 	switch (type) {
2451 	case STATUSTYPE_INFO:
2452 		DMEMIT("%llu %llu",
2453 			(unsigned long long)atomic64_read(&ic->number_of_mismatches),
2454 			(unsigned long long)ic->provided_data_sectors);
2455 		if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
2456 			DMEMIT(" %llu", (unsigned long long)le64_to_cpu(ic->sb->recalc_sector));
2457 		else
2458 			DMEMIT(" -");
2459 		break;
2460 
2461 	case STATUSTYPE_TABLE: {
2462 		__u64 watermark_percentage = (__u64)(ic->journal_entries - ic->free_sectors_threshold) * 100;
2463 		watermark_percentage += ic->journal_entries / 2;
2464 		do_div(watermark_percentage, ic->journal_entries);
2465 		arg_count = 5;
2466 		arg_count += !!ic->meta_dev;
2467 		arg_count += ic->sectors_per_block != 1;
2468 		arg_count += !!(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING));
2469 		arg_count += !!ic->internal_hash_alg.alg_string;
2470 		arg_count += !!ic->journal_crypt_alg.alg_string;
2471 		arg_count += !!ic->journal_mac_alg.alg_string;
2472 		DMEMIT("%s %llu %u %c %u", ic->dev->name, (unsigned long long)ic->start,
2473 		       ic->tag_size, ic->mode, arg_count);
2474 		if (ic->meta_dev)
2475 			DMEMIT(" meta_device:%s", ic->meta_dev->name);
2476 		if (ic->sectors_per_block != 1)
2477 			DMEMIT(" block_size:%u", ic->sectors_per_block << SECTOR_SHIFT);
2478 		if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
2479 			DMEMIT(" recalculate");
2480 		DMEMIT(" journal_sectors:%u", ic->initial_sectors - SB_SECTORS);
2481 		DMEMIT(" interleave_sectors:%u", 1U << ic->sb->log2_interleave_sectors);
2482 		DMEMIT(" buffer_sectors:%u", 1U << ic->log2_buffer_sectors);
2483 		DMEMIT(" journal_watermark:%u", (unsigned)watermark_percentage);
2484 		DMEMIT(" commit_time:%u", ic->autocommit_msec);
2485 
2486 #define EMIT_ALG(a, n)							\
2487 		do {							\
2488 			if (ic->a.alg_string) {				\
2489 				DMEMIT(" %s:%s", n, ic->a.alg_string);	\
2490 				if (ic->a.key_string)			\
2491 					DMEMIT(":%s", ic->a.key_string);\
2492 			}						\
2493 		} while (0)
2494 		EMIT_ALG(internal_hash_alg, "internal_hash");
2495 		EMIT_ALG(journal_crypt_alg, "journal_crypt");
2496 		EMIT_ALG(journal_mac_alg, "journal_mac");
2497 		break;
2498 	}
2499 	}
2500 }
2501 
2502 static int dm_integrity_iterate_devices(struct dm_target *ti,
2503 					iterate_devices_callout_fn fn, void *data)
2504 {
2505 	struct dm_integrity_c *ic = ti->private;
2506 
2507 	if (!ic->meta_dev)
2508 		return fn(ti, ic->dev, ic->start + ic->initial_sectors + ic->metadata_run, ti->len, data);
2509 	else
2510 		return fn(ti, ic->dev, 0, ti->len, data);
2511 }
2512 
2513 static void dm_integrity_io_hints(struct dm_target *ti, struct queue_limits *limits)
2514 {
2515 	struct dm_integrity_c *ic = ti->private;
2516 
2517 	if (ic->sectors_per_block > 1) {
2518 		limits->logical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
2519 		limits->physical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
2520 		blk_limits_io_min(limits, ic->sectors_per_block << SECTOR_SHIFT);
2521 	}
2522 }
2523 
2524 static void calculate_journal_section_size(struct dm_integrity_c *ic)
2525 {
2526 	unsigned sector_space = JOURNAL_SECTOR_DATA;
2527 
2528 	ic->journal_sections = le32_to_cpu(ic->sb->journal_sections);
2529 	ic->journal_entry_size = roundup(offsetof(struct journal_entry, last_bytes[ic->sectors_per_block]) + ic->tag_size,
2530 					 JOURNAL_ENTRY_ROUNDUP);
2531 
2532 	if (ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC))
2533 		sector_space -= JOURNAL_MAC_PER_SECTOR;
2534 	ic->journal_entries_per_sector = sector_space / ic->journal_entry_size;
2535 	ic->journal_section_entries = ic->journal_entries_per_sector * JOURNAL_BLOCK_SECTORS;
2536 	ic->journal_section_sectors = (ic->journal_section_entries << ic->sb->log2_sectors_per_block) + JOURNAL_BLOCK_SECTORS;
2537 	ic->journal_entries = ic->journal_section_entries * ic->journal_sections;
2538 }
2539 
2540 static int calculate_device_limits(struct dm_integrity_c *ic)
2541 {
2542 	__u64 initial_sectors;
2543 
2544 	calculate_journal_section_size(ic);
2545 	initial_sectors = SB_SECTORS + (__u64)ic->journal_section_sectors * ic->journal_sections;
2546 	if (initial_sectors + METADATA_PADDING_SECTORS >= ic->meta_device_sectors || initial_sectors > UINT_MAX)
2547 		return -EINVAL;
2548 	ic->initial_sectors = initial_sectors;
2549 
2550 	if (!ic->meta_dev) {
2551 		sector_t last_sector, last_area, last_offset;
2552 
2553 		ic->metadata_run = roundup((__u64)ic->tag_size << (ic->sb->log2_interleave_sectors - ic->sb->log2_sectors_per_block),
2554 					   (__u64)(1 << SECTOR_SHIFT << METADATA_PADDING_SECTORS)) >> SECTOR_SHIFT;
2555 		if (!(ic->metadata_run & (ic->metadata_run - 1)))
2556 			ic->log2_metadata_run = __ffs(ic->metadata_run);
2557 		else
2558 			ic->log2_metadata_run = -1;
2559 
2560 		get_area_and_offset(ic, ic->provided_data_sectors - 1, &last_area, &last_offset);
2561 		last_sector = get_data_sector(ic, last_area, last_offset);
2562 		if (last_sector < ic->start || last_sector >= ic->meta_device_sectors)
2563 			return -EINVAL;
2564 	} else {
2565 		__u64 meta_size = ic->provided_data_sectors * ic->tag_size;
2566 		meta_size = (meta_size + ((1U << (ic->log2_buffer_sectors + SECTOR_SHIFT)) - 1))
2567 				>> (ic->log2_buffer_sectors + SECTOR_SHIFT);
2568 		meta_size <<= ic->log2_buffer_sectors;
2569 		if (ic->initial_sectors + meta_size < ic->initial_sectors ||
2570 		    ic->initial_sectors + meta_size > ic->meta_device_sectors)
2571 			return -EINVAL;
2572 		ic->metadata_run = 1;
2573 		ic->log2_metadata_run = 0;
2574 	}
2575 
2576 	return 0;
2577 }
2578 
2579 static int initialize_superblock(struct dm_integrity_c *ic, unsigned journal_sectors, unsigned interleave_sectors)
2580 {
2581 	unsigned journal_sections;
2582 	int test_bit;
2583 
2584 	memset(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT);
2585 	memcpy(ic->sb->magic, SB_MAGIC, 8);
2586 	ic->sb->integrity_tag_size = cpu_to_le16(ic->tag_size);
2587 	ic->sb->log2_sectors_per_block = __ffs(ic->sectors_per_block);
2588 	if (ic->journal_mac_alg.alg_string)
2589 		ic->sb->flags |= cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC);
2590 
2591 	calculate_journal_section_size(ic);
2592 	journal_sections = journal_sectors / ic->journal_section_sectors;
2593 	if (!journal_sections)
2594 		journal_sections = 1;
2595 
2596 	if (!ic->meta_dev) {
2597 		ic->sb->journal_sections = cpu_to_le32(journal_sections);
2598 		if (!interleave_sectors)
2599 			interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
2600 		ic->sb->log2_interleave_sectors = __fls(interleave_sectors);
2601 		ic->sb->log2_interleave_sectors = max((__u8)MIN_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
2602 		ic->sb->log2_interleave_sectors = min((__u8)MAX_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
2603 
2604 		ic->provided_data_sectors = 0;
2605 		for (test_bit = fls64(ic->meta_device_sectors) - 1; test_bit >= 3; test_bit--) {
2606 			__u64 prev_data_sectors = ic->provided_data_sectors;
2607 
2608 			ic->provided_data_sectors |= (sector_t)1 << test_bit;
2609 			if (calculate_device_limits(ic))
2610 				ic->provided_data_sectors = prev_data_sectors;
2611 		}
2612 		if (!ic->provided_data_sectors)
2613 			return -EINVAL;
2614 	} else {
2615 		ic->sb->log2_interleave_sectors = 0;
2616 		ic->provided_data_sectors = ic->data_device_sectors;
2617 		ic->provided_data_sectors &= ~(sector_t)(ic->sectors_per_block - 1);
2618 
2619 try_smaller_buffer:
2620 		ic->sb->journal_sections = cpu_to_le32(0);
2621 		for (test_bit = fls(journal_sections) - 1; test_bit >= 0; test_bit--) {
2622 			__u32 prev_journal_sections = le32_to_cpu(ic->sb->journal_sections);
2623 			__u32 test_journal_sections = prev_journal_sections | (1U << test_bit);
2624 			if (test_journal_sections > journal_sections)
2625 				continue;
2626 			ic->sb->journal_sections = cpu_to_le32(test_journal_sections);
2627 			if (calculate_device_limits(ic))
2628 				ic->sb->journal_sections = cpu_to_le32(prev_journal_sections);
2629 
2630 		}
2631 		if (!le32_to_cpu(ic->sb->journal_sections)) {
2632 			if (ic->log2_buffer_sectors > 3) {
2633 				ic->log2_buffer_sectors--;
2634 				goto try_smaller_buffer;
2635 			}
2636 			return -EINVAL;
2637 		}
2638 	}
2639 
2640 	ic->sb->provided_data_sectors = cpu_to_le64(ic->provided_data_sectors);
2641 
2642 	sb_set_version(ic);
2643 
2644 	return 0;
2645 }
2646 
2647 static void dm_integrity_set(struct dm_target *ti, struct dm_integrity_c *ic)
2648 {
2649 	struct gendisk *disk = dm_disk(dm_table_get_md(ti->table));
2650 	struct blk_integrity bi;
2651 
2652 	memset(&bi, 0, sizeof(bi));
2653 	bi.profile = &dm_integrity_profile;
2654 	bi.tuple_size = ic->tag_size;
2655 	bi.tag_size = bi.tuple_size;
2656 	bi.interval_exp = ic->sb->log2_sectors_per_block + SECTOR_SHIFT;
2657 
2658 	blk_integrity_register(disk, &bi);
2659 	blk_queue_max_integrity_segments(disk->queue, UINT_MAX);
2660 }
2661 
2662 static void dm_integrity_free_page_list(struct dm_integrity_c *ic, struct page_list *pl)
2663 {
2664 	unsigned i;
2665 
2666 	if (!pl)
2667 		return;
2668 	for (i = 0; i < ic->journal_pages; i++)
2669 		if (pl[i].page)
2670 			__free_page(pl[i].page);
2671 	kvfree(pl);
2672 }
2673 
2674 static struct page_list *dm_integrity_alloc_page_list(struct dm_integrity_c *ic)
2675 {
2676 	size_t page_list_desc_size = ic->journal_pages * sizeof(struct page_list);
2677 	struct page_list *pl;
2678 	unsigned i;
2679 
2680 	pl = kvmalloc(page_list_desc_size, GFP_KERNEL | __GFP_ZERO);
2681 	if (!pl)
2682 		return NULL;
2683 
2684 	for (i = 0; i < ic->journal_pages; i++) {
2685 		pl[i].page = alloc_page(GFP_KERNEL);
2686 		if (!pl[i].page) {
2687 			dm_integrity_free_page_list(ic, pl);
2688 			return NULL;
2689 		}
2690 		if (i)
2691 			pl[i - 1].next = &pl[i];
2692 	}
2693 
2694 	return pl;
2695 }
2696 
2697 static void dm_integrity_free_journal_scatterlist(struct dm_integrity_c *ic, struct scatterlist **sl)
2698 {
2699 	unsigned i;
2700 	for (i = 0; i < ic->journal_sections; i++)
2701 		kvfree(sl[i]);
2702 	kvfree(sl);
2703 }
2704 
2705 static struct scatterlist **dm_integrity_alloc_journal_scatterlist(struct dm_integrity_c *ic, struct page_list *pl)
2706 {
2707 	struct scatterlist **sl;
2708 	unsigned i;
2709 
2710 	sl = kvmalloc_array(ic->journal_sections,
2711 			    sizeof(struct scatterlist *),
2712 			    GFP_KERNEL | __GFP_ZERO);
2713 	if (!sl)
2714 		return NULL;
2715 
2716 	for (i = 0; i < ic->journal_sections; i++) {
2717 		struct scatterlist *s;
2718 		unsigned start_index, start_offset;
2719 		unsigned end_index, end_offset;
2720 		unsigned n_pages;
2721 		unsigned idx;
2722 
2723 		page_list_location(ic, i, 0, &start_index, &start_offset);
2724 		page_list_location(ic, i, ic->journal_section_sectors - 1, &end_index, &end_offset);
2725 
2726 		n_pages = (end_index - start_index + 1);
2727 
2728 		s = kvmalloc_array(n_pages, sizeof(struct scatterlist),
2729 				   GFP_KERNEL);
2730 		if (!s) {
2731 			dm_integrity_free_journal_scatterlist(ic, sl);
2732 			return NULL;
2733 		}
2734 
2735 		sg_init_table(s, n_pages);
2736 		for (idx = start_index; idx <= end_index; idx++) {
2737 			char *va = lowmem_page_address(pl[idx].page);
2738 			unsigned start = 0, end = PAGE_SIZE;
2739 			if (idx == start_index)
2740 				start = start_offset;
2741 			if (idx == end_index)
2742 				end = end_offset + (1 << SECTOR_SHIFT);
2743 			sg_set_buf(&s[idx - start_index], va + start, end - start);
2744 		}
2745 
2746 		sl[i] = s;
2747 	}
2748 
2749 	return sl;
2750 }
2751 
2752 static void free_alg(struct alg_spec *a)
2753 {
2754 	kzfree(a->alg_string);
2755 	kzfree(a->key);
2756 	memset(a, 0, sizeof *a);
2757 }
2758 
2759 static int get_alg_and_key(const char *arg, struct alg_spec *a, char **error, char *error_inval)
2760 {
2761 	char *k;
2762 
2763 	free_alg(a);
2764 
2765 	a->alg_string = kstrdup(strchr(arg, ':') + 1, GFP_KERNEL);
2766 	if (!a->alg_string)
2767 		goto nomem;
2768 
2769 	k = strchr(a->alg_string, ':');
2770 	if (k) {
2771 		*k = 0;
2772 		a->key_string = k + 1;
2773 		if (strlen(a->key_string) & 1)
2774 			goto inval;
2775 
2776 		a->key_size = strlen(a->key_string) / 2;
2777 		a->key = kmalloc(a->key_size, GFP_KERNEL);
2778 		if (!a->key)
2779 			goto nomem;
2780 		if (hex2bin(a->key, a->key_string, a->key_size))
2781 			goto inval;
2782 	}
2783 
2784 	return 0;
2785 inval:
2786 	*error = error_inval;
2787 	return -EINVAL;
2788 nomem:
2789 	*error = "Out of memory for an argument";
2790 	return -ENOMEM;
2791 }
2792 
2793 static int get_mac(struct crypto_shash **hash, struct alg_spec *a, char **error,
2794 		   char *error_alg, char *error_key)
2795 {
2796 	int r;
2797 
2798 	if (a->alg_string) {
2799 		*hash = crypto_alloc_shash(a->alg_string, 0, 0);
2800 		if (IS_ERR(*hash)) {
2801 			*error = error_alg;
2802 			r = PTR_ERR(*hash);
2803 			*hash = NULL;
2804 			return r;
2805 		}
2806 
2807 		if (a->key) {
2808 			r = crypto_shash_setkey(*hash, a->key, a->key_size);
2809 			if (r) {
2810 				*error = error_key;
2811 				return r;
2812 			}
2813 		} else if (crypto_shash_get_flags(*hash) & CRYPTO_TFM_NEED_KEY) {
2814 			*error = error_key;
2815 			return -ENOKEY;
2816 		}
2817 	}
2818 
2819 	return 0;
2820 }
2821 
2822 static int create_journal(struct dm_integrity_c *ic, char **error)
2823 {
2824 	int r = 0;
2825 	unsigned i;
2826 	__u64 journal_pages, journal_desc_size, journal_tree_size;
2827 	unsigned char *crypt_data = NULL, *crypt_iv = NULL;
2828 	struct skcipher_request *req = NULL;
2829 
2830 	ic->commit_ids[0] = cpu_to_le64(0x1111111111111111ULL);
2831 	ic->commit_ids[1] = cpu_to_le64(0x2222222222222222ULL);
2832 	ic->commit_ids[2] = cpu_to_le64(0x3333333333333333ULL);
2833 	ic->commit_ids[3] = cpu_to_le64(0x4444444444444444ULL);
2834 
2835 	journal_pages = roundup((__u64)ic->journal_sections * ic->journal_section_sectors,
2836 				PAGE_SIZE >> SECTOR_SHIFT) >> (PAGE_SHIFT - SECTOR_SHIFT);
2837 	journal_desc_size = journal_pages * sizeof(struct page_list);
2838 	if (journal_pages >= totalram_pages() - totalhigh_pages() || journal_desc_size > ULONG_MAX) {
2839 		*error = "Journal doesn't fit into memory";
2840 		r = -ENOMEM;
2841 		goto bad;
2842 	}
2843 	ic->journal_pages = journal_pages;
2844 
2845 	ic->journal = dm_integrity_alloc_page_list(ic);
2846 	if (!ic->journal) {
2847 		*error = "Could not allocate memory for journal";
2848 		r = -ENOMEM;
2849 		goto bad;
2850 	}
2851 	if (ic->journal_crypt_alg.alg_string) {
2852 		unsigned ivsize, blocksize;
2853 		struct journal_completion comp;
2854 
2855 		comp.ic = ic;
2856 		ic->journal_crypt = crypto_alloc_skcipher(ic->journal_crypt_alg.alg_string, 0, 0);
2857 		if (IS_ERR(ic->journal_crypt)) {
2858 			*error = "Invalid journal cipher";
2859 			r = PTR_ERR(ic->journal_crypt);
2860 			ic->journal_crypt = NULL;
2861 			goto bad;
2862 		}
2863 		ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
2864 		blocksize = crypto_skcipher_blocksize(ic->journal_crypt);
2865 
2866 		if (ic->journal_crypt_alg.key) {
2867 			r = crypto_skcipher_setkey(ic->journal_crypt, ic->journal_crypt_alg.key,
2868 						   ic->journal_crypt_alg.key_size);
2869 			if (r) {
2870 				*error = "Error setting encryption key";
2871 				goto bad;
2872 			}
2873 		}
2874 		DEBUG_print("cipher %s, block size %u iv size %u\n",
2875 			    ic->journal_crypt_alg.alg_string, blocksize, ivsize);
2876 
2877 		ic->journal_io = dm_integrity_alloc_page_list(ic);
2878 		if (!ic->journal_io) {
2879 			*error = "Could not allocate memory for journal io";
2880 			r = -ENOMEM;
2881 			goto bad;
2882 		}
2883 
2884 		if (blocksize == 1) {
2885 			struct scatterlist *sg;
2886 
2887 			req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
2888 			if (!req) {
2889 				*error = "Could not allocate crypt request";
2890 				r = -ENOMEM;
2891 				goto bad;
2892 			}
2893 
2894 			crypt_iv = kmalloc(ivsize, GFP_KERNEL);
2895 			if (!crypt_iv) {
2896 				*error = "Could not allocate iv";
2897 				r = -ENOMEM;
2898 				goto bad;
2899 			}
2900 
2901 			ic->journal_xor = dm_integrity_alloc_page_list(ic);
2902 			if (!ic->journal_xor) {
2903 				*error = "Could not allocate memory for journal xor";
2904 				r = -ENOMEM;
2905 				goto bad;
2906 			}
2907 
2908 			sg = kvmalloc_array(ic->journal_pages + 1,
2909 					    sizeof(struct scatterlist),
2910 					    GFP_KERNEL);
2911 			if (!sg) {
2912 				*error = "Unable to allocate sg list";
2913 				r = -ENOMEM;
2914 				goto bad;
2915 			}
2916 			sg_init_table(sg, ic->journal_pages + 1);
2917 			for (i = 0; i < ic->journal_pages; i++) {
2918 				char *va = lowmem_page_address(ic->journal_xor[i].page);
2919 				clear_page(va);
2920 				sg_set_buf(&sg[i], va, PAGE_SIZE);
2921 			}
2922 			sg_set_buf(&sg[i], &ic->commit_ids, sizeof ic->commit_ids);
2923 			memset(crypt_iv, 0x00, ivsize);
2924 
2925 			skcipher_request_set_crypt(req, sg, sg, PAGE_SIZE * ic->journal_pages + sizeof ic->commit_ids, crypt_iv);
2926 			init_completion(&comp.comp);
2927 			comp.in_flight = (atomic_t)ATOMIC_INIT(1);
2928 			if (do_crypt(true, req, &comp))
2929 				wait_for_completion(&comp.comp);
2930 			kvfree(sg);
2931 			r = dm_integrity_failed(ic);
2932 			if (r) {
2933 				*error = "Unable to encrypt journal";
2934 				goto bad;
2935 			}
2936 			DEBUG_bytes(lowmem_page_address(ic->journal_xor[0].page), 64, "xor data");
2937 
2938 			crypto_free_skcipher(ic->journal_crypt);
2939 			ic->journal_crypt = NULL;
2940 		} else {
2941 			unsigned crypt_len = roundup(ivsize, blocksize);
2942 
2943 			req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
2944 			if (!req) {
2945 				*error = "Could not allocate crypt request";
2946 				r = -ENOMEM;
2947 				goto bad;
2948 			}
2949 
2950 			crypt_iv = kmalloc(ivsize, GFP_KERNEL);
2951 			if (!crypt_iv) {
2952 				*error = "Could not allocate iv";
2953 				r = -ENOMEM;
2954 				goto bad;
2955 			}
2956 
2957 			crypt_data = kmalloc(crypt_len, GFP_KERNEL);
2958 			if (!crypt_data) {
2959 				*error = "Unable to allocate crypt data";
2960 				r = -ENOMEM;
2961 				goto bad;
2962 			}
2963 
2964 			ic->journal_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal);
2965 			if (!ic->journal_scatterlist) {
2966 				*error = "Unable to allocate sg list";
2967 				r = -ENOMEM;
2968 				goto bad;
2969 			}
2970 			ic->journal_io_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal_io);
2971 			if (!ic->journal_io_scatterlist) {
2972 				*error = "Unable to allocate sg list";
2973 				r = -ENOMEM;
2974 				goto bad;
2975 			}
2976 			ic->sk_requests = kvmalloc_array(ic->journal_sections,
2977 							 sizeof(struct skcipher_request *),
2978 							 GFP_KERNEL | __GFP_ZERO);
2979 			if (!ic->sk_requests) {
2980 				*error = "Unable to allocate sk requests";
2981 				r = -ENOMEM;
2982 				goto bad;
2983 			}
2984 			for (i = 0; i < ic->journal_sections; i++) {
2985 				struct scatterlist sg;
2986 				struct skcipher_request *section_req;
2987 				__u32 section_le = cpu_to_le32(i);
2988 
2989 				memset(crypt_iv, 0x00, ivsize);
2990 				memset(crypt_data, 0x00, crypt_len);
2991 				memcpy(crypt_data, &section_le, min((size_t)crypt_len, sizeof(section_le)));
2992 
2993 				sg_init_one(&sg, crypt_data, crypt_len);
2994 				skcipher_request_set_crypt(req, &sg, &sg, crypt_len, crypt_iv);
2995 				init_completion(&comp.comp);
2996 				comp.in_flight = (atomic_t)ATOMIC_INIT(1);
2997 				if (do_crypt(true, req, &comp))
2998 					wait_for_completion(&comp.comp);
2999 
3000 				r = dm_integrity_failed(ic);
3001 				if (r) {
3002 					*error = "Unable to generate iv";
3003 					goto bad;
3004 				}
3005 
3006 				section_req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
3007 				if (!section_req) {
3008 					*error = "Unable to allocate crypt request";
3009 					r = -ENOMEM;
3010 					goto bad;
3011 				}
3012 				section_req->iv = kmalloc_array(ivsize, 2,
3013 								GFP_KERNEL);
3014 				if (!section_req->iv) {
3015 					skcipher_request_free(section_req);
3016 					*error = "Unable to allocate iv";
3017 					r = -ENOMEM;
3018 					goto bad;
3019 				}
3020 				memcpy(section_req->iv + ivsize, crypt_data, ivsize);
3021 				section_req->cryptlen = (size_t)ic->journal_section_sectors << SECTOR_SHIFT;
3022 				ic->sk_requests[i] = section_req;
3023 				DEBUG_bytes(crypt_data, ivsize, "iv(%u)", i);
3024 			}
3025 		}
3026 	}
3027 
3028 	for (i = 0; i < N_COMMIT_IDS; i++) {
3029 		unsigned j;
3030 retest_commit_id:
3031 		for (j = 0; j < i; j++) {
3032 			if (ic->commit_ids[j] == ic->commit_ids[i]) {
3033 				ic->commit_ids[i] = cpu_to_le64(le64_to_cpu(ic->commit_ids[i]) + 1);
3034 				goto retest_commit_id;
3035 			}
3036 		}
3037 		DEBUG_print("commit id %u: %016llx\n", i, ic->commit_ids[i]);
3038 	}
3039 
3040 	journal_tree_size = (__u64)ic->journal_entries * sizeof(struct journal_node);
3041 	if (journal_tree_size > ULONG_MAX) {
3042 		*error = "Journal doesn't fit into memory";
3043 		r = -ENOMEM;
3044 		goto bad;
3045 	}
3046 	ic->journal_tree = kvmalloc(journal_tree_size, GFP_KERNEL);
3047 	if (!ic->journal_tree) {
3048 		*error = "Could not allocate memory for journal tree";
3049 		r = -ENOMEM;
3050 	}
3051 bad:
3052 	kfree(crypt_data);
3053 	kfree(crypt_iv);
3054 	skcipher_request_free(req);
3055 
3056 	return r;
3057 }
3058 
3059 /*
3060  * Construct a integrity mapping
3061  *
3062  * Arguments:
3063  *	device
3064  *	offset from the start of the device
3065  *	tag size
3066  *	D - direct writes, J - journal writes, R - recovery mode
3067  *	number of optional arguments
3068  *	optional arguments:
3069  *		journal_sectors
3070  *		interleave_sectors
3071  *		buffer_sectors
3072  *		journal_watermark
3073  *		commit_time
3074  *		internal_hash
3075  *		journal_crypt
3076  *		journal_mac
3077  *		block_size
3078  */
3079 static int dm_integrity_ctr(struct dm_target *ti, unsigned argc, char **argv)
3080 {
3081 	struct dm_integrity_c *ic;
3082 	char dummy;
3083 	int r;
3084 	unsigned extra_args;
3085 	struct dm_arg_set as;
3086 	static const struct dm_arg _args[] = {
3087 		{0, 9, "Invalid number of feature args"},
3088 	};
3089 	unsigned journal_sectors, interleave_sectors, buffer_sectors, journal_watermark, sync_msec;
3090 	bool recalculate;
3091 	bool should_write_sb;
3092 	__u64 threshold;
3093 	unsigned long long start;
3094 
3095 #define DIRECT_ARGUMENTS	4
3096 
3097 	if (argc <= DIRECT_ARGUMENTS) {
3098 		ti->error = "Invalid argument count";
3099 		return -EINVAL;
3100 	}
3101 
3102 	ic = kzalloc(sizeof(struct dm_integrity_c), GFP_KERNEL);
3103 	if (!ic) {
3104 		ti->error = "Cannot allocate integrity context";
3105 		return -ENOMEM;
3106 	}
3107 	ti->private = ic;
3108 	ti->per_io_data_size = sizeof(struct dm_integrity_io);
3109 
3110 	ic->in_progress = RB_ROOT;
3111 	INIT_LIST_HEAD(&ic->wait_list);
3112 	init_waitqueue_head(&ic->endio_wait);
3113 	bio_list_init(&ic->flush_bio_list);
3114 	init_waitqueue_head(&ic->copy_to_journal_wait);
3115 	init_completion(&ic->crypto_backoff);
3116 	atomic64_set(&ic->number_of_mismatches, 0);
3117 
3118 	r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &ic->dev);
3119 	if (r) {
3120 		ti->error = "Device lookup failed";
3121 		goto bad;
3122 	}
3123 
3124 	if (sscanf(argv[1], "%llu%c", &start, &dummy) != 1 || start != (sector_t)start) {
3125 		ti->error = "Invalid starting offset";
3126 		r = -EINVAL;
3127 		goto bad;
3128 	}
3129 	ic->start = start;
3130 
3131 	if (strcmp(argv[2], "-")) {
3132 		if (sscanf(argv[2], "%u%c", &ic->tag_size, &dummy) != 1 || !ic->tag_size) {
3133 			ti->error = "Invalid tag size";
3134 			r = -EINVAL;
3135 			goto bad;
3136 		}
3137 	}
3138 
3139 	if (!strcmp(argv[3], "J") || !strcmp(argv[3], "D") || !strcmp(argv[3], "R"))
3140 		ic->mode = argv[3][0];
3141 	else {
3142 		ti->error = "Invalid mode (expecting J, D, R)";
3143 		r = -EINVAL;
3144 		goto bad;
3145 	}
3146 
3147 	journal_sectors = 0;
3148 	interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
3149 	buffer_sectors = DEFAULT_BUFFER_SECTORS;
3150 	journal_watermark = DEFAULT_JOURNAL_WATERMARK;
3151 	sync_msec = DEFAULT_SYNC_MSEC;
3152 	recalculate = false;
3153 	ic->sectors_per_block = 1;
3154 
3155 	as.argc = argc - DIRECT_ARGUMENTS;
3156 	as.argv = argv + DIRECT_ARGUMENTS;
3157 	r = dm_read_arg_group(_args, &as, &extra_args, &ti->error);
3158 	if (r)
3159 		goto bad;
3160 
3161 	while (extra_args--) {
3162 		const char *opt_string;
3163 		unsigned val;
3164 		opt_string = dm_shift_arg(&as);
3165 		if (!opt_string) {
3166 			r = -EINVAL;
3167 			ti->error = "Not enough feature arguments";
3168 			goto bad;
3169 		}
3170 		if (sscanf(opt_string, "journal_sectors:%u%c", &val, &dummy) == 1)
3171 			journal_sectors = val ? val : 1;
3172 		else if (sscanf(opt_string, "interleave_sectors:%u%c", &val, &dummy) == 1)
3173 			interleave_sectors = val;
3174 		else if (sscanf(opt_string, "buffer_sectors:%u%c", &val, &dummy) == 1)
3175 			buffer_sectors = val;
3176 		else if (sscanf(opt_string, "journal_watermark:%u%c", &val, &dummy) == 1 && val <= 100)
3177 			journal_watermark = val;
3178 		else if (sscanf(opt_string, "commit_time:%u%c", &val, &dummy) == 1)
3179 			sync_msec = val;
3180 		else if (!strncmp(opt_string, "meta_device:", strlen("meta_device:"))) {
3181 			if (ic->meta_dev) {
3182 				dm_put_device(ti, ic->meta_dev);
3183 				ic->meta_dev = NULL;
3184 			}
3185 			r = dm_get_device(ti, strchr(opt_string, ':') + 1, dm_table_get_mode(ti->table), &ic->meta_dev);
3186 			if (r) {
3187 				ti->error = "Device lookup failed";
3188 				goto bad;
3189 			}
3190 		} else if (sscanf(opt_string, "block_size:%u%c", &val, &dummy) == 1) {
3191 			if (val < 1 << SECTOR_SHIFT ||
3192 			    val > MAX_SECTORS_PER_BLOCK << SECTOR_SHIFT ||
3193 			    (val & (val -1))) {
3194 				r = -EINVAL;
3195 				ti->error = "Invalid block_size argument";
3196 				goto bad;
3197 			}
3198 			ic->sectors_per_block = val >> SECTOR_SHIFT;
3199 		} else if (!strncmp(opt_string, "internal_hash:", strlen("internal_hash:"))) {
3200 			r = get_alg_and_key(opt_string, &ic->internal_hash_alg, &ti->error,
3201 					    "Invalid internal_hash argument");
3202 			if (r)
3203 				goto bad;
3204 		} else if (!strncmp(opt_string, "journal_crypt:", strlen("journal_crypt:"))) {
3205 			r = get_alg_and_key(opt_string, &ic->journal_crypt_alg, &ti->error,
3206 					    "Invalid journal_crypt argument");
3207 			if (r)
3208 				goto bad;
3209 		} else if (!strncmp(opt_string, "journal_mac:", strlen("journal_mac:"))) {
3210 			r = get_alg_and_key(opt_string, &ic->journal_mac_alg,  &ti->error,
3211 					    "Invalid journal_mac argument");
3212 			if (r)
3213 				goto bad;
3214 		} else if (!strcmp(opt_string, "recalculate")) {
3215 			recalculate = true;
3216 		} else {
3217 			r = -EINVAL;
3218 			ti->error = "Invalid argument";
3219 			goto bad;
3220 		}
3221 	}
3222 
3223 	ic->data_device_sectors = i_size_read(ic->dev->bdev->bd_inode) >> SECTOR_SHIFT;
3224 	if (!ic->meta_dev)
3225 		ic->meta_device_sectors = ic->data_device_sectors;
3226 	else
3227 		ic->meta_device_sectors = i_size_read(ic->meta_dev->bdev->bd_inode) >> SECTOR_SHIFT;
3228 
3229 	if (!journal_sectors) {
3230 		journal_sectors = min((sector_t)DEFAULT_MAX_JOURNAL_SECTORS,
3231 			ic->data_device_sectors >> DEFAULT_JOURNAL_SIZE_FACTOR);
3232 	}
3233 
3234 	if (!buffer_sectors)
3235 		buffer_sectors = 1;
3236 	ic->log2_buffer_sectors = min((int)__fls(buffer_sectors), 31 - SECTOR_SHIFT);
3237 
3238 	r = get_mac(&ic->internal_hash, &ic->internal_hash_alg, &ti->error,
3239 		    "Invalid internal hash", "Error setting internal hash key");
3240 	if (r)
3241 		goto bad;
3242 
3243 	r = get_mac(&ic->journal_mac, &ic->journal_mac_alg, &ti->error,
3244 		    "Invalid journal mac", "Error setting journal mac key");
3245 	if (r)
3246 		goto bad;
3247 
3248 	if (!ic->tag_size) {
3249 		if (!ic->internal_hash) {
3250 			ti->error = "Unknown tag size";
3251 			r = -EINVAL;
3252 			goto bad;
3253 		}
3254 		ic->tag_size = crypto_shash_digestsize(ic->internal_hash);
3255 	}
3256 	if (ic->tag_size > MAX_TAG_SIZE) {
3257 		ti->error = "Too big tag size";
3258 		r = -EINVAL;
3259 		goto bad;
3260 	}
3261 	if (!(ic->tag_size & (ic->tag_size - 1)))
3262 		ic->log2_tag_size = __ffs(ic->tag_size);
3263 	else
3264 		ic->log2_tag_size = -1;
3265 
3266 	ic->autocommit_jiffies = msecs_to_jiffies(sync_msec);
3267 	ic->autocommit_msec = sync_msec;
3268 	timer_setup(&ic->autocommit_timer, autocommit_fn, 0);
3269 
3270 	ic->io = dm_io_client_create();
3271 	if (IS_ERR(ic->io)) {
3272 		r = PTR_ERR(ic->io);
3273 		ic->io = NULL;
3274 		ti->error = "Cannot allocate dm io";
3275 		goto bad;
3276 	}
3277 
3278 	r = mempool_init_slab_pool(&ic->journal_io_mempool, JOURNAL_IO_MEMPOOL, journal_io_cache);
3279 	if (r) {
3280 		ti->error = "Cannot allocate mempool";
3281 		goto bad;
3282 	}
3283 
3284 	ic->metadata_wq = alloc_workqueue("dm-integrity-metadata",
3285 					  WQ_MEM_RECLAIM, METADATA_WORKQUEUE_MAX_ACTIVE);
3286 	if (!ic->metadata_wq) {
3287 		ti->error = "Cannot allocate workqueue";
3288 		r = -ENOMEM;
3289 		goto bad;
3290 	}
3291 
3292 	/*
3293 	 * If this workqueue were percpu, it would cause bio reordering
3294 	 * and reduced performance.
3295 	 */
3296 	ic->wait_wq = alloc_workqueue("dm-integrity-wait", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
3297 	if (!ic->wait_wq) {
3298 		ti->error = "Cannot allocate workqueue";
3299 		r = -ENOMEM;
3300 		goto bad;
3301 	}
3302 
3303 	ic->commit_wq = alloc_workqueue("dm-integrity-commit", WQ_MEM_RECLAIM, 1);
3304 	if (!ic->commit_wq) {
3305 		ti->error = "Cannot allocate workqueue";
3306 		r = -ENOMEM;
3307 		goto bad;
3308 	}
3309 	INIT_WORK(&ic->commit_work, integrity_commit);
3310 
3311 	if (ic->mode == 'J') {
3312 		ic->writer_wq = alloc_workqueue("dm-integrity-writer", WQ_MEM_RECLAIM, 1);
3313 		if (!ic->writer_wq) {
3314 			ti->error = "Cannot allocate workqueue";
3315 			r = -ENOMEM;
3316 			goto bad;
3317 		}
3318 		INIT_WORK(&ic->writer_work, integrity_writer);
3319 	}
3320 
3321 	ic->sb = alloc_pages_exact(SB_SECTORS << SECTOR_SHIFT, GFP_KERNEL);
3322 	if (!ic->sb) {
3323 		r = -ENOMEM;
3324 		ti->error = "Cannot allocate superblock area";
3325 		goto bad;
3326 	}
3327 
3328 	r = sync_rw_sb(ic, REQ_OP_READ, 0);
3329 	if (r) {
3330 		ti->error = "Error reading superblock";
3331 		goto bad;
3332 	}
3333 	should_write_sb = false;
3334 	if (memcmp(ic->sb->magic, SB_MAGIC, 8)) {
3335 		if (ic->mode != 'R') {
3336 			if (memchr_inv(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT)) {
3337 				r = -EINVAL;
3338 				ti->error = "The device is not initialized";
3339 				goto bad;
3340 			}
3341 		}
3342 
3343 		r = initialize_superblock(ic, journal_sectors, interleave_sectors);
3344 		if (r) {
3345 			ti->error = "Could not initialize superblock";
3346 			goto bad;
3347 		}
3348 		if (ic->mode != 'R')
3349 			should_write_sb = true;
3350 	}
3351 
3352 	if (!ic->sb->version || ic->sb->version > SB_VERSION_2) {
3353 		r = -EINVAL;
3354 		ti->error = "Unknown version";
3355 		goto bad;
3356 	}
3357 	if (le16_to_cpu(ic->sb->integrity_tag_size) != ic->tag_size) {
3358 		r = -EINVAL;
3359 		ti->error = "Tag size doesn't match the information in superblock";
3360 		goto bad;
3361 	}
3362 	if (ic->sb->log2_sectors_per_block != __ffs(ic->sectors_per_block)) {
3363 		r = -EINVAL;
3364 		ti->error = "Block size doesn't match the information in superblock";
3365 		goto bad;
3366 	}
3367 	if (!le32_to_cpu(ic->sb->journal_sections)) {
3368 		r = -EINVAL;
3369 		ti->error = "Corrupted superblock, journal_sections is 0";
3370 		goto bad;
3371 	}
3372 	/* make sure that ti->max_io_len doesn't overflow */
3373 	if (!ic->meta_dev) {
3374 		if (ic->sb->log2_interleave_sectors < MIN_LOG2_INTERLEAVE_SECTORS ||
3375 		    ic->sb->log2_interleave_sectors > MAX_LOG2_INTERLEAVE_SECTORS) {
3376 			r = -EINVAL;
3377 			ti->error = "Invalid interleave_sectors in the superblock";
3378 			goto bad;
3379 		}
3380 	} else {
3381 		if (ic->sb->log2_interleave_sectors) {
3382 			r = -EINVAL;
3383 			ti->error = "Invalid interleave_sectors in the superblock";
3384 			goto bad;
3385 		}
3386 	}
3387 	ic->provided_data_sectors = le64_to_cpu(ic->sb->provided_data_sectors);
3388 	if (ic->provided_data_sectors != le64_to_cpu(ic->sb->provided_data_sectors)) {
3389 		/* test for overflow */
3390 		r = -EINVAL;
3391 		ti->error = "The superblock has 64-bit device size, but the kernel was compiled with 32-bit sectors";
3392 		goto bad;
3393 	}
3394 	if (!!(ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC)) != !!ic->journal_mac_alg.alg_string) {
3395 		r = -EINVAL;
3396 		ti->error = "Journal mac mismatch";
3397 		goto bad;
3398 	}
3399 
3400 try_smaller_buffer:
3401 	r = calculate_device_limits(ic);
3402 	if (r) {
3403 		if (ic->meta_dev) {
3404 			if (ic->log2_buffer_sectors > 3) {
3405 				ic->log2_buffer_sectors--;
3406 				goto try_smaller_buffer;
3407 			}
3408 		}
3409 		ti->error = "The device is too small";
3410 		goto bad;
3411 	}
3412 	if (!ic->meta_dev)
3413 		ic->log2_buffer_sectors = min(ic->log2_buffer_sectors, (__u8)__ffs(ic->metadata_run));
3414 
3415 	if (ti->len > ic->provided_data_sectors) {
3416 		r = -EINVAL;
3417 		ti->error = "Not enough provided sectors for requested mapping size";
3418 		goto bad;
3419 	}
3420 
3421 
3422 	threshold = (__u64)ic->journal_entries * (100 - journal_watermark);
3423 	threshold += 50;
3424 	do_div(threshold, 100);
3425 	ic->free_sectors_threshold = threshold;
3426 
3427 	DEBUG_print("initialized:\n");
3428 	DEBUG_print("	integrity_tag_size %u\n", le16_to_cpu(ic->sb->integrity_tag_size));
3429 	DEBUG_print("	journal_entry_size %u\n", ic->journal_entry_size);
3430 	DEBUG_print("	journal_entries_per_sector %u\n", ic->journal_entries_per_sector);
3431 	DEBUG_print("	journal_section_entries %u\n", ic->journal_section_entries);
3432 	DEBUG_print("	journal_section_sectors %u\n", ic->journal_section_sectors);
3433 	DEBUG_print("	journal_sections %u\n", (unsigned)le32_to_cpu(ic->sb->journal_sections));
3434 	DEBUG_print("	journal_entries %u\n", ic->journal_entries);
3435 	DEBUG_print("	log2_interleave_sectors %d\n", ic->sb->log2_interleave_sectors);
3436 	DEBUG_print("	device_sectors 0x%llx\n", (unsigned long long)ic->device_sectors);
3437 	DEBUG_print("	initial_sectors 0x%x\n", ic->initial_sectors);
3438 	DEBUG_print("	metadata_run 0x%x\n", ic->metadata_run);
3439 	DEBUG_print("	log2_metadata_run %d\n", ic->log2_metadata_run);
3440 	DEBUG_print("	provided_data_sectors 0x%llx (%llu)\n", (unsigned long long)ic->provided_data_sectors,
3441 		    (unsigned long long)ic->provided_data_sectors);
3442 	DEBUG_print("	log2_buffer_sectors %u\n", ic->log2_buffer_sectors);
3443 
3444 	if (recalculate && !(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))) {
3445 		ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
3446 		ic->sb->recalc_sector = cpu_to_le64(0);
3447 	}
3448 
3449 	if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
3450 		if (!ic->internal_hash) {
3451 			r = -EINVAL;
3452 			ti->error = "Recalculate is only valid with internal hash";
3453 			goto bad;
3454 		}
3455 		ic->recalc_wq = alloc_workqueue("dm-integrity-recalc", WQ_MEM_RECLAIM, 1);
3456 		if (!ic->recalc_wq ) {
3457 			ti->error = "Cannot allocate workqueue";
3458 			r = -ENOMEM;
3459 			goto bad;
3460 		}
3461 		INIT_WORK(&ic->recalc_work, integrity_recalc);
3462 		ic->recalc_buffer = vmalloc(RECALC_SECTORS << SECTOR_SHIFT);
3463 		if (!ic->recalc_buffer) {
3464 			ti->error = "Cannot allocate buffer for recalculating";
3465 			r = -ENOMEM;
3466 			goto bad;
3467 		}
3468 		ic->recalc_tags = kvmalloc_array(RECALC_SECTORS >> ic->sb->log2_sectors_per_block,
3469 						 ic->tag_size, GFP_KERNEL);
3470 		if (!ic->recalc_tags) {
3471 			ti->error = "Cannot allocate tags for recalculating";
3472 			r = -ENOMEM;
3473 			goto bad;
3474 		}
3475 	}
3476 
3477 	ic->bufio = dm_bufio_client_create(ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev,
3478 			1U << (SECTOR_SHIFT + ic->log2_buffer_sectors), 1, 0, NULL, NULL);
3479 	if (IS_ERR(ic->bufio)) {
3480 		r = PTR_ERR(ic->bufio);
3481 		ti->error = "Cannot initialize dm-bufio";
3482 		ic->bufio = NULL;
3483 		goto bad;
3484 	}
3485 	dm_bufio_set_sector_offset(ic->bufio, ic->start + ic->initial_sectors);
3486 
3487 	if (ic->mode != 'R') {
3488 		r = create_journal(ic, &ti->error);
3489 		if (r)
3490 			goto bad;
3491 	}
3492 
3493 	if (should_write_sb) {
3494 		int r;
3495 
3496 		init_journal(ic, 0, ic->journal_sections, 0);
3497 		r = dm_integrity_failed(ic);
3498 		if (unlikely(r)) {
3499 			ti->error = "Error initializing journal";
3500 			goto bad;
3501 		}
3502 		r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
3503 		if (r) {
3504 			ti->error = "Error initializing superblock";
3505 			goto bad;
3506 		}
3507 		ic->just_formatted = true;
3508 	}
3509 
3510 	if (!ic->meta_dev) {
3511 		r = dm_set_target_max_io_len(ti, 1U << ic->sb->log2_interleave_sectors);
3512 		if (r)
3513 			goto bad;
3514 	}
3515 
3516 	if (!ic->internal_hash)
3517 		dm_integrity_set(ti, ic);
3518 
3519 	ti->num_flush_bios = 1;
3520 	ti->flush_supported = true;
3521 
3522 	return 0;
3523 bad:
3524 	dm_integrity_dtr(ti);
3525 	return r;
3526 }
3527 
3528 static void dm_integrity_dtr(struct dm_target *ti)
3529 {
3530 	struct dm_integrity_c *ic = ti->private;
3531 
3532 	BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
3533 	BUG_ON(!list_empty(&ic->wait_list));
3534 
3535 	if (ic->metadata_wq)
3536 		destroy_workqueue(ic->metadata_wq);
3537 	if (ic->wait_wq)
3538 		destroy_workqueue(ic->wait_wq);
3539 	if (ic->commit_wq)
3540 		destroy_workqueue(ic->commit_wq);
3541 	if (ic->writer_wq)
3542 		destroy_workqueue(ic->writer_wq);
3543 	if (ic->recalc_wq)
3544 		destroy_workqueue(ic->recalc_wq);
3545 	if (ic->recalc_buffer)
3546 		vfree(ic->recalc_buffer);
3547 	if (ic->recalc_tags)
3548 		kvfree(ic->recalc_tags);
3549 	if (ic->bufio)
3550 		dm_bufio_client_destroy(ic->bufio);
3551 	mempool_exit(&ic->journal_io_mempool);
3552 	if (ic->io)
3553 		dm_io_client_destroy(ic->io);
3554 	if (ic->dev)
3555 		dm_put_device(ti, ic->dev);
3556 	if (ic->meta_dev)
3557 		dm_put_device(ti, ic->meta_dev);
3558 	dm_integrity_free_page_list(ic, ic->journal);
3559 	dm_integrity_free_page_list(ic, ic->journal_io);
3560 	dm_integrity_free_page_list(ic, ic->journal_xor);
3561 	if (ic->journal_scatterlist)
3562 		dm_integrity_free_journal_scatterlist(ic, ic->journal_scatterlist);
3563 	if (ic->journal_io_scatterlist)
3564 		dm_integrity_free_journal_scatterlist(ic, ic->journal_io_scatterlist);
3565 	if (ic->sk_requests) {
3566 		unsigned i;
3567 
3568 		for (i = 0; i < ic->journal_sections; i++) {
3569 			struct skcipher_request *req = ic->sk_requests[i];
3570 			if (req) {
3571 				kzfree(req->iv);
3572 				skcipher_request_free(req);
3573 			}
3574 		}
3575 		kvfree(ic->sk_requests);
3576 	}
3577 	kvfree(ic->journal_tree);
3578 	if (ic->sb)
3579 		free_pages_exact(ic->sb, SB_SECTORS << SECTOR_SHIFT);
3580 
3581 	if (ic->internal_hash)
3582 		crypto_free_shash(ic->internal_hash);
3583 	free_alg(&ic->internal_hash_alg);
3584 
3585 	if (ic->journal_crypt)
3586 		crypto_free_skcipher(ic->journal_crypt);
3587 	free_alg(&ic->journal_crypt_alg);
3588 
3589 	if (ic->journal_mac)
3590 		crypto_free_shash(ic->journal_mac);
3591 	free_alg(&ic->journal_mac_alg);
3592 
3593 	kfree(ic);
3594 }
3595 
3596 static struct target_type integrity_target = {
3597 	.name			= "integrity",
3598 	.version		= {1, 2, 0},
3599 	.module			= THIS_MODULE,
3600 	.features		= DM_TARGET_SINGLETON | DM_TARGET_INTEGRITY,
3601 	.ctr			= dm_integrity_ctr,
3602 	.dtr			= dm_integrity_dtr,
3603 	.map			= dm_integrity_map,
3604 	.postsuspend		= dm_integrity_postsuspend,
3605 	.resume			= dm_integrity_resume,
3606 	.status			= dm_integrity_status,
3607 	.iterate_devices	= dm_integrity_iterate_devices,
3608 	.io_hints		= dm_integrity_io_hints,
3609 };
3610 
3611 static int __init dm_integrity_init(void)
3612 {
3613 	int r;
3614 
3615 	journal_io_cache = kmem_cache_create("integrity_journal_io",
3616 					     sizeof(struct journal_io), 0, 0, NULL);
3617 	if (!journal_io_cache) {
3618 		DMERR("can't allocate journal io cache");
3619 		return -ENOMEM;
3620 	}
3621 
3622 	r = dm_register_target(&integrity_target);
3623 
3624 	if (r < 0)
3625 		DMERR("register failed %d", r);
3626 
3627 	return r;
3628 }
3629 
3630 static void __exit dm_integrity_exit(void)
3631 {
3632 	dm_unregister_target(&integrity_target);
3633 	kmem_cache_destroy(journal_io_cache);
3634 }
3635 
3636 module_init(dm_integrity_init);
3637 module_exit(dm_integrity_exit);
3638 
3639 MODULE_AUTHOR("Milan Broz");
3640 MODULE_AUTHOR("Mikulas Patocka");
3641 MODULE_DESCRIPTION(DM_NAME " target for integrity tags extension");
3642 MODULE_LICENSE("GPL");
3643