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