1 // SPDX-License-Identifier: GPL-2.0-only
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
7 * This file is released under the GPL.
10 #include "dm-bio-record.h"
12 #include <linux/compiler.h>
13 #include <linux/module.h>
14 #include <linux/device-mapper.h>
15 #include <linux/dm-io.h>
16 #include <linux/vmalloc.h>
17 #include <linux/sort.h>
18 #include <linux/rbtree.h>
19 #include <linux/delay.h>
20 #include <linux/random.h>
21 #include <linux/reboot.h>
22 #include <crypto/hash.h>
23 #include <crypto/skcipher.h>
24 #include <linux/async_tx.h>
25 #include <linux/dm-bufio.h>
29 #define DM_MSG_PREFIX "integrity"
31 #define DEFAULT_INTERLEAVE_SECTORS 32768
32 #define DEFAULT_JOURNAL_SIZE_FACTOR 7
33 #define DEFAULT_SECTORS_PER_BITMAP_BIT 32768
34 #define DEFAULT_BUFFER_SECTORS 128
35 #define DEFAULT_JOURNAL_WATERMARK 50
36 #define DEFAULT_SYNC_MSEC 10000
37 #define DEFAULT_MAX_JOURNAL_SECTORS (IS_ENABLED(CONFIG_64BIT) ? 131072 : 8192)
38 #define MIN_LOG2_INTERLEAVE_SECTORS 3
39 #define MAX_LOG2_INTERLEAVE_SECTORS 31
40 #define METADATA_WORKQUEUE_MAX_ACTIVE 16
41 #define RECALC_SECTORS (IS_ENABLED(CONFIG_64BIT) ? 32768 : 2048)
42 #define RECALC_WRITE_SUPER 16
43 #define BITMAP_BLOCK_SIZE 4096 /* don't change it */
44 #define BITMAP_FLUSH_INTERVAL (10 * HZ)
45 #define DISCARD_FILLER 0xf6
49 * Warning - DEBUG_PRINT prints security-sensitive data to the log,
50 * so it should not be enabled in the official kernel
53 //#define INTERNAL_VERIFY
59 #define SB_MAGIC "integrt"
60 #define SB_VERSION_1 1
61 #define SB_VERSION_2 2
62 #define SB_VERSION_3 3
63 #define SB_VERSION_4 4
64 #define SB_VERSION_5 5
66 #define MAX_SECTORS_PER_BLOCK 8
71 __u8 log2_interleave_sectors;
72 __le16 integrity_tag_size;
73 __le32 journal_sections;
74 __le64 provided_data_sectors; /* userspace uses this value */
76 __u8 log2_sectors_per_block;
77 __u8 log2_blocks_per_bitmap_bit;
84 #define SB_FLAG_HAVE_JOURNAL_MAC 0x1
85 #define SB_FLAG_RECALCULATING 0x2
86 #define SB_FLAG_DIRTY_BITMAP 0x4
87 #define SB_FLAG_FIXED_PADDING 0x8
88 #define SB_FLAG_FIXED_HMAC 0x10
90 #define JOURNAL_ENTRY_ROUNDUP 8
92 typedef __le64 commit_id_t;
93 #define JOURNAL_MAC_PER_SECTOR 8
95 struct journal_entry {
103 commit_id_t last_bytes[];
107 #define journal_entry_tag(ic, je) ((__u8 *)&(je)->last_bytes[(ic)->sectors_per_block])
109 #if BITS_PER_LONG == 64
110 #define journal_entry_set_sector(je, x) do { smp_wmb(); WRITE_ONCE((je)->u.sector, cpu_to_le64(x)); } while (0)
112 #define journal_entry_set_sector(je, x) do { (je)->u.s.sector_lo = cpu_to_le32(x); smp_wmb(); WRITE_ONCE((je)->u.s.sector_hi, cpu_to_le32((x) >> 32)); } while (0)
114 #define journal_entry_get_sector(je) le64_to_cpu((je)->u.sector)
115 #define journal_entry_is_unused(je) ((je)->u.s.sector_hi == cpu_to_le32(-1))
116 #define journal_entry_set_unused(je) ((je)->u.s.sector_hi = cpu_to_le32(-1))
117 #define journal_entry_is_inprogress(je) ((je)->u.s.sector_hi == cpu_to_le32(-2))
118 #define journal_entry_set_inprogress(je) ((je)->u.s.sector_hi = cpu_to_le32(-2))
120 #define JOURNAL_BLOCK_SECTORS 8
121 #define JOURNAL_SECTOR_DATA ((1 << SECTOR_SHIFT) - sizeof(commit_id_t))
122 #define JOURNAL_MAC_SIZE (JOURNAL_MAC_PER_SECTOR * JOURNAL_BLOCK_SECTORS)
124 struct journal_sector {
125 struct_group(sectors,
126 __u8 entries[JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR];
127 __u8 mac[JOURNAL_MAC_PER_SECTOR];
129 commit_id_t commit_id;
132 #define MAX_TAG_SIZE (JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR - offsetof(struct journal_entry, last_bytes[MAX_SECTORS_PER_BLOCK]))
134 #define METADATA_PADDING_SECTORS 8
136 #define N_COMMIT_IDS 4
138 static unsigned char prev_commit_seq(unsigned char seq)
140 return (seq + N_COMMIT_IDS - 1) % N_COMMIT_IDS;
143 static unsigned char next_commit_seq(unsigned char seq)
145 return (seq + 1) % N_COMMIT_IDS;
149 * In-memory structures
152 struct journal_node {
161 unsigned int key_size;
164 struct dm_integrity_c {
166 struct dm_dev *meta_dev;
167 unsigned int tag_size;
170 mempool_t journal_io_mempool;
171 struct dm_io_client *io;
172 struct dm_bufio_client *bufio;
173 struct workqueue_struct *metadata_wq;
174 struct superblock *sb;
175 unsigned int journal_pages;
176 unsigned int n_bitmap_blocks;
178 struct page_list *journal;
179 struct page_list *journal_io;
180 struct page_list *journal_xor;
181 struct page_list *recalc_bitmap;
182 struct page_list *may_write_bitmap;
183 struct bitmap_block_status *bbs;
184 unsigned int bitmap_flush_interval;
185 int synchronous_mode;
186 struct bio_list synchronous_bios;
187 struct delayed_work bitmap_flush_work;
189 struct crypto_skcipher *journal_crypt;
190 struct scatterlist **journal_scatterlist;
191 struct scatterlist **journal_io_scatterlist;
192 struct skcipher_request **sk_requests;
194 struct crypto_shash *journal_mac;
196 struct journal_node *journal_tree;
197 struct rb_root journal_tree_root;
199 sector_t provided_data_sectors;
201 unsigned short journal_entry_size;
202 unsigned char journal_entries_per_sector;
203 unsigned char journal_section_entries;
204 unsigned short journal_section_sectors;
205 unsigned int journal_sections;
206 unsigned int journal_entries;
207 sector_t data_device_sectors;
208 sector_t meta_device_sectors;
209 unsigned int initial_sectors;
210 unsigned int metadata_run;
211 __s8 log2_metadata_run;
212 __u8 log2_buffer_sectors;
213 __u8 sectors_per_block;
214 __u8 log2_blocks_per_bitmap_bit;
220 struct crypto_shash *internal_hash;
222 struct dm_target *ti;
224 /* these variables are locked with endio_wait.lock */
225 struct rb_root in_progress;
226 struct list_head wait_list;
227 wait_queue_head_t endio_wait;
228 struct workqueue_struct *wait_wq;
229 struct workqueue_struct *offload_wq;
231 unsigned char commit_seq;
232 commit_id_t commit_ids[N_COMMIT_IDS];
234 unsigned int committed_section;
235 unsigned int n_committed_sections;
237 unsigned int uncommitted_section;
238 unsigned int n_uncommitted_sections;
240 unsigned int free_section;
241 unsigned char free_section_entry;
242 unsigned int free_sectors;
244 unsigned int free_sectors_threshold;
246 struct workqueue_struct *commit_wq;
247 struct work_struct commit_work;
249 struct workqueue_struct *writer_wq;
250 struct work_struct writer_work;
252 struct workqueue_struct *recalc_wq;
253 struct work_struct recalc_work;
255 struct bio_list flush_bio_list;
257 unsigned long autocommit_jiffies;
258 struct timer_list autocommit_timer;
259 unsigned int autocommit_msec;
261 wait_queue_head_t copy_to_journal_wait;
263 struct completion crypto_backoff;
265 bool wrote_to_journal;
266 bool journal_uptodate;
268 bool recalculate_flag;
269 bool reset_recalculate_flag;
273 bool legacy_recalculate;
275 struct alg_spec internal_hash_alg;
276 struct alg_spec journal_crypt_alg;
277 struct alg_spec journal_mac_alg;
279 atomic64_t number_of_mismatches;
281 struct notifier_block reboot_notifier;
284 struct dm_integrity_range {
285 sector_t logical_sector;
291 struct task_struct *task;
292 struct list_head wait_entry;
297 struct dm_integrity_io {
298 struct work_struct work;
300 struct dm_integrity_c *ic;
304 struct dm_integrity_range range;
306 sector_t metadata_block;
307 unsigned int metadata_offset;
310 blk_status_t bi_status;
312 struct completion *completion;
314 struct dm_bio_details bio_details;
317 struct journal_completion {
318 struct dm_integrity_c *ic;
320 struct completion comp;
324 struct dm_integrity_range range;
325 struct journal_completion *comp;
328 struct bitmap_block_status {
329 struct work_struct work;
330 struct dm_integrity_c *ic;
332 unsigned long *bitmap;
333 struct bio_list bio_queue;
334 spinlock_t bio_queue_lock;
338 static struct kmem_cache *journal_io_cache;
340 #define JOURNAL_IO_MEMPOOL 32
343 #define DEBUG_print(x, ...) printk(KERN_DEBUG x, ##__VA_ARGS__)
344 #define DEBUG_bytes(bytes, len, msg, ...) printk(KERN_DEBUG msg "%s%*ph\n", ##__VA_ARGS__, \
345 len ? ": " : "", len, bytes)
347 #define DEBUG_print(x, ...) do { } while (0)
348 #define DEBUG_bytes(bytes, len, msg, ...) do { } while (0)
351 static void dm_integrity_prepare(struct request *rq)
355 static void dm_integrity_complete(struct request *rq, unsigned int nr_bytes)
360 * DM Integrity profile, protection is performed layer above (dm-crypt)
362 static const struct blk_integrity_profile dm_integrity_profile = {
363 .name = "DM-DIF-EXT-TAG",
366 .prepare_fn = dm_integrity_prepare,
367 .complete_fn = dm_integrity_complete,
370 static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map);
371 static void integrity_bio_wait(struct work_struct *w);
372 static void dm_integrity_dtr(struct dm_target *ti);
374 static void dm_integrity_io_error(struct dm_integrity_c *ic, const char *msg, int err)
377 atomic64_inc(&ic->number_of_mismatches);
378 if (!cmpxchg(&ic->failed, 0, err))
379 DMERR("Error on %s: %d", msg, err);
382 static int dm_integrity_failed(struct dm_integrity_c *ic)
384 return READ_ONCE(ic->failed);
387 static bool dm_integrity_disable_recalculate(struct dm_integrity_c *ic)
389 if (ic->legacy_recalculate)
391 if (!(ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) ?
392 ic->internal_hash_alg.key || ic->journal_mac_alg.key :
393 ic->internal_hash_alg.key && !ic->journal_mac_alg.key)
398 static commit_id_t dm_integrity_commit_id(struct dm_integrity_c *ic, unsigned int i,
399 unsigned int j, unsigned char seq)
402 * Xor the number with section and sector, so that if a piece of
403 * journal is written at wrong place, it is detected.
405 return ic->commit_ids[seq] ^ cpu_to_le64(((__u64)i << 32) ^ j);
408 static void get_area_and_offset(struct dm_integrity_c *ic, sector_t data_sector,
409 sector_t *area, sector_t *offset)
412 __u8 log2_interleave_sectors = ic->sb->log2_interleave_sectors;
413 *area = data_sector >> log2_interleave_sectors;
414 *offset = (unsigned int)data_sector & ((1U << log2_interleave_sectors) - 1);
417 *offset = data_sector;
421 #define sector_to_block(ic, n) \
423 BUG_ON((n) & (unsigned int)((ic)->sectors_per_block - 1)); \
424 (n) >>= (ic)->sb->log2_sectors_per_block; \
427 static __u64 get_metadata_sector_and_offset(struct dm_integrity_c *ic, sector_t area,
428 sector_t offset, unsigned int *metadata_offset)
433 ms = area << ic->sb->log2_interleave_sectors;
434 if (likely(ic->log2_metadata_run >= 0))
435 ms += area << ic->log2_metadata_run;
437 ms += area * ic->metadata_run;
438 ms >>= ic->log2_buffer_sectors;
440 sector_to_block(ic, offset);
442 if (likely(ic->log2_tag_size >= 0)) {
443 ms += offset >> (SECTOR_SHIFT + ic->log2_buffer_sectors - ic->log2_tag_size);
444 mo = (offset << ic->log2_tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
446 ms += (__u64)offset * ic->tag_size >> (SECTOR_SHIFT + ic->log2_buffer_sectors);
447 mo = (offset * ic->tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
449 *metadata_offset = mo;
453 static sector_t get_data_sector(struct dm_integrity_c *ic, sector_t area, sector_t offset)
460 result = area << ic->sb->log2_interleave_sectors;
461 if (likely(ic->log2_metadata_run >= 0))
462 result += (area + 1) << ic->log2_metadata_run;
464 result += (area + 1) * ic->metadata_run;
466 result += (sector_t)ic->initial_sectors + offset;
472 static void wraparound_section(struct dm_integrity_c *ic, unsigned int *sec_ptr)
474 if (unlikely(*sec_ptr >= ic->journal_sections))
475 *sec_ptr -= ic->journal_sections;
478 static void sb_set_version(struct dm_integrity_c *ic)
480 if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC))
481 ic->sb->version = SB_VERSION_5;
482 else if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING))
483 ic->sb->version = SB_VERSION_4;
484 else if (ic->mode == 'B' || ic->sb->flags & cpu_to_le32(SB_FLAG_DIRTY_BITMAP))
485 ic->sb->version = SB_VERSION_3;
486 else if (ic->meta_dev || ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
487 ic->sb->version = SB_VERSION_2;
489 ic->sb->version = SB_VERSION_1;
492 static int sb_mac(struct dm_integrity_c *ic, bool wr)
494 SHASH_DESC_ON_STACK(desc, ic->journal_mac);
496 unsigned int size = crypto_shash_digestsize(ic->journal_mac);
498 if (sizeof(struct superblock) + size > 1 << SECTOR_SHIFT) {
499 dm_integrity_io_error(ic, "digest is too long", -EINVAL);
503 desc->tfm = ic->journal_mac;
505 r = crypto_shash_init(desc);
506 if (unlikely(r < 0)) {
507 dm_integrity_io_error(ic, "crypto_shash_init", r);
511 r = crypto_shash_update(desc, (__u8 *)ic->sb, (1 << SECTOR_SHIFT) - size);
512 if (unlikely(r < 0)) {
513 dm_integrity_io_error(ic, "crypto_shash_update", r);
518 r = crypto_shash_final(desc, (__u8 *)ic->sb + (1 << SECTOR_SHIFT) - size);
519 if (unlikely(r < 0)) {
520 dm_integrity_io_error(ic, "crypto_shash_final", r);
524 __u8 result[HASH_MAX_DIGESTSIZE];
526 r = crypto_shash_final(desc, result);
527 if (unlikely(r < 0)) {
528 dm_integrity_io_error(ic, "crypto_shash_final", r);
531 if (memcmp((__u8 *)ic->sb + (1 << SECTOR_SHIFT) - size, result, size)) {
532 dm_integrity_io_error(ic, "superblock mac", -EILSEQ);
533 dm_audit_log_target(DM_MSG_PREFIX, "mac-superblock", ic->ti, 0);
541 static int sync_rw_sb(struct dm_integrity_c *ic, blk_opf_t opf)
543 struct dm_io_request io_req;
544 struct dm_io_region io_loc;
545 const enum req_op op = opf & REQ_OP_MASK;
549 io_req.mem.type = DM_IO_KMEM;
550 io_req.mem.ptr.addr = ic->sb;
551 io_req.notify.fn = NULL;
552 io_req.client = ic->io;
553 io_loc.bdev = ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev;
554 io_loc.sector = ic->start;
555 io_loc.count = SB_SECTORS;
557 if (op == REQ_OP_WRITE) {
559 if (ic->journal_mac && ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
560 r = sb_mac(ic, true);
566 r = dm_io(&io_req, 1, &io_loc, NULL);
570 if (op == REQ_OP_READ) {
571 if (ic->mode != 'R' && ic->journal_mac && ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
572 r = sb_mac(ic, false);
581 #define BITMAP_OP_TEST_ALL_SET 0
582 #define BITMAP_OP_TEST_ALL_CLEAR 1
583 #define BITMAP_OP_SET 2
584 #define BITMAP_OP_CLEAR 3
586 static bool block_bitmap_op(struct dm_integrity_c *ic, struct page_list *bitmap,
587 sector_t sector, sector_t n_sectors, int mode)
589 unsigned long bit, end_bit, this_end_bit, page, end_page;
592 if (unlikely(((sector | n_sectors) & ((1 << ic->sb->log2_sectors_per_block) - 1)) != 0)) {
593 DMCRIT("invalid bitmap access (%llx,%llx,%d,%d,%d)",
596 ic->sb->log2_sectors_per_block,
597 ic->log2_blocks_per_bitmap_bit,
602 if (unlikely(!n_sectors))
605 bit = sector >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
606 end_bit = (sector + n_sectors - 1) >>
607 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
609 page = bit / (PAGE_SIZE * 8);
610 bit %= PAGE_SIZE * 8;
612 end_page = end_bit / (PAGE_SIZE * 8);
613 end_bit %= PAGE_SIZE * 8;
617 this_end_bit = PAGE_SIZE * 8 - 1;
619 this_end_bit = end_bit;
621 data = lowmem_page_address(bitmap[page].page);
623 if (mode == BITMAP_OP_TEST_ALL_SET) {
624 while (bit <= this_end_bit) {
625 if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
627 if (data[bit / BITS_PER_LONG] != -1)
629 bit += BITS_PER_LONG;
630 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
633 if (!test_bit(bit, data))
637 } else if (mode == BITMAP_OP_TEST_ALL_CLEAR) {
638 while (bit <= this_end_bit) {
639 if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
641 if (data[bit / BITS_PER_LONG] != 0)
643 bit += BITS_PER_LONG;
644 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
647 if (test_bit(bit, data))
651 } else if (mode == BITMAP_OP_SET) {
652 while (bit <= this_end_bit) {
653 if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
655 data[bit / BITS_PER_LONG] = -1;
656 bit += BITS_PER_LONG;
657 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
660 __set_bit(bit, data);
663 } else if (mode == BITMAP_OP_CLEAR) {
664 if (!bit && this_end_bit == PAGE_SIZE * 8 - 1)
667 while (bit <= this_end_bit) {
668 if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
670 data[bit / BITS_PER_LONG] = 0;
671 bit += BITS_PER_LONG;
672 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
675 __clear_bit(bit, data);
683 if (unlikely(page < end_page)) {
692 static void block_bitmap_copy(struct dm_integrity_c *ic, struct page_list *dst, struct page_list *src)
694 unsigned int n_bitmap_pages = DIV_ROUND_UP(ic->n_bitmap_blocks, PAGE_SIZE / BITMAP_BLOCK_SIZE);
697 for (i = 0; i < n_bitmap_pages; i++) {
698 unsigned long *dst_data = lowmem_page_address(dst[i].page);
699 unsigned long *src_data = lowmem_page_address(src[i].page);
701 copy_page(dst_data, src_data);
705 static struct bitmap_block_status *sector_to_bitmap_block(struct dm_integrity_c *ic, sector_t sector)
707 unsigned int bit = sector >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
708 unsigned int bitmap_block = bit / (BITMAP_BLOCK_SIZE * 8);
710 BUG_ON(bitmap_block >= ic->n_bitmap_blocks);
711 return &ic->bbs[bitmap_block];
714 static void access_journal_check(struct dm_integrity_c *ic, unsigned int section, unsigned int offset,
715 bool e, const char *function)
717 #if defined(CONFIG_DM_DEBUG) || defined(INTERNAL_VERIFY)
718 unsigned int limit = e ? ic->journal_section_entries : ic->journal_section_sectors;
720 if (unlikely(section >= ic->journal_sections) ||
721 unlikely(offset >= limit)) {
722 DMCRIT("%s: invalid access at (%u,%u), limit (%u,%u)",
723 function, section, offset, ic->journal_sections, limit);
729 static void page_list_location(struct dm_integrity_c *ic, unsigned int section, unsigned int offset,
730 unsigned int *pl_index, unsigned int *pl_offset)
734 access_journal_check(ic, section, offset, false, "page_list_location");
736 sector = section * ic->journal_section_sectors + offset;
738 *pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
739 *pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
742 static struct journal_sector *access_page_list(struct dm_integrity_c *ic, struct page_list *pl,
743 unsigned int section, unsigned int offset, unsigned int *n_sectors)
745 unsigned int pl_index, pl_offset;
748 page_list_location(ic, section, offset, &pl_index, &pl_offset);
751 *n_sectors = (PAGE_SIZE - pl_offset) >> SECTOR_SHIFT;
753 va = lowmem_page_address(pl[pl_index].page);
755 return (struct journal_sector *)(va + pl_offset);
758 static struct journal_sector *access_journal(struct dm_integrity_c *ic, unsigned int section, unsigned int offset)
760 return access_page_list(ic, ic->journal, section, offset, NULL);
763 static struct journal_entry *access_journal_entry(struct dm_integrity_c *ic, unsigned int section, unsigned int n)
765 unsigned int rel_sector, offset;
766 struct journal_sector *js;
768 access_journal_check(ic, section, n, true, "access_journal_entry");
770 rel_sector = n % JOURNAL_BLOCK_SECTORS;
771 offset = n / JOURNAL_BLOCK_SECTORS;
773 js = access_journal(ic, section, rel_sector);
774 return (struct journal_entry *)((char *)js + offset * ic->journal_entry_size);
777 static struct journal_sector *access_journal_data(struct dm_integrity_c *ic, unsigned int section, unsigned int n)
779 n <<= ic->sb->log2_sectors_per_block;
781 n += JOURNAL_BLOCK_SECTORS;
783 access_journal_check(ic, section, n, false, "access_journal_data");
785 return access_journal(ic, section, n);
788 static void section_mac(struct dm_integrity_c *ic, unsigned int section, __u8 result[JOURNAL_MAC_SIZE])
790 SHASH_DESC_ON_STACK(desc, ic->journal_mac);
792 unsigned int j, size;
794 desc->tfm = ic->journal_mac;
796 r = crypto_shash_init(desc);
797 if (unlikely(r < 0)) {
798 dm_integrity_io_error(ic, "crypto_shash_init", r);
802 if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
805 r = crypto_shash_update(desc, (__u8 *)&ic->sb->salt, SALT_SIZE);
806 if (unlikely(r < 0)) {
807 dm_integrity_io_error(ic, "crypto_shash_update", r);
811 section_le = cpu_to_le64(section);
812 r = crypto_shash_update(desc, (__u8 *)§ion_le, sizeof(section_le));
813 if (unlikely(r < 0)) {
814 dm_integrity_io_error(ic, "crypto_shash_update", r);
819 for (j = 0; j < ic->journal_section_entries; j++) {
820 struct journal_entry *je = access_journal_entry(ic, section, j);
822 r = crypto_shash_update(desc, (__u8 *)&je->u.sector, sizeof(je->u.sector));
823 if (unlikely(r < 0)) {
824 dm_integrity_io_error(ic, "crypto_shash_update", r);
829 size = crypto_shash_digestsize(ic->journal_mac);
831 if (likely(size <= JOURNAL_MAC_SIZE)) {
832 r = crypto_shash_final(desc, result);
833 if (unlikely(r < 0)) {
834 dm_integrity_io_error(ic, "crypto_shash_final", r);
837 memset(result + size, 0, JOURNAL_MAC_SIZE - size);
839 __u8 digest[HASH_MAX_DIGESTSIZE];
841 if (WARN_ON(size > sizeof(digest))) {
842 dm_integrity_io_error(ic, "digest_size", -EINVAL);
845 r = crypto_shash_final(desc, digest);
846 if (unlikely(r < 0)) {
847 dm_integrity_io_error(ic, "crypto_shash_final", r);
850 memcpy(result, digest, JOURNAL_MAC_SIZE);
855 memset(result, 0, JOURNAL_MAC_SIZE);
858 static void rw_section_mac(struct dm_integrity_c *ic, unsigned int section, bool wr)
860 __u8 result[JOURNAL_MAC_SIZE];
863 if (!ic->journal_mac)
866 section_mac(ic, section, result);
868 for (j = 0; j < JOURNAL_BLOCK_SECTORS; j++) {
869 struct journal_sector *js = access_journal(ic, section, j);
872 memcpy(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR);
874 if (memcmp(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR)) {
875 dm_integrity_io_error(ic, "journal mac", -EILSEQ);
876 dm_audit_log_target(DM_MSG_PREFIX, "mac-journal", ic->ti, 0);
882 static void complete_journal_op(void *context)
884 struct journal_completion *comp = context;
886 BUG_ON(!atomic_read(&comp->in_flight));
887 if (likely(atomic_dec_and_test(&comp->in_flight)))
888 complete(&comp->comp);
891 static void xor_journal(struct dm_integrity_c *ic, bool encrypt, unsigned int section,
892 unsigned int n_sections, struct journal_completion *comp)
894 struct async_submit_ctl submit;
895 size_t n_bytes = (size_t)(n_sections * ic->journal_section_sectors) << SECTOR_SHIFT;
896 unsigned int pl_index, pl_offset, section_index;
897 struct page_list *source_pl, *target_pl;
899 if (likely(encrypt)) {
900 source_pl = ic->journal;
901 target_pl = ic->journal_io;
903 source_pl = ic->journal_io;
904 target_pl = ic->journal;
907 page_list_location(ic, section, 0, &pl_index, &pl_offset);
909 atomic_add(roundup(pl_offset + n_bytes, PAGE_SIZE) >> PAGE_SHIFT, &comp->in_flight);
911 init_async_submit(&submit, ASYNC_TX_XOR_ZERO_DST, NULL, complete_journal_op, comp, NULL);
913 section_index = pl_index;
917 struct page *src_pages[2];
918 struct page *dst_page;
920 while (unlikely(pl_index == section_index)) {
924 rw_section_mac(ic, section, true);
929 page_list_location(ic, section, 0, §ion_index, &dummy);
932 this_step = min(n_bytes, (size_t)PAGE_SIZE - pl_offset);
933 dst_page = target_pl[pl_index].page;
934 src_pages[0] = source_pl[pl_index].page;
935 src_pages[1] = ic->journal_xor[pl_index].page;
937 async_xor(dst_page, src_pages, pl_offset, 2, this_step, &submit);
941 n_bytes -= this_step;
946 async_tx_issue_pending_all();
949 static void complete_journal_encrypt(void *data, int err)
951 struct journal_completion *comp = data;
954 if (likely(err == -EINPROGRESS)) {
955 complete(&comp->ic->crypto_backoff);
958 dm_integrity_io_error(comp->ic, "asynchronous encrypt", err);
960 complete_journal_op(comp);
963 static bool do_crypt(bool encrypt, struct skcipher_request *req, struct journal_completion *comp)
967 skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
968 complete_journal_encrypt, comp);
970 r = crypto_skcipher_encrypt(req);
972 r = crypto_skcipher_decrypt(req);
975 if (likely(r == -EINPROGRESS))
977 if (likely(r == -EBUSY)) {
978 wait_for_completion(&comp->ic->crypto_backoff);
979 reinit_completion(&comp->ic->crypto_backoff);
982 dm_integrity_io_error(comp->ic, "encrypt", r);
986 static void crypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned int section,
987 unsigned int n_sections, struct journal_completion *comp)
989 struct scatterlist **source_sg;
990 struct scatterlist **target_sg;
992 atomic_add(2, &comp->in_flight);
994 if (likely(encrypt)) {
995 source_sg = ic->journal_scatterlist;
996 target_sg = ic->journal_io_scatterlist;
998 source_sg = ic->journal_io_scatterlist;
999 target_sg = ic->journal_scatterlist;
1003 struct skcipher_request *req;
1004 unsigned int ivsize;
1007 if (likely(encrypt))
1008 rw_section_mac(ic, section, true);
1010 req = ic->sk_requests[section];
1011 ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
1014 memcpy(iv, iv + ivsize, ivsize);
1016 req->src = source_sg[section];
1017 req->dst = target_sg[section];
1019 if (unlikely(do_crypt(encrypt, req, comp)))
1020 atomic_inc(&comp->in_flight);
1024 } while (n_sections);
1026 atomic_dec(&comp->in_flight);
1027 complete_journal_op(comp);
1030 static void encrypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned int section,
1031 unsigned int n_sections, struct journal_completion *comp)
1033 if (ic->journal_xor)
1034 return xor_journal(ic, encrypt, section, n_sections, comp);
1036 return crypt_journal(ic, encrypt, section, n_sections, comp);
1039 static void complete_journal_io(unsigned long error, void *context)
1041 struct journal_completion *comp = context;
1043 if (unlikely(error != 0))
1044 dm_integrity_io_error(comp->ic, "writing journal", -EIO);
1045 complete_journal_op(comp);
1048 static void rw_journal_sectors(struct dm_integrity_c *ic, blk_opf_t opf,
1049 unsigned int sector, unsigned int n_sectors,
1050 struct journal_completion *comp)
1052 struct dm_io_request io_req;
1053 struct dm_io_region io_loc;
1054 unsigned int pl_index, pl_offset;
1057 if (unlikely(dm_integrity_failed(ic))) {
1059 complete_journal_io(-1UL, comp);
1063 pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
1064 pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
1066 io_req.bi_opf = opf;
1067 io_req.mem.type = DM_IO_PAGE_LIST;
1069 io_req.mem.ptr.pl = &ic->journal_io[pl_index];
1071 io_req.mem.ptr.pl = &ic->journal[pl_index];
1072 io_req.mem.offset = pl_offset;
1073 if (likely(comp != NULL)) {
1074 io_req.notify.fn = complete_journal_io;
1075 io_req.notify.context = comp;
1077 io_req.notify.fn = NULL;
1079 io_req.client = ic->io;
1080 io_loc.bdev = ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev;
1081 io_loc.sector = ic->start + SB_SECTORS + sector;
1082 io_loc.count = n_sectors;
1084 r = dm_io(&io_req, 1, &io_loc, NULL);
1086 dm_integrity_io_error(ic, (opf & REQ_OP_MASK) == REQ_OP_READ ?
1087 "reading journal" : "writing journal", r);
1089 WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
1090 complete_journal_io(-1UL, comp);
1095 static void rw_journal(struct dm_integrity_c *ic, blk_opf_t opf,
1096 unsigned int section, unsigned int n_sections,
1097 struct journal_completion *comp)
1099 unsigned int sector, n_sectors;
1101 sector = section * ic->journal_section_sectors;
1102 n_sectors = n_sections * ic->journal_section_sectors;
1104 rw_journal_sectors(ic, opf, sector, n_sectors, comp);
1107 static void write_journal(struct dm_integrity_c *ic, unsigned int commit_start, unsigned int commit_sections)
1109 struct journal_completion io_comp;
1110 struct journal_completion crypt_comp_1;
1111 struct journal_completion crypt_comp_2;
1115 init_completion(&io_comp.comp);
1117 if (commit_start + commit_sections <= ic->journal_sections) {
1118 io_comp.in_flight = (atomic_t)ATOMIC_INIT(1);
1119 if (ic->journal_io) {
1120 crypt_comp_1.ic = ic;
1121 init_completion(&crypt_comp_1.comp);
1122 crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
1123 encrypt_journal(ic, true, commit_start, commit_sections, &crypt_comp_1);
1124 wait_for_completion_io(&crypt_comp_1.comp);
1126 for (i = 0; i < commit_sections; i++)
1127 rw_section_mac(ic, commit_start + i, true);
1129 rw_journal(ic, REQ_OP_WRITE | REQ_FUA | REQ_SYNC, commit_start,
1130 commit_sections, &io_comp);
1132 unsigned int to_end;
1134 io_comp.in_flight = (atomic_t)ATOMIC_INIT(2);
1135 to_end = ic->journal_sections - commit_start;
1136 if (ic->journal_io) {
1137 crypt_comp_1.ic = ic;
1138 init_completion(&crypt_comp_1.comp);
1139 crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
1140 encrypt_journal(ic, true, commit_start, to_end, &crypt_comp_1);
1141 if (try_wait_for_completion(&crypt_comp_1.comp)) {
1142 rw_journal(ic, REQ_OP_WRITE | REQ_FUA,
1143 commit_start, to_end, &io_comp);
1144 reinit_completion(&crypt_comp_1.comp);
1145 crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
1146 encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_1);
1147 wait_for_completion_io(&crypt_comp_1.comp);
1149 crypt_comp_2.ic = ic;
1150 init_completion(&crypt_comp_2.comp);
1151 crypt_comp_2.in_flight = (atomic_t)ATOMIC_INIT(0);
1152 encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_2);
1153 wait_for_completion_io(&crypt_comp_1.comp);
1154 rw_journal(ic, REQ_OP_WRITE | REQ_FUA, commit_start, to_end, &io_comp);
1155 wait_for_completion_io(&crypt_comp_2.comp);
1158 for (i = 0; i < to_end; i++)
1159 rw_section_mac(ic, commit_start + i, true);
1160 rw_journal(ic, REQ_OP_WRITE | REQ_FUA, commit_start, to_end, &io_comp);
1161 for (i = 0; i < commit_sections - to_end; i++)
1162 rw_section_mac(ic, i, true);
1164 rw_journal(ic, REQ_OP_WRITE | REQ_FUA, 0, commit_sections - to_end, &io_comp);
1167 wait_for_completion_io(&io_comp.comp);
1170 static void copy_from_journal(struct dm_integrity_c *ic, unsigned int section, unsigned int offset,
1171 unsigned int n_sectors, sector_t target, io_notify_fn fn, void *data)
1173 struct dm_io_request io_req;
1174 struct dm_io_region io_loc;
1176 unsigned int sector, pl_index, pl_offset;
1178 BUG_ON((target | n_sectors | offset) & (unsigned int)(ic->sectors_per_block - 1));
1180 if (unlikely(dm_integrity_failed(ic))) {
1185 sector = section * ic->journal_section_sectors + JOURNAL_BLOCK_SECTORS + offset;
1187 pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
1188 pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
1190 io_req.bi_opf = REQ_OP_WRITE;
1191 io_req.mem.type = DM_IO_PAGE_LIST;
1192 io_req.mem.ptr.pl = &ic->journal[pl_index];
1193 io_req.mem.offset = pl_offset;
1194 io_req.notify.fn = fn;
1195 io_req.notify.context = data;
1196 io_req.client = ic->io;
1197 io_loc.bdev = ic->dev->bdev;
1198 io_loc.sector = target;
1199 io_loc.count = n_sectors;
1201 r = dm_io(&io_req, 1, &io_loc, NULL);
1203 WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
1208 static bool ranges_overlap(struct dm_integrity_range *range1, struct dm_integrity_range *range2)
1210 return range1->logical_sector < range2->logical_sector + range2->n_sectors &&
1211 range1->logical_sector + range1->n_sectors > range2->logical_sector;
1214 static bool add_new_range(struct dm_integrity_c *ic, struct dm_integrity_range *new_range, bool check_waiting)
1216 struct rb_node **n = &ic->in_progress.rb_node;
1217 struct rb_node *parent;
1219 BUG_ON((new_range->logical_sector | new_range->n_sectors) & (unsigned int)(ic->sectors_per_block - 1));
1221 if (likely(check_waiting)) {
1222 struct dm_integrity_range *range;
1224 list_for_each_entry(range, &ic->wait_list, wait_entry) {
1225 if (unlikely(ranges_overlap(range, new_range)))
1233 struct dm_integrity_range *range = container_of(*n, struct dm_integrity_range, node);
1236 if (new_range->logical_sector + new_range->n_sectors <= range->logical_sector)
1237 n = &range->node.rb_left;
1238 else if (new_range->logical_sector >= range->logical_sector + range->n_sectors)
1239 n = &range->node.rb_right;
1244 rb_link_node(&new_range->node, parent, n);
1245 rb_insert_color(&new_range->node, &ic->in_progress);
1250 static void remove_range_unlocked(struct dm_integrity_c *ic, struct dm_integrity_range *range)
1252 rb_erase(&range->node, &ic->in_progress);
1253 while (unlikely(!list_empty(&ic->wait_list))) {
1254 struct dm_integrity_range *last_range =
1255 list_first_entry(&ic->wait_list, struct dm_integrity_range, wait_entry);
1256 struct task_struct *last_range_task;
1258 last_range_task = last_range->task;
1259 list_del(&last_range->wait_entry);
1260 if (!add_new_range(ic, last_range, false)) {
1261 last_range->task = last_range_task;
1262 list_add(&last_range->wait_entry, &ic->wait_list);
1265 last_range->waiting = false;
1266 wake_up_process(last_range_task);
1270 static void remove_range(struct dm_integrity_c *ic, struct dm_integrity_range *range)
1272 unsigned long flags;
1274 spin_lock_irqsave(&ic->endio_wait.lock, flags);
1275 remove_range_unlocked(ic, range);
1276 spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1279 static void wait_and_add_new_range(struct dm_integrity_c *ic, struct dm_integrity_range *new_range)
1281 new_range->waiting = true;
1282 list_add_tail(&new_range->wait_entry, &ic->wait_list);
1283 new_range->task = current;
1285 __set_current_state(TASK_UNINTERRUPTIBLE);
1286 spin_unlock_irq(&ic->endio_wait.lock);
1288 spin_lock_irq(&ic->endio_wait.lock);
1289 } while (unlikely(new_range->waiting));
1292 static void add_new_range_and_wait(struct dm_integrity_c *ic, struct dm_integrity_range *new_range)
1294 if (unlikely(!add_new_range(ic, new_range, true)))
1295 wait_and_add_new_range(ic, new_range);
1298 static void init_journal_node(struct journal_node *node)
1300 RB_CLEAR_NODE(&node->node);
1301 node->sector = (sector_t)-1;
1304 static void add_journal_node(struct dm_integrity_c *ic, struct journal_node *node, sector_t sector)
1306 struct rb_node **link;
1307 struct rb_node *parent;
1309 node->sector = sector;
1310 BUG_ON(!RB_EMPTY_NODE(&node->node));
1312 link = &ic->journal_tree_root.rb_node;
1316 struct journal_node *j;
1319 j = container_of(parent, struct journal_node, node);
1320 if (sector < j->sector)
1321 link = &j->node.rb_left;
1323 link = &j->node.rb_right;
1326 rb_link_node(&node->node, parent, link);
1327 rb_insert_color(&node->node, &ic->journal_tree_root);
1330 static void remove_journal_node(struct dm_integrity_c *ic, struct journal_node *node)
1332 BUG_ON(RB_EMPTY_NODE(&node->node));
1333 rb_erase(&node->node, &ic->journal_tree_root);
1334 init_journal_node(node);
1337 #define NOT_FOUND (-1U)
1339 static unsigned int find_journal_node(struct dm_integrity_c *ic, sector_t sector, sector_t *next_sector)
1341 struct rb_node *n = ic->journal_tree_root.rb_node;
1342 unsigned int found = NOT_FOUND;
1344 *next_sector = (sector_t)-1;
1346 struct journal_node *j = container_of(n, struct journal_node, node);
1348 if (sector == j->sector)
1349 found = j - ic->journal_tree;
1351 if (sector < j->sector) {
1352 *next_sector = j->sector;
1353 n = j->node.rb_left;
1355 n = j->node.rb_right;
1361 static bool test_journal_node(struct dm_integrity_c *ic, unsigned int pos, sector_t sector)
1363 struct journal_node *node, *next_node;
1364 struct rb_node *next;
1366 if (unlikely(pos >= ic->journal_entries))
1368 node = &ic->journal_tree[pos];
1369 if (unlikely(RB_EMPTY_NODE(&node->node)))
1371 if (unlikely(node->sector != sector))
1374 next = rb_next(&node->node);
1375 if (unlikely(!next))
1378 next_node = container_of(next, struct journal_node, node);
1379 return next_node->sector != sector;
1382 static bool find_newer_committed_node(struct dm_integrity_c *ic, struct journal_node *node)
1384 struct rb_node *next;
1385 struct journal_node *next_node;
1386 unsigned int next_section;
1388 BUG_ON(RB_EMPTY_NODE(&node->node));
1390 next = rb_next(&node->node);
1391 if (unlikely(!next))
1394 next_node = container_of(next, struct journal_node, node);
1396 if (next_node->sector != node->sector)
1399 next_section = (unsigned int)(next_node - ic->journal_tree) / ic->journal_section_entries;
1400 if (next_section >= ic->committed_section &&
1401 next_section < ic->committed_section + ic->n_committed_sections)
1403 if (next_section + ic->journal_sections < ic->committed_section + ic->n_committed_sections)
1413 static int dm_integrity_rw_tag(struct dm_integrity_c *ic, unsigned char *tag, sector_t *metadata_block,
1414 unsigned int *metadata_offset, unsigned int total_size, int op)
1416 #define MAY_BE_FILLER 1
1417 #define MAY_BE_HASH 2
1418 unsigned int hash_offset = 0;
1419 unsigned int may_be = MAY_BE_HASH | (ic->discard ? MAY_BE_FILLER : 0);
1422 unsigned char *data, *dp;
1423 struct dm_buffer *b;
1424 unsigned int to_copy;
1427 r = dm_integrity_failed(ic);
1431 data = dm_bufio_read(ic->bufio, *metadata_block, &b);
1433 return PTR_ERR(data);
1435 to_copy = min((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - *metadata_offset, total_size);
1436 dp = data + *metadata_offset;
1437 if (op == TAG_READ) {
1438 memcpy(tag, dp, to_copy);
1439 } else if (op == TAG_WRITE) {
1440 if (memcmp(dp, tag, to_copy)) {
1441 memcpy(dp, tag, to_copy);
1442 dm_bufio_mark_partial_buffer_dirty(b, *metadata_offset, *metadata_offset + to_copy);
1445 /* e.g.: op == TAG_CMP */
1447 if (likely(is_power_of_2(ic->tag_size))) {
1448 if (unlikely(memcmp(dp, tag, to_copy)))
1449 if (unlikely(!ic->discard) ||
1450 unlikely(memchr_inv(dp, DISCARD_FILLER, to_copy) != NULL)) {
1458 for (i = 0; i < to_copy; i++, ts--) {
1459 if (unlikely(dp[i] != tag[i]))
1460 may_be &= ~MAY_BE_HASH;
1461 if (likely(dp[i] != DISCARD_FILLER))
1462 may_be &= ~MAY_BE_FILLER;
1464 if (unlikely(hash_offset == ic->tag_size)) {
1465 if (unlikely(!may_be)) {
1466 dm_bufio_release(b);
1470 may_be = MAY_BE_HASH | (ic->discard ? MAY_BE_FILLER : 0);
1475 dm_bufio_release(b);
1478 *metadata_offset += to_copy;
1479 if (unlikely(*metadata_offset == 1U << SECTOR_SHIFT << ic->log2_buffer_sectors)) {
1480 (*metadata_block)++;
1481 *metadata_offset = 0;
1484 if (unlikely(!is_power_of_2(ic->tag_size)))
1485 hash_offset = (hash_offset + to_copy) % ic->tag_size;
1487 total_size -= to_copy;
1488 } while (unlikely(total_size));
1491 #undef MAY_BE_FILLER
1495 struct flush_request {
1496 struct dm_io_request io_req;
1497 struct dm_io_region io_reg;
1498 struct dm_integrity_c *ic;
1499 struct completion comp;
1502 static void flush_notify(unsigned long error, void *fr_)
1504 struct flush_request *fr = fr_;
1506 if (unlikely(error != 0))
1507 dm_integrity_io_error(fr->ic, "flushing disk cache", -EIO);
1508 complete(&fr->comp);
1511 static void dm_integrity_flush_buffers(struct dm_integrity_c *ic, bool flush_data)
1514 struct flush_request fr;
1519 fr.io_req.bi_opf = REQ_OP_WRITE | REQ_PREFLUSH | REQ_SYNC,
1520 fr.io_req.mem.type = DM_IO_KMEM,
1521 fr.io_req.mem.ptr.addr = NULL,
1522 fr.io_req.notify.fn = flush_notify,
1523 fr.io_req.notify.context = &fr;
1524 fr.io_req.client = dm_bufio_get_dm_io_client(ic->bufio),
1525 fr.io_reg.bdev = ic->dev->bdev,
1526 fr.io_reg.sector = 0,
1527 fr.io_reg.count = 0,
1529 init_completion(&fr.comp);
1530 r = dm_io(&fr.io_req, 1, &fr.io_reg, NULL);
1534 r = dm_bufio_write_dirty_buffers(ic->bufio);
1536 dm_integrity_io_error(ic, "writing tags", r);
1539 wait_for_completion(&fr.comp);
1542 static void sleep_on_endio_wait(struct dm_integrity_c *ic)
1544 DECLARE_WAITQUEUE(wait, current);
1546 __add_wait_queue(&ic->endio_wait, &wait);
1547 __set_current_state(TASK_UNINTERRUPTIBLE);
1548 spin_unlock_irq(&ic->endio_wait.lock);
1550 spin_lock_irq(&ic->endio_wait.lock);
1551 __remove_wait_queue(&ic->endio_wait, &wait);
1554 static void autocommit_fn(struct timer_list *t)
1556 struct dm_integrity_c *ic = from_timer(ic, t, autocommit_timer);
1558 if (likely(!dm_integrity_failed(ic)))
1559 queue_work(ic->commit_wq, &ic->commit_work);
1562 static void schedule_autocommit(struct dm_integrity_c *ic)
1564 if (!timer_pending(&ic->autocommit_timer))
1565 mod_timer(&ic->autocommit_timer, jiffies + ic->autocommit_jiffies);
1568 static void submit_flush_bio(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
1571 unsigned long flags;
1573 spin_lock_irqsave(&ic->endio_wait.lock, flags);
1574 bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1575 bio_list_add(&ic->flush_bio_list, bio);
1576 spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1578 queue_work(ic->commit_wq, &ic->commit_work);
1581 static void do_endio(struct dm_integrity_c *ic, struct bio *bio)
1585 r = dm_integrity_failed(ic);
1586 if (unlikely(r) && !bio->bi_status)
1587 bio->bi_status = errno_to_blk_status(r);
1588 if (unlikely(ic->synchronous_mode) && bio_op(bio) == REQ_OP_WRITE) {
1589 unsigned long flags;
1591 spin_lock_irqsave(&ic->endio_wait.lock, flags);
1592 bio_list_add(&ic->synchronous_bios, bio);
1593 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
1594 spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1600 static void do_endio_flush(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
1602 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1604 if (unlikely(dio->fua) && likely(!bio->bi_status) && likely(!dm_integrity_failed(ic)))
1605 submit_flush_bio(ic, dio);
1610 static void dec_in_flight(struct dm_integrity_io *dio)
1612 if (atomic_dec_and_test(&dio->in_flight)) {
1613 struct dm_integrity_c *ic = dio->ic;
1616 remove_range(ic, &dio->range);
1618 if (dio->op == REQ_OP_WRITE || unlikely(dio->op == REQ_OP_DISCARD))
1619 schedule_autocommit(ic);
1621 bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1622 if (unlikely(dio->bi_status) && !bio->bi_status)
1623 bio->bi_status = dio->bi_status;
1624 if (likely(!bio->bi_status) && unlikely(bio_sectors(bio) != dio->range.n_sectors)) {
1625 dio->range.logical_sector += dio->range.n_sectors;
1626 bio_advance(bio, dio->range.n_sectors << SECTOR_SHIFT);
1627 INIT_WORK(&dio->work, integrity_bio_wait);
1628 queue_work(ic->offload_wq, &dio->work);
1631 do_endio_flush(ic, dio);
1635 static void integrity_end_io(struct bio *bio)
1637 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
1639 dm_bio_restore(&dio->bio_details, bio);
1640 if (bio->bi_integrity)
1641 bio->bi_opf |= REQ_INTEGRITY;
1643 if (dio->completion)
1644 complete(dio->completion);
1649 static void integrity_sector_checksum(struct dm_integrity_c *ic, sector_t sector,
1650 const char *data, char *result)
1652 __le64 sector_le = cpu_to_le64(sector);
1653 SHASH_DESC_ON_STACK(req, ic->internal_hash);
1655 unsigned int digest_size;
1657 req->tfm = ic->internal_hash;
1659 r = crypto_shash_init(req);
1660 if (unlikely(r < 0)) {
1661 dm_integrity_io_error(ic, "crypto_shash_init", r);
1665 if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
1666 r = crypto_shash_update(req, (__u8 *)&ic->sb->salt, SALT_SIZE);
1667 if (unlikely(r < 0)) {
1668 dm_integrity_io_error(ic, "crypto_shash_update", r);
1673 r = crypto_shash_update(req, (const __u8 *)§or_le, sizeof(sector_le));
1674 if (unlikely(r < 0)) {
1675 dm_integrity_io_error(ic, "crypto_shash_update", r);
1679 r = crypto_shash_update(req, data, ic->sectors_per_block << SECTOR_SHIFT);
1680 if (unlikely(r < 0)) {
1681 dm_integrity_io_error(ic, "crypto_shash_update", r);
1685 r = crypto_shash_final(req, result);
1686 if (unlikely(r < 0)) {
1687 dm_integrity_io_error(ic, "crypto_shash_final", r);
1691 digest_size = crypto_shash_digestsize(ic->internal_hash);
1692 if (unlikely(digest_size < ic->tag_size))
1693 memset(result + digest_size, 0, ic->tag_size - digest_size);
1698 /* this shouldn't happen anyway, the hash functions have no reason to fail */
1699 get_random_bytes(result, ic->tag_size);
1702 static void integrity_metadata(struct work_struct *w)
1704 struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
1705 struct dm_integrity_c *ic = dio->ic;
1709 if (ic->internal_hash) {
1710 struct bvec_iter iter;
1712 unsigned int digest_size = crypto_shash_digestsize(ic->internal_hash);
1713 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1715 unsigned int extra_space = unlikely(digest_size > ic->tag_size) ? digest_size - ic->tag_size : 0;
1716 char checksums_onstack[max_t(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
1718 unsigned int sectors_to_process;
1720 if (unlikely(ic->mode == 'R'))
1723 if (likely(dio->op != REQ_OP_DISCARD))
1724 checksums = kmalloc((PAGE_SIZE >> SECTOR_SHIFT >> ic->sb->log2_sectors_per_block) * ic->tag_size + extra_space,
1725 GFP_NOIO | __GFP_NORETRY | __GFP_NOWARN);
1727 checksums = kmalloc(PAGE_SIZE, GFP_NOIO | __GFP_NORETRY | __GFP_NOWARN);
1729 checksums = checksums_onstack;
1730 if (WARN_ON(extra_space &&
1731 digest_size > sizeof(checksums_onstack))) {
1737 if (unlikely(dio->op == REQ_OP_DISCARD)) {
1738 unsigned int bi_size = dio->bio_details.bi_iter.bi_size;
1739 unsigned int max_size = likely(checksums != checksums_onstack) ? PAGE_SIZE : HASH_MAX_DIGESTSIZE;
1740 unsigned int max_blocks = max_size / ic->tag_size;
1742 memset(checksums, DISCARD_FILLER, max_size);
1745 unsigned int this_step_blocks = bi_size >> (SECTOR_SHIFT + ic->sb->log2_sectors_per_block);
1747 this_step_blocks = min(this_step_blocks, max_blocks);
1748 r = dm_integrity_rw_tag(ic, checksums, &dio->metadata_block, &dio->metadata_offset,
1749 this_step_blocks * ic->tag_size, TAG_WRITE);
1751 if (likely(checksums != checksums_onstack))
1756 bi_size -= this_step_blocks << (SECTOR_SHIFT + ic->sb->log2_sectors_per_block);
1759 if (likely(checksums != checksums_onstack))
1764 sector = dio->range.logical_sector;
1765 sectors_to_process = dio->range.n_sectors;
1767 __bio_for_each_segment(bv, bio, iter, dio->bio_details.bi_iter) {
1769 char *mem, *checksums_ptr;
1772 mem = bvec_kmap_local(&bv);
1774 checksums_ptr = checksums;
1776 integrity_sector_checksum(ic, sector, mem + pos, checksums_ptr);
1777 checksums_ptr += ic->tag_size;
1778 sectors_to_process -= ic->sectors_per_block;
1779 pos += ic->sectors_per_block << SECTOR_SHIFT;
1780 sector += ic->sectors_per_block;
1781 } while (pos < bv.bv_len && sectors_to_process && checksums != checksums_onstack);
1784 r = dm_integrity_rw_tag(ic, checksums, &dio->metadata_block, &dio->metadata_offset,
1785 checksums_ptr - checksums, dio->op == REQ_OP_READ ? TAG_CMP : TAG_WRITE);
1790 s = sector - ((r + ic->tag_size - 1) / ic->tag_size);
1791 DMERR_LIMIT("%pg: Checksum failed at sector 0x%llx",
1794 atomic64_inc(&ic->number_of_mismatches);
1795 dm_audit_log_bio(DM_MSG_PREFIX, "integrity-checksum",
1798 if (likely(checksums != checksums_onstack))
1803 if (!sectors_to_process)
1806 if (unlikely(pos < bv.bv_len)) {
1807 bv.bv_offset += pos;
1813 if (likely(checksums != checksums_onstack))
1816 struct bio_integrity_payload *bip = dio->bio_details.bi_integrity;
1820 struct bvec_iter iter;
1821 unsigned int data_to_process = dio->range.n_sectors;
1823 sector_to_block(ic, data_to_process);
1824 data_to_process *= ic->tag_size;
1826 bip_for_each_vec(biv, bip, iter) {
1828 unsigned int this_len;
1830 BUG_ON(PageHighMem(biv.bv_page));
1831 tag = bvec_virt(&biv);
1832 this_len = min(biv.bv_len, data_to_process);
1833 r = dm_integrity_rw_tag(ic, tag, &dio->metadata_block, &dio->metadata_offset,
1834 this_len, dio->op == REQ_OP_READ ? TAG_READ : TAG_WRITE);
1837 data_to_process -= this_len;
1838 if (!data_to_process)
1847 dio->bi_status = errno_to_blk_status(r);
1851 static int dm_integrity_map(struct dm_target *ti, struct bio *bio)
1853 struct dm_integrity_c *ic = ti->private;
1854 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
1855 struct bio_integrity_payload *bip;
1857 sector_t area, offset;
1861 dio->op = bio_op(bio);
1863 if (unlikely(dio->op == REQ_OP_DISCARD)) {
1864 if (ti->max_io_len) {
1865 sector_t sec = dm_target_offset(ti, bio->bi_iter.bi_sector);
1866 unsigned int log2_max_io_len = __fls(ti->max_io_len);
1867 sector_t start_boundary = sec >> log2_max_io_len;
1868 sector_t end_boundary = (sec + bio_sectors(bio) - 1) >> log2_max_io_len;
1870 if (start_boundary < end_boundary) {
1871 sector_t len = ti->max_io_len - (sec & (ti->max_io_len - 1));
1873 dm_accept_partial_bio(bio, len);
1878 if (unlikely(bio->bi_opf & REQ_PREFLUSH)) {
1879 submit_flush_bio(ic, dio);
1880 return DM_MAPIO_SUBMITTED;
1883 dio->range.logical_sector = dm_target_offset(ti, bio->bi_iter.bi_sector);
1884 dio->fua = dio->op == REQ_OP_WRITE && bio->bi_opf & REQ_FUA;
1885 if (unlikely(dio->fua)) {
1887 * Don't pass down the FUA flag because we have to flush
1888 * disk cache anyway.
1890 bio->bi_opf &= ~REQ_FUA;
1892 if (unlikely(dio->range.logical_sector + bio_sectors(bio) > ic->provided_data_sectors)) {
1893 DMERR("Too big sector number: 0x%llx + 0x%x > 0x%llx",
1894 dio->range.logical_sector, bio_sectors(bio),
1895 ic->provided_data_sectors);
1896 return DM_MAPIO_KILL;
1898 if (unlikely((dio->range.logical_sector | bio_sectors(bio)) & (unsigned int)(ic->sectors_per_block - 1))) {
1899 DMERR("Bio not aligned on %u sectors: 0x%llx, 0x%x",
1900 ic->sectors_per_block,
1901 dio->range.logical_sector, bio_sectors(bio));
1902 return DM_MAPIO_KILL;
1905 if (ic->sectors_per_block > 1 && likely(dio->op != REQ_OP_DISCARD)) {
1906 struct bvec_iter iter;
1909 bio_for_each_segment(bv, bio, iter) {
1910 if (unlikely(bv.bv_len & ((ic->sectors_per_block << SECTOR_SHIFT) - 1))) {
1911 DMERR("Bio vector (%u,%u) is not aligned on %u-sector boundary",
1912 bv.bv_offset, bv.bv_len, ic->sectors_per_block);
1913 return DM_MAPIO_KILL;
1918 bip = bio_integrity(bio);
1919 if (!ic->internal_hash) {
1921 unsigned int wanted_tag_size = bio_sectors(bio) >> ic->sb->log2_sectors_per_block;
1923 if (ic->log2_tag_size >= 0)
1924 wanted_tag_size <<= ic->log2_tag_size;
1926 wanted_tag_size *= ic->tag_size;
1927 if (unlikely(wanted_tag_size != bip->bip_iter.bi_size)) {
1928 DMERR("Invalid integrity data size %u, expected %u",
1929 bip->bip_iter.bi_size, wanted_tag_size);
1930 return DM_MAPIO_KILL;
1934 if (unlikely(bip != NULL)) {
1935 DMERR("Unexpected integrity data when using internal hash");
1936 return DM_MAPIO_KILL;
1940 if (unlikely(ic->mode == 'R') && unlikely(dio->op != REQ_OP_READ))
1941 return DM_MAPIO_KILL;
1943 get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
1944 dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
1945 bio->bi_iter.bi_sector = get_data_sector(ic, area, offset);
1947 dm_integrity_map_continue(dio, true);
1948 return DM_MAPIO_SUBMITTED;
1951 static bool __journal_read_write(struct dm_integrity_io *dio, struct bio *bio,
1952 unsigned int journal_section, unsigned int journal_entry)
1954 struct dm_integrity_c *ic = dio->ic;
1955 sector_t logical_sector;
1956 unsigned int n_sectors;
1958 logical_sector = dio->range.logical_sector;
1959 n_sectors = dio->range.n_sectors;
1961 struct bio_vec bv = bio_iovec(bio);
1964 if (unlikely(bv.bv_len >> SECTOR_SHIFT > n_sectors))
1965 bv.bv_len = n_sectors << SECTOR_SHIFT;
1966 n_sectors -= bv.bv_len >> SECTOR_SHIFT;
1967 bio_advance_iter(bio, &bio->bi_iter, bv.bv_len);
1969 mem = kmap_local_page(bv.bv_page);
1970 if (likely(dio->op == REQ_OP_WRITE))
1971 flush_dcache_page(bv.bv_page);
1974 struct journal_entry *je = access_journal_entry(ic, journal_section, journal_entry);
1976 if (unlikely(dio->op == REQ_OP_READ)) {
1977 struct journal_sector *js;
1981 if (unlikely(journal_entry_is_inprogress(je))) {
1982 flush_dcache_page(bv.bv_page);
1985 __io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
1989 BUG_ON(journal_entry_get_sector(je) != logical_sector);
1990 js = access_journal_data(ic, journal_section, journal_entry);
1991 mem_ptr = mem + bv.bv_offset;
1994 memcpy(mem_ptr, js, JOURNAL_SECTOR_DATA);
1995 *(commit_id_t *)(mem_ptr + JOURNAL_SECTOR_DATA) = je->last_bytes[s];
1997 mem_ptr += 1 << SECTOR_SHIFT;
1998 } while (++s < ic->sectors_per_block);
1999 #ifdef INTERNAL_VERIFY
2000 if (ic->internal_hash) {
2001 char checksums_onstack[max_t(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
2003 integrity_sector_checksum(ic, logical_sector, mem + bv.bv_offset, checksums_onstack);
2004 if (unlikely(memcmp(checksums_onstack, journal_entry_tag(ic, je), ic->tag_size))) {
2005 DMERR_LIMIT("Checksum failed when reading from journal, at sector 0x%llx",
2007 dm_audit_log_bio(DM_MSG_PREFIX, "journal-checksum",
2008 bio, logical_sector, 0);
2014 if (!ic->internal_hash) {
2015 struct bio_integrity_payload *bip = bio_integrity(bio);
2016 unsigned int tag_todo = ic->tag_size;
2017 char *tag_ptr = journal_entry_tag(ic, je);
2021 struct bio_vec biv = bvec_iter_bvec(bip->bip_vec, bip->bip_iter);
2022 unsigned int tag_now = min(biv.bv_len, tag_todo);
2025 BUG_ON(PageHighMem(biv.bv_page));
2026 tag_addr = bvec_virt(&biv);
2027 if (likely(dio->op == REQ_OP_WRITE))
2028 memcpy(tag_ptr, tag_addr, tag_now);
2030 memcpy(tag_addr, tag_ptr, tag_now);
2031 bvec_iter_advance(bip->bip_vec, &bip->bip_iter, tag_now);
2033 tag_todo -= tag_now;
2034 } while (unlikely(tag_todo));
2035 } else if (likely(dio->op == REQ_OP_WRITE))
2036 memset(tag_ptr, 0, tag_todo);
2039 if (likely(dio->op == REQ_OP_WRITE)) {
2040 struct journal_sector *js;
2043 js = access_journal_data(ic, journal_section, journal_entry);
2044 memcpy(js, mem + bv.bv_offset, ic->sectors_per_block << SECTOR_SHIFT);
2048 je->last_bytes[s] = js[s].commit_id;
2049 } while (++s < ic->sectors_per_block);
2051 if (ic->internal_hash) {
2052 unsigned int digest_size = crypto_shash_digestsize(ic->internal_hash);
2054 if (unlikely(digest_size > ic->tag_size)) {
2055 char checksums_onstack[HASH_MAX_DIGESTSIZE];
2057 integrity_sector_checksum(ic, logical_sector, (char *)js, checksums_onstack);
2058 memcpy(journal_entry_tag(ic, je), checksums_onstack, ic->tag_size);
2060 integrity_sector_checksum(ic, logical_sector, (char *)js, journal_entry_tag(ic, je));
2063 journal_entry_set_sector(je, logical_sector);
2065 logical_sector += ic->sectors_per_block;
2068 if (unlikely(journal_entry == ic->journal_section_entries)) {
2071 wraparound_section(ic, &journal_section);
2074 bv.bv_offset += ic->sectors_per_block << SECTOR_SHIFT;
2075 } while (bv.bv_len -= ic->sectors_per_block << SECTOR_SHIFT);
2077 if (unlikely(dio->op == REQ_OP_READ))
2078 flush_dcache_page(bv.bv_page);
2080 } while (n_sectors);
2082 if (likely(dio->op == REQ_OP_WRITE)) {
2084 if (unlikely(waitqueue_active(&ic->copy_to_journal_wait)))
2085 wake_up(&ic->copy_to_journal_wait);
2086 if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold)
2087 queue_work(ic->commit_wq, &ic->commit_work);
2089 schedule_autocommit(ic);
2091 remove_range(ic, &dio->range);
2093 if (unlikely(bio->bi_iter.bi_size)) {
2094 sector_t area, offset;
2096 dio->range.logical_sector = logical_sector;
2097 get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
2098 dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
2105 static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map)
2107 struct dm_integrity_c *ic = dio->ic;
2108 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
2109 unsigned int journal_section, journal_entry;
2110 unsigned int journal_read_pos;
2111 struct completion read_comp;
2112 bool discard_retried = false;
2113 bool need_sync_io = ic->internal_hash && dio->op == REQ_OP_READ;
2115 if (unlikely(dio->op == REQ_OP_DISCARD) && ic->mode != 'D')
2116 need_sync_io = true;
2118 if (need_sync_io && from_map) {
2119 INIT_WORK(&dio->work, integrity_bio_wait);
2120 queue_work(ic->offload_wq, &dio->work);
2125 spin_lock_irq(&ic->endio_wait.lock);
2127 if (unlikely(dm_integrity_failed(ic))) {
2128 spin_unlock_irq(&ic->endio_wait.lock);
2132 dio->range.n_sectors = bio_sectors(bio);
2133 journal_read_pos = NOT_FOUND;
2134 if (ic->mode == 'J' && likely(dio->op != REQ_OP_DISCARD)) {
2135 if (dio->op == REQ_OP_WRITE) {
2136 unsigned int next_entry, i, pos;
2137 unsigned int ws, we, range_sectors;
2139 dio->range.n_sectors = min(dio->range.n_sectors,
2140 (sector_t)ic->free_sectors << ic->sb->log2_sectors_per_block);
2141 if (unlikely(!dio->range.n_sectors)) {
2143 goto offload_to_thread;
2144 sleep_on_endio_wait(ic);
2147 range_sectors = dio->range.n_sectors >> ic->sb->log2_sectors_per_block;
2148 ic->free_sectors -= range_sectors;
2149 journal_section = ic->free_section;
2150 journal_entry = ic->free_section_entry;
2152 next_entry = ic->free_section_entry + range_sectors;
2153 ic->free_section_entry = next_entry % ic->journal_section_entries;
2154 ic->free_section += next_entry / ic->journal_section_entries;
2155 ic->n_uncommitted_sections += next_entry / ic->journal_section_entries;
2156 wraparound_section(ic, &ic->free_section);
2158 pos = journal_section * ic->journal_section_entries + journal_entry;
2159 ws = journal_section;
2163 struct journal_entry *je;
2165 add_journal_node(ic, &ic->journal_tree[pos], dio->range.logical_sector + i);
2167 if (unlikely(pos >= ic->journal_entries))
2170 je = access_journal_entry(ic, ws, we);
2171 BUG_ON(!journal_entry_is_unused(je));
2172 journal_entry_set_inprogress(je);
2174 if (unlikely(we == ic->journal_section_entries)) {
2177 wraparound_section(ic, &ws);
2179 } while ((i += ic->sectors_per_block) < dio->range.n_sectors);
2181 spin_unlock_irq(&ic->endio_wait.lock);
2182 goto journal_read_write;
2184 sector_t next_sector;
2186 journal_read_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
2187 if (likely(journal_read_pos == NOT_FOUND)) {
2188 if (unlikely(dio->range.n_sectors > next_sector - dio->range.logical_sector))
2189 dio->range.n_sectors = next_sector - dio->range.logical_sector;
2192 unsigned int jp = journal_read_pos + 1;
2194 for (i = ic->sectors_per_block; i < dio->range.n_sectors; i += ic->sectors_per_block, jp++) {
2195 if (!test_journal_node(ic, jp, dio->range.logical_sector + i))
2198 dio->range.n_sectors = i;
2202 if (unlikely(!add_new_range(ic, &dio->range, true))) {
2204 * We must not sleep in the request routine because it could
2205 * stall bios on current->bio_list.
2206 * So, we offload the bio to a workqueue if we have to sleep.
2210 spin_unlock_irq(&ic->endio_wait.lock);
2211 INIT_WORK(&dio->work, integrity_bio_wait);
2212 queue_work(ic->wait_wq, &dio->work);
2215 if (journal_read_pos != NOT_FOUND)
2216 dio->range.n_sectors = ic->sectors_per_block;
2217 wait_and_add_new_range(ic, &dio->range);
2219 * wait_and_add_new_range drops the spinlock, so the journal
2220 * may have been changed arbitrarily. We need to recheck.
2221 * To simplify the code, we restrict I/O size to just one block.
2223 if (journal_read_pos != NOT_FOUND) {
2224 sector_t next_sector;
2225 unsigned int new_pos;
2227 new_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
2228 if (unlikely(new_pos != journal_read_pos)) {
2229 remove_range_unlocked(ic, &dio->range);
2234 if (ic->mode == 'J' && likely(dio->op == REQ_OP_DISCARD) && !discard_retried) {
2235 sector_t next_sector;
2236 unsigned int new_pos;
2238 new_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
2239 if (unlikely(new_pos != NOT_FOUND) ||
2240 unlikely(next_sector < dio->range.logical_sector - dio->range.n_sectors)) {
2241 remove_range_unlocked(ic, &dio->range);
2242 spin_unlock_irq(&ic->endio_wait.lock);
2243 queue_work(ic->commit_wq, &ic->commit_work);
2244 flush_workqueue(ic->commit_wq);
2245 queue_work(ic->writer_wq, &ic->writer_work);
2246 flush_workqueue(ic->writer_wq);
2247 discard_retried = true;
2251 spin_unlock_irq(&ic->endio_wait.lock);
2253 if (unlikely(journal_read_pos != NOT_FOUND)) {
2254 journal_section = journal_read_pos / ic->journal_section_entries;
2255 journal_entry = journal_read_pos % ic->journal_section_entries;
2256 goto journal_read_write;
2259 if (ic->mode == 'B' && (dio->op == REQ_OP_WRITE || unlikely(dio->op == REQ_OP_DISCARD))) {
2260 if (!block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
2261 dio->range.n_sectors, BITMAP_OP_TEST_ALL_SET)) {
2262 struct bitmap_block_status *bbs;
2264 bbs = sector_to_bitmap_block(ic, dio->range.logical_sector);
2265 spin_lock(&bbs->bio_queue_lock);
2266 bio_list_add(&bbs->bio_queue, bio);
2267 spin_unlock(&bbs->bio_queue_lock);
2268 queue_work(ic->writer_wq, &bbs->work);
2273 dio->in_flight = (atomic_t)ATOMIC_INIT(2);
2276 init_completion(&read_comp);
2277 dio->completion = &read_comp;
2279 dio->completion = NULL;
2281 dm_bio_record(&dio->bio_details, bio);
2282 bio_set_dev(bio, ic->dev->bdev);
2283 bio->bi_integrity = NULL;
2284 bio->bi_opf &= ~REQ_INTEGRITY;
2285 bio->bi_end_io = integrity_end_io;
2286 bio->bi_iter.bi_size = dio->range.n_sectors << SECTOR_SHIFT;
2288 if (unlikely(dio->op == REQ_OP_DISCARD) && likely(ic->mode != 'D')) {
2289 integrity_metadata(&dio->work);
2290 dm_integrity_flush_buffers(ic, false);
2292 dio->in_flight = (atomic_t)ATOMIC_INIT(1);
2293 dio->completion = NULL;
2295 submit_bio_noacct(bio);
2300 submit_bio_noacct(bio);
2303 wait_for_completion_io(&read_comp);
2304 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
2305 dio->range.logical_sector + dio->range.n_sectors > le64_to_cpu(ic->sb->recalc_sector))
2307 if (ic->mode == 'B') {
2308 if (!block_bitmap_op(ic, ic->recalc_bitmap, dio->range.logical_sector,
2309 dio->range.n_sectors, BITMAP_OP_TEST_ALL_CLEAR))
2313 if (likely(!bio->bi_status))
2314 integrity_metadata(&dio->work);
2319 INIT_WORK(&dio->work, integrity_metadata);
2320 queue_work(ic->metadata_wq, &dio->work);
2326 if (unlikely(__journal_read_write(dio, bio, journal_section, journal_entry)))
2329 do_endio_flush(ic, dio);
2333 static void integrity_bio_wait(struct work_struct *w)
2335 struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
2337 dm_integrity_map_continue(dio, false);
2340 static void pad_uncommitted(struct dm_integrity_c *ic)
2342 if (ic->free_section_entry) {
2343 ic->free_sectors -= ic->journal_section_entries - ic->free_section_entry;
2344 ic->free_section_entry = 0;
2346 wraparound_section(ic, &ic->free_section);
2347 ic->n_uncommitted_sections++;
2349 if (WARN_ON(ic->journal_sections * ic->journal_section_entries !=
2350 (ic->n_uncommitted_sections + ic->n_committed_sections) *
2351 ic->journal_section_entries + ic->free_sectors)) {
2352 DMCRIT("journal_sections %u, journal_section_entries %u, "
2353 "n_uncommitted_sections %u, n_committed_sections %u, "
2354 "journal_section_entries %u, free_sectors %u",
2355 ic->journal_sections, ic->journal_section_entries,
2356 ic->n_uncommitted_sections, ic->n_committed_sections,
2357 ic->journal_section_entries, ic->free_sectors);
2361 static void integrity_commit(struct work_struct *w)
2363 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, commit_work);
2364 unsigned int commit_start, commit_sections;
2365 unsigned int i, j, n;
2366 struct bio *flushes;
2368 del_timer(&ic->autocommit_timer);
2370 spin_lock_irq(&ic->endio_wait.lock);
2371 flushes = bio_list_get(&ic->flush_bio_list);
2372 if (unlikely(ic->mode != 'J')) {
2373 spin_unlock_irq(&ic->endio_wait.lock);
2374 dm_integrity_flush_buffers(ic, true);
2375 goto release_flush_bios;
2378 pad_uncommitted(ic);
2379 commit_start = ic->uncommitted_section;
2380 commit_sections = ic->n_uncommitted_sections;
2381 spin_unlock_irq(&ic->endio_wait.lock);
2383 if (!commit_sections)
2384 goto release_flush_bios;
2386 ic->wrote_to_journal = true;
2389 for (n = 0; n < commit_sections; n++) {
2390 for (j = 0; j < ic->journal_section_entries; j++) {
2391 struct journal_entry *je;
2393 je = access_journal_entry(ic, i, j);
2394 io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
2396 for (j = 0; j < ic->journal_section_sectors; j++) {
2397 struct journal_sector *js;
2399 js = access_journal(ic, i, j);
2400 js->commit_id = dm_integrity_commit_id(ic, i, j, ic->commit_seq);
2403 if (unlikely(i >= ic->journal_sections))
2404 ic->commit_seq = next_commit_seq(ic->commit_seq);
2405 wraparound_section(ic, &i);
2409 write_journal(ic, commit_start, commit_sections);
2411 spin_lock_irq(&ic->endio_wait.lock);
2412 ic->uncommitted_section += commit_sections;
2413 wraparound_section(ic, &ic->uncommitted_section);
2414 ic->n_uncommitted_sections -= commit_sections;
2415 ic->n_committed_sections += commit_sections;
2416 spin_unlock_irq(&ic->endio_wait.lock);
2418 if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold)
2419 queue_work(ic->writer_wq, &ic->writer_work);
2423 struct bio *next = flushes->bi_next;
2425 flushes->bi_next = NULL;
2426 do_endio(ic, flushes);
2431 static void complete_copy_from_journal(unsigned long error, void *context)
2433 struct journal_io *io = context;
2434 struct journal_completion *comp = io->comp;
2435 struct dm_integrity_c *ic = comp->ic;
2437 remove_range(ic, &io->range);
2438 mempool_free(io, &ic->journal_io_mempool);
2439 if (unlikely(error != 0))
2440 dm_integrity_io_error(ic, "copying from journal", -EIO);
2441 complete_journal_op(comp);
2444 static void restore_last_bytes(struct dm_integrity_c *ic, struct journal_sector *js,
2445 struct journal_entry *je)
2450 js->commit_id = je->last_bytes[s];
2452 } while (++s < ic->sectors_per_block);
2455 static void do_journal_write(struct dm_integrity_c *ic, unsigned int write_start,
2456 unsigned int write_sections, bool from_replay)
2458 unsigned int i, j, n;
2459 struct journal_completion comp;
2460 struct blk_plug plug;
2462 blk_start_plug(&plug);
2465 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
2466 init_completion(&comp.comp);
2469 for (n = 0; n < write_sections; n++, i++, wraparound_section(ic, &i)) {
2470 #ifndef INTERNAL_VERIFY
2471 if (unlikely(from_replay))
2473 rw_section_mac(ic, i, false);
2474 for (j = 0; j < ic->journal_section_entries; j++) {
2475 struct journal_entry *je = access_journal_entry(ic, i, j);
2476 sector_t sec, area, offset;
2477 unsigned int k, l, next_loop;
2478 sector_t metadata_block;
2479 unsigned int metadata_offset;
2480 struct journal_io *io;
2482 if (journal_entry_is_unused(je))
2484 BUG_ON(unlikely(journal_entry_is_inprogress(je)) && !from_replay);
2485 sec = journal_entry_get_sector(je);
2486 if (unlikely(from_replay)) {
2487 if (unlikely(sec & (unsigned int)(ic->sectors_per_block - 1))) {
2488 dm_integrity_io_error(ic, "invalid sector in journal", -EIO);
2489 sec &= ~(sector_t)(ic->sectors_per_block - 1);
2491 if (unlikely(sec >= ic->provided_data_sectors)) {
2492 journal_entry_set_unused(je);
2496 get_area_and_offset(ic, sec, &area, &offset);
2497 restore_last_bytes(ic, access_journal_data(ic, i, j), je);
2498 for (k = j + 1; k < ic->journal_section_entries; k++) {
2499 struct journal_entry *je2 = access_journal_entry(ic, i, k);
2500 sector_t sec2, area2, offset2;
2502 if (journal_entry_is_unused(je2))
2504 BUG_ON(unlikely(journal_entry_is_inprogress(je2)) && !from_replay);
2505 sec2 = journal_entry_get_sector(je2);
2506 if (unlikely(sec2 >= ic->provided_data_sectors))
2508 get_area_and_offset(ic, sec2, &area2, &offset2);
2509 if (area2 != area || offset2 != offset + ((k - j) << ic->sb->log2_sectors_per_block))
2511 restore_last_bytes(ic, access_journal_data(ic, i, k), je2);
2515 io = mempool_alloc(&ic->journal_io_mempool, GFP_NOIO);
2517 io->range.logical_sector = sec;
2518 io->range.n_sectors = (k - j) << ic->sb->log2_sectors_per_block;
2520 spin_lock_irq(&ic->endio_wait.lock);
2521 add_new_range_and_wait(ic, &io->range);
2523 if (likely(!from_replay)) {
2524 struct journal_node *section_node = &ic->journal_tree[i * ic->journal_section_entries];
2526 /* don't write if there is newer committed sector */
2527 while (j < k && find_newer_committed_node(ic, §ion_node[j])) {
2528 struct journal_entry *je2 = access_journal_entry(ic, i, j);
2530 journal_entry_set_unused(je2);
2531 remove_journal_node(ic, §ion_node[j]);
2533 sec += ic->sectors_per_block;
2534 offset += ic->sectors_per_block;
2536 while (j < k && find_newer_committed_node(ic, §ion_node[k - 1])) {
2537 struct journal_entry *je2 = access_journal_entry(ic, i, k - 1);
2539 journal_entry_set_unused(je2);
2540 remove_journal_node(ic, §ion_node[k - 1]);
2544 remove_range_unlocked(ic, &io->range);
2545 spin_unlock_irq(&ic->endio_wait.lock);
2546 mempool_free(io, &ic->journal_io_mempool);
2549 for (l = j; l < k; l++)
2550 remove_journal_node(ic, §ion_node[l]);
2552 spin_unlock_irq(&ic->endio_wait.lock);
2554 metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
2555 for (l = j; l < k; l++) {
2557 struct journal_entry *je2 = access_journal_entry(ic, i, l);
2560 #ifndef INTERNAL_VERIFY
2561 unlikely(from_replay) &&
2563 ic->internal_hash) {
2564 char test_tag[max_t(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
2566 integrity_sector_checksum(ic, sec + ((l - j) << ic->sb->log2_sectors_per_block),
2567 (char *)access_journal_data(ic, i, l), test_tag);
2568 if (unlikely(memcmp(test_tag, journal_entry_tag(ic, je2), ic->tag_size))) {
2569 dm_integrity_io_error(ic, "tag mismatch when replaying journal", -EILSEQ);
2570 dm_audit_log_target(DM_MSG_PREFIX, "integrity-replay-journal", ic->ti, 0);
2574 journal_entry_set_unused(je2);
2575 r = dm_integrity_rw_tag(ic, journal_entry_tag(ic, je2), &metadata_block, &metadata_offset,
2576 ic->tag_size, TAG_WRITE);
2578 dm_integrity_io_error(ic, "reading tags", r);
2581 atomic_inc(&comp.in_flight);
2582 copy_from_journal(ic, i, j << ic->sb->log2_sectors_per_block,
2583 (k - j) << ic->sb->log2_sectors_per_block,
2584 get_data_sector(ic, area, offset),
2585 complete_copy_from_journal, io);
2591 dm_bufio_write_dirty_buffers_async(ic->bufio);
2593 blk_finish_plug(&plug);
2595 complete_journal_op(&comp);
2596 wait_for_completion_io(&comp.comp);
2598 dm_integrity_flush_buffers(ic, true);
2601 static void integrity_writer(struct work_struct *w)
2603 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, writer_work);
2604 unsigned int write_start, write_sections;
2605 unsigned int prev_free_sectors;
2607 spin_lock_irq(&ic->endio_wait.lock);
2608 write_start = ic->committed_section;
2609 write_sections = ic->n_committed_sections;
2610 spin_unlock_irq(&ic->endio_wait.lock);
2612 if (!write_sections)
2615 do_journal_write(ic, write_start, write_sections, false);
2617 spin_lock_irq(&ic->endio_wait.lock);
2619 ic->committed_section += write_sections;
2620 wraparound_section(ic, &ic->committed_section);
2621 ic->n_committed_sections -= write_sections;
2623 prev_free_sectors = ic->free_sectors;
2624 ic->free_sectors += write_sections * ic->journal_section_entries;
2625 if (unlikely(!prev_free_sectors))
2626 wake_up_locked(&ic->endio_wait);
2628 spin_unlock_irq(&ic->endio_wait.lock);
2631 static void recalc_write_super(struct dm_integrity_c *ic)
2635 dm_integrity_flush_buffers(ic, false);
2636 if (dm_integrity_failed(ic))
2639 r = sync_rw_sb(ic, REQ_OP_WRITE);
2641 dm_integrity_io_error(ic, "writing superblock", r);
2644 static void integrity_recalc(struct work_struct *w)
2646 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, recalc_work);
2647 size_t recalc_tags_size;
2648 u8 *recalc_buffer = NULL;
2649 u8 *recalc_tags = NULL;
2650 struct dm_integrity_range range;
2651 struct dm_io_request io_req;
2652 struct dm_io_region io_loc;
2653 sector_t area, offset;
2654 sector_t metadata_block;
2655 unsigned int metadata_offset;
2656 sector_t logical_sector, n_sectors;
2660 unsigned int super_counter = 0;
2662 recalc_buffer = __vmalloc(RECALC_SECTORS << SECTOR_SHIFT, GFP_NOIO);
2663 if (!recalc_buffer) {
2664 DMCRIT("out of memory for recalculate buffer - recalculation disabled");
2667 recalc_tags_size = (RECALC_SECTORS >> ic->sb->log2_sectors_per_block) * ic->tag_size;
2668 if (crypto_shash_digestsize(ic->internal_hash) > ic->tag_size)
2669 recalc_tags_size += crypto_shash_digestsize(ic->internal_hash) - ic->tag_size;
2670 recalc_tags = kvmalloc(recalc_tags_size, GFP_NOIO);
2672 DMCRIT("out of memory for recalculate buffer - recalculation disabled");
2676 DEBUG_print("start recalculation... (position %llx)\n", le64_to_cpu(ic->sb->recalc_sector));
2678 spin_lock_irq(&ic->endio_wait.lock);
2682 if (unlikely(dm_post_suspending(ic->ti)))
2685 range.logical_sector = le64_to_cpu(ic->sb->recalc_sector);
2686 if (unlikely(range.logical_sector >= ic->provided_data_sectors)) {
2687 if (ic->mode == 'B') {
2688 block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
2689 DEBUG_print("queue_delayed_work: bitmap_flush_work\n");
2690 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
2695 get_area_and_offset(ic, range.logical_sector, &area, &offset);
2696 range.n_sectors = min((sector_t)RECALC_SECTORS, ic->provided_data_sectors - range.logical_sector);
2698 range.n_sectors = min(range.n_sectors, ((sector_t)1U << ic->sb->log2_interleave_sectors) - (unsigned int)offset);
2700 add_new_range_and_wait(ic, &range);
2701 spin_unlock_irq(&ic->endio_wait.lock);
2702 logical_sector = range.logical_sector;
2703 n_sectors = range.n_sectors;
2705 if (ic->mode == 'B') {
2706 if (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector, n_sectors, BITMAP_OP_TEST_ALL_CLEAR))
2707 goto advance_and_next;
2709 while (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector,
2710 ic->sectors_per_block, BITMAP_OP_TEST_ALL_CLEAR)) {
2711 logical_sector += ic->sectors_per_block;
2712 n_sectors -= ic->sectors_per_block;
2715 while (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector + n_sectors - ic->sectors_per_block,
2716 ic->sectors_per_block, BITMAP_OP_TEST_ALL_CLEAR)) {
2717 n_sectors -= ic->sectors_per_block;
2720 get_area_and_offset(ic, logical_sector, &area, &offset);
2723 DEBUG_print("recalculating: %llx, %llx\n", logical_sector, n_sectors);
2725 if (unlikely(++super_counter == RECALC_WRITE_SUPER)) {
2726 recalc_write_super(ic);
2727 if (ic->mode == 'B')
2728 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, ic->bitmap_flush_interval);
2733 if (unlikely(dm_integrity_failed(ic)))
2736 io_req.bi_opf = REQ_OP_READ;
2737 io_req.mem.type = DM_IO_VMA;
2738 io_req.mem.ptr.addr = recalc_buffer;
2739 io_req.notify.fn = NULL;
2740 io_req.client = ic->io;
2741 io_loc.bdev = ic->dev->bdev;
2742 io_loc.sector = get_data_sector(ic, area, offset);
2743 io_loc.count = n_sectors;
2745 r = dm_io(&io_req, 1, &io_loc, NULL);
2747 dm_integrity_io_error(ic, "reading data", r);
2752 for (i = 0; i < n_sectors; i += ic->sectors_per_block) {
2753 integrity_sector_checksum(ic, logical_sector + i, recalc_buffer + (i << SECTOR_SHIFT), t);
2757 metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
2759 r = dm_integrity_rw_tag(ic, recalc_tags, &metadata_block, &metadata_offset, t - recalc_tags, TAG_WRITE);
2761 dm_integrity_io_error(ic, "writing tags", r);
2765 if (ic->mode == 'B') {
2766 sector_t start, end;
2768 start = (range.logical_sector >>
2769 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit)) <<
2770 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
2771 end = ((range.logical_sector + range.n_sectors) >>
2772 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit)) <<
2773 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
2774 block_bitmap_op(ic, ic->recalc_bitmap, start, end - start, BITMAP_OP_CLEAR);
2780 spin_lock_irq(&ic->endio_wait.lock);
2781 remove_range_unlocked(ic, &range);
2782 ic->sb->recalc_sector = cpu_to_le64(range.logical_sector + range.n_sectors);
2786 remove_range(ic, &range);
2790 spin_unlock_irq(&ic->endio_wait.lock);
2792 recalc_write_super(ic);
2795 vfree(recalc_buffer);
2796 kvfree(recalc_tags);
2799 static void bitmap_block_work(struct work_struct *w)
2801 struct bitmap_block_status *bbs = container_of(w, struct bitmap_block_status, work);
2802 struct dm_integrity_c *ic = bbs->ic;
2804 struct bio_list bio_queue;
2805 struct bio_list waiting;
2807 bio_list_init(&waiting);
2809 spin_lock(&bbs->bio_queue_lock);
2810 bio_queue = bbs->bio_queue;
2811 bio_list_init(&bbs->bio_queue);
2812 spin_unlock(&bbs->bio_queue_lock);
2814 while ((bio = bio_list_pop(&bio_queue))) {
2815 struct dm_integrity_io *dio;
2817 dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
2819 if (block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
2820 dio->range.n_sectors, BITMAP_OP_TEST_ALL_SET)) {
2821 remove_range(ic, &dio->range);
2822 INIT_WORK(&dio->work, integrity_bio_wait);
2823 queue_work(ic->offload_wq, &dio->work);
2825 block_bitmap_op(ic, ic->journal, dio->range.logical_sector,
2826 dio->range.n_sectors, BITMAP_OP_SET);
2827 bio_list_add(&waiting, bio);
2831 if (bio_list_empty(&waiting))
2834 rw_journal_sectors(ic, REQ_OP_WRITE | REQ_FUA | REQ_SYNC,
2835 bbs->idx * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT),
2836 BITMAP_BLOCK_SIZE >> SECTOR_SHIFT, NULL);
2838 while ((bio = bio_list_pop(&waiting))) {
2839 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
2841 block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
2842 dio->range.n_sectors, BITMAP_OP_SET);
2844 remove_range(ic, &dio->range);
2845 INIT_WORK(&dio->work, integrity_bio_wait);
2846 queue_work(ic->offload_wq, &dio->work);
2849 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, ic->bitmap_flush_interval);
2852 static void bitmap_flush_work(struct work_struct *work)
2854 struct dm_integrity_c *ic = container_of(work, struct dm_integrity_c, bitmap_flush_work.work);
2855 struct dm_integrity_range range;
2856 unsigned long limit;
2859 dm_integrity_flush_buffers(ic, false);
2861 range.logical_sector = 0;
2862 range.n_sectors = ic->provided_data_sectors;
2864 spin_lock_irq(&ic->endio_wait.lock);
2865 add_new_range_and_wait(ic, &range);
2866 spin_unlock_irq(&ic->endio_wait.lock);
2868 dm_integrity_flush_buffers(ic, true);
2870 limit = ic->provided_data_sectors;
2871 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
2872 limit = le64_to_cpu(ic->sb->recalc_sector)
2873 >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit)
2874 << (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
2876 /*DEBUG_print("zeroing journal\n");*/
2877 block_bitmap_op(ic, ic->journal, 0, limit, BITMAP_OP_CLEAR);
2878 block_bitmap_op(ic, ic->may_write_bitmap, 0, limit, BITMAP_OP_CLEAR);
2880 rw_journal_sectors(ic, REQ_OP_WRITE | REQ_FUA | REQ_SYNC, 0,
2881 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
2883 spin_lock_irq(&ic->endio_wait.lock);
2884 remove_range_unlocked(ic, &range);
2885 while (unlikely((bio = bio_list_pop(&ic->synchronous_bios)) != NULL)) {
2887 spin_unlock_irq(&ic->endio_wait.lock);
2888 spin_lock_irq(&ic->endio_wait.lock);
2890 spin_unlock_irq(&ic->endio_wait.lock);
2894 static void init_journal(struct dm_integrity_c *ic, unsigned int start_section,
2895 unsigned int n_sections, unsigned char commit_seq)
2897 unsigned int i, j, n;
2902 for (n = 0; n < n_sections; n++) {
2903 i = start_section + n;
2904 wraparound_section(ic, &i);
2905 for (j = 0; j < ic->journal_section_sectors; j++) {
2906 struct journal_sector *js = access_journal(ic, i, j);
2908 BUILD_BUG_ON(sizeof(js->sectors) != JOURNAL_SECTOR_DATA);
2909 memset(&js->sectors, 0, sizeof(js->sectors));
2910 js->commit_id = dm_integrity_commit_id(ic, i, j, commit_seq);
2912 for (j = 0; j < ic->journal_section_entries; j++) {
2913 struct journal_entry *je = access_journal_entry(ic, i, j);
2915 journal_entry_set_unused(je);
2919 write_journal(ic, start_section, n_sections);
2922 static int find_commit_seq(struct dm_integrity_c *ic, unsigned int i, unsigned int j, commit_id_t id)
2926 for (k = 0; k < N_COMMIT_IDS; k++) {
2927 if (dm_integrity_commit_id(ic, i, j, k) == id)
2930 dm_integrity_io_error(ic, "journal commit id", -EIO);
2934 static void replay_journal(struct dm_integrity_c *ic)
2937 bool used_commit_ids[N_COMMIT_IDS];
2938 unsigned int max_commit_id_sections[N_COMMIT_IDS];
2939 unsigned int write_start, write_sections;
2940 unsigned int continue_section;
2942 unsigned char unused, last_used, want_commit_seq;
2944 if (ic->mode == 'R')
2947 if (ic->journal_uptodate)
2953 if (!ic->just_formatted) {
2954 DEBUG_print("reading journal\n");
2955 rw_journal(ic, REQ_OP_READ, 0, ic->journal_sections, NULL);
2957 DEBUG_bytes(lowmem_page_address(ic->journal_io[0].page), 64, "read journal");
2958 if (ic->journal_io) {
2959 struct journal_completion crypt_comp;
2962 init_completion(&crypt_comp.comp);
2963 crypt_comp.in_flight = (atomic_t)ATOMIC_INIT(0);
2964 encrypt_journal(ic, false, 0, ic->journal_sections, &crypt_comp);
2965 wait_for_completion(&crypt_comp.comp);
2967 DEBUG_bytes(lowmem_page_address(ic->journal[0].page), 64, "decrypted journal");
2970 if (dm_integrity_failed(ic))
2973 journal_empty = true;
2974 memset(used_commit_ids, 0, sizeof(used_commit_ids));
2975 memset(max_commit_id_sections, 0, sizeof(max_commit_id_sections));
2976 for (i = 0; i < ic->journal_sections; i++) {
2977 for (j = 0; j < ic->journal_section_sectors; j++) {
2979 struct journal_sector *js = access_journal(ic, i, j);
2981 k = find_commit_seq(ic, i, j, js->commit_id);
2984 used_commit_ids[k] = true;
2985 max_commit_id_sections[k] = i;
2987 if (journal_empty) {
2988 for (j = 0; j < ic->journal_section_entries; j++) {
2989 struct journal_entry *je = access_journal_entry(ic, i, j);
2991 if (!journal_entry_is_unused(je)) {
2992 journal_empty = false;
2999 if (!used_commit_ids[N_COMMIT_IDS - 1]) {
3000 unused = N_COMMIT_IDS - 1;
3001 while (unused && !used_commit_ids[unused - 1])
3004 for (unused = 0; unused < N_COMMIT_IDS; unused++)
3005 if (!used_commit_ids[unused])
3007 if (unused == N_COMMIT_IDS) {
3008 dm_integrity_io_error(ic, "journal commit ids", -EIO);
3012 DEBUG_print("first unused commit seq %d [%d,%d,%d,%d]\n",
3013 unused, used_commit_ids[0], used_commit_ids[1],
3014 used_commit_ids[2], used_commit_ids[3]);
3016 last_used = prev_commit_seq(unused);
3017 want_commit_seq = prev_commit_seq(last_used);
3019 if (!used_commit_ids[want_commit_seq] && used_commit_ids[prev_commit_seq(want_commit_seq)])
3020 journal_empty = true;
3022 write_start = max_commit_id_sections[last_used] + 1;
3023 if (unlikely(write_start >= ic->journal_sections))
3024 want_commit_seq = next_commit_seq(want_commit_seq);
3025 wraparound_section(ic, &write_start);
3028 for (write_sections = 0; write_sections < ic->journal_sections; write_sections++) {
3029 for (j = 0; j < ic->journal_section_sectors; j++) {
3030 struct journal_sector *js = access_journal(ic, i, j);
3032 if (js->commit_id != dm_integrity_commit_id(ic, i, j, want_commit_seq)) {
3034 * This could be caused by crash during writing.
3035 * We won't replay the inconsistent part of the
3038 DEBUG_print("commit id mismatch at position (%u, %u): %d != %d\n",
3039 i, j, find_commit_seq(ic, i, j, js->commit_id), want_commit_seq);
3044 if (unlikely(i >= ic->journal_sections))
3045 want_commit_seq = next_commit_seq(want_commit_seq);
3046 wraparound_section(ic, &i);
3050 if (!journal_empty) {
3051 DEBUG_print("replaying %u sections, starting at %u, commit seq %d\n",
3052 write_sections, write_start, want_commit_seq);
3053 do_journal_write(ic, write_start, write_sections, true);
3056 if (write_sections == ic->journal_sections && (ic->mode == 'J' || journal_empty)) {
3057 continue_section = write_start;
3058 ic->commit_seq = want_commit_seq;
3059 DEBUG_print("continuing from section %u, commit seq %d\n", write_start, ic->commit_seq);
3062 unsigned char erase_seq;
3065 DEBUG_print("clearing journal\n");
3067 erase_seq = prev_commit_seq(prev_commit_seq(last_used));
3069 init_journal(ic, s, 1, erase_seq);
3071 wraparound_section(ic, &s);
3072 if (ic->journal_sections >= 2) {
3073 init_journal(ic, s, ic->journal_sections - 2, erase_seq);
3074 s += ic->journal_sections - 2;
3075 wraparound_section(ic, &s);
3076 init_journal(ic, s, 1, erase_seq);
3079 continue_section = 0;
3080 ic->commit_seq = next_commit_seq(erase_seq);
3083 ic->committed_section = continue_section;
3084 ic->n_committed_sections = 0;
3086 ic->uncommitted_section = continue_section;
3087 ic->n_uncommitted_sections = 0;
3089 ic->free_section = continue_section;
3090 ic->free_section_entry = 0;
3091 ic->free_sectors = ic->journal_entries;
3093 ic->journal_tree_root = RB_ROOT;
3094 for (i = 0; i < ic->journal_entries; i++)
3095 init_journal_node(&ic->journal_tree[i]);
3098 static void dm_integrity_enter_synchronous_mode(struct dm_integrity_c *ic)
3100 DEBUG_print("%s\n", __func__);
3102 if (ic->mode == 'B') {
3103 ic->bitmap_flush_interval = msecs_to_jiffies(10) + 1;
3104 ic->synchronous_mode = 1;
3106 cancel_delayed_work_sync(&ic->bitmap_flush_work);
3107 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
3108 flush_workqueue(ic->commit_wq);
3112 static int dm_integrity_reboot(struct notifier_block *n, unsigned long code, void *x)
3114 struct dm_integrity_c *ic = container_of(n, struct dm_integrity_c, reboot_notifier);
3116 DEBUG_print("%s\n", __func__);
3118 dm_integrity_enter_synchronous_mode(ic);
3123 static void dm_integrity_postsuspend(struct dm_target *ti)
3125 struct dm_integrity_c *ic = ti->private;
3128 WARN_ON(unregister_reboot_notifier(&ic->reboot_notifier));
3130 del_timer_sync(&ic->autocommit_timer);
3133 drain_workqueue(ic->recalc_wq);
3135 if (ic->mode == 'B')
3136 cancel_delayed_work_sync(&ic->bitmap_flush_work);
3138 queue_work(ic->commit_wq, &ic->commit_work);
3139 drain_workqueue(ic->commit_wq);
3141 if (ic->mode == 'J') {
3142 queue_work(ic->writer_wq, &ic->writer_work);
3143 drain_workqueue(ic->writer_wq);
3144 dm_integrity_flush_buffers(ic, true);
3145 if (ic->wrote_to_journal) {
3146 init_journal(ic, ic->free_section,
3147 ic->journal_sections - ic->free_section, ic->commit_seq);
3148 if (ic->free_section) {
3149 init_journal(ic, 0, ic->free_section,
3150 next_commit_seq(ic->commit_seq));
3155 if (ic->mode == 'B') {
3156 dm_integrity_flush_buffers(ic, true);
3158 /* set to 0 to test bitmap replay code */
3159 init_journal(ic, 0, ic->journal_sections, 0);
3160 ic->sb->flags &= ~cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
3161 r = sync_rw_sb(ic, REQ_OP_WRITE | REQ_FUA);
3163 dm_integrity_io_error(ic, "writing superblock", r);
3167 BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
3169 ic->journal_uptodate = true;
3172 static void dm_integrity_resume(struct dm_target *ti)
3174 struct dm_integrity_c *ic = ti->private;
3175 __u64 old_provided_data_sectors = le64_to_cpu(ic->sb->provided_data_sectors);
3178 DEBUG_print("resume\n");
3180 ic->wrote_to_journal = false;
3182 if (ic->provided_data_sectors != old_provided_data_sectors) {
3183 if (ic->provided_data_sectors > old_provided_data_sectors &&
3185 ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit) {
3186 rw_journal_sectors(ic, REQ_OP_READ, 0,
3187 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3188 block_bitmap_op(ic, ic->journal, old_provided_data_sectors,
3189 ic->provided_data_sectors - old_provided_data_sectors, BITMAP_OP_SET);
3190 rw_journal_sectors(ic, REQ_OP_WRITE | REQ_FUA | REQ_SYNC, 0,
3191 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3194 ic->sb->provided_data_sectors = cpu_to_le64(ic->provided_data_sectors);
3195 r = sync_rw_sb(ic, REQ_OP_WRITE | REQ_FUA);
3197 dm_integrity_io_error(ic, "writing superblock", r);
3200 if (ic->sb->flags & cpu_to_le32(SB_FLAG_DIRTY_BITMAP)) {
3201 DEBUG_print("resume dirty_bitmap\n");
3202 rw_journal_sectors(ic, REQ_OP_READ, 0,
3203 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3204 if (ic->mode == 'B') {
3205 if (ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit &&
3206 !ic->reset_recalculate_flag) {
3207 block_bitmap_copy(ic, ic->recalc_bitmap, ic->journal);
3208 block_bitmap_copy(ic, ic->may_write_bitmap, ic->journal);
3209 if (!block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors,
3210 BITMAP_OP_TEST_ALL_CLEAR)) {
3211 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
3212 ic->sb->recalc_sector = cpu_to_le64(0);
3215 DEBUG_print("non-matching blocks_per_bitmap_bit: %u, %u\n",
3216 ic->sb->log2_blocks_per_bitmap_bit, ic->log2_blocks_per_bitmap_bit);
3217 ic->sb->log2_blocks_per_bitmap_bit = ic->log2_blocks_per_bitmap_bit;
3218 block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_SET);
3219 block_bitmap_op(ic, ic->may_write_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_SET);
3220 block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_SET);
3221 rw_journal_sectors(ic, REQ_OP_WRITE | REQ_FUA | REQ_SYNC, 0,
3222 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3223 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
3224 ic->sb->recalc_sector = cpu_to_le64(0);
3227 if (!(ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit &&
3228 block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_TEST_ALL_CLEAR)) ||
3229 ic->reset_recalculate_flag) {
3230 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
3231 ic->sb->recalc_sector = cpu_to_le64(0);
3233 init_journal(ic, 0, ic->journal_sections, 0);
3235 ic->sb->flags &= ~cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
3237 r = sync_rw_sb(ic, REQ_OP_WRITE | REQ_FUA);
3239 dm_integrity_io_error(ic, "writing superblock", r);
3242 if (ic->reset_recalculate_flag) {
3243 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
3244 ic->sb->recalc_sector = cpu_to_le64(0);
3246 if (ic->mode == 'B') {
3247 ic->sb->flags |= cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
3248 ic->sb->log2_blocks_per_bitmap_bit = ic->log2_blocks_per_bitmap_bit;
3249 r = sync_rw_sb(ic, REQ_OP_WRITE | REQ_FUA);
3251 dm_integrity_io_error(ic, "writing superblock", r);
3253 block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
3254 block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
3255 block_bitmap_op(ic, ic->may_write_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
3256 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
3257 le64_to_cpu(ic->sb->recalc_sector) < ic->provided_data_sectors) {
3258 block_bitmap_op(ic, ic->journal, le64_to_cpu(ic->sb->recalc_sector),
3259 ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
3260 block_bitmap_op(ic, ic->recalc_bitmap, le64_to_cpu(ic->sb->recalc_sector),
3261 ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
3262 block_bitmap_op(ic, ic->may_write_bitmap, le64_to_cpu(ic->sb->recalc_sector),
3263 ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
3265 rw_journal_sectors(ic, REQ_OP_WRITE | REQ_FUA | REQ_SYNC, 0,
3266 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3270 DEBUG_print("testing recalc: %x\n", ic->sb->flags);
3271 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
3272 __u64 recalc_pos = le64_to_cpu(ic->sb->recalc_sector);
3274 DEBUG_print("recalc pos: %llx / %llx\n", recalc_pos, ic->provided_data_sectors);
3275 if (recalc_pos < ic->provided_data_sectors) {
3276 queue_work(ic->recalc_wq, &ic->recalc_work);
3277 } else if (recalc_pos > ic->provided_data_sectors) {
3278 ic->sb->recalc_sector = cpu_to_le64(ic->provided_data_sectors);
3279 recalc_write_super(ic);
3283 ic->reboot_notifier.notifier_call = dm_integrity_reboot;
3284 ic->reboot_notifier.next = NULL;
3285 ic->reboot_notifier.priority = INT_MAX - 1; /* be notified after md and before hardware drivers */
3286 WARN_ON(register_reboot_notifier(&ic->reboot_notifier));
3289 /* set to 1 to stress test synchronous mode */
3290 dm_integrity_enter_synchronous_mode(ic);
3294 static void dm_integrity_status(struct dm_target *ti, status_type_t type,
3295 unsigned int status_flags, char *result, unsigned int maxlen)
3297 struct dm_integrity_c *ic = ti->private;
3298 unsigned int arg_count;
3302 case STATUSTYPE_INFO:
3304 (unsigned long long)atomic64_read(&ic->number_of_mismatches),
3305 ic->provided_data_sectors);
3306 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
3307 DMEMIT(" %llu", le64_to_cpu(ic->sb->recalc_sector));
3312 case STATUSTYPE_TABLE: {
3313 __u64 watermark_percentage = (__u64)(ic->journal_entries - ic->free_sectors_threshold) * 100;
3315 watermark_percentage += ic->journal_entries / 2;
3316 do_div(watermark_percentage, ic->journal_entries);
3318 arg_count += !!ic->meta_dev;
3319 arg_count += ic->sectors_per_block != 1;
3320 arg_count += !!(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING));
3321 arg_count += ic->reset_recalculate_flag;
3322 arg_count += ic->discard;
3323 arg_count += ic->mode == 'J';
3324 arg_count += ic->mode == 'J';
3325 arg_count += ic->mode == 'B';
3326 arg_count += ic->mode == 'B';
3327 arg_count += !!ic->internal_hash_alg.alg_string;
3328 arg_count += !!ic->journal_crypt_alg.alg_string;
3329 arg_count += !!ic->journal_mac_alg.alg_string;
3330 arg_count += (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING)) != 0;
3331 arg_count += (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) != 0;
3332 arg_count += ic->legacy_recalculate;
3333 DMEMIT("%s %llu %u %c %u", ic->dev->name, ic->start,
3334 ic->tag_size, ic->mode, arg_count);
3336 DMEMIT(" meta_device:%s", ic->meta_dev->name);
3337 if (ic->sectors_per_block != 1)
3338 DMEMIT(" block_size:%u", ic->sectors_per_block << SECTOR_SHIFT);
3339 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
3340 DMEMIT(" recalculate");
3341 if (ic->reset_recalculate_flag)
3342 DMEMIT(" reset_recalculate");
3344 DMEMIT(" allow_discards");
3345 DMEMIT(" journal_sectors:%u", ic->initial_sectors - SB_SECTORS);
3346 DMEMIT(" interleave_sectors:%u", 1U << ic->sb->log2_interleave_sectors);
3347 DMEMIT(" buffer_sectors:%u", 1U << ic->log2_buffer_sectors);
3348 if (ic->mode == 'J') {
3349 DMEMIT(" journal_watermark:%u", (unsigned int)watermark_percentage);
3350 DMEMIT(" commit_time:%u", ic->autocommit_msec);
3352 if (ic->mode == 'B') {
3353 DMEMIT(" sectors_per_bit:%llu", (sector_t)ic->sectors_per_block << ic->log2_blocks_per_bitmap_bit);
3354 DMEMIT(" bitmap_flush_interval:%u", jiffies_to_msecs(ic->bitmap_flush_interval));
3356 if ((ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING)) != 0)
3357 DMEMIT(" fix_padding");
3358 if ((ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) != 0)
3359 DMEMIT(" fix_hmac");
3360 if (ic->legacy_recalculate)
3361 DMEMIT(" legacy_recalculate");
3363 #define EMIT_ALG(a, n) \
3365 if (ic->a.alg_string) { \
3366 DMEMIT(" %s:%s", n, ic->a.alg_string); \
3367 if (ic->a.key_string) \
3368 DMEMIT(":%s", ic->a.key_string);\
3371 EMIT_ALG(internal_hash_alg, "internal_hash");
3372 EMIT_ALG(journal_crypt_alg, "journal_crypt");
3373 EMIT_ALG(journal_mac_alg, "journal_mac");
3376 case STATUSTYPE_IMA:
3377 DMEMIT_TARGET_NAME_VERSION(ti->type);
3378 DMEMIT(",dev_name=%s,start=%llu,tag_size=%u,mode=%c",
3379 ic->dev->name, ic->start, ic->tag_size, ic->mode);
3382 DMEMIT(",meta_device=%s", ic->meta_dev->name);
3383 if (ic->sectors_per_block != 1)
3384 DMEMIT(",block_size=%u", ic->sectors_per_block << SECTOR_SHIFT);
3386 DMEMIT(",recalculate=%c", (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) ?
3388 DMEMIT(",allow_discards=%c", ic->discard ? 'y' : 'n');
3389 DMEMIT(",fix_padding=%c",
3390 ((ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING)) != 0) ? 'y' : 'n');
3391 DMEMIT(",fix_hmac=%c",
3392 ((ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) != 0) ? 'y' : 'n');
3393 DMEMIT(",legacy_recalculate=%c", ic->legacy_recalculate ? 'y' : 'n');
3395 DMEMIT(",journal_sectors=%u", ic->initial_sectors - SB_SECTORS);
3396 DMEMIT(",interleave_sectors=%u", 1U << ic->sb->log2_interleave_sectors);
3397 DMEMIT(",buffer_sectors=%u", 1U << ic->log2_buffer_sectors);
3403 static int dm_integrity_iterate_devices(struct dm_target *ti,
3404 iterate_devices_callout_fn fn, void *data)
3406 struct dm_integrity_c *ic = ti->private;
3409 return fn(ti, ic->dev, ic->start + ic->initial_sectors + ic->metadata_run, ti->len, data);
3411 return fn(ti, ic->dev, 0, ti->len, data);
3414 static void dm_integrity_io_hints(struct dm_target *ti, struct queue_limits *limits)
3416 struct dm_integrity_c *ic = ti->private;
3418 if (ic->sectors_per_block > 1) {
3419 limits->logical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
3420 limits->physical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
3421 blk_limits_io_min(limits, ic->sectors_per_block << SECTOR_SHIFT);
3422 limits->dma_alignment = limits->logical_block_size - 1;
3426 static void calculate_journal_section_size(struct dm_integrity_c *ic)
3428 unsigned int sector_space = JOURNAL_SECTOR_DATA;
3430 ic->journal_sections = le32_to_cpu(ic->sb->journal_sections);
3431 ic->journal_entry_size = roundup(offsetof(struct journal_entry, last_bytes[ic->sectors_per_block]) + ic->tag_size,
3432 JOURNAL_ENTRY_ROUNDUP);
3434 if (ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC))
3435 sector_space -= JOURNAL_MAC_PER_SECTOR;
3436 ic->journal_entries_per_sector = sector_space / ic->journal_entry_size;
3437 ic->journal_section_entries = ic->journal_entries_per_sector * JOURNAL_BLOCK_SECTORS;
3438 ic->journal_section_sectors = (ic->journal_section_entries << ic->sb->log2_sectors_per_block) + JOURNAL_BLOCK_SECTORS;
3439 ic->journal_entries = ic->journal_section_entries * ic->journal_sections;
3442 static int calculate_device_limits(struct dm_integrity_c *ic)
3444 __u64 initial_sectors;
3446 calculate_journal_section_size(ic);
3447 initial_sectors = SB_SECTORS + (__u64)ic->journal_section_sectors * ic->journal_sections;
3448 if (initial_sectors + METADATA_PADDING_SECTORS >= ic->meta_device_sectors || initial_sectors > UINT_MAX)
3450 ic->initial_sectors = initial_sectors;
3452 if (!ic->meta_dev) {
3453 sector_t last_sector, last_area, last_offset;
3455 /* we have to maintain excessive padding for compatibility with existing volumes */
3456 __u64 metadata_run_padding =
3457 ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING) ?
3458 (__u64)(METADATA_PADDING_SECTORS << SECTOR_SHIFT) :
3459 (__u64)(1 << SECTOR_SHIFT << METADATA_PADDING_SECTORS);
3461 ic->metadata_run = round_up((__u64)ic->tag_size << (ic->sb->log2_interleave_sectors - ic->sb->log2_sectors_per_block),
3462 metadata_run_padding) >> SECTOR_SHIFT;
3463 if (!(ic->metadata_run & (ic->metadata_run - 1)))
3464 ic->log2_metadata_run = __ffs(ic->metadata_run);
3466 ic->log2_metadata_run = -1;
3468 get_area_and_offset(ic, ic->provided_data_sectors - 1, &last_area, &last_offset);
3469 last_sector = get_data_sector(ic, last_area, last_offset);
3470 if (last_sector < ic->start || last_sector >= ic->meta_device_sectors)
3473 __u64 meta_size = (ic->provided_data_sectors >> ic->sb->log2_sectors_per_block) * ic->tag_size;
3475 meta_size = (meta_size + ((1U << (ic->log2_buffer_sectors + SECTOR_SHIFT)) - 1))
3476 >> (ic->log2_buffer_sectors + SECTOR_SHIFT);
3477 meta_size <<= ic->log2_buffer_sectors;
3478 if (ic->initial_sectors + meta_size < ic->initial_sectors ||
3479 ic->initial_sectors + meta_size > ic->meta_device_sectors)
3481 ic->metadata_run = 1;
3482 ic->log2_metadata_run = 0;
3488 static void get_provided_data_sectors(struct dm_integrity_c *ic)
3490 if (!ic->meta_dev) {
3493 ic->provided_data_sectors = 0;
3494 for (test_bit = fls64(ic->meta_device_sectors) - 1; test_bit >= 3; test_bit--) {
3495 __u64 prev_data_sectors = ic->provided_data_sectors;
3497 ic->provided_data_sectors |= (sector_t)1 << test_bit;
3498 if (calculate_device_limits(ic))
3499 ic->provided_data_sectors = prev_data_sectors;
3502 ic->provided_data_sectors = ic->data_device_sectors;
3503 ic->provided_data_sectors &= ~(sector_t)(ic->sectors_per_block - 1);
3507 static int initialize_superblock(struct dm_integrity_c *ic,
3508 unsigned int journal_sectors, unsigned int interleave_sectors)
3510 unsigned int journal_sections;
3513 memset(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT);
3514 memcpy(ic->sb->magic, SB_MAGIC, 8);
3515 ic->sb->integrity_tag_size = cpu_to_le16(ic->tag_size);
3516 ic->sb->log2_sectors_per_block = __ffs(ic->sectors_per_block);
3517 if (ic->journal_mac_alg.alg_string)
3518 ic->sb->flags |= cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC);
3520 calculate_journal_section_size(ic);
3521 journal_sections = journal_sectors / ic->journal_section_sectors;
3522 if (!journal_sections)
3523 journal_sections = 1;
3525 if (ic->fix_hmac && (ic->internal_hash_alg.alg_string || ic->journal_mac_alg.alg_string)) {
3526 ic->sb->flags |= cpu_to_le32(SB_FLAG_FIXED_HMAC);
3527 get_random_bytes(ic->sb->salt, SALT_SIZE);
3530 if (!ic->meta_dev) {
3531 if (ic->fix_padding)
3532 ic->sb->flags |= cpu_to_le32(SB_FLAG_FIXED_PADDING);
3533 ic->sb->journal_sections = cpu_to_le32(journal_sections);
3534 if (!interleave_sectors)
3535 interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
3536 ic->sb->log2_interleave_sectors = __fls(interleave_sectors);
3537 ic->sb->log2_interleave_sectors = max_t(__u8, MIN_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
3538 ic->sb->log2_interleave_sectors = min_t(__u8, MAX_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
3540 get_provided_data_sectors(ic);
3541 if (!ic->provided_data_sectors)
3544 ic->sb->log2_interleave_sectors = 0;
3546 get_provided_data_sectors(ic);
3547 if (!ic->provided_data_sectors)
3551 ic->sb->journal_sections = cpu_to_le32(0);
3552 for (test_bit = fls(journal_sections) - 1; test_bit >= 0; test_bit--) {
3553 __u32 prev_journal_sections = le32_to_cpu(ic->sb->journal_sections);
3554 __u32 test_journal_sections = prev_journal_sections | (1U << test_bit);
3556 if (test_journal_sections > journal_sections)
3558 ic->sb->journal_sections = cpu_to_le32(test_journal_sections);
3559 if (calculate_device_limits(ic))
3560 ic->sb->journal_sections = cpu_to_le32(prev_journal_sections);
3563 if (!le32_to_cpu(ic->sb->journal_sections)) {
3564 if (ic->log2_buffer_sectors > 3) {
3565 ic->log2_buffer_sectors--;
3566 goto try_smaller_buffer;
3572 ic->sb->provided_data_sectors = cpu_to_le64(ic->provided_data_sectors);
3579 static void dm_integrity_set(struct dm_target *ti, struct dm_integrity_c *ic)
3581 struct gendisk *disk = dm_disk(dm_table_get_md(ti->table));
3582 struct blk_integrity bi;
3584 memset(&bi, 0, sizeof(bi));
3585 bi.profile = &dm_integrity_profile;
3586 bi.tuple_size = ic->tag_size;
3587 bi.tag_size = bi.tuple_size;
3588 bi.interval_exp = ic->sb->log2_sectors_per_block + SECTOR_SHIFT;
3590 blk_integrity_register(disk, &bi);
3591 blk_queue_max_integrity_segments(disk->queue, UINT_MAX);
3594 static void dm_integrity_free_page_list(struct page_list *pl)
3600 for (i = 0; pl[i].page; i++)
3601 __free_page(pl[i].page);
3605 static struct page_list *dm_integrity_alloc_page_list(unsigned int n_pages)
3607 struct page_list *pl;
3610 pl = kvmalloc_array(n_pages + 1, sizeof(struct page_list), GFP_KERNEL | __GFP_ZERO);
3614 for (i = 0; i < n_pages; i++) {
3615 pl[i].page = alloc_page(GFP_KERNEL);
3617 dm_integrity_free_page_list(pl);
3621 pl[i - 1].next = &pl[i];
3629 static void dm_integrity_free_journal_scatterlist(struct dm_integrity_c *ic, struct scatterlist **sl)
3633 for (i = 0; i < ic->journal_sections; i++)
3638 static struct scatterlist **dm_integrity_alloc_journal_scatterlist(struct dm_integrity_c *ic,
3639 struct page_list *pl)
3641 struct scatterlist **sl;
3644 sl = kvmalloc_array(ic->journal_sections,
3645 sizeof(struct scatterlist *),
3646 GFP_KERNEL | __GFP_ZERO);
3650 for (i = 0; i < ic->journal_sections; i++) {
3651 struct scatterlist *s;
3652 unsigned int start_index, start_offset;
3653 unsigned int end_index, end_offset;
3654 unsigned int n_pages;
3657 page_list_location(ic, i, 0, &start_index, &start_offset);
3658 page_list_location(ic, i, ic->journal_section_sectors - 1,
3659 &end_index, &end_offset);
3661 n_pages = (end_index - start_index + 1);
3663 s = kvmalloc_array(n_pages, sizeof(struct scatterlist),
3666 dm_integrity_free_journal_scatterlist(ic, sl);
3670 sg_init_table(s, n_pages);
3671 for (idx = start_index; idx <= end_index; idx++) {
3672 char *va = lowmem_page_address(pl[idx].page);
3673 unsigned int start = 0, end = PAGE_SIZE;
3675 if (idx == start_index)
3676 start = start_offset;
3677 if (idx == end_index)
3678 end = end_offset + (1 << SECTOR_SHIFT);
3679 sg_set_buf(&s[idx - start_index], va + start, end - start);
3688 static void free_alg(struct alg_spec *a)
3690 kfree_sensitive(a->alg_string);
3691 kfree_sensitive(a->key);
3692 memset(a, 0, sizeof(*a));
3695 static int get_alg_and_key(const char *arg, struct alg_spec *a, char **error, char *error_inval)
3701 a->alg_string = kstrdup(strchr(arg, ':') + 1, GFP_KERNEL);
3705 k = strchr(a->alg_string, ':');
3708 a->key_string = k + 1;
3709 if (strlen(a->key_string) & 1)
3712 a->key_size = strlen(a->key_string) / 2;
3713 a->key = kmalloc(a->key_size, GFP_KERNEL);
3716 if (hex2bin(a->key, a->key_string, a->key_size))
3722 *error = error_inval;
3725 *error = "Out of memory for an argument";
3729 static int get_mac(struct crypto_shash **hash, struct alg_spec *a, char **error,
3730 char *error_alg, char *error_key)
3734 if (a->alg_string) {
3735 *hash = crypto_alloc_shash(a->alg_string, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
3736 if (IS_ERR(*hash)) {
3744 r = crypto_shash_setkey(*hash, a->key, a->key_size);
3749 } else if (crypto_shash_get_flags(*hash) & CRYPTO_TFM_NEED_KEY) {
3758 static int create_journal(struct dm_integrity_c *ic, char **error)
3762 __u64 journal_pages, journal_desc_size, journal_tree_size;
3763 unsigned char *crypt_data = NULL, *crypt_iv = NULL;
3764 struct skcipher_request *req = NULL;
3766 ic->commit_ids[0] = cpu_to_le64(0x1111111111111111ULL);
3767 ic->commit_ids[1] = cpu_to_le64(0x2222222222222222ULL);
3768 ic->commit_ids[2] = cpu_to_le64(0x3333333333333333ULL);
3769 ic->commit_ids[3] = cpu_to_le64(0x4444444444444444ULL);
3771 journal_pages = roundup((__u64)ic->journal_sections * ic->journal_section_sectors,
3772 PAGE_SIZE >> SECTOR_SHIFT) >> (PAGE_SHIFT - SECTOR_SHIFT);
3773 journal_desc_size = journal_pages * sizeof(struct page_list);
3774 if (journal_pages >= totalram_pages() - totalhigh_pages() || journal_desc_size > ULONG_MAX) {
3775 *error = "Journal doesn't fit into memory";
3779 ic->journal_pages = journal_pages;
3781 ic->journal = dm_integrity_alloc_page_list(ic->journal_pages);
3783 *error = "Could not allocate memory for journal";
3787 if (ic->journal_crypt_alg.alg_string) {
3788 unsigned int ivsize, blocksize;
3789 struct journal_completion comp;
3792 ic->journal_crypt = crypto_alloc_skcipher(ic->journal_crypt_alg.alg_string, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
3793 if (IS_ERR(ic->journal_crypt)) {
3794 *error = "Invalid journal cipher";
3795 r = PTR_ERR(ic->journal_crypt);
3796 ic->journal_crypt = NULL;
3799 ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
3800 blocksize = crypto_skcipher_blocksize(ic->journal_crypt);
3802 if (ic->journal_crypt_alg.key) {
3803 r = crypto_skcipher_setkey(ic->journal_crypt, ic->journal_crypt_alg.key,
3804 ic->journal_crypt_alg.key_size);
3806 *error = "Error setting encryption key";
3810 DEBUG_print("cipher %s, block size %u iv size %u\n",
3811 ic->journal_crypt_alg.alg_string, blocksize, ivsize);
3813 ic->journal_io = dm_integrity_alloc_page_list(ic->journal_pages);
3814 if (!ic->journal_io) {
3815 *error = "Could not allocate memory for journal io";
3820 if (blocksize == 1) {
3821 struct scatterlist *sg;
3823 req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
3825 *error = "Could not allocate crypt request";
3830 crypt_iv = kzalloc(ivsize, GFP_KERNEL);
3832 *error = "Could not allocate iv";
3837 ic->journal_xor = dm_integrity_alloc_page_list(ic->journal_pages);
3838 if (!ic->journal_xor) {
3839 *error = "Could not allocate memory for journal xor";
3844 sg = kvmalloc_array(ic->journal_pages + 1,
3845 sizeof(struct scatterlist),
3848 *error = "Unable to allocate sg list";
3852 sg_init_table(sg, ic->journal_pages + 1);
3853 for (i = 0; i < ic->journal_pages; i++) {
3854 char *va = lowmem_page_address(ic->journal_xor[i].page);
3857 sg_set_buf(&sg[i], va, PAGE_SIZE);
3859 sg_set_buf(&sg[i], &ic->commit_ids, sizeof(ic->commit_ids));
3861 skcipher_request_set_crypt(req, sg, sg,
3862 PAGE_SIZE * ic->journal_pages + sizeof(ic->commit_ids), crypt_iv);
3863 init_completion(&comp.comp);
3864 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
3865 if (do_crypt(true, req, &comp))
3866 wait_for_completion(&comp.comp);
3868 r = dm_integrity_failed(ic);
3870 *error = "Unable to encrypt journal";
3873 DEBUG_bytes(lowmem_page_address(ic->journal_xor[0].page), 64, "xor data");
3875 crypto_free_skcipher(ic->journal_crypt);
3876 ic->journal_crypt = NULL;
3878 unsigned int crypt_len = roundup(ivsize, blocksize);
3880 req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
3882 *error = "Could not allocate crypt request";
3887 crypt_iv = kmalloc(ivsize, GFP_KERNEL);
3889 *error = "Could not allocate iv";
3894 crypt_data = kmalloc(crypt_len, GFP_KERNEL);
3896 *error = "Unable to allocate crypt data";
3901 ic->journal_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal);
3902 if (!ic->journal_scatterlist) {
3903 *error = "Unable to allocate sg list";
3907 ic->journal_io_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal_io);
3908 if (!ic->journal_io_scatterlist) {
3909 *error = "Unable to allocate sg list";
3913 ic->sk_requests = kvmalloc_array(ic->journal_sections,
3914 sizeof(struct skcipher_request *),
3915 GFP_KERNEL | __GFP_ZERO);
3916 if (!ic->sk_requests) {
3917 *error = "Unable to allocate sk requests";
3921 for (i = 0; i < ic->journal_sections; i++) {
3922 struct scatterlist sg;
3923 struct skcipher_request *section_req;
3924 __le32 section_le = cpu_to_le32(i);
3926 memset(crypt_iv, 0x00, ivsize);
3927 memset(crypt_data, 0x00, crypt_len);
3928 memcpy(crypt_data, §ion_le, min_t(size_t, crypt_len, sizeof(section_le)));
3930 sg_init_one(&sg, crypt_data, crypt_len);
3931 skcipher_request_set_crypt(req, &sg, &sg, crypt_len, crypt_iv);
3932 init_completion(&comp.comp);
3933 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
3934 if (do_crypt(true, req, &comp))
3935 wait_for_completion(&comp.comp);
3937 r = dm_integrity_failed(ic);
3939 *error = "Unable to generate iv";
3943 section_req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
3945 *error = "Unable to allocate crypt request";
3949 section_req->iv = kmalloc_array(ivsize, 2,
3951 if (!section_req->iv) {
3952 skcipher_request_free(section_req);
3953 *error = "Unable to allocate iv";
3957 memcpy(section_req->iv + ivsize, crypt_data, ivsize);
3958 section_req->cryptlen = (size_t)ic->journal_section_sectors << SECTOR_SHIFT;
3959 ic->sk_requests[i] = section_req;
3960 DEBUG_bytes(crypt_data, ivsize, "iv(%u)", i);
3965 for (i = 0; i < N_COMMIT_IDS; i++) {
3969 for (j = 0; j < i; j++) {
3970 if (ic->commit_ids[j] == ic->commit_ids[i]) {
3971 ic->commit_ids[i] = cpu_to_le64(le64_to_cpu(ic->commit_ids[i]) + 1);
3972 goto retest_commit_id;
3975 DEBUG_print("commit id %u: %016llx\n", i, ic->commit_ids[i]);
3978 journal_tree_size = (__u64)ic->journal_entries * sizeof(struct journal_node);
3979 if (journal_tree_size > ULONG_MAX) {
3980 *error = "Journal doesn't fit into memory";
3984 ic->journal_tree = kvmalloc(journal_tree_size, GFP_KERNEL);
3985 if (!ic->journal_tree) {
3986 *error = "Could not allocate memory for journal tree";
3992 skcipher_request_free(req);
3998 * Construct a integrity mapping
4002 * offset from the start of the device
4004 * D - direct writes, J - journal writes, B - bitmap mode, R - recovery mode
4005 * number of optional arguments
4006 * optional arguments:
4008 * interleave_sectors
4015 * bitmap_flush_interval
4021 static int dm_integrity_ctr(struct dm_target *ti, unsigned int argc, char **argv)
4023 struct dm_integrity_c *ic;
4026 unsigned int extra_args;
4027 struct dm_arg_set as;
4028 static const struct dm_arg _args[] = {
4029 {0, 18, "Invalid number of feature args"},
4031 unsigned int journal_sectors, interleave_sectors, buffer_sectors, journal_watermark, sync_msec;
4032 bool should_write_sb;
4034 unsigned long long start;
4035 __s8 log2_sectors_per_bitmap_bit = -1;
4036 __s8 log2_blocks_per_bitmap_bit;
4037 __u64 bits_in_journal;
4038 __u64 n_bitmap_bits;
4040 #define DIRECT_ARGUMENTS 4
4042 if (argc <= DIRECT_ARGUMENTS) {
4043 ti->error = "Invalid argument count";
4047 ic = kzalloc(sizeof(struct dm_integrity_c), GFP_KERNEL);
4049 ti->error = "Cannot allocate integrity context";
4053 ti->per_io_data_size = sizeof(struct dm_integrity_io);
4056 ic->in_progress = RB_ROOT;
4057 INIT_LIST_HEAD(&ic->wait_list);
4058 init_waitqueue_head(&ic->endio_wait);
4059 bio_list_init(&ic->flush_bio_list);
4060 init_waitqueue_head(&ic->copy_to_journal_wait);
4061 init_completion(&ic->crypto_backoff);
4062 atomic64_set(&ic->number_of_mismatches, 0);
4063 ic->bitmap_flush_interval = BITMAP_FLUSH_INTERVAL;
4065 r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &ic->dev);
4067 ti->error = "Device lookup failed";
4071 if (sscanf(argv[1], "%llu%c", &start, &dummy) != 1 || start != (sector_t)start) {
4072 ti->error = "Invalid starting offset";
4078 if (strcmp(argv[2], "-")) {
4079 if (sscanf(argv[2], "%u%c", &ic->tag_size, &dummy) != 1 || !ic->tag_size) {
4080 ti->error = "Invalid tag size";
4086 if (!strcmp(argv[3], "J") || !strcmp(argv[3], "B") ||
4087 !strcmp(argv[3], "D") || !strcmp(argv[3], "R")) {
4088 ic->mode = argv[3][0];
4090 ti->error = "Invalid mode (expecting J, B, D, R)";
4095 journal_sectors = 0;
4096 interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
4097 buffer_sectors = DEFAULT_BUFFER_SECTORS;
4098 journal_watermark = DEFAULT_JOURNAL_WATERMARK;
4099 sync_msec = DEFAULT_SYNC_MSEC;
4100 ic->sectors_per_block = 1;
4102 as.argc = argc - DIRECT_ARGUMENTS;
4103 as.argv = argv + DIRECT_ARGUMENTS;
4104 r = dm_read_arg_group(_args, &as, &extra_args, &ti->error);
4108 while (extra_args--) {
4109 const char *opt_string;
4111 unsigned long long llval;
4113 opt_string = dm_shift_arg(&as);
4116 ti->error = "Not enough feature arguments";
4119 if (sscanf(opt_string, "journal_sectors:%u%c", &val, &dummy) == 1)
4120 journal_sectors = val ? val : 1;
4121 else if (sscanf(opt_string, "interleave_sectors:%u%c", &val, &dummy) == 1)
4122 interleave_sectors = val;
4123 else if (sscanf(opt_string, "buffer_sectors:%u%c", &val, &dummy) == 1)
4124 buffer_sectors = val;
4125 else if (sscanf(opt_string, "journal_watermark:%u%c", &val, &dummy) == 1 && val <= 100)
4126 journal_watermark = val;
4127 else if (sscanf(opt_string, "commit_time:%u%c", &val, &dummy) == 1)
4129 else if (!strncmp(opt_string, "meta_device:", strlen("meta_device:"))) {
4131 dm_put_device(ti, ic->meta_dev);
4132 ic->meta_dev = NULL;
4134 r = dm_get_device(ti, strchr(opt_string, ':') + 1,
4135 dm_table_get_mode(ti->table), &ic->meta_dev);
4137 ti->error = "Device lookup failed";
4140 } else if (sscanf(opt_string, "block_size:%u%c", &val, &dummy) == 1) {
4141 if (val < 1 << SECTOR_SHIFT ||
4142 val > MAX_SECTORS_PER_BLOCK << SECTOR_SHIFT ||
4143 (val & (val - 1))) {
4145 ti->error = "Invalid block_size argument";
4148 ic->sectors_per_block = val >> SECTOR_SHIFT;
4149 } else if (sscanf(opt_string, "sectors_per_bit:%llu%c", &llval, &dummy) == 1) {
4150 log2_sectors_per_bitmap_bit = !llval ? 0 : __ilog2_u64(llval);
4151 } else if (sscanf(opt_string, "bitmap_flush_interval:%u%c", &val, &dummy) == 1) {
4152 if (val >= (uint64_t)UINT_MAX * 1000 / HZ) {
4154 ti->error = "Invalid bitmap_flush_interval argument";
4157 ic->bitmap_flush_interval = msecs_to_jiffies(val);
4158 } else if (!strncmp(opt_string, "internal_hash:", strlen("internal_hash:"))) {
4159 r = get_alg_and_key(opt_string, &ic->internal_hash_alg, &ti->error,
4160 "Invalid internal_hash argument");
4163 } else if (!strncmp(opt_string, "journal_crypt:", strlen("journal_crypt:"))) {
4164 r = get_alg_and_key(opt_string, &ic->journal_crypt_alg, &ti->error,
4165 "Invalid journal_crypt argument");
4168 } else if (!strncmp(opt_string, "journal_mac:", strlen("journal_mac:"))) {
4169 r = get_alg_and_key(opt_string, &ic->journal_mac_alg, &ti->error,
4170 "Invalid journal_mac argument");
4173 } else if (!strcmp(opt_string, "recalculate")) {
4174 ic->recalculate_flag = true;
4175 } else if (!strcmp(opt_string, "reset_recalculate")) {
4176 ic->recalculate_flag = true;
4177 ic->reset_recalculate_flag = true;
4178 } else if (!strcmp(opt_string, "allow_discards")) {
4180 } else if (!strcmp(opt_string, "fix_padding")) {
4181 ic->fix_padding = true;
4182 } else if (!strcmp(opt_string, "fix_hmac")) {
4183 ic->fix_hmac = true;
4184 } else if (!strcmp(opt_string, "legacy_recalculate")) {
4185 ic->legacy_recalculate = true;
4188 ti->error = "Invalid argument";
4193 ic->data_device_sectors = bdev_nr_sectors(ic->dev->bdev);
4195 ic->meta_device_sectors = ic->data_device_sectors;
4197 ic->meta_device_sectors = bdev_nr_sectors(ic->meta_dev->bdev);
4199 if (!journal_sectors) {
4200 journal_sectors = min((sector_t)DEFAULT_MAX_JOURNAL_SECTORS,
4201 ic->data_device_sectors >> DEFAULT_JOURNAL_SIZE_FACTOR);
4204 if (!buffer_sectors)
4206 ic->log2_buffer_sectors = min((int)__fls(buffer_sectors), 31 - SECTOR_SHIFT);
4208 r = get_mac(&ic->internal_hash, &ic->internal_hash_alg, &ti->error,
4209 "Invalid internal hash", "Error setting internal hash key");
4213 r = get_mac(&ic->journal_mac, &ic->journal_mac_alg, &ti->error,
4214 "Invalid journal mac", "Error setting journal mac key");
4218 if (!ic->tag_size) {
4219 if (!ic->internal_hash) {
4220 ti->error = "Unknown tag size";
4224 ic->tag_size = crypto_shash_digestsize(ic->internal_hash);
4226 if (ic->tag_size > MAX_TAG_SIZE) {
4227 ti->error = "Too big tag size";
4231 if (!(ic->tag_size & (ic->tag_size - 1)))
4232 ic->log2_tag_size = __ffs(ic->tag_size);
4234 ic->log2_tag_size = -1;
4236 if (ic->mode == 'B' && !ic->internal_hash) {
4238 ti->error = "Bitmap mode can be only used with internal hash";
4242 if (ic->discard && !ic->internal_hash) {
4244 ti->error = "Discard can be only used with internal hash";
4248 ic->autocommit_jiffies = msecs_to_jiffies(sync_msec);
4249 ic->autocommit_msec = sync_msec;
4250 timer_setup(&ic->autocommit_timer, autocommit_fn, 0);
4252 ic->io = dm_io_client_create();
4253 if (IS_ERR(ic->io)) {
4254 r = PTR_ERR(ic->io);
4256 ti->error = "Cannot allocate dm io";
4260 r = mempool_init_slab_pool(&ic->journal_io_mempool, JOURNAL_IO_MEMPOOL, journal_io_cache);
4262 ti->error = "Cannot allocate mempool";
4266 ic->metadata_wq = alloc_workqueue("dm-integrity-metadata",
4267 WQ_MEM_RECLAIM, METADATA_WORKQUEUE_MAX_ACTIVE);
4268 if (!ic->metadata_wq) {
4269 ti->error = "Cannot allocate workqueue";
4275 * If this workqueue were percpu, it would cause bio reordering
4276 * and reduced performance.
4278 ic->wait_wq = alloc_workqueue("dm-integrity-wait", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
4280 ti->error = "Cannot allocate workqueue";
4285 ic->offload_wq = alloc_workqueue("dm-integrity-offload", WQ_MEM_RECLAIM,
4286 METADATA_WORKQUEUE_MAX_ACTIVE);
4287 if (!ic->offload_wq) {
4288 ti->error = "Cannot allocate workqueue";
4293 ic->commit_wq = alloc_workqueue("dm-integrity-commit", WQ_MEM_RECLAIM, 1);
4294 if (!ic->commit_wq) {
4295 ti->error = "Cannot allocate workqueue";
4299 INIT_WORK(&ic->commit_work, integrity_commit);
4301 if (ic->mode == 'J' || ic->mode == 'B') {
4302 ic->writer_wq = alloc_workqueue("dm-integrity-writer", WQ_MEM_RECLAIM, 1);
4303 if (!ic->writer_wq) {
4304 ti->error = "Cannot allocate workqueue";
4308 INIT_WORK(&ic->writer_work, integrity_writer);
4311 ic->sb = alloc_pages_exact(SB_SECTORS << SECTOR_SHIFT, GFP_KERNEL);
4314 ti->error = "Cannot allocate superblock area";
4318 r = sync_rw_sb(ic, REQ_OP_READ);
4320 ti->error = "Error reading superblock";
4323 should_write_sb = false;
4324 if (memcmp(ic->sb->magic, SB_MAGIC, 8)) {
4325 if (ic->mode != 'R') {
4326 if (memchr_inv(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT)) {
4328 ti->error = "The device is not initialized";
4333 r = initialize_superblock(ic, journal_sectors, interleave_sectors);
4335 ti->error = "Could not initialize superblock";
4338 if (ic->mode != 'R')
4339 should_write_sb = true;
4342 if (!ic->sb->version || ic->sb->version > SB_VERSION_5) {
4344 ti->error = "Unknown version";
4347 if (le16_to_cpu(ic->sb->integrity_tag_size) != ic->tag_size) {
4349 ti->error = "Tag size doesn't match the information in superblock";
4352 if (ic->sb->log2_sectors_per_block != __ffs(ic->sectors_per_block)) {
4354 ti->error = "Block size doesn't match the information in superblock";
4357 if (!le32_to_cpu(ic->sb->journal_sections)) {
4359 ti->error = "Corrupted superblock, journal_sections is 0";
4362 /* make sure that ti->max_io_len doesn't overflow */
4363 if (!ic->meta_dev) {
4364 if (ic->sb->log2_interleave_sectors < MIN_LOG2_INTERLEAVE_SECTORS ||
4365 ic->sb->log2_interleave_sectors > MAX_LOG2_INTERLEAVE_SECTORS) {
4367 ti->error = "Invalid interleave_sectors in the superblock";
4371 if (ic->sb->log2_interleave_sectors) {
4373 ti->error = "Invalid interleave_sectors in the superblock";
4377 if (!!(ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC)) != !!ic->journal_mac_alg.alg_string) {
4379 ti->error = "Journal mac mismatch";
4383 get_provided_data_sectors(ic);
4384 if (!ic->provided_data_sectors) {
4386 ti->error = "The device is too small";
4391 r = calculate_device_limits(ic);
4394 if (ic->log2_buffer_sectors > 3) {
4395 ic->log2_buffer_sectors--;
4396 goto try_smaller_buffer;
4399 ti->error = "The device is too small";
4403 if (log2_sectors_per_bitmap_bit < 0)
4404 log2_sectors_per_bitmap_bit = __fls(DEFAULT_SECTORS_PER_BITMAP_BIT);
4405 if (log2_sectors_per_bitmap_bit < ic->sb->log2_sectors_per_block)
4406 log2_sectors_per_bitmap_bit = ic->sb->log2_sectors_per_block;
4408 bits_in_journal = ((__u64)ic->journal_section_sectors * ic->journal_sections) << (SECTOR_SHIFT + 3);
4409 if (bits_in_journal > UINT_MAX)
4410 bits_in_journal = UINT_MAX;
4411 while (bits_in_journal < (ic->provided_data_sectors + ((sector_t)1 << log2_sectors_per_bitmap_bit) - 1) >> log2_sectors_per_bitmap_bit)
4412 log2_sectors_per_bitmap_bit++;
4414 log2_blocks_per_bitmap_bit = log2_sectors_per_bitmap_bit - ic->sb->log2_sectors_per_block;
4415 ic->log2_blocks_per_bitmap_bit = log2_blocks_per_bitmap_bit;
4416 if (should_write_sb)
4417 ic->sb->log2_blocks_per_bitmap_bit = log2_blocks_per_bitmap_bit;
4419 n_bitmap_bits = ((ic->provided_data_sectors >> ic->sb->log2_sectors_per_block)
4420 + (((sector_t)1 << log2_blocks_per_bitmap_bit) - 1)) >> log2_blocks_per_bitmap_bit;
4421 ic->n_bitmap_blocks = DIV_ROUND_UP(n_bitmap_bits, BITMAP_BLOCK_SIZE * 8);
4424 ic->log2_buffer_sectors = min(ic->log2_buffer_sectors, (__u8)__ffs(ic->metadata_run));
4426 if (ti->len > ic->provided_data_sectors) {
4428 ti->error = "Not enough provided sectors for requested mapping size";
4433 threshold = (__u64)ic->journal_entries * (100 - journal_watermark);
4435 do_div(threshold, 100);
4436 ic->free_sectors_threshold = threshold;
4438 DEBUG_print("initialized:\n");
4439 DEBUG_print(" integrity_tag_size %u\n", le16_to_cpu(ic->sb->integrity_tag_size));
4440 DEBUG_print(" journal_entry_size %u\n", ic->journal_entry_size);
4441 DEBUG_print(" journal_entries_per_sector %u\n", ic->journal_entries_per_sector);
4442 DEBUG_print(" journal_section_entries %u\n", ic->journal_section_entries);
4443 DEBUG_print(" journal_section_sectors %u\n", ic->journal_section_sectors);
4444 DEBUG_print(" journal_sections %u\n", (unsigned int)le32_to_cpu(ic->sb->journal_sections));
4445 DEBUG_print(" journal_entries %u\n", ic->journal_entries);
4446 DEBUG_print(" log2_interleave_sectors %d\n", ic->sb->log2_interleave_sectors);
4447 DEBUG_print(" data_device_sectors 0x%llx\n", bdev_nr_sectors(ic->dev->bdev));
4448 DEBUG_print(" initial_sectors 0x%x\n", ic->initial_sectors);
4449 DEBUG_print(" metadata_run 0x%x\n", ic->metadata_run);
4450 DEBUG_print(" log2_metadata_run %d\n", ic->log2_metadata_run);
4451 DEBUG_print(" provided_data_sectors 0x%llx (%llu)\n", ic->provided_data_sectors, ic->provided_data_sectors);
4452 DEBUG_print(" log2_buffer_sectors %u\n", ic->log2_buffer_sectors);
4453 DEBUG_print(" bits_in_journal %llu\n", bits_in_journal);
4455 if (ic->recalculate_flag && !(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))) {
4456 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
4457 ic->sb->recalc_sector = cpu_to_le64(0);
4460 if (ic->internal_hash) {
4461 ic->recalc_wq = alloc_workqueue("dm-integrity-recalc", WQ_MEM_RECLAIM, 1);
4462 if (!ic->recalc_wq) {
4463 ti->error = "Cannot allocate workqueue";
4467 INIT_WORK(&ic->recalc_work, integrity_recalc);
4469 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
4470 ti->error = "Recalculate can only be specified with internal_hash";
4476 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
4477 le64_to_cpu(ic->sb->recalc_sector) < ic->provided_data_sectors &&
4478 dm_integrity_disable_recalculate(ic)) {
4479 ti->error = "Recalculating with HMAC is disabled for security reasons - if you really need it, use the argument \"legacy_recalculate\"";
4484 ic->bufio = dm_bufio_client_create(ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev,
4485 1U << (SECTOR_SHIFT + ic->log2_buffer_sectors), 1, 0, NULL, NULL, 0);
4486 if (IS_ERR(ic->bufio)) {
4487 r = PTR_ERR(ic->bufio);
4488 ti->error = "Cannot initialize dm-bufio";
4492 dm_bufio_set_sector_offset(ic->bufio, ic->start + ic->initial_sectors);
4494 if (ic->mode != 'R') {
4495 r = create_journal(ic, &ti->error);
4501 if (ic->mode == 'B') {
4503 unsigned int n_bitmap_pages = DIV_ROUND_UP(ic->n_bitmap_blocks, PAGE_SIZE / BITMAP_BLOCK_SIZE);
4505 ic->recalc_bitmap = dm_integrity_alloc_page_list(n_bitmap_pages);
4506 if (!ic->recalc_bitmap) {
4510 ic->may_write_bitmap = dm_integrity_alloc_page_list(n_bitmap_pages);
4511 if (!ic->may_write_bitmap) {
4515 ic->bbs = kvmalloc_array(ic->n_bitmap_blocks, sizeof(struct bitmap_block_status), GFP_KERNEL);
4520 INIT_DELAYED_WORK(&ic->bitmap_flush_work, bitmap_flush_work);
4521 for (i = 0; i < ic->n_bitmap_blocks; i++) {
4522 struct bitmap_block_status *bbs = &ic->bbs[i];
4523 unsigned int sector, pl_index, pl_offset;
4525 INIT_WORK(&bbs->work, bitmap_block_work);
4528 bio_list_init(&bbs->bio_queue);
4529 spin_lock_init(&bbs->bio_queue_lock);
4531 sector = i * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT);
4532 pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
4533 pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
4535 bbs->bitmap = lowmem_page_address(ic->journal[pl_index].page) + pl_offset;
4539 if (should_write_sb) {
4540 init_journal(ic, 0, ic->journal_sections, 0);
4541 r = dm_integrity_failed(ic);
4543 ti->error = "Error initializing journal";
4546 r = sync_rw_sb(ic, REQ_OP_WRITE | REQ_FUA);
4548 ti->error = "Error initializing superblock";
4551 ic->just_formatted = true;
4554 if (!ic->meta_dev) {
4555 r = dm_set_target_max_io_len(ti, 1U << ic->sb->log2_interleave_sectors);
4559 if (ic->mode == 'B') {
4560 unsigned int max_io_len;
4562 max_io_len = ((sector_t)ic->sectors_per_block << ic->log2_blocks_per_bitmap_bit) * (BITMAP_BLOCK_SIZE * 8);
4564 max_io_len = 1U << 31;
4565 DEBUG_print("max_io_len: old %u, new %u\n", ti->max_io_len, max_io_len);
4566 if (!ti->max_io_len || ti->max_io_len > max_io_len) {
4567 r = dm_set_target_max_io_len(ti, max_io_len);
4573 if (!ic->internal_hash)
4574 dm_integrity_set(ti, ic);
4576 ti->num_flush_bios = 1;
4577 ti->flush_supported = true;
4579 ti->num_discard_bios = 1;
4581 dm_audit_log_ctr(DM_MSG_PREFIX, ti, 1);
4585 dm_audit_log_ctr(DM_MSG_PREFIX, ti, 0);
4586 dm_integrity_dtr(ti);
4590 static void dm_integrity_dtr(struct dm_target *ti)
4592 struct dm_integrity_c *ic = ti->private;
4594 BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
4595 BUG_ON(!list_empty(&ic->wait_list));
4597 if (ic->mode == 'B')
4598 cancel_delayed_work_sync(&ic->bitmap_flush_work);
4599 if (ic->metadata_wq)
4600 destroy_workqueue(ic->metadata_wq);
4602 destroy_workqueue(ic->wait_wq);
4604 destroy_workqueue(ic->offload_wq);
4606 destroy_workqueue(ic->commit_wq);
4608 destroy_workqueue(ic->writer_wq);
4610 destroy_workqueue(ic->recalc_wq);
4613 dm_bufio_client_destroy(ic->bufio);
4614 mempool_exit(&ic->journal_io_mempool);
4616 dm_io_client_destroy(ic->io);
4618 dm_put_device(ti, ic->dev);
4620 dm_put_device(ti, ic->meta_dev);
4621 dm_integrity_free_page_list(ic->journal);
4622 dm_integrity_free_page_list(ic->journal_io);
4623 dm_integrity_free_page_list(ic->journal_xor);
4624 dm_integrity_free_page_list(ic->recalc_bitmap);
4625 dm_integrity_free_page_list(ic->may_write_bitmap);
4626 if (ic->journal_scatterlist)
4627 dm_integrity_free_journal_scatterlist(ic, ic->journal_scatterlist);
4628 if (ic->journal_io_scatterlist)
4629 dm_integrity_free_journal_scatterlist(ic, ic->journal_io_scatterlist);
4630 if (ic->sk_requests) {
4633 for (i = 0; i < ic->journal_sections; i++) {
4634 struct skcipher_request *req;
4636 req = ic->sk_requests[i];
4638 kfree_sensitive(req->iv);
4639 skcipher_request_free(req);
4642 kvfree(ic->sk_requests);
4644 kvfree(ic->journal_tree);
4646 free_pages_exact(ic->sb, SB_SECTORS << SECTOR_SHIFT);
4648 if (ic->internal_hash)
4649 crypto_free_shash(ic->internal_hash);
4650 free_alg(&ic->internal_hash_alg);
4652 if (ic->journal_crypt)
4653 crypto_free_skcipher(ic->journal_crypt);
4654 free_alg(&ic->journal_crypt_alg);
4656 if (ic->journal_mac)
4657 crypto_free_shash(ic->journal_mac);
4658 free_alg(&ic->journal_mac_alg);
4661 dm_audit_log_dtr(DM_MSG_PREFIX, ti, 1);
4664 static struct target_type integrity_target = {
4665 .name = "integrity",
4666 .version = {1, 10, 0},
4667 .module = THIS_MODULE,
4668 .features = DM_TARGET_SINGLETON | DM_TARGET_INTEGRITY,
4669 .ctr = dm_integrity_ctr,
4670 .dtr = dm_integrity_dtr,
4671 .map = dm_integrity_map,
4672 .postsuspend = dm_integrity_postsuspend,
4673 .resume = dm_integrity_resume,
4674 .status = dm_integrity_status,
4675 .iterate_devices = dm_integrity_iterate_devices,
4676 .io_hints = dm_integrity_io_hints,
4679 static int __init dm_integrity_init(void)
4683 journal_io_cache = kmem_cache_create("integrity_journal_io",
4684 sizeof(struct journal_io), 0, 0, NULL);
4685 if (!journal_io_cache) {
4686 DMERR("can't allocate journal io cache");
4690 r = dm_register_target(&integrity_target);
4692 kmem_cache_destroy(journal_io_cache);
4699 static void __exit dm_integrity_exit(void)
4701 dm_unregister_target(&integrity_target);
4702 kmem_cache_destroy(journal_io_cache);
4705 module_init(dm_integrity_init);
4706 module_exit(dm_integrity_exit);
4708 MODULE_AUTHOR("Milan Broz");
4709 MODULE_AUTHOR("Mikulas Patocka");
4710 MODULE_DESCRIPTION(DM_NAME " target for integrity tags extension");
4711 MODULE_LICENSE("GPL");