2 * Copyright (C) 2016-2017 Red Hat, Inc. All rights reserved.
3 * Copyright (C) 2016-2017 Milan Broz
4 * Copyright (C) 2016-2017 Mikulas Patocka
6 * This file is released under the GPL.
9 #include "dm-bio-record.h"
11 #include <linux/compiler.h>
12 #include <linux/module.h>
13 #include <linux/device-mapper.h>
14 #include <linux/dm-io.h>
15 #include <linux/vmalloc.h>
16 #include <linux/sort.h>
17 #include <linux/rbtree.h>
18 #include <linux/delay.h>
19 #include <linux/random.h>
20 #include <linux/reboot.h>
21 #include <crypto/hash.h>
22 #include <crypto/skcipher.h>
23 #include <linux/async_tx.h>
24 #include <linux/dm-bufio.h>
28 #define DM_MSG_PREFIX "integrity"
30 #define DEFAULT_INTERLEAVE_SECTORS 32768
31 #define DEFAULT_JOURNAL_SIZE_FACTOR 7
32 #define DEFAULT_SECTORS_PER_BITMAP_BIT 32768
33 #define DEFAULT_BUFFER_SECTORS 128
34 #define DEFAULT_JOURNAL_WATERMARK 50
35 #define DEFAULT_SYNC_MSEC 10000
36 #define DEFAULT_MAX_JOURNAL_SECTORS 131072
37 #define MIN_LOG2_INTERLEAVE_SECTORS 3
38 #define MAX_LOG2_INTERLEAVE_SECTORS 31
39 #define METADATA_WORKQUEUE_MAX_ACTIVE 16
40 #define RECALC_SECTORS 32768
41 #define RECALC_WRITE_SUPER 16
42 #define BITMAP_BLOCK_SIZE 4096 /* don't change it */
43 #define BITMAP_FLUSH_INTERVAL (10 * HZ)
44 #define DISCARD_FILLER 0xf6
48 * Warning - DEBUG_PRINT prints security-sensitive data to the log,
49 * so it should not be enabled in the official kernel
52 //#define INTERNAL_VERIFY
58 #define SB_MAGIC "integrt"
59 #define SB_VERSION_1 1
60 #define SB_VERSION_2 2
61 #define SB_VERSION_3 3
62 #define SB_VERSION_4 4
63 #define SB_VERSION_5 5
65 #define MAX_SECTORS_PER_BLOCK 8
70 __u8 log2_interleave_sectors;
71 __le16 integrity_tag_size;
72 __le32 journal_sections;
73 __le64 provided_data_sectors; /* userspace uses this value */
75 __u8 log2_sectors_per_block;
76 __u8 log2_blocks_per_bitmap_bit;
83 #define SB_FLAG_HAVE_JOURNAL_MAC 0x1
84 #define SB_FLAG_RECALCULATING 0x2
85 #define SB_FLAG_DIRTY_BITMAP 0x4
86 #define SB_FLAG_FIXED_PADDING 0x8
87 #define SB_FLAG_FIXED_HMAC 0x10
89 #define JOURNAL_ENTRY_ROUNDUP 8
91 typedef __le64 commit_id_t;
92 #define JOURNAL_MAC_PER_SECTOR 8
94 struct journal_entry {
102 commit_id_t last_bytes[];
106 #define journal_entry_tag(ic, je) ((__u8 *)&(je)->last_bytes[(ic)->sectors_per_block])
108 #if BITS_PER_LONG == 64
109 #define journal_entry_set_sector(je, x) do { smp_wmb(); WRITE_ONCE((je)->u.sector, cpu_to_le64(x)); } while (0)
111 #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)
113 #define journal_entry_get_sector(je) le64_to_cpu((je)->u.sector)
114 #define journal_entry_is_unused(je) ((je)->u.s.sector_hi == cpu_to_le32(-1))
115 #define journal_entry_set_unused(je) do { ((je)->u.s.sector_hi = cpu_to_le32(-1)); } while (0)
116 #define journal_entry_is_inprogress(je) ((je)->u.s.sector_hi == cpu_to_le32(-2))
117 #define journal_entry_set_inprogress(je) do { ((je)->u.s.sector_hi = cpu_to_le32(-2)); } while (0)
119 #define JOURNAL_BLOCK_SECTORS 8
120 #define JOURNAL_SECTOR_DATA ((1 << SECTOR_SHIFT) - sizeof(commit_id_t))
121 #define JOURNAL_MAC_SIZE (JOURNAL_MAC_PER_SECTOR * JOURNAL_BLOCK_SECTORS)
123 struct journal_sector {
124 __u8 entries[JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR];
125 __u8 mac[JOURNAL_MAC_PER_SECTOR];
126 commit_id_t commit_id;
129 #define MAX_TAG_SIZE (JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR - offsetof(struct journal_entry, last_bytes[MAX_SECTORS_PER_BLOCK]))
131 #define METADATA_PADDING_SECTORS 8
133 #define N_COMMIT_IDS 4
135 static unsigned char prev_commit_seq(unsigned char seq)
137 return (seq + N_COMMIT_IDS - 1) % N_COMMIT_IDS;
140 static unsigned char next_commit_seq(unsigned char seq)
142 return (seq + 1) % N_COMMIT_IDS;
146 * In-memory structures
149 struct journal_node {
161 struct dm_integrity_c {
163 struct dm_dev *meta_dev;
167 mempool_t journal_io_mempool;
168 struct dm_io_client *io;
169 struct dm_bufio_client *bufio;
170 struct workqueue_struct *metadata_wq;
171 struct superblock *sb;
172 unsigned journal_pages;
173 unsigned n_bitmap_blocks;
175 struct page_list *journal;
176 struct page_list *journal_io;
177 struct page_list *journal_xor;
178 struct page_list *recalc_bitmap;
179 struct page_list *may_write_bitmap;
180 struct bitmap_block_status *bbs;
181 unsigned bitmap_flush_interval;
182 int synchronous_mode;
183 struct bio_list synchronous_bios;
184 struct delayed_work bitmap_flush_work;
186 struct crypto_skcipher *journal_crypt;
187 struct scatterlist **journal_scatterlist;
188 struct scatterlist **journal_io_scatterlist;
189 struct skcipher_request **sk_requests;
191 struct crypto_shash *journal_mac;
193 struct journal_node *journal_tree;
194 struct rb_root journal_tree_root;
196 sector_t provided_data_sectors;
198 unsigned short journal_entry_size;
199 unsigned char journal_entries_per_sector;
200 unsigned char journal_section_entries;
201 unsigned short journal_section_sectors;
202 unsigned journal_sections;
203 unsigned journal_entries;
204 sector_t data_device_sectors;
205 sector_t meta_device_sectors;
206 unsigned initial_sectors;
207 unsigned metadata_run;
208 __s8 log2_metadata_run;
209 __u8 log2_buffer_sectors;
210 __u8 sectors_per_block;
211 __u8 log2_blocks_per_bitmap_bit;
217 struct crypto_shash *internal_hash;
219 struct dm_target *ti;
221 /* these variables are locked with endio_wait.lock */
222 struct rb_root in_progress;
223 struct list_head wait_list;
224 wait_queue_head_t endio_wait;
225 struct workqueue_struct *wait_wq;
226 struct workqueue_struct *offload_wq;
228 unsigned char commit_seq;
229 commit_id_t commit_ids[N_COMMIT_IDS];
231 unsigned committed_section;
232 unsigned n_committed_sections;
234 unsigned uncommitted_section;
235 unsigned n_uncommitted_sections;
237 unsigned free_section;
238 unsigned char free_section_entry;
239 unsigned free_sectors;
241 unsigned free_sectors_threshold;
243 struct workqueue_struct *commit_wq;
244 struct work_struct commit_work;
246 struct workqueue_struct *writer_wq;
247 struct work_struct writer_work;
249 struct workqueue_struct *recalc_wq;
250 struct work_struct recalc_work;
254 struct bio_list flush_bio_list;
256 unsigned long autocommit_jiffies;
257 struct timer_list autocommit_timer;
258 unsigned autocommit_msec;
260 wait_queue_head_t copy_to_journal_wait;
262 struct completion crypto_backoff;
264 bool journal_uptodate;
266 bool recalculate_flag;
267 bool reset_recalculate_flag;
271 bool legacy_recalculate;
273 struct alg_spec internal_hash_alg;
274 struct alg_spec journal_crypt_alg;
275 struct alg_spec journal_mac_alg;
277 atomic64_t number_of_mismatches;
279 struct notifier_block reboot_notifier;
282 struct dm_integrity_range {
283 sector_t logical_sector;
289 struct task_struct *task;
290 struct list_head wait_entry;
295 struct dm_integrity_io {
296 struct work_struct work;
298 struct dm_integrity_c *ic;
302 struct dm_integrity_range range;
304 sector_t metadata_block;
305 unsigned metadata_offset;
308 blk_status_t bi_status;
310 struct completion *completion;
312 struct dm_bio_details bio_details;
315 struct journal_completion {
316 struct dm_integrity_c *ic;
318 struct completion comp;
322 struct dm_integrity_range range;
323 struct journal_completion *comp;
326 struct bitmap_block_status {
327 struct work_struct work;
328 struct dm_integrity_c *ic;
330 unsigned long *bitmap;
331 struct bio_list bio_queue;
332 spinlock_t bio_queue_lock;
336 static struct kmem_cache *journal_io_cache;
338 #define JOURNAL_IO_MEMPOOL 32
341 #define DEBUG_print(x, ...) printk(KERN_DEBUG x, ##__VA_ARGS__)
342 static void __DEBUG_bytes(__u8 *bytes, size_t len, const char *msg, ...)
351 pr_cont(" %02x", *bytes);
357 #define DEBUG_bytes(bytes, len, msg, ...) __DEBUG_bytes(bytes, len, KERN_DEBUG msg, ##__VA_ARGS__)
359 #define DEBUG_print(x, ...) do { } while (0)
360 #define DEBUG_bytes(bytes, len, msg, ...) do { } while (0)
363 static void dm_integrity_prepare(struct request *rq)
367 static void dm_integrity_complete(struct request *rq, unsigned int nr_bytes)
372 * DM Integrity profile, protection is performed layer above (dm-crypt)
374 static const struct blk_integrity_profile dm_integrity_profile = {
375 .name = "DM-DIF-EXT-TAG",
378 .prepare_fn = dm_integrity_prepare,
379 .complete_fn = dm_integrity_complete,
382 static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map);
383 static void integrity_bio_wait(struct work_struct *w);
384 static void dm_integrity_dtr(struct dm_target *ti);
386 static void dm_integrity_io_error(struct dm_integrity_c *ic, const char *msg, int err)
389 atomic64_inc(&ic->number_of_mismatches);
390 if (!cmpxchg(&ic->failed, 0, err))
391 DMERR("Error on %s: %d", msg, err);
394 static int dm_integrity_failed(struct dm_integrity_c *ic)
396 return READ_ONCE(ic->failed);
399 static bool dm_integrity_disable_recalculate(struct dm_integrity_c *ic)
401 if (ic->legacy_recalculate)
403 if (!(ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) ?
404 ic->internal_hash_alg.key || ic->journal_mac_alg.key :
405 ic->internal_hash_alg.key && !ic->journal_mac_alg.key)
410 static commit_id_t dm_integrity_commit_id(struct dm_integrity_c *ic, unsigned i,
411 unsigned j, unsigned char seq)
414 * Xor the number with section and sector, so that if a piece of
415 * journal is written at wrong place, it is detected.
417 return ic->commit_ids[seq] ^ cpu_to_le64(((__u64)i << 32) ^ j);
420 static void get_area_and_offset(struct dm_integrity_c *ic, sector_t data_sector,
421 sector_t *area, sector_t *offset)
424 __u8 log2_interleave_sectors = ic->sb->log2_interleave_sectors;
425 *area = data_sector >> log2_interleave_sectors;
426 *offset = (unsigned)data_sector & ((1U << log2_interleave_sectors) - 1);
429 *offset = data_sector;
433 #define sector_to_block(ic, n) \
435 BUG_ON((n) & (unsigned)((ic)->sectors_per_block - 1)); \
436 (n) >>= (ic)->sb->log2_sectors_per_block; \
439 static __u64 get_metadata_sector_and_offset(struct dm_integrity_c *ic, sector_t area,
440 sector_t offset, unsigned *metadata_offset)
445 ms = area << ic->sb->log2_interleave_sectors;
446 if (likely(ic->log2_metadata_run >= 0))
447 ms += area << ic->log2_metadata_run;
449 ms += area * ic->metadata_run;
450 ms >>= ic->log2_buffer_sectors;
452 sector_to_block(ic, offset);
454 if (likely(ic->log2_tag_size >= 0)) {
455 ms += offset >> (SECTOR_SHIFT + ic->log2_buffer_sectors - ic->log2_tag_size);
456 mo = (offset << ic->log2_tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
458 ms += (__u64)offset * ic->tag_size >> (SECTOR_SHIFT + ic->log2_buffer_sectors);
459 mo = (offset * ic->tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
461 *metadata_offset = mo;
465 static sector_t get_data_sector(struct dm_integrity_c *ic, sector_t area, sector_t offset)
472 result = area << ic->sb->log2_interleave_sectors;
473 if (likely(ic->log2_metadata_run >= 0))
474 result += (area + 1) << ic->log2_metadata_run;
476 result += (area + 1) * ic->metadata_run;
478 result += (sector_t)ic->initial_sectors + offset;
484 static void wraparound_section(struct dm_integrity_c *ic, unsigned *sec_ptr)
486 if (unlikely(*sec_ptr >= ic->journal_sections))
487 *sec_ptr -= ic->journal_sections;
490 static void sb_set_version(struct dm_integrity_c *ic)
492 if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC))
493 ic->sb->version = SB_VERSION_5;
494 else if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING))
495 ic->sb->version = SB_VERSION_4;
496 else if (ic->mode == 'B' || ic->sb->flags & cpu_to_le32(SB_FLAG_DIRTY_BITMAP))
497 ic->sb->version = SB_VERSION_3;
498 else if (ic->meta_dev || ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
499 ic->sb->version = SB_VERSION_2;
501 ic->sb->version = SB_VERSION_1;
504 static int sb_mac(struct dm_integrity_c *ic, bool wr)
506 SHASH_DESC_ON_STACK(desc, ic->journal_mac);
508 unsigned size = crypto_shash_digestsize(ic->journal_mac);
510 if (sizeof(struct superblock) + size > 1 << SECTOR_SHIFT) {
511 dm_integrity_io_error(ic, "digest is too long", -EINVAL);
515 desc->tfm = ic->journal_mac;
517 r = crypto_shash_init(desc);
518 if (unlikely(r < 0)) {
519 dm_integrity_io_error(ic, "crypto_shash_init", r);
523 r = crypto_shash_update(desc, (__u8 *)ic->sb, (1 << SECTOR_SHIFT) - size);
524 if (unlikely(r < 0)) {
525 dm_integrity_io_error(ic, "crypto_shash_update", r);
530 r = crypto_shash_final(desc, (__u8 *)ic->sb + (1 << SECTOR_SHIFT) - size);
531 if (unlikely(r < 0)) {
532 dm_integrity_io_error(ic, "crypto_shash_final", r);
536 __u8 result[HASH_MAX_DIGESTSIZE];
537 r = crypto_shash_final(desc, result);
538 if (unlikely(r < 0)) {
539 dm_integrity_io_error(ic, "crypto_shash_final", r);
542 if (memcmp((__u8 *)ic->sb + (1 << SECTOR_SHIFT) - size, result, size)) {
543 dm_integrity_io_error(ic, "superblock mac", -EILSEQ);
544 dm_audit_log_target(DM_MSG_PREFIX, "mac-superblock", ic->ti, 0);
552 static int sync_rw_sb(struct dm_integrity_c *ic, int op, int op_flags)
554 struct dm_io_request io_req;
555 struct dm_io_region io_loc;
559 io_req.bi_op_flags = op_flags;
560 io_req.mem.type = DM_IO_KMEM;
561 io_req.mem.ptr.addr = ic->sb;
562 io_req.notify.fn = NULL;
563 io_req.client = ic->io;
564 io_loc.bdev = ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev;
565 io_loc.sector = ic->start;
566 io_loc.count = SB_SECTORS;
568 if (op == REQ_OP_WRITE) {
570 if (ic->journal_mac && ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
571 r = sb_mac(ic, true);
577 r = dm_io(&io_req, 1, &io_loc, NULL);
581 if (op == REQ_OP_READ) {
582 if (ic->mode != 'R' && ic->journal_mac && ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
583 r = sb_mac(ic, false);
592 #define BITMAP_OP_TEST_ALL_SET 0
593 #define BITMAP_OP_TEST_ALL_CLEAR 1
594 #define BITMAP_OP_SET 2
595 #define BITMAP_OP_CLEAR 3
597 static bool block_bitmap_op(struct dm_integrity_c *ic, struct page_list *bitmap,
598 sector_t sector, sector_t n_sectors, int mode)
600 unsigned long bit, end_bit, this_end_bit, page, end_page;
603 if (unlikely(((sector | n_sectors) & ((1 << ic->sb->log2_sectors_per_block) - 1)) != 0)) {
604 DMCRIT("invalid bitmap access (%llx,%llx,%d,%d,%d)",
607 ic->sb->log2_sectors_per_block,
608 ic->log2_blocks_per_bitmap_bit,
613 if (unlikely(!n_sectors))
616 bit = sector >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
617 end_bit = (sector + n_sectors - 1) >>
618 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
620 page = bit / (PAGE_SIZE * 8);
621 bit %= PAGE_SIZE * 8;
623 end_page = end_bit / (PAGE_SIZE * 8);
624 end_bit %= PAGE_SIZE * 8;
627 if (page < end_page) {
628 this_end_bit = PAGE_SIZE * 8 - 1;
630 this_end_bit = end_bit;
633 data = lowmem_page_address(bitmap[page].page);
635 if (mode == BITMAP_OP_TEST_ALL_SET) {
636 while (bit <= this_end_bit) {
637 if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
639 if (data[bit / BITS_PER_LONG] != -1)
641 bit += BITS_PER_LONG;
642 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
645 if (!test_bit(bit, data))
649 } else if (mode == BITMAP_OP_TEST_ALL_CLEAR) {
650 while (bit <= this_end_bit) {
651 if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
653 if (data[bit / BITS_PER_LONG] != 0)
655 bit += BITS_PER_LONG;
656 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
659 if (test_bit(bit, data))
663 } else if (mode == BITMAP_OP_SET) {
664 while (bit <= this_end_bit) {
665 if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
667 data[bit / BITS_PER_LONG] = -1;
668 bit += BITS_PER_LONG;
669 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
672 __set_bit(bit, data);
675 } else if (mode == BITMAP_OP_CLEAR) {
676 if (!bit && this_end_bit == PAGE_SIZE * 8 - 1)
678 else while (bit <= this_end_bit) {
679 if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
681 data[bit / BITS_PER_LONG] = 0;
682 bit += BITS_PER_LONG;
683 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
686 __clear_bit(bit, data);
693 if (unlikely(page < end_page)) {
702 static void block_bitmap_copy(struct dm_integrity_c *ic, struct page_list *dst, struct page_list *src)
704 unsigned n_bitmap_pages = DIV_ROUND_UP(ic->n_bitmap_blocks, PAGE_SIZE / BITMAP_BLOCK_SIZE);
707 for (i = 0; i < n_bitmap_pages; i++) {
708 unsigned long *dst_data = lowmem_page_address(dst[i].page);
709 unsigned long *src_data = lowmem_page_address(src[i].page);
710 copy_page(dst_data, src_data);
714 static struct bitmap_block_status *sector_to_bitmap_block(struct dm_integrity_c *ic, sector_t sector)
716 unsigned bit = sector >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
717 unsigned bitmap_block = bit / (BITMAP_BLOCK_SIZE * 8);
719 BUG_ON(bitmap_block >= ic->n_bitmap_blocks);
720 return &ic->bbs[bitmap_block];
723 static void access_journal_check(struct dm_integrity_c *ic, unsigned section, unsigned offset,
724 bool e, const char *function)
726 #if defined(CONFIG_DM_DEBUG) || defined(INTERNAL_VERIFY)
727 unsigned limit = e ? ic->journal_section_entries : ic->journal_section_sectors;
729 if (unlikely(section >= ic->journal_sections) ||
730 unlikely(offset >= limit)) {
731 DMCRIT("%s: invalid access at (%u,%u), limit (%u,%u)",
732 function, section, offset, ic->journal_sections, limit);
738 static void page_list_location(struct dm_integrity_c *ic, unsigned section, unsigned offset,
739 unsigned *pl_index, unsigned *pl_offset)
743 access_journal_check(ic, section, offset, false, "page_list_location");
745 sector = section * ic->journal_section_sectors + offset;
747 *pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
748 *pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
751 static struct journal_sector *access_page_list(struct dm_integrity_c *ic, struct page_list *pl,
752 unsigned section, unsigned offset, unsigned *n_sectors)
754 unsigned pl_index, pl_offset;
757 page_list_location(ic, section, offset, &pl_index, &pl_offset);
760 *n_sectors = (PAGE_SIZE - pl_offset) >> SECTOR_SHIFT;
762 va = lowmem_page_address(pl[pl_index].page);
764 return (struct journal_sector *)(va + pl_offset);
767 static struct journal_sector *access_journal(struct dm_integrity_c *ic, unsigned section, unsigned offset)
769 return access_page_list(ic, ic->journal, section, offset, NULL);
772 static struct journal_entry *access_journal_entry(struct dm_integrity_c *ic, unsigned section, unsigned n)
774 unsigned rel_sector, offset;
775 struct journal_sector *js;
777 access_journal_check(ic, section, n, true, "access_journal_entry");
779 rel_sector = n % JOURNAL_BLOCK_SECTORS;
780 offset = n / JOURNAL_BLOCK_SECTORS;
782 js = access_journal(ic, section, rel_sector);
783 return (struct journal_entry *)((char *)js + offset * ic->journal_entry_size);
786 static struct journal_sector *access_journal_data(struct dm_integrity_c *ic, unsigned section, unsigned n)
788 n <<= ic->sb->log2_sectors_per_block;
790 n += JOURNAL_BLOCK_SECTORS;
792 access_journal_check(ic, section, n, false, "access_journal_data");
794 return access_journal(ic, section, n);
797 static void section_mac(struct dm_integrity_c *ic, unsigned section, __u8 result[JOURNAL_MAC_SIZE])
799 SHASH_DESC_ON_STACK(desc, ic->journal_mac);
803 desc->tfm = ic->journal_mac;
805 r = crypto_shash_init(desc);
806 if (unlikely(r < 0)) {
807 dm_integrity_io_error(ic, "crypto_shash_init", r);
811 if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
814 r = crypto_shash_update(desc, (__u8 *)&ic->sb->salt, SALT_SIZE);
815 if (unlikely(r < 0)) {
816 dm_integrity_io_error(ic, "crypto_shash_update", r);
820 section_le = cpu_to_le64(section);
821 r = crypto_shash_update(desc, (__u8 *)§ion_le, sizeof section_le);
822 if (unlikely(r < 0)) {
823 dm_integrity_io_error(ic, "crypto_shash_update", r);
828 for (j = 0; j < ic->journal_section_entries; j++) {
829 struct journal_entry *je = access_journal_entry(ic, section, j);
830 r = crypto_shash_update(desc, (__u8 *)&je->u.sector, sizeof je->u.sector);
831 if (unlikely(r < 0)) {
832 dm_integrity_io_error(ic, "crypto_shash_update", r);
837 size = crypto_shash_digestsize(ic->journal_mac);
839 if (likely(size <= JOURNAL_MAC_SIZE)) {
840 r = crypto_shash_final(desc, result);
841 if (unlikely(r < 0)) {
842 dm_integrity_io_error(ic, "crypto_shash_final", r);
845 memset(result + size, 0, JOURNAL_MAC_SIZE - size);
847 __u8 digest[HASH_MAX_DIGESTSIZE];
849 if (WARN_ON(size > sizeof(digest))) {
850 dm_integrity_io_error(ic, "digest_size", -EINVAL);
853 r = crypto_shash_final(desc, digest);
854 if (unlikely(r < 0)) {
855 dm_integrity_io_error(ic, "crypto_shash_final", r);
858 memcpy(result, digest, JOURNAL_MAC_SIZE);
863 memset(result, 0, JOURNAL_MAC_SIZE);
866 static void rw_section_mac(struct dm_integrity_c *ic, unsigned section, bool wr)
868 __u8 result[JOURNAL_MAC_SIZE];
871 if (!ic->journal_mac)
874 section_mac(ic, section, result);
876 for (j = 0; j < JOURNAL_BLOCK_SECTORS; j++) {
877 struct journal_sector *js = access_journal(ic, section, j);
880 memcpy(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR);
882 if (memcmp(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR)) {
883 dm_integrity_io_error(ic, "journal mac", -EILSEQ);
884 dm_audit_log_target(DM_MSG_PREFIX, "mac-journal", ic->ti, 0);
890 static void complete_journal_op(void *context)
892 struct journal_completion *comp = context;
893 BUG_ON(!atomic_read(&comp->in_flight));
894 if (likely(atomic_dec_and_test(&comp->in_flight)))
895 complete(&comp->comp);
898 static void xor_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
899 unsigned n_sections, struct journal_completion *comp)
901 struct async_submit_ctl submit;
902 size_t n_bytes = (size_t)(n_sections * ic->journal_section_sectors) << SECTOR_SHIFT;
903 unsigned pl_index, pl_offset, section_index;
904 struct page_list *source_pl, *target_pl;
906 if (likely(encrypt)) {
907 source_pl = ic->journal;
908 target_pl = ic->journal_io;
910 source_pl = ic->journal_io;
911 target_pl = ic->journal;
914 page_list_location(ic, section, 0, &pl_index, &pl_offset);
916 atomic_add(roundup(pl_offset + n_bytes, PAGE_SIZE) >> PAGE_SHIFT, &comp->in_flight);
918 init_async_submit(&submit, ASYNC_TX_XOR_ZERO_DST, NULL, complete_journal_op, comp, NULL);
920 section_index = pl_index;
924 struct page *src_pages[2];
925 struct page *dst_page;
927 while (unlikely(pl_index == section_index)) {
930 rw_section_mac(ic, section, true);
935 page_list_location(ic, section, 0, §ion_index, &dummy);
938 this_step = min(n_bytes, (size_t)PAGE_SIZE - pl_offset);
939 dst_page = target_pl[pl_index].page;
940 src_pages[0] = source_pl[pl_index].page;
941 src_pages[1] = ic->journal_xor[pl_index].page;
943 async_xor(dst_page, src_pages, pl_offset, 2, this_step, &submit);
947 n_bytes -= this_step;
952 async_tx_issue_pending_all();
955 static void complete_journal_encrypt(struct crypto_async_request *req, int err)
957 struct journal_completion *comp = req->data;
959 if (likely(err == -EINPROGRESS)) {
960 complete(&comp->ic->crypto_backoff);
963 dm_integrity_io_error(comp->ic, "asynchronous encrypt", err);
965 complete_journal_op(comp);
968 static bool do_crypt(bool encrypt, struct skcipher_request *req, struct journal_completion *comp)
971 skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
972 complete_journal_encrypt, comp);
974 r = crypto_skcipher_encrypt(req);
976 r = crypto_skcipher_decrypt(req);
979 if (likely(r == -EINPROGRESS))
981 if (likely(r == -EBUSY)) {
982 wait_for_completion(&comp->ic->crypto_backoff);
983 reinit_completion(&comp->ic->crypto_backoff);
986 dm_integrity_io_error(comp->ic, "encrypt", r);
990 static void crypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
991 unsigned n_sections, struct journal_completion *comp)
993 struct scatterlist **source_sg;
994 struct scatterlist **target_sg;
996 atomic_add(2, &comp->in_flight);
998 if (likely(encrypt)) {
999 source_sg = ic->journal_scatterlist;
1000 target_sg = ic->journal_io_scatterlist;
1002 source_sg = ic->journal_io_scatterlist;
1003 target_sg = ic->journal_scatterlist;
1007 struct skcipher_request *req;
1011 if (likely(encrypt))
1012 rw_section_mac(ic, section, true);
1014 req = ic->sk_requests[section];
1015 ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
1018 memcpy(iv, iv + ivsize, ivsize);
1020 req->src = source_sg[section];
1021 req->dst = target_sg[section];
1023 if (unlikely(do_crypt(encrypt, req, comp)))
1024 atomic_inc(&comp->in_flight);
1028 } while (n_sections);
1030 atomic_dec(&comp->in_flight);
1031 complete_journal_op(comp);
1034 static void encrypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
1035 unsigned n_sections, struct journal_completion *comp)
1037 if (ic->journal_xor)
1038 return xor_journal(ic, encrypt, section, n_sections, comp);
1040 return crypt_journal(ic, encrypt, section, n_sections, comp);
1043 static void complete_journal_io(unsigned long error, void *context)
1045 struct journal_completion *comp = context;
1046 if (unlikely(error != 0))
1047 dm_integrity_io_error(comp->ic, "writing journal", -EIO);
1048 complete_journal_op(comp);
1051 static void rw_journal_sectors(struct dm_integrity_c *ic, int op, int op_flags,
1052 unsigned sector, unsigned n_sectors, struct journal_completion *comp)
1054 struct dm_io_request io_req;
1055 struct dm_io_region io_loc;
1056 unsigned pl_index, pl_offset;
1059 if (unlikely(dm_integrity_failed(ic))) {
1061 complete_journal_io(-1UL, comp);
1065 pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
1066 pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
1069 io_req.bi_op_flags = op_flags;
1070 io_req.mem.type = DM_IO_PAGE_LIST;
1072 io_req.mem.ptr.pl = &ic->journal_io[pl_index];
1074 io_req.mem.ptr.pl = &ic->journal[pl_index];
1075 io_req.mem.offset = pl_offset;
1076 if (likely(comp != NULL)) {
1077 io_req.notify.fn = complete_journal_io;
1078 io_req.notify.context = comp;
1080 io_req.notify.fn = NULL;
1082 io_req.client = ic->io;
1083 io_loc.bdev = ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev;
1084 io_loc.sector = ic->start + SB_SECTORS + sector;
1085 io_loc.count = n_sectors;
1087 r = dm_io(&io_req, 1, &io_loc, NULL);
1089 dm_integrity_io_error(ic, op == REQ_OP_READ ? "reading journal" : "writing journal", r);
1091 WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
1092 complete_journal_io(-1UL, comp);
1097 static void rw_journal(struct dm_integrity_c *ic, int op, int op_flags, unsigned section,
1098 unsigned n_sections, struct journal_completion *comp)
1100 unsigned sector, n_sectors;
1102 sector = section * ic->journal_section_sectors;
1103 n_sectors = n_sections * ic->journal_section_sectors;
1105 rw_journal_sectors(ic, op, op_flags, sector, n_sectors, comp);
1108 static void write_journal(struct dm_integrity_c *ic, unsigned commit_start, unsigned commit_sections)
1110 struct journal_completion io_comp;
1111 struct journal_completion crypt_comp_1;
1112 struct journal_completion crypt_comp_2;
1116 init_completion(&io_comp.comp);
1118 if (commit_start + commit_sections <= ic->journal_sections) {
1119 io_comp.in_flight = (atomic_t)ATOMIC_INIT(1);
1120 if (ic->journal_io) {
1121 crypt_comp_1.ic = ic;
1122 init_completion(&crypt_comp_1.comp);
1123 crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
1124 encrypt_journal(ic, true, commit_start, commit_sections, &crypt_comp_1);
1125 wait_for_completion_io(&crypt_comp_1.comp);
1127 for (i = 0; i < commit_sections; i++)
1128 rw_section_mac(ic, commit_start + i, true);
1130 rw_journal(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, commit_start,
1131 commit_sections, &io_comp);
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, commit_start, to_end, &io_comp);
1143 reinit_completion(&crypt_comp_1.comp);
1144 crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
1145 encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_1);
1146 wait_for_completion_io(&crypt_comp_1.comp);
1148 crypt_comp_2.ic = ic;
1149 init_completion(&crypt_comp_2.comp);
1150 crypt_comp_2.in_flight = (atomic_t)ATOMIC_INIT(0);
1151 encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_2);
1152 wait_for_completion_io(&crypt_comp_1.comp);
1153 rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
1154 wait_for_completion_io(&crypt_comp_2.comp);
1157 for (i = 0; i < to_end; i++)
1158 rw_section_mac(ic, commit_start + i, true);
1159 rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
1160 for (i = 0; i < commit_sections - to_end; i++)
1161 rw_section_mac(ic, i, true);
1163 rw_journal(ic, REQ_OP_WRITE, REQ_FUA, 0, commit_sections - to_end, &io_comp);
1166 wait_for_completion_io(&io_comp.comp);
1169 static void copy_from_journal(struct dm_integrity_c *ic, unsigned section, unsigned offset,
1170 unsigned n_sectors, sector_t target, io_notify_fn fn, void *data)
1172 struct dm_io_request io_req;
1173 struct dm_io_region io_loc;
1175 unsigned sector, pl_index, pl_offset;
1177 BUG_ON((target | n_sectors | offset) & (unsigned)(ic->sectors_per_block - 1));
1179 if (unlikely(dm_integrity_failed(ic))) {
1184 sector = section * ic->journal_section_sectors + JOURNAL_BLOCK_SECTORS + offset;
1186 pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
1187 pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
1189 io_req.bi_op = REQ_OP_WRITE;
1190 io_req.bi_op_flags = 0;
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)(ic->sectors_per_block - 1));
1221 if (likely(check_waiting)) {
1222 struct dm_integrity_range *range;
1223 list_for_each_entry(range, &ic->wait_list, wait_entry) {
1224 if (unlikely(ranges_overlap(range, new_range)))
1232 struct dm_integrity_range *range = container_of(*n, struct dm_integrity_range, node);
1235 if (new_range->logical_sector + new_range->n_sectors <= range->logical_sector) {
1236 n = &range->node.rb_left;
1237 } else if (new_range->logical_sector >= range->logical_sector + range->n_sectors) {
1238 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;
1257 last_range_task = last_range->task;
1258 list_del(&last_range->wait_entry);
1259 if (!add_new_range(ic, last_range, false)) {
1260 last_range->task = last_range_task;
1261 list_add(&last_range->wait_entry, &ic->wait_list);
1264 last_range->waiting = false;
1265 wake_up_process(last_range_task);
1269 static void remove_range(struct dm_integrity_c *ic, struct dm_integrity_range *range)
1271 unsigned long flags;
1273 spin_lock_irqsave(&ic->endio_wait.lock, flags);
1274 remove_range_unlocked(ic, range);
1275 spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1278 static void wait_and_add_new_range(struct dm_integrity_c *ic, struct dm_integrity_range *new_range)
1280 new_range->waiting = true;
1281 list_add_tail(&new_range->wait_entry, &ic->wait_list);
1282 new_range->task = current;
1284 __set_current_state(TASK_UNINTERRUPTIBLE);
1285 spin_unlock_irq(&ic->endio_wait.lock);
1287 spin_lock_irq(&ic->endio_wait.lock);
1288 } while (unlikely(new_range->waiting));
1291 static void add_new_range_and_wait(struct dm_integrity_c *ic, struct dm_integrity_range *new_range)
1293 if (unlikely(!add_new_range(ic, new_range, true)))
1294 wait_and_add_new_range(ic, new_range);
1297 static void init_journal_node(struct journal_node *node)
1299 RB_CLEAR_NODE(&node->node);
1300 node->sector = (sector_t)-1;
1303 static void add_journal_node(struct dm_integrity_c *ic, struct journal_node *node, sector_t sector)
1305 struct rb_node **link;
1306 struct rb_node *parent;
1308 node->sector = sector;
1309 BUG_ON(!RB_EMPTY_NODE(&node->node));
1311 link = &ic->journal_tree_root.rb_node;
1315 struct journal_node *j;
1317 j = container_of(parent, struct journal_node, node);
1318 if (sector < j->sector)
1319 link = &j->node.rb_left;
1321 link = &j->node.rb_right;
1324 rb_link_node(&node->node, parent, link);
1325 rb_insert_color(&node->node, &ic->journal_tree_root);
1328 static void remove_journal_node(struct dm_integrity_c *ic, struct journal_node *node)
1330 BUG_ON(RB_EMPTY_NODE(&node->node));
1331 rb_erase(&node->node, &ic->journal_tree_root);
1332 init_journal_node(node);
1335 #define NOT_FOUND (-1U)
1337 static unsigned find_journal_node(struct dm_integrity_c *ic, sector_t sector, sector_t *next_sector)
1339 struct rb_node *n = ic->journal_tree_root.rb_node;
1340 unsigned found = NOT_FOUND;
1341 *next_sector = (sector_t)-1;
1343 struct journal_node *j = container_of(n, struct journal_node, node);
1344 if (sector == j->sector) {
1345 found = j - ic->journal_tree;
1347 if (sector < j->sector) {
1348 *next_sector = j->sector;
1349 n = j->node.rb_left;
1351 n = j->node.rb_right;
1358 static bool test_journal_node(struct dm_integrity_c *ic, unsigned pos, sector_t sector)
1360 struct journal_node *node, *next_node;
1361 struct rb_node *next;
1363 if (unlikely(pos >= ic->journal_entries))
1365 node = &ic->journal_tree[pos];
1366 if (unlikely(RB_EMPTY_NODE(&node->node)))
1368 if (unlikely(node->sector != sector))
1371 next = rb_next(&node->node);
1372 if (unlikely(!next))
1375 next_node = container_of(next, struct journal_node, node);
1376 return next_node->sector != sector;
1379 static bool find_newer_committed_node(struct dm_integrity_c *ic, struct journal_node *node)
1381 struct rb_node *next;
1382 struct journal_node *next_node;
1383 unsigned next_section;
1385 BUG_ON(RB_EMPTY_NODE(&node->node));
1387 next = rb_next(&node->node);
1388 if (unlikely(!next))
1391 next_node = container_of(next, struct journal_node, node);
1393 if (next_node->sector != node->sector)
1396 next_section = (unsigned)(next_node - ic->journal_tree) / ic->journal_section_entries;
1397 if (next_section >= ic->committed_section &&
1398 next_section < ic->committed_section + ic->n_committed_sections)
1400 if (next_section + ic->journal_sections < ic->committed_section + ic->n_committed_sections)
1410 static int dm_integrity_rw_tag(struct dm_integrity_c *ic, unsigned char *tag, sector_t *metadata_block,
1411 unsigned *metadata_offset, unsigned total_size, int op)
1413 #define MAY_BE_FILLER 1
1414 #define MAY_BE_HASH 2
1415 unsigned hash_offset = 0;
1416 unsigned may_be = MAY_BE_HASH | (ic->discard ? MAY_BE_FILLER : 0);
1419 unsigned char *data, *dp;
1420 struct dm_buffer *b;
1424 r = dm_integrity_failed(ic);
1428 data = dm_bufio_read(ic->bufio, *metadata_block, &b);
1430 return PTR_ERR(data);
1432 to_copy = min((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - *metadata_offset, total_size);
1433 dp = data + *metadata_offset;
1434 if (op == TAG_READ) {
1435 memcpy(tag, dp, to_copy);
1436 } else if (op == TAG_WRITE) {
1437 if (memcmp(dp, tag, to_copy)) {
1438 memcpy(dp, tag, to_copy);
1439 dm_bufio_mark_partial_buffer_dirty(b, *metadata_offset, *metadata_offset + to_copy);
1442 /* e.g.: op == TAG_CMP */
1444 if (likely(is_power_of_2(ic->tag_size))) {
1445 if (unlikely(memcmp(dp, tag, to_copy)))
1446 if (unlikely(!ic->discard) ||
1447 unlikely(memchr_inv(dp, DISCARD_FILLER, to_copy) != NULL)) {
1455 for (i = 0; i < to_copy; i++, ts--) {
1456 if (unlikely(dp[i] != tag[i]))
1457 may_be &= ~MAY_BE_HASH;
1458 if (likely(dp[i] != DISCARD_FILLER))
1459 may_be &= ~MAY_BE_FILLER;
1461 if (unlikely(hash_offset == ic->tag_size)) {
1462 if (unlikely(!may_be)) {
1463 dm_bufio_release(b);
1467 may_be = MAY_BE_HASH | (ic->discard ? MAY_BE_FILLER : 0);
1472 dm_bufio_release(b);
1475 *metadata_offset += to_copy;
1476 if (unlikely(*metadata_offset == 1U << SECTOR_SHIFT << ic->log2_buffer_sectors)) {
1477 (*metadata_block)++;
1478 *metadata_offset = 0;
1481 if (unlikely(!is_power_of_2(ic->tag_size))) {
1482 hash_offset = (hash_offset + to_copy) % ic->tag_size;
1485 total_size -= to_copy;
1486 } while (unlikely(total_size));
1489 #undef MAY_BE_FILLER
1493 struct flush_request {
1494 struct dm_io_request io_req;
1495 struct dm_io_region io_reg;
1496 struct dm_integrity_c *ic;
1497 struct completion comp;
1500 static void flush_notify(unsigned long error, void *fr_)
1502 struct flush_request *fr = fr_;
1503 if (unlikely(error != 0))
1504 dm_integrity_io_error(fr->ic, "flushing disk cache", -EIO);
1505 complete(&fr->comp);
1508 static void dm_integrity_flush_buffers(struct dm_integrity_c *ic, bool flush_data)
1512 struct flush_request fr;
1517 fr.io_req.bi_op = REQ_OP_WRITE,
1518 fr.io_req.bi_op_flags = REQ_PREFLUSH | REQ_SYNC,
1519 fr.io_req.mem.type = DM_IO_KMEM,
1520 fr.io_req.mem.ptr.addr = NULL,
1521 fr.io_req.notify.fn = flush_notify,
1522 fr.io_req.notify.context = &fr;
1523 fr.io_req.client = dm_bufio_get_dm_io_client(ic->bufio),
1524 fr.io_reg.bdev = ic->dev->bdev,
1525 fr.io_reg.sector = 0,
1526 fr.io_reg.count = 0,
1528 init_completion(&fr.comp);
1529 r = dm_io(&fr.io_req, 1, &fr.io_reg, NULL);
1533 r = dm_bufio_write_dirty_buffers(ic->bufio);
1535 dm_integrity_io_error(ic, "writing tags", r);
1538 wait_for_completion(&fr.comp);
1541 static void sleep_on_endio_wait(struct dm_integrity_c *ic)
1543 DECLARE_WAITQUEUE(wait, current);
1544 __add_wait_queue(&ic->endio_wait, &wait);
1545 __set_current_state(TASK_UNINTERRUPTIBLE);
1546 spin_unlock_irq(&ic->endio_wait.lock);
1548 spin_lock_irq(&ic->endio_wait.lock);
1549 __remove_wait_queue(&ic->endio_wait, &wait);
1552 static void autocommit_fn(struct timer_list *t)
1554 struct dm_integrity_c *ic = from_timer(ic, t, autocommit_timer);
1556 if (likely(!dm_integrity_failed(ic)))
1557 queue_work(ic->commit_wq, &ic->commit_work);
1560 static void schedule_autocommit(struct dm_integrity_c *ic)
1562 if (!timer_pending(&ic->autocommit_timer))
1563 mod_timer(&ic->autocommit_timer, jiffies + ic->autocommit_jiffies);
1566 static void submit_flush_bio(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
1569 unsigned long flags;
1571 spin_lock_irqsave(&ic->endio_wait.lock, flags);
1572 bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1573 bio_list_add(&ic->flush_bio_list, bio);
1574 spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1576 queue_work(ic->commit_wq, &ic->commit_work);
1579 static void do_endio(struct dm_integrity_c *ic, struct bio *bio)
1581 int r = dm_integrity_failed(ic);
1582 if (unlikely(r) && !bio->bi_status)
1583 bio->bi_status = errno_to_blk_status(r);
1584 if (unlikely(ic->synchronous_mode) && bio_op(bio) == REQ_OP_WRITE) {
1585 unsigned long flags;
1586 spin_lock_irqsave(&ic->endio_wait.lock, flags);
1587 bio_list_add(&ic->synchronous_bios, bio);
1588 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
1589 spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1595 static void do_endio_flush(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
1597 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1599 if (unlikely(dio->fua) && likely(!bio->bi_status) && likely(!dm_integrity_failed(ic)))
1600 submit_flush_bio(ic, dio);
1605 static void dec_in_flight(struct dm_integrity_io *dio)
1607 if (atomic_dec_and_test(&dio->in_flight)) {
1608 struct dm_integrity_c *ic = dio->ic;
1611 remove_range(ic, &dio->range);
1613 if (dio->op == REQ_OP_WRITE || unlikely(dio->op == REQ_OP_DISCARD))
1614 schedule_autocommit(ic);
1616 bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1618 if (unlikely(dio->bi_status) && !bio->bi_status)
1619 bio->bi_status = dio->bi_status;
1620 if (likely(!bio->bi_status) && unlikely(bio_sectors(bio) != dio->range.n_sectors)) {
1621 dio->range.logical_sector += dio->range.n_sectors;
1622 bio_advance(bio, dio->range.n_sectors << SECTOR_SHIFT);
1623 INIT_WORK(&dio->work, integrity_bio_wait);
1624 queue_work(ic->offload_wq, &dio->work);
1627 do_endio_flush(ic, dio);
1631 static void integrity_end_io(struct bio *bio)
1633 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
1635 dm_bio_restore(&dio->bio_details, bio);
1636 if (bio->bi_integrity)
1637 bio->bi_opf |= REQ_INTEGRITY;
1639 if (dio->completion)
1640 complete(dio->completion);
1645 static void integrity_sector_checksum(struct dm_integrity_c *ic, sector_t sector,
1646 const char *data, char *result)
1648 __le64 sector_le = cpu_to_le64(sector);
1649 SHASH_DESC_ON_STACK(req, ic->internal_hash);
1651 unsigned digest_size;
1653 req->tfm = ic->internal_hash;
1655 r = crypto_shash_init(req);
1656 if (unlikely(r < 0)) {
1657 dm_integrity_io_error(ic, "crypto_shash_init", r);
1661 if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
1662 r = crypto_shash_update(req, (__u8 *)&ic->sb->salt, SALT_SIZE);
1663 if (unlikely(r < 0)) {
1664 dm_integrity_io_error(ic, "crypto_shash_update", r);
1669 r = crypto_shash_update(req, (const __u8 *)§or_le, sizeof sector_le);
1670 if (unlikely(r < 0)) {
1671 dm_integrity_io_error(ic, "crypto_shash_update", r);
1675 r = crypto_shash_update(req, data, ic->sectors_per_block << SECTOR_SHIFT);
1676 if (unlikely(r < 0)) {
1677 dm_integrity_io_error(ic, "crypto_shash_update", r);
1681 r = crypto_shash_final(req, result);
1682 if (unlikely(r < 0)) {
1683 dm_integrity_io_error(ic, "crypto_shash_final", r);
1687 digest_size = crypto_shash_digestsize(ic->internal_hash);
1688 if (unlikely(digest_size < ic->tag_size))
1689 memset(result + digest_size, 0, ic->tag_size - digest_size);
1694 /* this shouldn't happen anyway, the hash functions have no reason to fail */
1695 get_random_bytes(result, ic->tag_size);
1698 static void integrity_metadata(struct work_struct *w)
1700 struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
1701 struct dm_integrity_c *ic = dio->ic;
1705 if (ic->internal_hash) {
1706 struct bvec_iter iter;
1708 unsigned digest_size = crypto_shash_digestsize(ic->internal_hash);
1709 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1711 unsigned extra_space = unlikely(digest_size > ic->tag_size) ? digest_size - ic->tag_size : 0;
1712 char checksums_onstack[max((size_t)HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
1714 unsigned sectors_to_process;
1716 if (unlikely(ic->mode == 'R'))
1719 if (likely(dio->op != REQ_OP_DISCARD))
1720 checksums = kmalloc((PAGE_SIZE >> SECTOR_SHIFT >> ic->sb->log2_sectors_per_block) * ic->tag_size + extra_space,
1721 GFP_NOIO | __GFP_NORETRY | __GFP_NOWARN);
1723 checksums = kmalloc(PAGE_SIZE, GFP_NOIO | __GFP_NORETRY | __GFP_NOWARN);
1725 checksums = checksums_onstack;
1726 if (WARN_ON(extra_space &&
1727 digest_size > sizeof(checksums_onstack))) {
1733 if (unlikely(dio->op == REQ_OP_DISCARD)) {
1734 sector_t bi_sector = dio->bio_details.bi_iter.bi_sector;
1735 unsigned bi_size = dio->bio_details.bi_iter.bi_size;
1736 unsigned max_size = likely(checksums != checksums_onstack) ? PAGE_SIZE : HASH_MAX_DIGESTSIZE;
1737 unsigned max_blocks = max_size / ic->tag_size;
1738 memset(checksums, DISCARD_FILLER, max_size);
1741 unsigned this_step_blocks = bi_size >> (SECTOR_SHIFT + ic->sb->log2_sectors_per_block);
1742 this_step_blocks = min(this_step_blocks, max_blocks);
1743 r = dm_integrity_rw_tag(ic, checksums, &dio->metadata_block, &dio->metadata_offset,
1744 this_step_blocks * ic->tag_size, TAG_WRITE);
1746 if (likely(checksums != checksums_onstack))
1751 /*if (bi_size < this_step_blocks << (SECTOR_SHIFT + ic->sb->log2_sectors_per_block)) {
1752 printk("BUGG: bi_sector: %llx, bi_size: %u\n", bi_sector, bi_size);
1753 printk("BUGG: this_step_blocks: %u\n", this_step_blocks);
1756 bi_size -= this_step_blocks << (SECTOR_SHIFT + ic->sb->log2_sectors_per_block);
1757 bi_sector += this_step_blocks << ic->sb->log2_sectors_per_block;
1760 if (likely(checksums != checksums_onstack))
1765 sector = dio->range.logical_sector;
1766 sectors_to_process = dio->range.n_sectors;
1768 __bio_for_each_segment(bv, bio, iter, dio->bio_details.bi_iter) {
1770 char *mem, *checksums_ptr;
1773 mem = bvec_kmap_local(&bv);
1775 checksums_ptr = checksums;
1777 integrity_sector_checksum(ic, sector, mem + pos, checksums_ptr);
1778 checksums_ptr += ic->tag_size;
1779 sectors_to_process -= ic->sectors_per_block;
1780 pos += ic->sectors_per_block << SECTOR_SHIFT;
1781 sector += ic->sectors_per_block;
1782 } while (pos < bv.bv_len && sectors_to_process && checksums != checksums_onstack);
1785 r = dm_integrity_rw_tag(ic, checksums, &dio->metadata_block, &dio->metadata_offset,
1786 checksums_ptr - checksums, dio->op == REQ_OP_READ ? TAG_CMP : TAG_WRITE);
1789 char b[BDEVNAME_SIZE];
1792 s = sector - ((r + ic->tag_size - 1) / ic->tag_size);
1793 DMERR_LIMIT("%s: Checksum failed at sector 0x%llx",
1794 bio_devname(bio, b), s);
1796 atomic64_inc(&ic->number_of_mismatches);
1797 dm_audit_log_bio(DM_MSG_PREFIX, "integrity-checksum",
1800 if (likely(checksums != checksums_onstack))
1805 if (!sectors_to_process)
1808 if (unlikely(pos < bv.bv_len)) {
1809 bv.bv_offset += pos;
1815 if (likely(checksums != checksums_onstack))
1818 struct bio_integrity_payload *bip = dio->bio_details.bi_integrity;
1822 struct bvec_iter iter;
1823 unsigned data_to_process = dio->range.n_sectors;
1824 sector_to_block(ic, data_to_process);
1825 data_to_process *= ic->tag_size;
1827 bip_for_each_vec(biv, bip, iter) {
1831 BUG_ON(PageHighMem(biv.bv_page));
1832 tag = bvec_virt(&biv);
1833 this_len = min(biv.bv_len, data_to_process);
1834 r = dm_integrity_rw_tag(ic, tag, &dio->metadata_block, &dio->metadata_offset,
1835 this_len, dio->op == REQ_OP_READ ? TAG_READ : TAG_WRITE);
1838 data_to_process -= this_len;
1839 if (!data_to_process)
1848 dio->bi_status = errno_to_blk_status(r);
1852 static int dm_integrity_map(struct dm_target *ti, struct bio *bio)
1854 struct dm_integrity_c *ic = ti->private;
1855 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
1856 struct bio_integrity_payload *bip;
1858 sector_t area, offset;
1862 dio->op = bio_op(bio);
1864 if (unlikely(dio->op == REQ_OP_DISCARD)) {
1865 if (ti->max_io_len) {
1866 sector_t sec = dm_target_offset(ti, bio->bi_iter.bi_sector);
1867 unsigned log2_max_io_len = __fls(ti->max_io_len);
1868 sector_t start_boundary = sec >> log2_max_io_len;
1869 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));
1872 dm_accept_partial_bio(bio, len);
1877 if (unlikely(bio->bi_opf & REQ_PREFLUSH)) {
1878 submit_flush_bio(ic, dio);
1879 return DM_MAPIO_SUBMITTED;
1882 dio->range.logical_sector = dm_target_offset(ti, bio->bi_iter.bi_sector);
1883 dio->fua = dio->op == REQ_OP_WRITE && bio->bi_opf & REQ_FUA;
1884 if (unlikely(dio->fua)) {
1886 * Don't pass down the FUA flag because we have to flush
1887 * disk cache anyway.
1889 bio->bi_opf &= ~REQ_FUA;
1891 if (unlikely(dio->range.logical_sector + bio_sectors(bio) > ic->provided_data_sectors)) {
1892 DMERR("Too big sector number: 0x%llx + 0x%x > 0x%llx",
1893 dio->range.logical_sector, bio_sectors(bio),
1894 ic->provided_data_sectors);
1895 return DM_MAPIO_KILL;
1897 if (unlikely((dio->range.logical_sector | bio_sectors(bio)) & (unsigned)(ic->sectors_per_block - 1))) {
1898 DMERR("Bio not aligned on %u sectors: 0x%llx, 0x%x",
1899 ic->sectors_per_block,
1900 dio->range.logical_sector, bio_sectors(bio));
1901 return DM_MAPIO_KILL;
1904 if (ic->sectors_per_block > 1 && likely(dio->op != REQ_OP_DISCARD)) {
1905 struct bvec_iter iter;
1907 bio_for_each_segment(bv, bio, iter) {
1908 if (unlikely(bv.bv_len & ((ic->sectors_per_block << SECTOR_SHIFT) - 1))) {
1909 DMERR("Bio vector (%u,%u) is not aligned on %u-sector boundary",
1910 bv.bv_offset, bv.bv_len, ic->sectors_per_block);
1911 return DM_MAPIO_KILL;
1916 bip = bio_integrity(bio);
1917 if (!ic->internal_hash) {
1919 unsigned wanted_tag_size = bio_sectors(bio) >> ic->sb->log2_sectors_per_block;
1920 if (ic->log2_tag_size >= 0)
1921 wanted_tag_size <<= ic->log2_tag_size;
1923 wanted_tag_size *= ic->tag_size;
1924 if (unlikely(wanted_tag_size != bip->bip_iter.bi_size)) {
1925 DMERR("Invalid integrity data size %u, expected %u",
1926 bip->bip_iter.bi_size, wanted_tag_size);
1927 return DM_MAPIO_KILL;
1931 if (unlikely(bip != NULL)) {
1932 DMERR("Unexpected integrity data when using internal hash");
1933 return DM_MAPIO_KILL;
1937 if (unlikely(ic->mode == 'R') && unlikely(dio->op != REQ_OP_READ))
1938 return DM_MAPIO_KILL;
1940 get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
1941 dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
1942 bio->bi_iter.bi_sector = get_data_sector(ic, area, offset);
1944 dm_integrity_map_continue(dio, true);
1945 return DM_MAPIO_SUBMITTED;
1948 static bool __journal_read_write(struct dm_integrity_io *dio, struct bio *bio,
1949 unsigned journal_section, unsigned journal_entry)
1951 struct dm_integrity_c *ic = dio->ic;
1952 sector_t logical_sector;
1955 logical_sector = dio->range.logical_sector;
1956 n_sectors = dio->range.n_sectors;
1958 struct bio_vec bv = bio_iovec(bio);
1961 if (unlikely(bv.bv_len >> SECTOR_SHIFT > n_sectors))
1962 bv.bv_len = n_sectors << SECTOR_SHIFT;
1963 n_sectors -= bv.bv_len >> SECTOR_SHIFT;
1964 bio_advance_iter(bio, &bio->bi_iter, bv.bv_len);
1966 mem = bvec_kmap_local(&bv);
1967 if (likely(dio->op == REQ_OP_WRITE))
1968 flush_dcache_page(bv.bv_page);
1971 struct journal_entry *je = access_journal_entry(ic, journal_section, journal_entry);
1973 if (unlikely(dio->op == REQ_OP_READ)) {
1974 struct journal_sector *js;
1978 if (unlikely(journal_entry_is_inprogress(je))) {
1979 flush_dcache_page(bv.bv_page);
1982 __io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
1986 BUG_ON(journal_entry_get_sector(je) != logical_sector);
1987 js = access_journal_data(ic, journal_section, journal_entry);
1988 mem_ptr = mem + bv.bv_offset;
1991 memcpy(mem_ptr, js, JOURNAL_SECTOR_DATA);
1992 *(commit_id_t *)(mem_ptr + JOURNAL_SECTOR_DATA) = je->last_bytes[s];
1994 mem_ptr += 1 << SECTOR_SHIFT;
1995 } while (++s < ic->sectors_per_block);
1996 #ifdef INTERNAL_VERIFY
1997 if (ic->internal_hash) {
1998 char checksums_onstack[max((size_t)HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
2000 integrity_sector_checksum(ic, logical_sector, mem + bv.bv_offset, checksums_onstack);
2001 if (unlikely(memcmp(checksums_onstack, journal_entry_tag(ic, je), ic->tag_size))) {
2002 DMERR_LIMIT("Checksum failed when reading from journal, at sector 0x%llx",
2004 dm_audit_log_bio(DM_MSG_PREFIX, "journal-checksum",
2005 bio, logical_sector, 0);
2011 if (!ic->internal_hash) {
2012 struct bio_integrity_payload *bip = bio_integrity(bio);
2013 unsigned tag_todo = ic->tag_size;
2014 char *tag_ptr = journal_entry_tag(ic, je);
2017 struct bio_vec biv = bvec_iter_bvec(bip->bip_vec, bip->bip_iter);
2018 unsigned tag_now = min(biv.bv_len, tag_todo);
2020 BUG_ON(PageHighMem(biv.bv_page));
2021 tag_addr = bvec_virt(&biv);
2022 if (likely(dio->op == REQ_OP_WRITE))
2023 memcpy(tag_ptr, tag_addr, tag_now);
2025 memcpy(tag_addr, tag_ptr, tag_now);
2026 bvec_iter_advance(bip->bip_vec, &bip->bip_iter, tag_now);
2028 tag_todo -= tag_now;
2029 } while (unlikely(tag_todo)); else {
2030 if (likely(dio->op == REQ_OP_WRITE))
2031 memset(tag_ptr, 0, tag_todo);
2035 if (likely(dio->op == REQ_OP_WRITE)) {
2036 struct journal_sector *js;
2039 js = access_journal_data(ic, journal_section, journal_entry);
2040 memcpy(js, mem + bv.bv_offset, ic->sectors_per_block << SECTOR_SHIFT);
2044 je->last_bytes[s] = js[s].commit_id;
2045 } while (++s < ic->sectors_per_block);
2047 if (ic->internal_hash) {
2048 unsigned digest_size = crypto_shash_digestsize(ic->internal_hash);
2049 if (unlikely(digest_size > ic->tag_size)) {
2050 char checksums_onstack[HASH_MAX_DIGESTSIZE];
2051 integrity_sector_checksum(ic, logical_sector, (char *)js, checksums_onstack);
2052 memcpy(journal_entry_tag(ic, je), checksums_onstack, ic->tag_size);
2054 integrity_sector_checksum(ic, logical_sector, (char *)js, journal_entry_tag(ic, je));
2057 journal_entry_set_sector(je, logical_sector);
2059 logical_sector += ic->sectors_per_block;
2062 if (unlikely(journal_entry == ic->journal_section_entries)) {
2065 wraparound_section(ic, &journal_section);
2068 bv.bv_offset += ic->sectors_per_block << SECTOR_SHIFT;
2069 } while (bv.bv_len -= ic->sectors_per_block << SECTOR_SHIFT);
2071 if (unlikely(dio->op == REQ_OP_READ))
2072 flush_dcache_page(bv.bv_page);
2074 } while (n_sectors);
2076 if (likely(dio->op == REQ_OP_WRITE)) {
2078 if (unlikely(waitqueue_active(&ic->copy_to_journal_wait)))
2079 wake_up(&ic->copy_to_journal_wait);
2080 if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold) {
2081 queue_work(ic->commit_wq, &ic->commit_work);
2083 schedule_autocommit(ic);
2086 remove_range(ic, &dio->range);
2089 if (unlikely(bio->bi_iter.bi_size)) {
2090 sector_t area, offset;
2092 dio->range.logical_sector = logical_sector;
2093 get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
2094 dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
2101 static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map)
2103 struct dm_integrity_c *ic = dio->ic;
2104 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
2105 unsigned journal_section, journal_entry;
2106 unsigned journal_read_pos;
2107 struct completion read_comp;
2108 bool discard_retried = false;
2109 bool need_sync_io = ic->internal_hash && dio->op == REQ_OP_READ;
2110 if (unlikely(dio->op == REQ_OP_DISCARD) && ic->mode != 'D')
2111 need_sync_io = true;
2113 if (need_sync_io && from_map) {
2114 INIT_WORK(&dio->work, integrity_bio_wait);
2115 queue_work(ic->offload_wq, &dio->work);
2120 spin_lock_irq(&ic->endio_wait.lock);
2122 if (unlikely(dm_integrity_failed(ic))) {
2123 spin_unlock_irq(&ic->endio_wait.lock);
2127 dio->range.n_sectors = bio_sectors(bio);
2128 journal_read_pos = NOT_FOUND;
2129 if (ic->mode == 'J' && likely(dio->op != REQ_OP_DISCARD)) {
2130 if (dio->op == REQ_OP_WRITE) {
2131 unsigned next_entry, i, pos;
2132 unsigned ws, we, range_sectors;
2134 dio->range.n_sectors = min(dio->range.n_sectors,
2135 (sector_t)ic->free_sectors << ic->sb->log2_sectors_per_block);
2136 if (unlikely(!dio->range.n_sectors)) {
2138 goto offload_to_thread;
2139 sleep_on_endio_wait(ic);
2142 range_sectors = dio->range.n_sectors >> ic->sb->log2_sectors_per_block;
2143 ic->free_sectors -= range_sectors;
2144 journal_section = ic->free_section;
2145 journal_entry = ic->free_section_entry;
2147 next_entry = ic->free_section_entry + range_sectors;
2148 ic->free_section_entry = next_entry % ic->journal_section_entries;
2149 ic->free_section += next_entry / ic->journal_section_entries;
2150 ic->n_uncommitted_sections += next_entry / ic->journal_section_entries;
2151 wraparound_section(ic, &ic->free_section);
2153 pos = journal_section * ic->journal_section_entries + journal_entry;
2154 ws = journal_section;
2158 struct journal_entry *je;
2160 add_journal_node(ic, &ic->journal_tree[pos], dio->range.logical_sector + i);
2162 if (unlikely(pos >= ic->journal_entries))
2165 je = access_journal_entry(ic, ws, we);
2166 BUG_ON(!journal_entry_is_unused(je));
2167 journal_entry_set_inprogress(je);
2169 if (unlikely(we == ic->journal_section_entries)) {
2172 wraparound_section(ic, &ws);
2174 } while ((i += ic->sectors_per_block) < dio->range.n_sectors);
2176 spin_unlock_irq(&ic->endio_wait.lock);
2177 goto journal_read_write;
2179 sector_t next_sector;
2180 journal_read_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
2181 if (likely(journal_read_pos == NOT_FOUND)) {
2182 if (unlikely(dio->range.n_sectors > next_sector - dio->range.logical_sector))
2183 dio->range.n_sectors = next_sector - dio->range.logical_sector;
2186 unsigned jp = journal_read_pos + 1;
2187 for (i = ic->sectors_per_block; i < dio->range.n_sectors; i += ic->sectors_per_block, jp++) {
2188 if (!test_journal_node(ic, jp, dio->range.logical_sector + i))
2191 dio->range.n_sectors = i;
2195 if (unlikely(!add_new_range(ic, &dio->range, true))) {
2197 * We must not sleep in the request routine because it could
2198 * stall bios on current->bio_list.
2199 * So, we offload the bio to a workqueue if we have to sleep.
2203 spin_unlock_irq(&ic->endio_wait.lock);
2204 INIT_WORK(&dio->work, integrity_bio_wait);
2205 queue_work(ic->wait_wq, &dio->work);
2208 if (journal_read_pos != NOT_FOUND)
2209 dio->range.n_sectors = ic->sectors_per_block;
2210 wait_and_add_new_range(ic, &dio->range);
2212 * wait_and_add_new_range drops the spinlock, so the journal
2213 * may have been changed arbitrarily. We need to recheck.
2214 * To simplify the code, we restrict I/O size to just one block.
2216 if (journal_read_pos != NOT_FOUND) {
2217 sector_t next_sector;
2218 unsigned new_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
2219 if (unlikely(new_pos != journal_read_pos)) {
2220 remove_range_unlocked(ic, &dio->range);
2225 if (ic->mode == 'J' && likely(dio->op == REQ_OP_DISCARD) && !discard_retried) {
2226 sector_t next_sector;
2227 unsigned new_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
2228 if (unlikely(new_pos != NOT_FOUND) ||
2229 unlikely(next_sector < dio->range.logical_sector - dio->range.n_sectors)) {
2230 remove_range_unlocked(ic, &dio->range);
2231 spin_unlock_irq(&ic->endio_wait.lock);
2232 queue_work(ic->commit_wq, &ic->commit_work);
2233 flush_workqueue(ic->commit_wq);
2234 queue_work(ic->writer_wq, &ic->writer_work);
2235 flush_workqueue(ic->writer_wq);
2236 discard_retried = true;
2240 spin_unlock_irq(&ic->endio_wait.lock);
2242 if (unlikely(journal_read_pos != NOT_FOUND)) {
2243 journal_section = journal_read_pos / ic->journal_section_entries;
2244 journal_entry = journal_read_pos % ic->journal_section_entries;
2245 goto journal_read_write;
2248 if (ic->mode == 'B' && (dio->op == REQ_OP_WRITE || unlikely(dio->op == REQ_OP_DISCARD))) {
2249 if (!block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
2250 dio->range.n_sectors, BITMAP_OP_TEST_ALL_SET)) {
2251 struct bitmap_block_status *bbs;
2253 bbs = sector_to_bitmap_block(ic, dio->range.logical_sector);
2254 spin_lock(&bbs->bio_queue_lock);
2255 bio_list_add(&bbs->bio_queue, bio);
2256 spin_unlock(&bbs->bio_queue_lock);
2257 queue_work(ic->writer_wq, &bbs->work);
2262 dio->in_flight = (atomic_t)ATOMIC_INIT(2);
2265 init_completion(&read_comp);
2266 dio->completion = &read_comp;
2268 dio->completion = NULL;
2270 dm_bio_record(&dio->bio_details, bio);
2271 bio_set_dev(bio, ic->dev->bdev);
2272 bio->bi_integrity = NULL;
2273 bio->bi_opf &= ~REQ_INTEGRITY;
2274 bio->bi_end_io = integrity_end_io;
2275 bio->bi_iter.bi_size = dio->range.n_sectors << SECTOR_SHIFT;
2277 if (unlikely(dio->op == REQ_OP_DISCARD) && likely(ic->mode != 'D')) {
2278 integrity_metadata(&dio->work);
2279 dm_integrity_flush_buffers(ic, false);
2281 dio->in_flight = (atomic_t)ATOMIC_INIT(1);
2282 dio->completion = NULL;
2284 submit_bio_noacct(bio);
2289 submit_bio_noacct(bio);
2292 wait_for_completion_io(&read_comp);
2293 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
2294 dio->range.logical_sector + dio->range.n_sectors > le64_to_cpu(ic->sb->recalc_sector))
2296 if (ic->mode == 'B') {
2297 if (!block_bitmap_op(ic, ic->recalc_bitmap, dio->range.logical_sector,
2298 dio->range.n_sectors, BITMAP_OP_TEST_ALL_CLEAR))
2302 if (likely(!bio->bi_status))
2303 integrity_metadata(&dio->work);
2309 INIT_WORK(&dio->work, integrity_metadata);
2310 queue_work(ic->metadata_wq, &dio->work);
2316 if (unlikely(__journal_read_write(dio, bio, journal_section, journal_entry)))
2319 do_endio_flush(ic, dio);
2323 static void integrity_bio_wait(struct work_struct *w)
2325 struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
2327 dm_integrity_map_continue(dio, false);
2330 static void pad_uncommitted(struct dm_integrity_c *ic)
2332 if (ic->free_section_entry) {
2333 ic->free_sectors -= ic->journal_section_entries - ic->free_section_entry;
2334 ic->free_section_entry = 0;
2336 wraparound_section(ic, &ic->free_section);
2337 ic->n_uncommitted_sections++;
2339 if (WARN_ON(ic->journal_sections * ic->journal_section_entries !=
2340 (ic->n_uncommitted_sections + ic->n_committed_sections) *
2341 ic->journal_section_entries + ic->free_sectors)) {
2342 DMCRIT("journal_sections %u, journal_section_entries %u, "
2343 "n_uncommitted_sections %u, n_committed_sections %u, "
2344 "journal_section_entries %u, free_sectors %u",
2345 ic->journal_sections, ic->journal_section_entries,
2346 ic->n_uncommitted_sections, ic->n_committed_sections,
2347 ic->journal_section_entries, ic->free_sectors);
2351 static void integrity_commit(struct work_struct *w)
2353 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, commit_work);
2354 unsigned commit_start, commit_sections;
2356 struct bio *flushes;
2358 del_timer(&ic->autocommit_timer);
2360 spin_lock_irq(&ic->endio_wait.lock);
2361 flushes = bio_list_get(&ic->flush_bio_list);
2362 if (unlikely(ic->mode != 'J')) {
2363 spin_unlock_irq(&ic->endio_wait.lock);
2364 dm_integrity_flush_buffers(ic, true);
2365 goto release_flush_bios;
2368 pad_uncommitted(ic);
2369 commit_start = ic->uncommitted_section;
2370 commit_sections = ic->n_uncommitted_sections;
2371 spin_unlock_irq(&ic->endio_wait.lock);
2373 if (!commit_sections)
2374 goto release_flush_bios;
2377 for (n = 0; n < commit_sections; n++) {
2378 for (j = 0; j < ic->journal_section_entries; j++) {
2379 struct journal_entry *je;
2380 je = access_journal_entry(ic, i, j);
2381 io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
2383 for (j = 0; j < ic->journal_section_sectors; j++) {
2384 struct journal_sector *js;
2385 js = access_journal(ic, i, j);
2386 js->commit_id = dm_integrity_commit_id(ic, i, j, ic->commit_seq);
2389 if (unlikely(i >= ic->journal_sections))
2390 ic->commit_seq = next_commit_seq(ic->commit_seq);
2391 wraparound_section(ic, &i);
2395 write_journal(ic, commit_start, commit_sections);
2397 spin_lock_irq(&ic->endio_wait.lock);
2398 ic->uncommitted_section += commit_sections;
2399 wraparound_section(ic, &ic->uncommitted_section);
2400 ic->n_uncommitted_sections -= commit_sections;
2401 ic->n_committed_sections += commit_sections;
2402 spin_unlock_irq(&ic->endio_wait.lock);
2404 if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold)
2405 queue_work(ic->writer_wq, &ic->writer_work);
2409 struct bio *next = flushes->bi_next;
2410 flushes->bi_next = NULL;
2411 do_endio(ic, flushes);
2416 static void complete_copy_from_journal(unsigned long error, void *context)
2418 struct journal_io *io = context;
2419 struct journal_completion *comp = io->comp;
2420 struct dm_integrity_c *ic = comp->ic;
2421 remove_range(ic, &io->range);
2422 mempool_free(io, &ic->journal_io_mempool);
2423 if (unlikely(error != 0))
2424 dm_integrity_io_error(ic, "copying from journal", -EIO);
2425 complete_journal_op(comp);
2428 static void restore_last_bytes(struct dm_integrity_c *ic, struct journal_sector *js,
2429 struct journal_entry *je)
2433 js->commit_id = je->last_bytes[s];
2435 } while (++s < ic->sectors_per_block);
2438 static void do_journal_write(struct dm_integrity_c *ic, unsigned write_start,
2439 unsigned write_sections, bool from_replay)
2442 struct journal_completion comp;
2443 struct blk_plug plug;
2445 blk_start_plug(&plug);
2448 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
2449 init_completion(&comp.comp);
2452 for (n = 0; n < write_sections; n++, i++, wraparound_section(ic, &i)) {
2453 #ifndef INTERNAL_VERIFY
2454 if (unlikely(from_replay))
2456 rw_section_mac(ic, i, false);
2457 for (j = 0; j < ic->journal_section_entries; j++) {
2458 struct journal_entry *je = access_journal_entry(ic, i, j);
2459 sector_t sec, area, offset;
2460 unsigned k, l, next_loop;
2461 sector_t metadata_block;
2462 unsigned metadata_offset;
2463 struct journal_io *io;
2465 if (journal_entry_is_unused(je))
2467 BUG_ON(unlikely(journal_entry_is_inprogress(je)) && !from_replay);
2468 sec = journal_entry_get_sector(je);
2469 if (unlikely(from_replay)) {
2470 if (unlikely(sec & (unsigned)(ic->sectors_per_block - 1))) {
2471 dm_integrity_io_error(ic, "invalid sector in journal", -EIO);
2472 sec &= ~(sector_t)(ic->sectors_per_block - 1);
2475 if (unlikely(sec >= ic->provided_data_sectors))
2477 get_area_and_offset(ic, sec, &area, &offset);
2478 restore_last_bytes(ic, access_journal_data(ic, i, j), je);
2479 for (k = j + 1; k < ic->journal_section_entries; k++) {
2480 struct journal_entry *je2 = access_journal_entry(ic, i, k);
2481 sector_t sec2, area2, offset2;
2482 if (journal_entry_is_unused(je2))
2484 BUG_ON(unlikely(journal_entry_is_inprogress(je2)) && !from_replay);
2485 sec2 = journal_entry_get_sector(je2);
2486 if (unlikely(sec2 >= ic->provided_data_sectors))
2488 get_area_and_offset(ic, sec2, &area2, &offset2);
2489 if (area2 != area || offset2 != offset + ((k - j) << ic->sb->log2_sectors_per_block))
2491 restore_last_bytes(ic, access_journal_data(ic, i, k), je2);
2495 io = mempool_alloc(&ic->journal_io_mempool, GFP_NOIO);
2497 io->range.logical_sector = sec;
2498 io->range.n_sectors = (k - j) << ic->sb->log2_sectors_per_block;
2500 spin_lock_irq(&ic->endio_wait.lock);
2501 add_new_range_and_wait(ic, &io->range);
2503 if (likely(!from_replay)) {
2504 struct journal_node *section_node = &ic->journal_tree[i * ic->journal_section_entries];
2506 /* don't write if there is newer committed sector */
2507 while (j < k && find_newer_committed_node(ic, §ion_node[j])) {
2508 struct journal_entry *je2 = access_journal_entry(ic, i, j);
2510 journal_entry_set_unused(je2);
2511 remove_journal_node(ic, §ion_node[j]);
2513 sec += ic->sectors_per_block;
2514 offset += ic->sectors_per_block;
2516 while (j < k && find_newer_committed_node(ic, §ion_node[k - 1])) {
2517 struct journal_entry *je2 = access_journal_entry(ic, i, k - 1);
2519 journal_entry_set_unused(je2);
2520 remove_journal_node(ic, §ion_node[k - 1]);
2524 remove_range_unlocked(ic, &io->range);
2525 spin_unlock_irq(&ic->endio_wait.lock);
2526 mempool_free(io, &ic->journal_io_mempool);
2529 for (l = j; l < k; l++) {
2530 remove_journal_node(ic, §ion_node[l]);
2533 spin_unlock_irq(&ic->endio_wait.lock);
2535 metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
2536 for (l = j; l < k; l++) {
2538 struct journal_entry *je2 = access_journal_entry(ic, i, l);
2541 #ifndef INTERNAL_VERIFY
2542 unlikely(from_replay) &&
2544 ic->internal_hash) {
2545 char test_tag[max_t(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
2547 integrity_sector_checksum(ic, sec + ((l - j) << ic->sb->log2_sectors_per_block),
2548 (char *)access_journal_data(ic, i, l), test_tag);
2549 if (unlikely(memcmp(test_tag, journal_entry_tag(ic, je2), ic->tag_size))) {
2550 dm_integrity_io_error(ic, "tag mismatch when replaying journal", -EILSEQ);
2551 dm_audit_log_target(DM_MSG_PREFIX, "integrity-replay-journal", ic->ti, 0);
2555 journal_entry_set_unused(je2);
2556 r = dm_integrity_rw_tag(ic, journal_entry_tag(ic, je2), &metadata_block, &metadata_offset,
2557 ic->tag_size, TAG_WRITE);
2559 dm_integrity_io_error(ic, "reading tags", r);
2563 atomic_inc(&comp.in_flight);
2564 copy_from_journal(ic, i, j << ic->sb->log2_sectors_per_block,
2565 (k - j) << ic->sb->log2_sectors_per_block,
2566 get_data_sector(ic, area, offset),
2567 complete_copy_from_journal, io);
2573 dm_bufio_write_dirty_buffers_async(ic->bufio);
2575 blk_finish_plug(&plug);
2577 complete_journal_op(&comp);
2578 wait_for_completion_io(&comp.comp);
2580 dm_integrity_flush_buffers(ic, true);
2583 static void integrity_writer(struct work_struct *w)
2585 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, writer_work);
2586 unsigned write_start, write_sections;
2588 unsigned prev_free_sectors;
2590 /* the following test is not needed, but it tests the replay code */
2591 if (unlikely(dm_post_suspending(ic->ti)) && !ic->meta_dev)
2594 spin_lock_irq(&ic->endio_wait.lock);
2595 write_start = ic->committed_section;
2596 write_sections = ic->n_committed_sections;
2597 spin_unlock_irq(&ic->endio_wait.lock);
2599 if (!write_sections)
2602 do_journal_write(ic, write_start, write_sections, false);
2604 spin_lock_irq(&ic->endio_wait.lock);
2606 ic->committed_section += write_sections;
2607 wraparound_section(ic, &ic->committed_section);
2608 ic->n_committed_sections -= write_sections;
2610 prev_free_sectors = ic->free_sectors;
2611 ic->free_sectors += write_sections * ic->journal_section_entries;
2612 if (unlikely(!prev_free_sectors))
2613 wake_up_locked(&ic->endio_wait);
2615 spin_unlock_irq(&ic->endio_wait.lock);
2618 static void recalc_write_super(struct dm_integrity_c *ic)
2622 dm_integrity_flush_buffers(ic, false);
2623 if (dm_integrity_failed(ic))
2626 r = sync_rw_sb(ic, REQ_OP_WRITE, 0);
2628 dm_integrity_io_error(ic, "writing superblock", r);
2631 static void integrity_recalc(struct work_struct *w)
2633 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, recalc_work);
2634 struct dm_integrity_range range;
2635 struct dm_io_request io_req;
2636 struct dm_io_region io_loc;
2637 sector_t area, offset;
2638 sector_t metadata_block;
2639 unsigned metadata_offset;
2640 sector_t logical_sector, n_sectors;
2644 unsigned super_counter = 0;
2646 DEBUG_print("start recalculation... (position %llx)\n", le64_to_cpu(ic->sb->recalc_sector));
2648 spin_lock_irq(&ic->endio_wait.lock);
2652 if (unlikely(dm_post_suspending(ic->ti)))
2655 range.logical_sector = le64_to_cpu(ic->sb->recalc_sector);
2656 if (unlikely(range.logical_sector >= ic->provided_data_sectors)) {
2657 if (ic->mode == 'B') {
2658 block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
2659 DEBUG_print("queue_delayed_work: bitmap_flush_work\n");
2660 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
2665 get_area_and_offset(ic, range.logical_sector, &area, &offset);
2666 range.n_sectors = min((sector_t)RECALC_SECTORS, ic->provided_data_sectors - range.logical_sector);
2668 range.n_sectors = min(range.n_sectors, ((sector_t)1U << ic->sb->log2_interleave_sectors) - (unsigned)offset);
2670 add_new_range_and_wait(ic, &range);
2671 spin_unlock_irq(&ic->endio_wait.lock);
2672 logical_sector = range.logical_sector;
2673 n_sectors = range.n_sectors;
2675 if (ic->mode == 'B') {
2676 if (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector, n_sectors, BITMAP_OP_TEST_ALL_CLEAR)) {
2677 goto advance_and_next;
2679 while (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector,
2680 ic->sectors_per_block, BITMAP_OP_TEST_ALL_CLEAR)) {
2681 logical_sector += ic->sectors_per_block;
2682 n_sectors -= ic->sectors_per_block;
2685 while (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector + n_sectors - ic->sectors_per_block,
2686 ic->sectors_per_block, BITMAP_OP_TEST_ALL_CLEAR)) {
2687 n_sectors -= ic->sectors_per_block;
2690 get_area_and_offset(ic, logical_sector, &area, &offset);
2693 DEBUG_print("recalculating: %llx, %llx\n", logical_sector, n_sectors);
2695 if (unlikely(++super_counter == RECALC_WRITE_SUPER)) {
2696 recalc_write_super(ic);
2697 if (ic->mode == 'B') {
2698 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, ic->bitmap_flush_interval);
2703 if (unlikely(dm_integrity_failed(ic)))
2706 io_req.bi_op = REQ_OP_READ;
2707 io_req.bi_op_flags = 0;
2708 io_req.mem.type = DM_IO_VMA;
2709 io_req.mem.ptr.addr = ic->recalc_buffer;
2710 io_req.notify.fn = NULL;
2711 io_req.client = ic->io;
2712 io_loc.bdev = ic->dev->bdev;
2713 io_loc.sector = get_data_sector(ic, area, offset);
2714 io_loc.count = n_sectors;
2716 r = dm_io(&io_req, 1, &io_loc, NULL);
2718 dm_integrity_io_error(ic, "reading data", r);
2722 t = ic->recalc_tags;
2723 for (i = 0; i < n_sectors; i += ic->sectors_per_block) {
2724 integrity_sector_checksum(ic, logical_sector + i, ic->recalc_buffer + (i << SECTOR_SHIFT), t);
2728 metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
2730 r = dm_integrity_rw_tag(ic, ic->recalc_tags, &metadata_block, &metadata_offset, t - ic->recalc_tags, TAG_WRITE);
2732 dm_integrity_io_error(ic, "writing tags", r);
2736 if (ic->mode == 'B') {
2737 sector_t start, end;
2738 start = (range.logical_sector >>
2739 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit)) <<
2740 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
2741 end = ((range.logical_sector + range.n_sectors) >>
2742 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit)) <<
2743 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
2744 block_bitmap_op(ic, ic->recalc_bitmap, start, end - start, BITMAP_OP_CLEAR);
2750 spin_lock_irq(&ic->endio_wait.lock);
2751 remove_range_unlocked(ic, &range);
2752 ic->sb->recalc_sector = cpu_to_le64(range.logical_sector + range.n_sectors);
2756 remove_range(ic, &range);
2760 spin_unlock_irq(&ic->endio_wait.lock);
2762 recalc_write_super(ic);
2765 static void bitmap_block_work(struct work_struct *w)
2767 struct bitmap_block_status *bbs = container_of(w, struct bitmap_block_status, work);
2768 struct dm_integrity_c *ic = bbs->ic;
2770 struct bio_list bio_queue;
2771 struct bio_list waiting;
2773 bio_list_init(&waiting);
2775 spin_lock(&bbs->bio_queue_lock);
2776 bio_queue = bbs->bio_queue;
2777 bio_list_init(&bbs->bio_queue);
2778 spin_unlock(&bbs->bio_queue_lock);
2780 while ((bio = bio_list_pop(&bio_queue))) {
2781 struct dm_integrity_io *dio;
2783 dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
2785 if (block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
2786 dio->range.n_sectors, BITMAP_OP_TEST_ALL_SET)) {
2787 remove_range(ic, &dio->range);
2788 INIT_WORK(&dio->work, integrity_bio_wait);
2789 queue_work(ic->offload_wq, &dio->work);
2791 block_bitmap_op(ic, ic->journal, dio->range.logical_sector,
2792 dio->range.n_sectors, BITMAP_OP_SET);
2793 bio_list_add(&waiting, bio);
2797 if (bio_list_empty(&waiting))
2800 rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC,
2801 bbs->idx * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT),
2802 BITMAP_BLOCK_SIZE >> SECTOR_SHIFT, NULL);
2804 while ((bio = bio_list_pop(&waiting))) {
2805 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
2807 block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
2808 dio->range.n_sectors, BITMAP_OP_SET);
2810 remove_range(ic, &dio->range);
2811 INIT_WORK(&dio->work, integrity_bio_wait);
2812 queue_work(ic->offload_wq, &dio->work);
2815 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, ic->bitmap_flush_interval);
2818 static void bitmap_flush_work(struct work_struct *work)
2820 struct dm_integrity_c *ic = container_of(work, struct dm_integrity_c, bitmap_flush_work.work);
2821 struct dm_integrity_range range;
2822 unsigned long limit;
2825 dm_integrity_flush_buffers(ic, false);
2827 range.logical_sector = 0;
2828 range.n_sectors = ic->provided_data_sectors;
2830 spin_lock_irq(&ic->endio_wait.lock);
2831 add_new_range_and_wait(ic, &range);
2832 spin_unlock_irq(&ic->endio_wait.lock);
2834 dm_integrity_flush_buffers(ic, true);
2836 limit = ic->provided_data_sectors;
2837 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
2838 limit = le64_to_cpu(ic->sb->recalc_sector)
2839 >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit)
2840 << (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
2842 /*DEBUG_print("zeroing journal\n");*/
2843 block_bitmap_op(ic, ic->journal, 0, limit, BITMAP_OP_CLEAR);
2844 block_bitmap_op(ic, ic->may_write_bitmap, 0, limit, BITMAP_OP_CLEAR);
2846 rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, 0,
2847 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
2849 spin_lock_irq(&ic->endio_wait.lock);
2850 remove_range_unlocked(ic, &range);
2851 while (unlikely((bio = bio_list_pop(&ic->synchronous_bios)) != NULL)) {
2853 spin_unlock_irq(&ic->endio_wait.lock);
2854 spin_lock_irq(&ic->endio_wait.lock);
2856 spin_unlock_irq(&ic->endio_wait.lock);
2860 static void init_journal(struct dm_integrity_c *ic, unsigned start_section,
2861 unsigned n_sections, unsigned char commit_seq)
2868 for (n = 0; n < n_sections; n++) {
2869 i = start_section + n;
2870 wraparound_section(ic, &i);
2871 for (j = 0; j < ic->journal_section_sectors; j++) {
2872 struct journal_sector *js = access_journal(ic, i, j);
2873 memset(&js->entries, 0, JOURNAL_SECTOR_DATA);
2874 js->commit_id = dm_integrity_commit_id(ic, i, j, commit_seq);
2876 for (j = 0; j < ic->journal_section_entries; j++) {
2877 struct journal_entry *je = access_journal_entry(ic, i, j);
2878 journal_entry_set_unused(je);
2882 write_journal(ic, start_section, n_sections);
2885 static int find_commit_seq(struct dm_integrity_c *ic, unsigned i, unsigned j, commit_id_t id)
2888 for (k = 0; k < N_COMMIT_IDS; k++) {
2889 if (dm_integrity_commit_id(ic, i, j, k) == id)
2892 dm_integrity_io_error(ic, "journal commit id", -EIO);
2896 static void replay_journal(struct dm_integrity_c *ic)
2899 bool used_commit_ids[N_COMMIT_IDS];
2900 unsigned max_commit_id_sections[N_COMMIT_IDS];
2901 unsigned write_start, write_sections;
2902 unsigned continue_section;
2904 unsigned char unused, last_used, want_commit_seq;
2906 if (ic->mode == 'R')
2909 if (ic->journal_uptodate)
2915 if (!ic->just_formatted) {
2916 DEBUG_print("reading journal\n");
2917 rw_journal(ic, REQ_OP_READ, 0, 0, ic->journal_sections, NULL);
2919 DEBUG_bytes(lowmem_page_address(ic->journal_io[0].page), 64, "read journal");
2920 if (ic->journal_io) {
2921 struct journal_completion crypt_comp;
2923 init_completion(&crypt_comp.comp);
2924 crypt_comp.in_flight = (atomic_t)ATOMIC_INIT(0);
2925 encrypt_journal(ic, false, 0, ic->journal_sections, &crypt_comp);
2926 wait_for_completion(&crypt_comp.comp);
2928 DEBUG_bytes(lowmem_page_address(ic->journal[0].page), 64, "decrypted journal");
2931 if (dm_integrity_failed(ic))
2934 journal_empty = true;
2935 memset(used_commit_ids, 0, sizeof used_commit_ids);
2936 memset(max_commit_id_sections, 0, sizeof max_commit_id_sections);
2937 for (i = 0; i < ic->journal_sections; i++) {
2938 for (j = 0; j < ic->journal_section_sectors; j++) {
2940 struct journal_sector *js = access_journal(ic, i, j);
2941 k = find_commit_seq(ic, i, j, js->commit_id);
2944 used_commit_ids[k] = true;
2945 max_commit_id_sections[k] = i;
2947 if (journal_empty) {
2948 for (j = 0; j < ic->journal_section_entries; j++) {
2949 struct journal_entry *je = access_journal_entry(ic, i, j);
2950 if (!journal_entry_is_unused(je)) {
2951 journal_empty = false;
2958 if (!used_commit_ids[N_COMMIT_IDS - 1]) {
2959 unused = N_COMMIT_IDS - 1;
2960 while (unused && !used_commit_ids[unused - 1])
2963 for (unused = 0; unused < N_COMMIT_IDS; unused++)
2964 if (!used_commit_ids[unused])
2966 if (unused == N_COMMIT_IDS) {
2967 dm_integrity_io_error(ic, "journal commit ids", -EIO);
2971 DEBUG_print("first unused commit seq %d [%d,%d,%d,%d]\n",
2972 unused, used_commit_ids[0], used_commit_ids[1],
2973 used_commit_ids[2], used_commit_ids[3]);
2975 last_used = prev_commit_seq(unused);
2976 want_commit_seq = prev_commit_seq(last_used);
2978 if (!used_commit_ids[want_commit_seq] && used_commit_ids[prev_commit_seq(want_commit_seq)])
2979 journal_empty = true;
2981 write_start = max_commit_id_sections[last_used] + 1;
2982 if (unlikely(write_start >= ic->journal_sections))
2983 want_commit_seq = next_commit_seq(want_commit_seq);
2984 wraparound_section(ic, &write_start);
2987 for (write_sections = 0; write_sections < ic->journal_sections; write_sections++) {
2988 for (j = 0; j < ic->journal_section_sectors; j++) {
2989 struct journal_sector *js = access_journal(ic, i, j);
2991 if (js->commit_id != dm_integrity_commit_id(ic, i, j, want_commit_seq)) {
2993 * This could be caused by crash during writing.
2994 * We won't replay the inconsistent part of the
2997 DEBUG_print("commit id mismatch at position (%u, %u): %d != %d\n",
2998 i, j, find_commit_seq(ic, i, j, js->commit_id), want_commit_seq);
3003 if (unlikely(i >= ic->journal_sections))
3004 want_commit_seq = next_commit_seq(want_commit_seq);
3005 wraparound_section(ic, &i);
3009 if (!journal_empty) {
3010 DEBUG_print("replaying %u sections, starting at %u, commit seq %d\n",
3011 write_sections, write_start, want_commit_seq);
3012 do_journal_write(ic, write_start, write_sections, true);
3015 if (write_sections == ic->journal_sections && (ic->mode == 'J' || journal_empty)) {
3016 continue_section = write_start;
3017 ic->commit_seq = want_commit_seq;
3018 DEBUG_print("continuing from section %u, commit seq %d\n", write_start, ic->commit_seq);
3021 unsigned char erase_seq;
3023 DEBUG_print("clearing journal\n");
3025 erase_seq = prev_commit_seq(prev_commit_seq(last_used));
3027 init_journal(ic, s, 1, erase_seq);
3029 wraparound_section(ic, &s);
3030 if (ic->journal_sections >= 2) {
3031 init_journal(ic, s, ic->journal_sections - 2, erase_seq);
3032 s += ic->journal_sections - 2;
3033 wraparound_section(ic, &s);
3034 init_journal(ic, s, 1, erase_seq);
3037 continue_section = 0;
3038 ic->commit_seq = next_commit_seq(erase_seq);
3041 ic->committed_section = continue_section;
3042 ic->n_committed_sections = 0;
3044 ic->uncommitted_section = continue_section;
3045 ic->n_uncommitted_sections = 0;
3047 ic->free_section = continue_section;
3048 ic->free_section_entry = 0;
3049 ic->free_sectors = ic->journal_entries;
3051 ic->journal_tree_root = RB_ROOT;
3052 for (i = 0; i < ic->journal_entries; i++)
3053 init_journal_node(&ic->journal_tree[i]);
3056 static void dm_integrity_enter_synchronous_mode(struct dm_integrity_c *ic)
3058 DEBUG_print("dm_integrity_enter_synchronous_mode\n");
3060 if (ic->mode == 'B') {
3061 ic->bitmap_flush_interval = msecs_to_jiffies(10) + 1;
3062 ic->synchronous_mode = 1;
3064 cancel_delayed_work_sync(&ic->bitmap_flush_work);
3065 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
3066 flush_workqueue(ic->commit_wq);
3070 static int dm_integrity_reboot(struct notifier_block *n, unsigned long code, void *x)
3072 struct dm_integrity_c *ic = container_of(n, struct dm_integrity_c, reboot_notifier);
3074 DEBUG_print("dm_integrity_reboot\n");
3076 dm_integrity_enter_synchronous_mode(ic);
3081 static void dm_integrity_postsuspend(struct dm_target *ti)
3083 struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
3086 WARN_ON(unregister_reboot_notifier(&ic->reboot_notifier));
3088 del_timer_sync(&ic->autocommit_timer);
3091 drain_workqueue(ic->recalc_wq);
3093 if (ic->mode == 'B')
3094 cancel_delayed_work_sync(&ic->bitmap_flush_work);
3096 queue_work(ic->commit_wq, &ic->commit_work);
3097 drain_workqueue(ic->commit_wq);
3099 if (ic->mode == 'J') {
3101 queue_work(ic->writer_wq, &ic->writer_work);
3102 drain_workqueue(ic->writer_wq);
3103 dm_integrity_flush_buffers(ic, true);
3106 if (ic->mode == 'B') {
3107 dm_integrity_flush_buffers(ic, true);
3109 /* set to 0 to test bitmap replay code */
3110 init_journal(ic, 0, ic->journal_sections, 0);
3111 ic->sb->flags &= ~cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
3112 r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
3114 dm_integrity_io_error(ic, "writing superblock", r);
3118 BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
3120 ic->journal_uptodate = true;
3123 static void dm_integrity_resume(struct dm_target *ti)
3125 struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
3126 __u64 old_provided_data_sectors = le64_to_cpu(ic->sb->provided_data_sectors);
3129 DEBUG_print("resume\n");
3131 if (ic->provided_data_sectors != old_provided_data_sectors) {
3132 if (ic->provided_data_sectors > old_provided_data_sectors &&
3134 ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit) {
3135 rw_journal_sectors(ic, REQ_OP_READ, 0, 0,
3136 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3137 block_bitmap_op(ic, ic->journal, old_provided_data_sectors,
3138 ic->provided_data_sectors - old_provided_data_sectors, BITMAP_OP_SET);
3139 rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, 0,
3140 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3143 ic->sb->provided_data_sectors = cpu_to_le64(ic->provided_data_sectors);
3144 r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
3146 dm_integrity_io_error(ic, "writing superblock", r);
3149 if (ic->sb->flags & cpu_to_le32(SB_FLAG_DIRTY_BITMAP)) {
3150 DEBUG_print("resume dirty_bitmap\n");
3151 rw_journal_sectors(ic, REQ_OP_READ, 0, 0,
3152 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3153 if (ic->mode == 'B') {
3154 if (ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit &&
3155 !ic->reset_recalculate_flag) {
3156 block_bitmap_copy(ic, ic->recalc_bitmap, ic->journal);
3157 block_bitmap_copy(ic, ic->may_write_bitmap, ic->journal);
3158 if (!block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors,
3159 BITMAP_OP_TEST_ALL_CLEAR)) {
3160 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
3161 ic->sb->recalc_sector = cpu_to_le64(0);
3164 DEBUG_print("non-matching blocks_per_bitmap_bit: %u, %u\n",
3165 ic->sb->log2_blocks_per_bitmap_bit, ic->log2_blocks_per_bitmap_bit);
3166 ic->sb->log2_blocks_per_bitmap_bit = ic->log2_blocks_per_bitmap_bit;
3167 block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_SET);
3168 block_bitmap_op(ic, ic->may_write_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_SET);
3169 block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_SET);
3170 rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, 0,
3171 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3172 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
3173 ic->sb->recalc_sector = cpu_to_le64(0);
3176 if (!(ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit &&
3177 block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_TEST_ALL_CLEAR)) ||
3178 ic->reset_recalculate_flag) {
3179 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
3180 ic->sb->recalc_sector = cpu_to_le64(0);
3182 init_journal(ic, 0, ic->journal_sections, 0);
3184 ic->sb->flags &= ~cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
3186 r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
3188 dm_integrity_io_error(ic, "writing superblock", r);
3191 if (ic->reset_recalculate_flag) {
3192 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
3193 ic->sb->recalc_sector = cpu_to_le64(0);
3195 if (ic->mode == 'B') {
3196 ic->sb->flags |= cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
3197 ic->sb->log2_blocks_per_bitmap_bit = ic->log2_blocks_per_bitmap_bit;
3198 r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
3200 dm_integrity_io_error(ic, "writing superblock", r);
3202 block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
3203 block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
3204 block_bitmap_op(ic, ic->may_write_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
3205 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
3206 le64_to_cpu(ic->sb->recalc_sector) < ic->provided_data_sectors) {
3207 block_bitmap_op(ic, ic->journal, le64_to_cpu(ic->sb->recalc_sector),
3208 ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
3209 block_bitmap_op(ic, ic->recalc_bitmap, le64_to_cpu(ic->sb->recalc_sector),
3210 ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
3211 block_bitmap_op(ic, ic->may_write_bitmap, le64_to_cpu(ic->sb->recalc_sector),
3212 ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
3214 rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, 0,
3215 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3219 DEBUG_print("testing recalc: %x\n", ic->sb->flags);
3220 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
3221 __u64 recalc_pos = le64_to_cpu(ic->sb->recalc_sector);
3222 DEBUG_print("recalc pos: %llx / %llx\n", recalc_pos, ic->provided_data_sectors);
3223 if (recalc_pos < ic->provided_data_sectors) {
3224 queue_work(ic->recalc_wq, &ic->recalc_work);
3225 } else if (recalc_pos > ic->provided_data_sectors) {
3226 ic->sb->recalc_sector = cpu_to_le64(ic->provided_data_sectors);
3227 recalc_write_super(ic);
3231 ic->reboot_notifier.notifier_call = dm_integrity_reboot;
3232 ic->reboot_notifier.next = NULL;
3233 ic->reboot_notifier.priority = INT_MAX - 1; /* be notified after md and before hardware drivers */
3234 WARN_ON(register_reboot_notifier(&ic->reboot_notifier));
3237 /* set to 1 to stress test synchronous mode */
3238 dm_integrity_enter_synchronous_mode(ic);
3242 static void dm_integrity_status(struct dm_target *ti, status_type_t type,
3243 unsigned status_flags, char *result, unsigned maxlen)
3245 struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
3250 case STATUSTYPE_INFO:
3252 (unsigned long long)atomic64_read(&ic->number_of_mismatches),
3253 ic->provided_data_sectors);
3254 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
3255 DMEMIT(" %llu", le64_to_cpu(ic->sb->recalc_sector));
3260 case STATUSTYPE_TABLE: {
3261 __u64 watermark_percentage = (__u64)(ic->journal_entries - ic->free_sectors_threshold) * 100;
3262 watermark_percentage += ic->journal_entries / 2;
3263 do_div(watermark_percentage, ic->journal_entries);
3265 arg_count += !!ic->meta_dev;
3266 arg_count += ic->sectors_per_block != 1;
3267 arg_count += !!(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING));
3268 arg_count += ic->reset_recalculate_flag;
3269 arg_count += ic->discard;
3270 arg_count += ic->mode == 'J';
3271 arg_count += ic->mode == 'J';
3272 arg_count += ic->mode == 'B';
3273 arg_count += ic->mode == 'B';
3274 arg_count += !!ic->internal_hash_alg.alg_string;
3275 arg_count += !!ic->journal_crypt_alg.alg_string;
3276 arg_count += !!ic->journal_mac_alg.alg_string;
3277 arg_count += (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING)) != 0;
3278 arg_count += (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) != 0;
3279 arg_count += ic->legacy_recalculate;
3280 DMEMIT("%s %llu %u %c %u", ic->dev->name, ic->start,
3281 ic->tag_size, ic->mode, arg_count);
3283 DMEMIT(" meta_device:%s", ic->meta_dev->name);
3284 if (ic->sectors_per_block != 1)
3285 DMEMIT(" block_size:%u", ic->sectors_per_block << SECTOR_SHIFT);
3286 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
3287 DMEMIT(" recalculate");
3288 if (ic->reset_recalculate_flag)
3289 DMEMIT(" reset_recalculate");
3291 DMEMIT(" allow_discards");
3292 DMEMIT(" journal_sectors:%u", ic->initial_sectors - SB_SECTORS);
3293 DMEMIT(" interleave_sectors:%u", 1U << ic->sb->log2_interleave_sectors);
3294 DMEMIT(" buffer_sectors:%u", 1U << ic->log2_buffer_sectors);
3295 if (ic->mode == 'J') {
3296 DMEMIT(" journal_watermark:%u", (unsigned)watermark_percentage);
3297 DMEMIT(" commit_time:%u", ic->autocommit_msec);
3299 if (ic->mode == 'B') {
3300 DMEMIT(" sectors_per_bit:%llu", (sector_t)ic->sectors_per_block << ic->log2_blocks_per_bitmap_bit);
3301 DMEMIT(" bitmap_flush_interval:%u", jiffies_to_msecs(ic->bitmap_flush_interval));
3303 if ((ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING)) != 0)
3304 DMEMIT(" fix_padding");
3305 if ((ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) != 0)
3306 DMEMIT(" fix_hmac");
3307 if (ic->legacy_recalculate)
3308 DMEMIT(" legacy_recalculate");
3310 #define EMIT_ALG(a, n) \
3312 if (ic->a.alg_string) { \
3313 DMEMIT(" %s:%s", n, ic->a.alg_string); \
3314 if (ic->a.key_string) \
3315 DMEMIT(":%s", ic->a.key_string);\
3318 EMIT_ALG(internal_hash_alg, "internal_hash");
3319 EMIT_ALG(journal_crypt_alg, "journal_crypt");
3320 EMIT_ALG(journal_mac_alg, "journal_mac");
3323 case STATUSTYPE_IMA:
3324 DMEMIT_TARGET_NAME_VERSION(ti->type);
3325 DMEMIT(",dev_name=%s,start=%llu,tag_size=%u,mode=%c",
3326 ic->dev->name, ic->start, ic->tag_size, ic->mode);
3329 DMEMIT(",meta_device=%s", ic->meta_dev->name);
3330 if (ic->sectors_per_block != 1)
3331 DMEMIT(",block_size=%u", ic->sectors_per_block << SECTOR_SHIFT);
3333 DMEMIT(",recalculate=%c", (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) ?
3335 DMEMIT(",allow_discards=%c", ic->discard ? 'y' : 'n');
3336 DMEMIT(",fix_padding=%c",
3337 ((ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING)) != 0) ? 'y' : 'n');
3338 DMEMIT(",fix_hmac=%c",
3339 ((ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) != 0) ? 'y' : 'n');
3340 DMEMIT(",legacy_recalculate=%c", ic->legacy_recalculate ? 'y' : 'n');
3342 DMEMIT(",journal_sectors=%u", ic->initial_sectors - SB_SECTORS);
3343 DMEMIT(",interleave_sectors=%u", 1U << ic->sb->log2_interleave_sectors);
3344 DMEMIT(",buffer_sectors=%u", 1U << ic->log2_buffer_sectors);
3350 static int dm_integrity_iterate_devices(struct dm_target *ti,
3351 iterate_devices_callout_fn fn, void *data)
3353 struct dm_integrity_c *ic = ti->private;
3356 return fn(ti, ic->dev, ic->start + ic->initial_sectors + ic->metadata_run, ti->len, data);
3358 return fn(ti, ic->dev, 0, ti->len, data);
3361 static void dm_integrity_io_hints(struct dm_target *ti, struct queue_limits *limits)
3363 struct dm_integrity_c *ic = ti->private;
3365 if (ic->sectors_per_block > 1) {
3366 limits->logical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
3367 limits->physical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
3368 blk_limits_io_min(limits, ic->sectors_per_block << SECTOR_SHIFT);
3372 static void calculate_journal_section_size(struct dm_integrity_c *ic)
3374 unsigned sector_space = JOURNAL_SECTOR_DATA;
3376 ic->journal_sections = le32_to_cpu(ic->sb->journal_sections);
3377 ic->journal_entry_size = roundup(offsetof(struct journal_entry, last_bytes[ic->sectors_per_block]) + ic->tag_size,
3378 JOURNAL_ENTRY_ROUNDUP);
3380 if (ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC))
3381 sector_space -= JOURNAL_MAC_PER_SECTOR;
3382 ic->journal_entries_per_sector = sector_space / ic->journal_entry_size;
3383 ic->journal_section_entries = ic->journal_entries_per_sector * JOURNAL_BLOCK_SECTORS;
3384 ic->journal_section_sectors = (ic->journal_section_entries << ic->sb->log2_sectors_per_block) + JOURNAL_BLOCK_SECTORS;
3385 ic->journal_entries = ic->journal_section_entries * ic->journal_sections;
3388 static int calculate_device_limits(struct dm_integrity_c *ic)
3390 __u64 initial_sectors;
3392 calculate_journal_section_size(ic);
3393 initial_sectors = SB_SECTORS + (__u64)ic->journal_section_sectors * ic->journal_sections;
3394 if (initial_sectors + METADATA_PADDING_SECTORS >= ic->meta_device_sectors || initial_sectors > UINT_MAX)
3396 ic->initial_sectors = initial_sectors;
3398 if (!ic->meta_dev) {
3399 sector_t last_sector, last_area, last_offset;
3401 /* we have to maintain excessive padding for compatibility with existing volumes */
3402 __u64 metadata_run_padding =
3403 ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING) ?
3404 (__u64)(METADATA_PADDING_SECTORS << SECTOR_SHIFT) :
3405 (__u64)(1 << SECTOR_SHIFT << METADATA_PADDING_SECTORS);
3407 ic->metadata_run = round_up((__u64)ic->tag_size << (ic->sb->log2_interleave_sectors - ic->sb->log2_sectors_per_block),
3408 metadata_run_padding) >> SECTOR_SHIFT;
3409 if (!(ic->metadata_run & (ic->metadata_run - 1)))
3410 ic->log2_metadata_run = __ffs(ic->metadata_run);
3412 ic->log2_metadata_run = -1;
3414 get_area_and_offset(ic, ic->provided_data_sectors - 1, &last_area, &last_offset);
3415 last_sector = get_data_sector(ic, last_area, last_offset);
3416 if (last_sector < ic->start || last_sector >= ic->meta_device_sectors)
3419 __u64 meta_size = (ic->provided_data_sectors >> ic->sb->log2_sectors_per_block) * ic->tag_size;
3420 meta_size = (meta_size + ((1U << (ic->log2_buffer_sectors + SECTOR_SHIFT)) - 1))
3421 >> (ic->log2_buffer_sectors + SECTOR_SHIFT);
3422 meta_size <<= ic->log2_buffer_sectors;
3423 if (ic->initial_sectors + meta_size < ic->initial_sectors ||
3424 ic->initial_sectors + meta_size > ic->meta_device_sectors)
3426 ic->metadata_run = 1;
3427 ic->log2_metadata_run = 0;
3433 static void get_provided_data_sectors(struct dm_integrity_c *ic)
3435 if (!ic->meta_dev) {
3437 ic->provided_data_sectors = 0;
3438 for (test_bit = fls64(ic->meta_device_sectors) - 1; test_bit >= 3; test_bit--) {
3439 __u64 prev_data_sectors = ic->provided_data_sectors;
3441 ic->provided_data_sectors |= (sector_t)1 << test_bit;
3442 if (calculate_device_limits(ic))
3443 ic->provided_data_sectors = prev_data_sectors;
3446 ic->provided_data_sectors = ic->data_device_sectors;
3447 ic->provided_data_sectors &= ~(sector_t)(ic->sectors_per_block - 1);
3451 static int initialize_superblock(struct dm_integrity_c *ic, unsigned journal_sectors, unsigned interleave_sectors)
3453 unsigned journal_sections;
3456 memset(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT);
3457 memcpy(ic->sb->magic, SB_MAGIC, 8);
3458 ic->sb->integrity_tag_size = cpu_to_le16(ic->tag_size);
3459 ic->sb->log2_sectors_per_block = __ffs(ic->sectors_per_block);
3460 if (ic->journal_mac_alg.alg_string)
3461 ic->sb->flags |= cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC);
3463 calculate_journal_section_size(ic);
3464 journal_sections = journal_sectors / ic->journal_section_sectors;
3465 if (!journal_sections)
3466 journal_sections = 1;
3468 if (ic->fix_hmac && (ic->internal_hash_alg.alg_string || ic->journal_mac_alg.alg_string)) {
3469 ic->sb->flags |= cpu_to_le32(SB_FLAG_FIXED_HMAC);
3470 get_random_bytes(ic->sb->salt, SALT_SIZE);
3473 if (!ic->meta_dev) {
3474 if (ic->fix_padding)
3475 ic->sb->flags |= cpu_to_le32(SB_FLAG_FIXED_PADDING);
3476 ic->sb->journal_sections = cpu_to_le32(journal_sections);
3477 if (!interleave_sectors)
3478 interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
3479 ic->sb->log2_interleave_sectors = __fls(interleave_sectors);
3480 ic->sb->log2_interleave_sectors = max((__u8)MIN_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
3481 ic->sb->log2_interleave_sectors = min((__u8)MAX_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
3483 get_provided_data_sectors(ic);
3484 if (!ic->provided_data_sectors)
3487 ic->sb->log2_interleave_sectors = 0;
3489 get_provided_data_sectors(ic);
3490 if (!ic->provided_data_sectors)
3494 ic->sb->journal_sections = cpu_to_le32(0);
3495 for (test_bit = fls(journal_sections) - 1; test_bit >= 0; test_bit--) {
3496 __u32 prev_journal_sections = le32_to_cpu(ic->sb->journal_sections);
3497 __u32 test_journal_sections = prev_journal_sections | (1U << test_bit);
3498 if (test_journal_sections > journal_sections)
3500 ic->sb->journal_sections = cpu_to_le32(test_journal_sections);
3501 if (calculate_device_limits(ic))
3502 ic->sb->journal_sections = cpu_to_le32(prev_journal_sections);
3505 if (!le32_to_cpu(ic->sb->journal_sections)) {
3506 if (ic->log2_buffer_sectors > 3) {
3507 ic->log2_buffer_sectors--;
3508 goto try_smaller_buffer;
3514 ic->sb->provided_data_sectors = cpu_to_le64(ic->provided_data_sectors);
3521 static void dm_integrity_set(struct dm_target *ti, struct dm_integrity_c *ic)
3523 struct gendisk *disk = dm_disk(dm_table_get_md(ti->table));
3524 struct blk_integrity bi;
3526 memset(&bi, 0, sizeof(bi));
3527 bi.profile = &dm_integrity_profile;
3528 bi.tuple_size = ic->tag_size;
3529 bi.tag_size = bi.tuple_size;
3530 bi.interval_exp = ic->sb->log2_sectors_per_block + SECTOR_SHIFT;
3532 blk_integrity_register(disk, &bi);
3533 blk_queue_max_integrity_segments(disk->queue, UINT_MAX);
3536 static void dm_integrity_free_page_list(struct page_list *pl)
3542 for (i = 0; pl[i].page; i++)
3543 __free_page(pl[i].page);
3547 static struct page_list *dm_integrity_alloc_page_list(unsigned n_pages)
3549 struct page_list *pl;
3552 pl = kvmalloc_array(n_pages + 1, sizeof(struct page_list), GFP_KERNEL | __GFP_ZERO);
3556 for (i = 0; i < n_pages; i++) {
3557 pl[i].page = alloc_page(GFP_KERNEL);
3559 dm_integrity_free_page_list(pl);
3563 pl[i - 1].next = &pl[i];
3571 static void dm_integrity_free_journal_scatterlist(struct dm_integrity_c *ic, struct scatterlist **sl)
3574 for (i = 0; i < ic->journal_sections; i++)
3579 static struct scatterlist **dm_integrity_alloc_journal_scatterlist(struct dm_integrity_c *ic,
3580 struct page_list *pl)
3582 struct scatterlist **sl;
3585 sl = kvmalloc_array(ic->journal_sections,
3586 sizeof(struct scatterlist *),
3587 GFP_KERNEL | __GFP_ZERO);
3591 for (i = 0; i < ic->journal_sections; i++) {
3592 struct scatterlist *s;
3593 unsigned start_index, start_offset;
3594 unsigned end_index, end_offset;
3598 page_list_location(ic, i, 0, &start_index, &start_offset);
3599 page_list_location(ic, i, ic->journal_section_sectors - 1,
3600 &end_index, &end_offset);
3602 n_pages = (end_index - start_index + 1);
3604 s = kvmalloc_array(n_pages, sizeof(struct scatterlist),
3607 dm_integrity_free_journal_scatterlist(ic, sl);
3611 sg_init_table(s, n_pages);
3612 for (idx = start_index; idx <= end_index; idx++) {
3613 char *va = lowmem_page_address(pl[idx].page);
3614 unsigned start = 0, end = PAGE_SIZE;
3615 if (idx == start_index)
3616 start = start_offset;
3617 if (idx == end_index)
3618 end = end_offset + (1 << SECTOR_SHIFT);
3619 sg_set_buf(&s[idx - start_index], va + start, end - start);
3628 static void free_alg(struct alg_spec *a)
3630 kfree_sensitive(a->alg_string);
3631 kfree_sensitive(a->key);
3632 memset(a, 0, sizeof *a);
3635 static int get_alg_and_key(const char *arg, struct alg_spec *a, char **error, char *error_inval)
3641 a->alg_string = kstrdup(strchr(arg, ':') + 1, GFP_KERNEL);
3645 k = strchr(a->alg_string, ':');
3648 a->key_string = k + 1;
3649 if (strlen(a->key_string) & 1)
3652 a->key_size = strlen(a->key_string) / 2;
3653 a->key = kmalloc(a->key_size, GFP_KERNEL);
3656 if (hex2bin(a->key, a->key_string, a->key_size))
3662 *error = error_inval;
3665 *error = "Out of memory for an argument";
3669 static int get_mac(struct crypto_shash **hash, struct alg_spec *a, char **error,
3670 char *error_alg, char *error_key)
3674 if (a->alg_string) {
3675 *hash = crypto_alloc_shash(a->alg_string, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
3676 if (IS_ERR(*hash)) {
3684 r = crypto_shash_setkey(*hash, a->key, a->key_size);
3689 } else if (crypto_shash_get_flags(*hash) & CRYPTO_TFM_NEED_KEY) {
3698 static int create_journal(struct dm_integrity_c *ic, char **error)
3702 __u64 journal_pages, journal_desc_size, journal_tree_size;
3703 unsigned char *crypt_data = NULL, *crypt_iv = NULL;
3704 struct skcipher_request *req = NULL;
3706 ic->commit_ids[0] = cpu_to_le64(0x1111111111111111ULL);
3707 ic->commit_ids[1] = cpu_to_le64(0x2222222222222222ULL);
3708 ic->commit_ids[2] = cpu_to_le64(0x3333333333333333ULL);
3709 ic->commit_ids[3] = cpu_to_le64(0x4444444444444444ULL);
3711 journal_pages = roundup((__u64)ic->journal_sections * ic->journal_section_sectors,
3712 PAGE_SIZE >> SECTOR_SHIFT) >> (PAGE_SHIFT - SECTOR_SHIFT);
3713 journal_desc_size = journal_pages * sizeof(struct page_list);
3714 if (journal_pages >= totalram_pages() - totalhigh_pages() || journal_desc_size > ULONG_MAX) {
3715 *error = "Journal doesn't fit into memory";
3719 ic->journal_pages = journal_pages;
3721 ic->journal = dm_integrity_alloc_page_list(ic->journal_pages);
3723 *error = "Could not allocate memory for journal";
3727 if (ic->journal_crypt_alg.alg_string) {
3728 unsigned ivsize, blocksize;
3729 struct journal_completion comp;
3732 ic->journal_crypt = crypto_alloc_skcipher(ic->journal_crypt_alg.alg_string, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
3733 if (IS_ERR(ic->journal_crypt)) {
3734 *error = "Invalid journal cipher";
3735 r = PTR_ERR(ic->journal_crypt);
3736 ic->journal_crypt = NULL;
3739 ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
3740 blocksize = crypto_skcipher_blocksize(ic->journal_crypt);
3742 if (ic->journal_crypt_alg.key) {
3743 r = crypto_skcipher_setkey(ic->journal_crypt, ic->journal_crypt_alg.key,
3744 ic->journal_crypt_alg.key_size);
3746 *error = "Error setting encryption key";
3750 DEBUG_print("cipher %s, block size %u iv size %u\n",
3751 ic->journal_crypt_alg.alg_string, blocksize, ivsize);
3753 ic->journal_io = dm_integrity_alloc_page_list(ic->journal_pages);
3754 if (!ic->journal_io) {
3755 *error = "Could not allocate memory for journal io";
3760 if (blocksize == 1) {
3761 struct scatterlist *sg;
3763 req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
3765 *error = "Could not allocate crypt request";
3770 crypt_iv = kzalloc(ivsize, GFP_KERNEL);
3772 *error = "Could not allocate iv";
3777 ic->journal_xor = dm_integrity_alloc_page_list(ic->journal_pages);
3778 if (!ic->journal_xor) {
3779 *error = "Could not allocate memory for journal xor";
3784 sg = kvmalloc_array(ic->journal_pages + 1,
3785 sizeof(struct scatterlist),
3788 *error = "Unable to allocate sg list";
3792 sg_init_table(sg, ic->journal_pages + 1);
3793 for (i = 0; i < ic->journal_pages; i++) {
3794 char *va = lowmem_page_address(ic->journal_xor[i].page);
3796 sg_set_buf(&sg[i], va, PAGE_SIZE);
3798 sg_set_buf(&sg[i], &ic->commit_ids, sizeof ic->commit_ids);
3800 skcipher_request_set_crypt(req, sg, sg,
3801 PAGE_SIZE * ic->journal_pages + sizeof ic->commit_ids, crypt_iv);
3802 init_completion(&comp.comp);
3803 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
3804 if (do_crypt(true, req, &comp))
3805 wait_for_completion(&comp.comp);
3807 r = dm_integrity_failed(ic);
3809 *error = "Unable to encrypt journal";
3812 DEBUG_bytes(lowmem_page_address(ic->journal_xor[0].page), 64, "xor data");
3814 crypto_free_skcipher(ic->journal_crypt);
3815 ic->journal_crypt = NULL;
3817 unsigned crypt_len = roundup(ivsize, blocksize);
3819 req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
3821 *error = "Could not allocate crypt request";
3826 crypt_iv = kmalloc(ivsize, GFP_KERNEL);
3828 *error = "Could not allocate iv";
3833 crypt_data = kmalloc(crypt_len, GFP_KERNEL);
3835 *error = "Unable to allocate crypt data";
3840 ic->journal_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal);
3841 if (!ic->journal_scatterlist) {
3842 *error = "Unable to allocate sg list";
3846 ic->journal_io_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal_io);
3847 if (!ic->journal_io_scatterlist) {
3848 *error = "Unable to allocate sg list";
3852 ic->sk_requests = kvmalloc_array(ic->journal_sections,
3853 sizeof(struct skcipher_request *),
3854 GFP_KERNEL | __GFP_ZERO);
3855 if (!ic->sk_requests) {
3856 *error = "Unable to allocate sk requests";
3860 for (i = 0; i < ic->journal_sections; i++) {
3861 struct scatterlist sg;
3862 struct skcipher_request *section_req;
3863 __le32 section_le = cpu_to_le32(i);
3865 memset(crypt_iv, 0x00, ivsize);
3866 memset(crypt_data, 0x00, crypt_len);
3867 memcpy(crypt_data, §ion_le, min((size_t)crypt_len, sizeof(section_le)));
3869 sg_init_one(&sg, crypt_data, crypt_len);
3870 skcipher_request_set_crypt(req, &sg, &sg, crypt_len, crypt_iv);
3871 init_completion(&comp.comp);
3872 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
3873 if (do_crypt(true, req, &comp))
3874 wait_for_completion(&comp.comp);
3876 r = dm_integrity_failed(ic);
3878 *error = "Unable to generate iv";
3882 section_req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
3884 *error = "Unable to allocate crypt request";
3888 section_req->iv = kmalloc_array(ivsize, 2,
3890 if (!section_req->iv) {
3891 skcipher_request_free(section_req);
3892 *error = "Unable to allocate iv";
3896 memcpy(section_req->iv + ivsize, crypt_data, ivsize);
3897 section_req->cryptlen = (size_t)ic->journal_section_sectors << SECTOR_SHIFT;
3898 ic->sk_requests[i] = section_req;
3899 DEBUG_bytes(crypt_data, ivsize, "iv(%u)", i);
3904 for (i = 0; i < N_COMMIT_IDS; i++) {
3907 for (j = 0; j < i; j++) {
3908 if (ic->commit_ids[j] == ic->commit_ids[i]) {
3909 ic->commit_ids[i] = cpu_to_le64(le64_to_cpu(ic->commit_ids[i]) + 1);
3910 goto retest_commit_id;
3913 DEBUG_print("commit id %u: %016llx\n", i, ic->commit_ids[i]);
3916 journal_tree_size = (__u64)ic->journal_entries * sizeof(struct journal_node);
3917 if (journal_tree_size > ULONG_MAX) {
3918 *error = "Journal doesn't fit into memory";
3922 ic->journal_tree = kvmalloc(journal_tree_size, GFP_KERNEL);
3923 if (!ic->journal_tree) {
3924 *error = "Could not allocate memory for journal tree";
3930 skcipher_request_free(req);
3936 * Construct a integrity mapping
3940 * offset from the start of the device
3942 * D - direct writes, J - journal writes, B - bitmap mode, R - recovery mode
3943 * number of optional arguments
3944 * optional arguments:
3946 * interleave_sectors
3953 * bitmap_flush_interval
3959 static int dm_integrity_ctr(struct dm_target *ti, unsigned argc, char **argv)
3961 struct dm_integrity_c *ic;
3964 unsigned extra_args;
3965 struct dm_arg_set as;
3966 static const struct dm_arg _args[] = {
3967 {0, 18, "Invalid number of feature args"},
3969 unsigned journal_sectors, interleave_sectors, buffer_sectors, journal_watermark, sync_msec;
3970 bool should_write_sb;
3972 unsigned long long start;
3973 __s8 log2_sectors_per_bitmap_bit = -1;
3974 __s8 log2_blocks_per_bitmap_bit;
3975 __u64 bits_in_journal;
3976 __u64 n_bitmap_bits;
3978 #define DIRECT_ARGUMENTS 4
3980 if (argc <= DIRECT_ARGUMENTS) {
3981 ti->error = "Invalid argument count";
3985 ic = kzalloc(sizeof(struct dm_integrity_c), GFP_KERNEL);
3987 ti->error = "Cannot allocate integrity context";
3991 ti->per_io_data_size = sizeof(struct dm_integrity_io);
3994 ic->in_progress = RB_ROOT;
3995 INIT_LIST_HEAD(&ic->wait_list);
3996 init_waitqueue_head(&ic->endio_wait);
3997 bio_list_init(&ic->flush_bio_list);
3998 init_waitqueue_head(&ic->copy_to_journal_wait);
3999 init_completion(&ic->crypto_backoff);
4000 atomic64_set(&ic->number_of_mismatches, 0);
4001 ic->bitmap_flush_interval = BITMAP_FLUSH_INTERVAL;
4003 r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &ic->dev);
4005 ti->error = "Device lookup failed";
4009 if (sscanf(argv[1], "%llu%c", &start, &dummy) != 1 || start != (sector_t)start) {
4010 ti->error = "Invalid starting offset";
4016 if (strcmp(argv[2], "-")) {
4017 if (sscanf(argv[2], "%u%c", &ic->tag_size, &dummy) != 1 || !ic->tag_size) {
4018 ti->error = "Invalid tag size";
4024 if (!strcmp(argv[3], "J") || !strcmp(argv[3], "B") ||
4025 !strcmp(argv[3], "D") || !strcmp(argv[3], "R")) {
4026 ic->mode = argv[3][0];
4028 ti->error = "Invalid mode (expecting J, B, D, R)";
4033 journal_sectors = 0;
4034 interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
4035 buffer_sectors = DEFAULT_BUFFER_SECTORS;
4036 journal_watermark = DEFAULT_JOURNAL_WATERMARK;
4037 sync_msec = DEFAULT_SYNC_MSEC;
4038 ic->sectors_per_block = 1;
4040 as.argc = argc - DIRECT_ARGUMENTS;
4041 as.argv = argv + DIRECT_ARGUMENTS;
4042 r = dm_read_arg_group(_args, &as, &extra_args, &ti->error);
4046 while (extra_args--) {
4047 const char *opt_string;
4049 unsigned long long llval;
4050 opt_string = dm_shift_arg(&as);
4053 ti->error = "Not enough feature arguments";
4056 if (sscanf(opt_string, "journal_sectors:%u%c", &val, &dummy) == 1)
4057 journal_sectors = val ? val : 1;
4058 else if (sscanf(opt_string, "interleave_sectors:%u%c", &val, &dummy) == 1)
4059 interleave_sectors = val;
4060 else if (sscanf(opt_string, "buffer_sectors:%u%c", &val, &dummy) == 1)
4061 buffer_sectors = val;
4062 else if (sscanf(opt_string, "journal_watermark:%u%c", &val, &dummy) == 1 && val <= 100)
4063 journal_watermark = val;
4064 else if (sscanf(opt_string, "commit_time:%u%c", &val, &dummy) == 1)
4066 else if (!strncmp(opt_string, "meta_device:", strlen("meta_device:"))) {
4068 dm_put_device(ti, ic->meta_dev);
4069 ic->meta_dev = NULL;
4071 r = dm_get_device(ti, strchr(opt_string, ':') + 1,
4072 dm_table_get_mode(ti->table), &ic->meta_dev);
4074 ti->error = "Device lookup failed";
4077 } else if (sscanf(opt_string, "block_size:%u%c", &val, &dummy) == 1) {
4078 if (val < 1 << SECTOR_SHIFT ||
4079 val > MAX_SECTORS_PER_BLOCK << SECTOR_SHIFT ||
4082 ti->error = "Invalid block_size argument";
4085 ic->sectors_per_block = val >> SECTOR_SHIFT;
4086 } else if (sscanf(opt_string, "sectors_per_bit:%llu%c", &llval, &dummy) == 1) {
4087 log2_sectors_per_bitmap_bit = !llval ? 0 : __ilog2_u64(llval);
4088 } else if (sscanf(opt_string, "bitmap_flush_interval:%u%c", &val, &dummy) == 1) {
4089 if (val >= (uint64_t)UINT_MAX * 1000 / HZ) {
4091 ti->error = "Invalid bitmap_flush_interval argument";
4094 ic->bitmap_flush_interval = msecs_to_jiffies(val);
4095 } else if (!strncmp(opt_string, "internal_hash:", strlen("internal_hash:"))) {
4096 r = get_alg_and_key(opt_string, &ic->internal_hash_alg, &ti->error,
4097 "Invalid internal_hash argument");
4100 } else if (!strncmp(opt_string, "journal_crypt:", strlen("journal_crypt:"))) {
4101 r = get_alg_and_key(opt_string, &ic->journal_crypt_alg, &ti->error,
4102 "Invalid journal_crypt argument");
4105 } else if (!strncmp(opt_string, "journal_mac:", strlen("journal_mac:"))) {
4106 r = get_alg_and_key(opt_string, &ic->journal_mac_alg, &ti->error,
4107 "Invalid journal_mac argument");
4110 } else if (!strcmp(opt_string, "recalculate")) {
4111 ic->recalculate_flag = true;
4112 } else if (!strcmp(opt_string, "reset_recalculate")) {
4113 ic->recalculate_flag = true;
4114 ic->reset_recalculate_flag = true;
4115 } else if (!strcmp(opt_string, "allow_discards")) {
4117 } else if (!strcmp(opt_string, "fix_padding")) {
4118 ic->fix_padding = true;
4119 } else if (!strcmp(opt_string, "fix_hmac")) {
4120 ic->fix_hmac = true;
4121 } else if (!strcmp(opt_string, "legacy_recalculate")) {
4122 ic->legacy_recalculate = true;
4125 ti->error = "Invalid argument";
4130 ic->data_device_sectors = bdev_nr_sectors(ic->dev->bdev);
4132 ic->meta_device_sectors = ic->data_device_sectors;
4134 ic->meta_device_sectors = bdev_nr_sectors(ic->meta_dev->bdev);
4136 if (!journal_sectors) {
4137 journal_sectors = min((sector_t)DEFAULT_MAX_JOURNAL_SECTORS,
4138 ic->data_device_sectors >> DEFAULT_JOURNAL_SIZE_FACTOR);
4141 if (!buffer_sectors)
4143 ic->log2_buffer_sectors = min((int)__fls(buffer_sectors), 31 - SECTOR_SHIFT);
4145 r = get_mac(&ic->internal_hash, &ic->internal_hash_alg, &ti->error,
4146 "Invalid internal hash", "Error setting internal hash key");
4150 r = get_mac(&ic->journal_mac, &ic->journal_mac_alg, &ti->error,
4151 "Invalid journal mac", "Error setting journal mac key");
4155 if (!ic->tag_size) {
4156 if (!ic->internal_hash) {
4157 ti->error = "Unknown tag size";
4161 ic->tag_size = crypto_shash_digestsize(ic->internal_hash);
4163 if (ic->tag_size > MAX_TAG_SIZE) {
4164 ti->error = "Too big tag size";
4168 if (!(ic->tag_size & (ic->tag_size - 1)))
4169 ic->log2_tag_size = __ffs(ic->tag_size);
4171 ic->log2_tag_size = -1;
4173 if (ic->mode == 'B' && !ic->internal_hash) {
4175 ti->error = "Bitmap mode can be only used with internal hash";
4179 if (ic->discard && !ic->internal_hash) {
4181 ti->error = "Discard can be only used with internal hash";
4185 ic->autocommit_jiffies = msecs_to_jiffies(sync_msec);
4186 ic->autocommit_msec = sync_msec;
4187 timer_setup(&ic->autocommit_timer, autocommit_fn, 0);
4189 ic->io = dm_io_client_create();
4190 if (IS_ERR(ic->io)) {
4191 r = PTR_ERR(ic->io);
4193 ti->error = "Cannot allocate dm io";
4197 r = mempool_init_slab_pool(&ic->journal_io_mempool, JOURNAL_IO_MEMPOOL, journal_io_cache);
4199 ti->error = "Cannot allocate mempool";
4203 ic->metadata_wq = alloc_workqueue("dm-integrity-metadata",
4204 WQ_MEM_RECLAIM, METADATA_WORKQUEUE_MAX_ACTIVE);
4205 if (!ic->metadata_wq) {
4206 ti->error = "Cannot allocate workqueue";
4212 * If this workqueue were percpu, it would cause bio reordering
4213 * and reduced performance.
4215 ic->wait_wq = alloc_workqueue("dm-integrity-wait", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
4217 ti->error = "Cannot allocate workqueue";
4222 ic->offload_wq = alloc_workqueue("dm-integrity-offload", WQ_MEM_RECLAIM,
4223 METADATA_WORKQUEUE_MAX_ACTIVE);
4224 if (!ic->offload_wq) {
4225 ti->error = "Cannot allocate workqueue";
4230 ic->commit_wq = alloc_workqueue("dm-integrity-commit", WQ_MEM_RECLAIM, 1);
4231 if (!ic->commit_wq) {
4232 ti->error = "Cannot allocate workqueue";
4236 INIT_WORK(&ic->commit_work, integrity_commit);
4238 if (ic->mode == 'J' || ic->mode == 'B') {
4239 ic->writer_wq = alloc_workqueue("dm-integrity-writer", WQ_MEM_RECLAIM, 1);
4240 if (!ic->writer_wq) {
4241 ti->error = "Cannot allocate workqueue";
4245 INIT_WORK(&ic->writer_work, integrity_writer);
4248 ic->sb = alloc_pages_exact(SB_SECTORS << SECTOR_SHIFT, GFP_KERNEL);
4251 ti->error = "Cannot allocate superblock area";
4255 r = sync_rw_sb(ic, REQ_OP_READ, 0);
4257 ti->error = "Error reading superblock";
4260 should_write_sb = false;
4261 if (memcmp(ic->sb->magic, SB_MAGIC, 8)) {
4262 if (ic->mode != 'R') {
4263 if (memchr_inv(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT)) {
4265 ti->error = "The device is not initialized";
4270 r = initialize_superblock(ic, journal_sectors, interleave_sectors);
4272 ti->error = "Could not initialize superblock";
4275 if (ic->mode != 'R')
4276 should_write_sb = true;
4279 if (!ic->sb->version || ic->sb->version > SB_VERSION_5) {
4281 ti->error = "Unknown version";
4284 if (le16_to_cpu(ic->sb->integrity_tag_size) != ic->tag_size) {
4286 ti->error = "Tag size doesn't match the information in superblock";
4289 if (ic->sb->log2_sectors_per_block != __ffs(ic->sectors_per_block)) {
4291 ti->error = "Block size doesn't match the information in superblock";
4294 if (!le32_to_cpu(ic->sb->journal_sections)) {
4296 ti->error = "Corrupted superblock, journal_sections is 0";
4299 /* make sure that ti->max_io_len doesn't overflow */
4300 if (!ic->meta_dev) {
4301 if (ic->sb->log2_interleave_sectors < MIN_LOG2_INTERLEAVE_SECTORS ||
4302 ic->sb->log2_interleave_sectors > MAX_LOG2_INTERLEAVE_SECTORS) {
4304 ti->error = "Invalid interleave_sectors in the superblock";
4308 if (ic->sb->log2_interleave_sectors) {
4310 ti->error = "Invalid interleave_sectors in the superblock";
4314 if (!!(ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC)) != !!ic->journal_mac_alg.alg_string) {
4316 ti->error = "Journal mac mismatch";
4320 get_provided_data_sectors(ic);
4321 if (!ic->provided_data_sectors) {
4323 ti->error = "The device is too small";
4328 r = calculate_device_limits(ic);
4331 if (ic->log2_buffer_sectors > 3) {
4332 ic->log2_buffer_sectors--;
4333 goto try_smaller_buffer;
4336 ti->error = "The device is too small";
4340 if (log2_sectors_per_bitmap_bit < 0)
4341 log2_sectors_per_bitmap_bit = __fls(DEFAULT_SECTORS_PER_BITMAP_BIT);
4342 if (log2_sectors_per_bitmap_bit < ic->sb->log2_sectors_per_block)
4343 log2_sectors_per_bitmap_bit = ic->sb->log2_sectors_per_block;
4345 bits_in_journal = ((__u64)ic->journal_section_sectors * ic->journal_sections) << (SECTOR_SHIFT + 3);
4346 if (bits_in_journal > UINT_MAX)
4347 bits_in_journal = UINT_MAX;
4348 while (bits_in_journal < (ic->provided_data_sectors + ((sector_t)1 << log2_sectors_per_bitmap_bit) - 1) >> log2_sectors_per_bitmap_bit)
4349 log2_sectors_per_bitmap_bit++;
4351 log2_blocks_per_bitmap_bit = log2_sectors_per_bitmap_bit - ic->sb->log2_sectors_per_block;
4352 ic->log2_blocks_per_bitmap_bit = log2_blocks_per_bitmap_bit;
4353 if (should_write_sb) {
4354 ic->sb->log2_blocks_per_bitmap_bit = log2_blocks_per_bitmap_bit;
4356 n_bitmap_bits = ((ic->provided_data_sectors >> ic->sb->log2_sectors_per_block)
4357 + (((sector_t)1 << log2_blocks_per_bitmap_bit) - 1)) >> log2_blocks_per_bitmap_bit;
4358 ic->n_bitmap_blocks = DIV_ROUND_UP(n_bitmap_bits, BITMAP_BLOCK_SIZE * 8);
4361 ic->log2_buffer_sectors = min(ic->log2_buffer_sectors, (__u8)__ffs(ic->metadata_run));
4363 if (ti->len > ic->provided_data_sectors) {
4365 ti->error = "Not enough provided sectors for requested mapping size";
4370 threshold = (__u64)ic->journal_entries * (100 - journal_watermark);
4372 do_div(threshold, 100);
4373 ic->free_sectors_threshold = threshold;
4375 DEBUG_print("initialized:\n");
4376 DEBUG_print(" integrity_tag_size %u\n", le16_to_cpu(ic->sb->integrity_tag_size));
4377 DEBUG_print(" journal_entry_size %u\n", ic->journal_entry_size);
4378 DEBUG_print(" journal_entries_per_sector %u\n", ic->journal_entries_per_sector);
4379 DEBUG_print(" journal_section_entries %u\n", ic->journal_section_entries);
4380 DEBUG_print(" journal_section_sectors %u\n", ic->journal_section_sectors);
4381 DEBUG_print(" journal_sections %u\n", (unsigned)le32_to_cpu(ic->sb->journal_sections));
4382 DEBUG_print(" journal_entries %u\n", ic->journal_entries);
4383 DEBUG_print(" log2_interleave_sectors %d\n", ic->sb->log2_interleave_sectors);
4384 DEBUG_print(" data_device_sectors 0x%llx\n", bdev_nr_sectors(ic->dev->bdev));
4385 DEBUG_print(" initial_sectors 0x%x\n", ic->initial_sectors);
4386 DEBUG_print(" metadata_run 0x%x\n", ic->metadata_run);
4387 DEBUG_print(" log2_metadata_run %d\n", ic->log2_metadata_run);
4388 DEBUG_print(" provided_data_sectors 0x%llx (%llu)\n", ic->provided_data_sectors, ic->provided_data_sectors);
4389 DEBUG_print(" log2_buffer_sectors %u\n", ic->log2_buffer_sectors);
4390 DEBUG_print(" bits_in_journal %llu\n", bits_in_journal);
4392 if (ic->recalculate_flag && !(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))) {
4393 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
4394 ic->sb->recalc_sector = cpu_to_le64(0);
4397 if (ic->internal_hash) {
4398 ic->recalc_wq = alloc_workqueue("dm-integrity-recalc", WQ_MEM_RECLAIM, 1);
4399 if (!ic->recalc_wq ) {
4400 ti->error = "Cannot allocate workqueue";
4404 INIT_WORK(&ic->recalc_work, integrity_recalc);
4405 ic->recalc_buffer = vmalloc(RECALC_SECTORS << SECTOR_SHIFT);
4406 if (!ic->recalc_buffer) {
4407 ti->error = "Cannot allocate buffer for recalculating";
4411 ic->recalc_tags = kvmalloc_array(RECALC_SECTORS >> ic->sb->log2_sectors_per_block,
4412 ic->tag_size, GFP_KERNEL);
4413 if (!ic->recalc_tags) {
4414 ti->error = "Cannot allocate tags for recalculating";
4419 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
4420 ti->error = "Recalculate can only be specified with internal_hash";
4426 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
4427 le64_to_cpu(ic->sb->recalc_sector) < ic->provided_data_sectors &&
4428 dm_integrity_disable_recalculate(ic)) {
4429 ti->error = "Recalculating with HMAC is disabled for security reasons - if you really need it, use the argument \"legacy_recalculate\"";
4434 ic->bufio = dm_bufio_client_create(ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev,
4435 1U << (SECTOR_SHIFT + ic->log2_buffer_sectors), 1, 0, NULL, NULL);
4436 if (IS_ERR(ic->bufio)) {
4437 r = PTR_ERR(ic->bufio);
4438 ti->error = "Cannot initialize dm-bufio";
4442 dm_bufio_set_sector_offset(ic->bufio, ic->start + ic->initial_sectors);
4444 if (ic->mode != 'R') {
4445 r = create_journal(ic, &ti->error);
4451 if (ic->mode == 'B') {
4453 unsigned n_bitmap_pages = DIV_ROUND_UP(ic->n_bitmap_blocks, PAGE_SIZE / BITMAP_BLOCK_SIZE);
4455 ic->recalc_bitmap = dm_integrity_alloc_page_list(n_bitmap_pages);
4456 if (!ic->recalc_bitmap) {
4460 ic->may_write_bitmap = dm_integrity_alloc_page_list(n_bitmap_pages);
4461 if (!ic->may_write_bitmap) {
4465 ic->bbs = kvmalloc_array(ic->n_bitmap_blocks, sizeof(struct bitmap_block_status), GFP_KERNEL);
4470 INIT_DELAYED_WORK(&ic->bitmap_flush_work, bitmap_flush_work);
4471 for (i = 0; i < ic->n_bitmap_blocks; i++) {
4472 struct bitmap_block_status *bbs = &ic->bbs[i];
4473 unsigned sector, pl_index, pl_offset;
4475 INIT_WORK(&bbs->work, bitmap_block_work);
4478 bio_list_init(&bbs->bio_queue);
4479 spin_lock_init(&bbs->bio_queue_lock);
4481 sector = i * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT);
4482 pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
4483 pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
4485 bbs->bitmap = lowmem_page_address(ic->journal[pl_index].page) + pl_offset;
4489 if (should_write_sb) {
4492 init_journal(ic, 0, ic->journal_sections, 0);
4493 r = dm_integrity_failed(ic);
4495 ti->error = "Error initializing journal";
4498 r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
4500 ti->error = "Error initializing superblock";
4503 ic->just_formatted = true;
4506 if (!ic->meta_dev) {
4507 r = dm_set_target_max_io_len(ti, 1U << ic->sb->log2_interleave_sectors);
4511 if (ic->mode == 'B') {
4512 unsigned max_io_len = ((sector_t)ic->sectors_per_block << ic->log2_blocks_per_bitmap_bit) * (BITMAP_BLOCK_SIZE * 8);
4514 max_io_len = 1U << 31;
4515 DEBUG_print("max_io_len: old %u, new %u\n", ti->max_io_len, max_io_len);
4516 if (!ti->max_io_len || ti->max_io_len > max_io_len) {
4517 r = dm_set_target_max_io_len(ti, max_io_len);
4523 if (!ic->internal_hash)
4524 dm_integrity_set(ti, ic);
4526 ti->num_flush_bios = 1;
4527 ti->flush_supported = true;
4529 ti->num_discard_bios = 1;
4531 dm_audit_log_ctr(DM_MSG_PREFIX, ti, 1);
4535 dm_audit_log_ctr(DM_MSG_PREFIX, ti, 0);
4536 dm_integrity_dtr(ti);
4540 static void dm_integrity_dtr(struct dm_target *ti)
4542 struct dm_integrity_c *ic = ti->private;
4544 BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
4545 BUG_ON(!list_empty(&ic->wait_list));
4547 if (ic->metadata_wq)
4548 destroy_workqueue(ic->metadata_wq);
4550 destroy_workqueue(ic->wait_wq);
4552 destroy_workqueue(ic->offload_wq);
4554 destroy_workqueue(ic->commit_wq);
4556 destroy_workqueue(ic->writer_wq);
4558 destroy_workqueue(ic->recalc_wq);
4559 vfree(ic->recalc_buffer);
4560 kvfree(ic->recalc_tags);
4563 dm_bufio_client_destroy(ic->bufio);
4564 mempool_exit(&ic->journal_io_mempool);
4566 dm_io_client_destroy(ic->io);
4568 dm_put_device(ti, ic->dev);
4570 dm_put_device(ti, ic->meta_dev);
4571 dm_integrity_free_page_list(ic->journal);
4572 dm_integrity_free_page_list(ic->journal_io);
4573 dm_integrity_free_page_list(ic->journal_xor);
4574 dm_integrity_free_page_list(ic->recalc_bitmap);
4575 dm_integrity_free_page_list(ic->may_write_bitmap);
4576 if (ic->journal_scatterlist)
4577 dm_integrity_free_journal_scatterlist(ic, ic->journal_scatterlist);
4578 if (ic->journal_io_scatterlist)
4579 dm_integrity_free_journal_scatterlist(ic, ic->journal_io_scatterlist);
4580 if (ic->sk_requests) {
4583 for (i = 0; i < ic->journal_sections; i++) {
4584 struct skcipher_request *req = ic->sk_requests[i];
4586 kfree_sensitive(req->iv);
4587 skcipher_request_free(req);
4590 kvfree(ic->sk_requests);
4592 kvfree(ic->journal_tree);
4594 free_pages_exact(ic->sb, SB_SECTORS << SECTOR_SHIFT);
4596 if (ic->internal_hash)
4597 crypto_free_shash(ic->internal_hash);
4598 free_alg(&ic->internal_hash_alg);
4600 if (ic->journal_crypt)
4601 crypto_free_skcipher(ic->journal_crypt);
4602 free_alg(&ic->journal_crypt_alg);
4604 if (ic->journal_mac)
4605 crypto_free_shash(ic->journal_mac);
4606 free_alg(&ic->journal_mac_alg);
4609 dm_audit_log_dtr(DM_MSG_PREFIX, ti, 1);
4612 static struct target_type integrity_target = {
4613 .name = "integrity",
4614 .version = {1, 10, 0},
4615 .module = THIS_MODULE,
4616 .features = DM_TARGET_SINGLETON | DM_TARGET_INTEGRITY,
4617 .ctr = dm_integrity_ctr,
4618 .dtr = dm_integrity_dtr,
4619 .map = dm_integrity_map,
4620 .postsuspend = dm_integrity_postsuspend,
4621 .resume = dm_integrity_resume,
4622 .status = dm_integrity_status,
4623 .iterate_devices = dm_integrity_iterate_devices,
4624 .io_hints = dm_integrity_io_hints,
4627 static int __init dm_integrity_init(void)
4631 journal_io_cache = kmem_cache_create("integrity_journal_io",
4632 sizeof(struct journal_io), 0, 0, NULL);
4633 if (!journal_io_cache) {
4634 DMERR("can't allocate journal io cache");
4638 r = dm_register_target(&integrity_target);
4641 DMERR("register failed %d", r);
4646 static void __exit dm_integrity_exit(void)
4648 dm_unregister_target(&integrity_target);
4649 kmem_cache_destroy(journal_io_cache);
4652 module_init(dm_integrity_init);
4653 module_exit(dm_integrity_exit);
4655 MODULE_AUTHOR("Milan Broz");
4656 MODULE_AUTHOR("Mikulas Patocka");
4657 MODULE_DESCRIPTION(DM_NAME " target for integrity tags extension");
4658 MODULE_LICENSE("GPL");