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