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