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 <linux/compiler.h>
10 #include <linux/module.h>
11 #include <linux/device-mapper.h>
12 #include <linux/dm-io.h>
13 #include <linux/vmalloc.h>
14 #include <linux/sort.h>
15 #include <linux/rbtree.h>
16 #include <linux/delay.h>
17 #include <linux/random.h>
18 #include <linux/reboot.h>
19 #include <crypto/hash.h>
20 #include <crypto/skcipher.h>
21 #include <linux/async_tx.h>
22 #include <linux/dm-bufio.h>
24 #define DM_MSG_PREFIX "integrity"
26 #define DEFAULT_INTERLEAVE_SECTORS 32768
27 #define DEFAULT_JOURNAL_SIZE_FACTOR 7
28 #define DEFAULT_SECTORS_PER_BITMAP_BIT 32768
29 #define DEFAULT_BUFFER_SECTORS 128
30 #define DEFAULT_JOURNAL_WATERMARK 50
31 #define DEFAULT_SYNC_MSEC 10000
32 #define DEFAULT_MAX_JOURNAL_SECTORS 131072
33 #define MIN_LOG2_INTERLEAVE_SECTORS 3
34 #define MAX_LOG2_INTERLEAVE_SECTORS 31
35 #define METADATA_WORKQUEUE_MAX_ACTIVE 16
36 #define RECALC_SECTORS 8192
37 #define RECALC_WRITE_SUPER 16
38 #define BITMAP_BLOCK_SIZE 4096 /* don't change it */
39 #define BITMAP_FLUSH_INTERVAL (10 * HZ)
42 * Warning - DEBUG_PRINT prints security-sensitive data to the log,
43 * so it should not be enabled in the official kernel
46 //#define INTERNAL_VERIFY
52 #define SB_MAGIC "integrt"
53 #define SB_VERSION_1 1
54 #define SB_VERSION_2 2
55 #define SB_VERSION_3 3
57 #define MAX_SECTORS_PER_BLOCK 8
62 __u8 log2_interleave_sectors;
63 __u16 integrity_tag_size;
64 __u32 journal_sections;
65 __u64 provided_data_sectors; /* userspace uses this value */
67 __u8 log2_sectors_per_block;
68 __u8 log2_blocks_per_bitmap_bit;
73 #define SB_FLAG_HAVE_JOURNAL_MAC 0x1
74 #define SB_FLAG_RECALCULATING 0x2
75 #define SB_FLAG_DIRTY_BITMAP 0x4
77 #define JOURNAL_ENTRY_ROUNDUP 8
79 typedef __u64 commit_id_t;
80 #define JOURNAL_MAC_PER_SECTOR 8
82 struct journal_entry {
90 commit_id_t last_bytes[0];
94 #define journal_entry_tag(ic, je) ((__u8 *)&(je)->last_bytes[(ic)->sectors_per_block])
96 #if BITS_PER_LONG == 64
97 #define journal_entry_set_sector(je, x) do { smp_wmb(); WRITE_ONCE((je)->u.sector, cpu_to_le64(x)); } while (0)
99 #define journal_entry_set_sector(je, x) do { (je)->u.s.sector_lo = cpu_to_le32(x); smp_wmb(); WRITE_ONCE((je)->u.s.sector_hi, cpu_to_le32((x) >> 32)); } while (0)
101 #define journal_entry_get_sector(je) le64_to_cpu((je)->u.sector)
102 #define journal_entry_is_unused(je) ((je)->u.s.sector_hi == cpu_to_le32(-1))
103 #define journal_entry_set_unused(je) do { ((je)->u.s.sector_hi = cpu_to_le32(-1)); } while (0)
104 #define journal_entry_is_inprogress(je) ((je)->u.s.sector_hi == cpu_to_le32(-2))
105 #define journal_entry_set_inprogress(je) do { ((je)->u.s.sector_hi = cpu_to_le32(-2)); } while (0)
107 #define JOURNAL_BLOCK_SECTORS 8
108 #define JOURNAL_SECTOR_DATA ((1 << SECTOR_SHIFT) - sizeof(commit_id_t))
109 #define JOURNAL_MAC_SIZE (JOURNAL_MAC_PER_SECTOR * JOURNAL_BLOCK_SECTORS)
111 struct journal_sector {
112 __u8 entries[JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR];
113 __u8 mac[JOURNAL_MAC_PER_SECTOR];
114 commit_id_t commit_id;
117 #define MAX_TAG_SIZE (JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR - offsetof(struct journal_entry, last_bytes[MAX_SECTORS_PER_BLOCK]))
119 #define METADATA_PADDING_SECTORS 8
121 #define N_COMMIT_IDS 4
123 static unsigned char prev_commit_seq(unsigned char seq)
125 return (seq + N_COMMIT_IDS - 1) % N_COMMIT_IDS;
128 static unsigned char next_commit_seq(unsigned char seq)
130 return (seq + 1) % N_COMMIT_IDS;
134 * In-memory structures
137 struct journal_node {
149 struct dm_integrity_c {
151 struct dm_dev *meta_dev;
155 mempool_t journal_io_mempool;
156 struct dm_io_client *io;
157 struct dm_bufio_client *bufio;
158 struct workqueue_struct *metadata_wq;
159 struct superblock *sb;
160 unsigned journal_pages;
161 unsigned n_bitmap_blocks;
163 struct page_list *journal;
164 struct page_list *journal_io;
165 struct page_list *journal_xor;
166 struct page_list *recalc_bitmap;
167 struct page_list *may_write_bitmap;
168 struct bitmap_block_status *bbs;
169 unsigned bitmap_flush_interval;
170 int synchronous_mode;
171 struct bio_list synchronous_bios;
172 struct delayed_work bitmap_flush_work;
174 struct crypto_skcipher *journal_crypt;
175 struct scatterlist **journal_scatterlist;
176 struct scatterlist **journal_io_scatterlist;
177 struct skcipher_request **sk_requests;
179 struct crypto_shash *journal_mac;
181 struct journal_node *journal_tree;
182 struct rb_root journal_tree_root;
184 sector_t provided_data_sectors;
186 unsigned short journal_entry_size;
187 unsigned char journal_entries_per_sector;
188 unsigned char journal_section_entries;
189 unsigned short journal_section_sectors;
190 unsigned journal_sections;
191 unsigned journal_entries;
192 sector_t data_device_sectors;
193 sector_t meta_device_sectors;
194 unsigned initial_sectors;
195 unsigned metadata_run;
196 __s8 log2_metadata_run;
197 __u8 log2_buffer_sectors;
198 __u8 sectors_per_block;
199 __u8 log2_blocks_per_bitmap_bit;
206 struct crypto_shash *internal_hash;
208 /* these variables are locked with endio_wait.lock */
209 struct rb_root in_progress;
210 struct list_head wait_list;
211 wait_queue_head_t endio_wait;
212 struct workqueue_struct *wait_wq;
214 unsigned char commit_seq;
215 commit_id_t commit_ids[N_COMMIT_IDS];
217 unsigned committed_section;
218 unsigned n_committed_sections;
220 unsigned uncommitted_section;
221 unsigned n_uncommitted_sections;
223 unsigned free_section;
224 unsigned char free_section_entry;
225 unsigned free_sectors;
227 unsigned free_sectors_threshold;
229 struct workqueue_struct *commit_wq;
230 struct work_struct commit_work;
232 struct workqueue_struct *writer_wq;
233 struct work_struct writer_work;
235 struct workqueue_struct *recalc_wq;
236 struct work_struct recalc_work;
240 struct bio_list flush_bio_list;
242 unsigned long autocommit_jiffies;
243 struct timer_list autocommit_timer;
244 unsigned autocommit_msec;
246 wait_queue_head_t copy_to_journal_wait;
248 struct completion crypto_backoff;
250 bool journal_uptodate;
252 bool recalculate_flag;
254 struct alg_spec internal_hash_alg;
255 struct alg_spec journal_crypt_alg;
256 struct alg_spec journal_mac_alg;
258 atomic64_t number_of_mismatches;
260 struct notifier_block reboot_notifier;
263 struct dm_integrity_range {
264 sector_t logical_sector;
270 struct task_struct *task;
271 struct list_head wait_entry;
276 struct dm_integrity_io {
277 struct work_struct work;
279 struct dm_integrity_c *ic;
283 struct dm_integrity_range range;
285 sector_t metadata_block;
286 unsigned metadata_offset;
289 blk_status_t bi_status;
291 struct completion *completion;
293 struct gendisk *orig_bi_disk;
295 bio_end_io_t *orig_bi_end_io;
296 struct bio_integrity_payload *orig_bi_integrity;
297 struct bvec_iter orig_bi_iter;
300 struct journal_completion {
301 struct dm_integrity_c *ic;
303 struct completion comp;
307 struct dm_integrity_range range;
308 struct journal_completion *comp;
311 struct bitmap_block_status {
312 struct work_struct work;
313 struct dm_integrity_c *ic;
315 unsigned long *bitmap;
316 struct bio_list bio_queue;
317 spinlock_t bio_queue_lock;
321 static struct kmem_cache *journal_io_cache;
323 #define JOURNAL_IO_MEMPOOL 32
326 #define DEBUG_print(x, ...) printk(KERN_DEBUG x, ##__VA_ARGS__)
327 static void __DEBUG_bytes(__u8 *bytes, size_t len, const char *msg, ...)
336 pr_cont(" %02x", *bytes);
342 #define DEBUG_bytes(bytes, len, msg, ...) __DEBUG_bytes(bytes, len, KERN_DEBUG msg, ##__VA_ARGS__)
344 #define DEBUG_print(x, ...) do { } while (0)
345 #define DEBUG_bytes(bytes, len, msg, ...) do { } while (0)
348 static void dm_integrity_prepare(struct request *rq)
352 static void dm_integrity_complete(struct request *rq, unsigned int nr_bytes)
357 * DM Integrity profile, protection is performed layer above (dm-crypt)
359 static const struct blk_integrity_profile dm_integrity_profile = {
360 .name = "DM-DIF-EXT-TAG",
363 .prepare_fn = dm_integrity_prepare,
364 .complete_fn = dm_integrity_complete,
367 static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map);
368 static void integrity_bio_wait(struct work_struct *w);
369 static void dm_integrity_dtr(struct dm_target *ti);
371 static void dm_integrity_io_error(struct dm_integrity_c *ic, const char *msg, int err)
374 atomic64_inc(&ic->number_of_mismatches);
375 if (!cmpxchg(&ic->failed, 0, err))
376 DMERR("Error on %s: %d", msg, err);
379 static int dm_integrity_failed(struct dm_integrity_c *ic)
381 return READ_ONCE(ic->failed);
384 static commit_id_t dm_integrity_commit_id(struct dm_integrity_c *ic, unsigned i,
385 unsigned j, unsigned char seq)
388 * Xor the number with section and sector, so that if a piece of
389 * journal is written at wrong place, it is detected.
391 return ic->commit_ids[seq] ^ cpu_to_le64(((__u64)i << 32) ^ j);
394 static void get_area_and_offset(struct dm_integrity_c *ic, sector_t data_sector,
395 sector_t *area, sector_t *offset)
398 __u8 log2_interleave_sectors = ic->sb->log2_interleave_sectors;
399 *area = data_sector >> log2_interleave_sectors;
400 *offset = (unsigned)data_sector & ((1U << log2_interleave_sectors) - 1);
403 *offset = data_sector;
407 #define sector_to_block(ic, n) \
409 BUG_ON((n) & (unsigned)((ic)->sectors_per_block - 1)); \
410 (n) >>= (ic)->sb->log2_sectors_per_block; \
413 static __u64 get_metadata_sector_and_offset(struct dm_integrity_c *ic, sector_t area,
414 sector_t offset, unsigned *metadata_offset)
419 ms = area << ic->sb->log2_interleave_sectors;
420 if (likely(ic->log2_metadata_run >= 0))
421 ms += area << ic->log2_metadata_run;
423 ms += area * ic->metadata_run;
424 ms >>= ic->log2_buffer_sectors;
426 sector_to_block(ic, offset);
428 if (likely(ic->log2_tag_size >= 0)) {
429 ms += offset >> (SECTOR_SHIFT + ic->log2_buffer_sectors - ic->log2_tag_size);
430 mo = (offset << ic->log2_tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
432 ms += (__u64)offset * ic->tag_size >> (SECTOR_SHIFT + ic->log2_buffer_sectors);
433 mo = (offset * ic->tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
435 *metadata_offset = mo;
439 static sector_t get_data_sector(struct dm_integrity_c *ic, sector_t area, sector_t offset)
446 result = area << ic->sb->log2_interleave_sectors;
447 if (likely(ic->log2_metadata_run >= 0))
448 result += (area + 1) << ic->log2_metadata_run;
450 result += (area + 1) * ic->metadata_run;
452 result += (sector_t)ic->initial_sectors + offset;
458 static void wraparound_section(struct dm_integrity_c *ic, unsigned *sec_ptr)
460 if (unlikely(*sec_ptr >= ic->journal_sections))
461 *sec_ptr -= ic->journal_sections;
464 static void sb_set_version(struct dm_integrity_c *ic)
466 if (ic->mode == 'B' || ic->sb->flags & cpu_to_le32(SB_FLAG_DIRTY_BITMAP))
467 ic->sb->version = SB_VERSION_3;
468 else if (ic->meta_dev || ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
469 ic->sb->version = SB_VERSION_2;
471 ic->sb->version = SB_VERSION_1;
474 static int sync_rw_sb(struct dm_integrity_c *ic, int op, int op_flags)
476 struct dm_io_request io_req;
477 struct dm_io_region io_loc;
480 io_req.bi_op_flags = op_flags;
481 io_req.mem.type = DM_IO_KMEM;
482 io_req.mem.ptr.addr = ic->sb;
483 io_req.notify.fn = NULL;
484 io_req.client = ic->io;
485 io_loc.bdev = ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev;
486 io_loc.sector = ic->start;
487 io_loc.count = SB_SECTORS;
489 if (op == REQ_OP_WRITE)
492 return dm_io(&io_req, 1, &io_loc, NULL);
495 #define BITMAP_OP_TEST_ALL_SET 0
496 #define BITMAP_OP_TEST_ALL_CLEAR 1
497 #define BITMAP_OP_SET 2
498 #define BITMAP_OP_CLEAR 3
500 static bool block_bitmap_op(struct dm_integrity_c *ic, struct page_list *bitmap,
501 sector_t sector, sector_t n_sectors, int mode)
503 unsigned long bit, end_bit, this_end_bit, page, end_page;
506 if (unlikely(((sector | n_sectors) & ((1 << ic->sb->log2_sectors_per_block) - 1)) != 0)) {
507 DMCRIT("invalid bitmap access (%llx,%llx,%d,%d,%d)",
508 (unsigned long long)sector,
509 (unsigned long long)n_sectors,
510 ic->sb->log2_sectors_per_block,
511 ic->log2_blocks_per_bitmap_bit,
516 if (unlikely(!n_sectors))
519 bit = sector >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
520 end_bit = (sector + n_sectors - 1) >>
521 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
523 page = bit / (PAGE_SIZE * 8);
524 bit %= PAGE_SIZE * 8;
526 end_page = end_bit / (PAGE_SIZE * 8);
527 end_bit %= PAGE_SIZE * 8;
530 if (page < end_page) {
531 this_end_bit = PAGE_SIZE * 8 - 1;
533 this_end_bit = end_bit;
536 data = lowmem_page_address(bitmap[page].page);
538 if (mode == BITMAP_OP_TEST_ALL_SET) {
539 while (bit <= this_end_bit) {
540 if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
542 if (data[bit / BITS_PER_LONG] != -1)
544 bit += BITS_PER_LONG;
545 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
548 if (!test_bit(bit, data))
552 } else if (mode == BITMAP_OP_TEST_ALL_CLEAR) {
553 while (bit <= this_end_bit) {
554 if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
556 if (data[bit / BITS_PER_LONG] != 0)
558 bit += BITS_PER_LONG;
559 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
562 if (test_bit(bit, data))
566 } else if (mode == BITMAP_OP_SET) {
567 while (bit <= this_end_bit) {
568 if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
570 data[bit / BITS_PER_LONG] = -1;
571 bit += BITS_PER_LONG;
572 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
575 __set_bit(bit, data);
578 } else if (mode == BITMAP_OP_CLEAR) {
579 if (!bit && this_end_bit == PAGE_SIZE * 8 - 1)
581 else while (bit <= this_end_bit) {
582 if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
584 data[bit / BITS_PER_LONG] = 0;
585 bit += BITS_PER_LONG;
586 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
589 __clear_bit(bit, data);
596 if (unlikely(page < end_page)) {
605 static void block_bitmap_copy(struct dm_integrity_c *ic, struct page_list *dst, struct page_list *src)
607 unsigned n_bitmap_pages = DIV_ROUND_UP(ic->n_bitmap_blocks, PAGE_SIZE / BITMAP_BLOCK_SIZE);
610 for (i = 0; i < n_bitmap_pages; i++) {
611 unsigned long *dst_data = lowmem_page_address(dst[i].page);
612 unsigned long *src_data = lowmem_page_address(src[i].page);
613 copy_page(dst_data, src_data);
617 static struct bitmap_block_status *sector_to_bitmap_block(struct dm_integrity_c *ic, sector_t sector)
619 unsigned bit = sector >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
620 unsigned bitmap_block = bit / (BITMAP_BLOCK_SIZE * 8);
622 BUG_ON(bitmap_block >= ic->n_bitmap_blocks);
623 return &ic->bbs[bitmap_block];
626 static void access_journal_check(struct dm_integrity_c *ic, unsigned section, unsigned offset,
627 bool e, const char *function)
629 #if defined(CONFIG_DM_DEBUG) || defined(INTERNAL_VERIFY)
630 unsigned limit = e ? ic->journal_section_entries : ic->journal_section_sectors;
632 if (unlikely(section >= ic->journal_sections) ||
633 unlikely(offset >= limit)) {
634 DMCRIT("%s: invalid access at (%u,%u), limit (%u,%u)",
635 function, section, offset, ic->journal_sections, limit);
641 static void page_list_location(struct dm_integrity_c *ic, unsigned section, unsigned offset,
642 unsigned *pl_index, unsigned *pl_offset)
646 access_journal_check(ic, section, offset, false, "page_list_location");
648 sector = section * ic->journal_section_sectors + offset;
650 *pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
651 *pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
654 static struct journal_sector *access_page_list(struct dm_integrity_c *ic, struct page_list *pl,
655 unsigned section, unsigned offset, unsigned *n_sectors)
657 unsigned pl_index, pl_offset;
660 page_list_location(ic, section, offset, &pl_index, &pl_offset);
663 *n_sectors = (PAGE_SIZE - pl_offset) >> SECTOR_SHIFT;
665 va = lowmem_page_address(pl[pl_index].page);
667 return (struct journal_sector *)(va + pl_offset);
670 static struct journal_sector *access_journal(struct dm_integrity_c *ic, unsigned section, unsigned offset)
672 return access_page_list(ic, ic->journal, section, offset, NULL);
675 static struct journal_entry *access_journal_entry(struct dm_integrity_c *ic, unsigned section, unsigned n)
677 unsigned rel_sector, offset;
678 struct journal_sector *js;
680 access_journal_check(ic, section, n, true, "access_journal_entry");
682 rel_sector = n % JOURNAL_BLOCK_SECTORS;
683 offset = n / JOURNAL_BLOCK_SECTORS;
685 js = access_journal(ic, section, rel_sector);
686 return (struct journal_entry *)((char *)js + offset * ic->journal_entry_size);
689 static struct journal_sector *access_journal_data(struct dm_integrity_c *ic, unsigned section, unsigned n)
691 n <<= ic->sb->log2_sectors_per_block;
693 n += JOURNAL_BLOCK_SECTORS;
695 access_journal_check(ic, section, n, false, "access_journal_data");
697 return access_journal(ic, section, n);
700 static void section_mac(struct dm_integrity_c *ic, unsigned section, __u8 result[JOURNAL_MAC_SIZE])
702 SHASH_DESC_ON_STACK(desc, ic->journal_mac);
706 desc->tfm = ic->journal_mac;
708 r = crypto_shash_init(desc);
710 dm_integrity_io_error(ic, "crypto_shash_init", r);
714 for (j = 0; j < ic->journal_section_entries; j++) {
715 struct journal_entry *je = access_journal_entry(ic, section, j);
716 r = crypto_shash_update(desc, (__u8 *)&je->u.sector, sizeof je->u.sector);
718 dm_integrity_io_error(ic, "crypto_shash_update", r);
723 size = crypto_shash_digestsize(ic->journal_mac);
725 if (likely(size <= JOURNAL_MAC_SIZE)) {
726 r = crypto_shash_final(desc, result);
728 dm_integrity_io_error(ic, "crypto_shash_final", r);
731 memset(result + size, 0, JOURNAL_MAC_SIZE - size);
733 __u8 digest[HASH_MAX_DIGESTSIZE];
735 if (WARN_ON(size > sizeof(digest))) {
736 dm_integrity_io_error(ic, "digest_size", -EINVAL);
739 r = crypto_shash_final(desc, digest);
741 dm_integrity_io_error(ic, "crypto_shash_final", r);
744 memcpy(result, digest, JOURNAL_MAC_SIZE);
749 memset(result, 0, JOURNAL_MAC_SIZE);
752 static void rw_section_mac(struct dm_integrity_c *ic, unsigned section, bool wr)
754 __u8 result[JOURNAL_MAC_SIZE];
757 if (!ic->journal_mac)
760 section_mac(ic, section, result);
762 for (j = 0; j < JOURNAL_BLOCK_SECTORS; j++) {
763 struct journal_sector *js = access_journal(ic, section, j);
766 memcpy(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR);
768 if (memcmp(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR))
769 dm_integrity_io_error(ic, "journal mac", -EILSEQ);
774 static void complete_journal_op(void *context)
776 struct journal_completion *comp = context;
777 BUG_ON(!atomic_read(&comp->in_flight));
778 if (likely(atomic_dec_and_test(&comp->in_flight)))
779 complete(&comp->comp);
782 static void xor_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
783 unsigned n_sections, struct journal_completion *comp)
785 struct async_submit_ctl submit;
786 size_t n_bytes = (size_t)(n_sections * ic->journal_section_sectors) << SECTOR_SHIFT;
787 unsigned pl_index, pl_offset, section_index;
788 struct page_list *source_pl, *target_pl;
790 if (likely(encrypt)) {
791 source_pl = ic->journal;
792 target_pl = ic->journal_io;
794 source_pl = ic->journal_io;
795 target_pl = ic->journal;
798 page_list_location(ic, section, 0, &pl_index, &pl_offset);
800 atomic_add(roundup(pl_offset + n_bytes, PAGE_SIZE) >> PAGE_SHIFT, &comp->in_flight);
802 init_async_submit(&submit, ASYNC_TX_XOR_ZERO_DST, NULL, complete_journal_op, comp, NULL);
804 section_index = pl_index;
808 struct page *src_pages[2];
809 struct page *dst_page;
811 while (unlikely(pl_index == section_index)) {
814 rw_section_mac(ic, section, true);
819 page_list_location(ic, section, 0, §ion_index, &dummy);
822 this_step = min(n_bytes, (size_t)PAGE_SIZE - pl_offset);
823 dst_page = target_pl[pl_index].page;
824 src_pages[0] = source_pl[pl_index].page;
825 src_pages[1] = ic->journal_xor[pl_index].page;
827 async_xor(dst_page, src_pages, pl_offset, 2, this_step, &submit);
831 n_bytes -= this_step;
836 async_tx_issue_pending_all();
839 static void complete_journal_encrypt(struct crypto_async_request *req, int err)
841 struct journal_completion *comp = req->data;
843 if (likely(err == -EINPROGRESS)) {
844 complete(&comp->ic->crypto_backoff);
847 dm_integrity_io_error(comp->ic, "asynchronous encrypt", err);
849 complete_journal_op(comp);
852 static bool do_crypt(bool encrypt, struct skcipher_request *req, struct journal_completion *comp)
855 skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
856 complete_journal_encrypt, comp);
858 r = crypto_skcipher_encrypt(req);
860 r = crypto_skcipher_decrypt(req);
863 if (likely(r == -EINPROGRESS))
865 if (likely(r == -EBUSY)) {
866 wait_for_completion(&comp->ic->crypto_backoff);
867 reinit_completion(&comp->ic->crypto_backoff);
870 dm_integrity_io_error(comp->ic, "encrypt", r);
874 static void crypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
875 unsigned n_sections, struct journal_completion *comp)
877 struct scatterlist **source_sg;
878 struct scatterlist **target_sg;
880 atomic_add(2, &comp->in_flight);
882 if (likely(encrypt)) {
883 source_sg = ic->journal_scatterlist;
884 target_sg = ic->journal_io_scatterlist;
886 source_sg = ic->journal_io_scatterlist;
887 target_sg = ic->journal_scatterlist;
891 struct skcipher_request *req;
896 rw_section_mac(ic, section, true);
898 req = ic->sk_requests[section];
899 ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
902 memcpy(iv, iv + ivsize, ivsize);
904 req->src = source_sg[section];
905 req->dst = target_sg[section];
907 if (unlikely(do_crypt(encrypt, req, comp)))
908 atomic_inc(&comp->in_flight);
912 } while (n_sections);
914 atomic_dec(&comp->in_flight);
915 complete_journal_op(comp);
918 static void encrypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
919 unsigned n_sections, struct journal_completion *comp)
922 return xor_journal(ic, encrypt, section, n_sections, comp);
924 return crypt_journal(ic, encrypt, section, n_sections, comp);
927 static void complete_journal_io(unsigned long error, void *context)
929 struct journal_completion *comp = context;
930 if (unlikely(error != 0))
931 dm_integrity_io_error(comp->ic, "writing journal", -EIO);
932 complete_journal_op(comp);
935 static void rw_journal_sectors(struct dm_integrity_c *ic, int op, int op_flags,
936 unsigned sector, unsigned n_sectors, struct journal_completion *comp)
938 struct dm_io_request io_req;
939 struct dm_io_region io_loc;
940 unsigned pl_index, pl_offset;
943 if (unlikely(dm_integrity_failed(ic))) {
945 complete_journal_io(-1UL, comp);
949 pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
950 pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
953 io_req.bi_op_flags = op_flags;
954 io_req.mem.type = DM_IO_PAGE_LIST;
956 io_req.mem.ptr.pl = &ic->journal_io[pl_index];
958 io_req.mem.ptr.pl = &ic->journal[pl_index];
959 io_req.mem.offset = pl_offset;
960 if (likely(comp != NULL)) {
961 io_req.notify.fn = complete_journal_io;
962 io_req.notify.context = comp;
964 io_req.notify.fn = NULL;
966 io_req.client = ic->io;
967 io_loc.bdev = ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev;
968 io_loc.sector = ic->start + SB_SECTORS + sector;
969 io_loc.count = n_sectors;
971 r = dm_io(&io_req, 1, &io_loc, NULL);
973 dm_integrity_io_error(ic, op == REQ_OP_READ ? "reading journal" : "writing journal", r);
975 WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
976 complete_journal_io(-1UL, comp);
981 static void rw_journal(struct dm_integrity_c *ic, int op, int op_flags, unsigned section,
982 unsigned n_sections, struct journal_completion *comp)
984 unsigned sector, n_sectors;
986 sector = section * ic->journal_section_sectors;
987 n_sectors = n_sections * ic->journal_section_sectors;
989 rw_journal_sectors(ic, op, op_flags, sector, n_sectors, comp);
992 static void write_journal(struct dm_integrity_c *ic, unsigned commit_start, unsigned commit_sections)
994 struct journal_completion io_comp;
995 struct journal_completion crypt_comp_1;
996 struct journal_completion crypt_comp_2;
1000 init_completion(&io_comp.comp);
1002 if (commit_start + commit_sections <= ic->journal_sections) {
1003 io_comp.in_flight = (atomic_t)ATOMIC_INIT(1);
1004 if (ic->journal_io) {
1005 crypt_comp_1.ic = ic;
1006 init_completion(&crypt_comp_1.comp);
1007 crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
1008 encrypt_journal(ic, true, commit_start, commit_sections, &crypt_comp_1);
1009 wait_for_completion_io(&crypt_comp_1.comp);
1011 for (i = 0; i < commit_sections; i++)
1012 rw_section_mac(ic, commit_start + i, true);
1014 rw_journal(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, commit_start,
1015 commit_sections, &io_comp);
1018 io_comp.in_flight = (atomic_t)ATOMIC_INIT(2);
1019 to_end = ic->journal_sections - commit_start;
1020 if (ic->journal_io) {
1021 crypt_comp_1.ic = ic;
1022 init_completion(&crypt_comp_1.comp);
1023 crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
1024 encrypt_journal(ic, true, commit_start, to_end, &crypt_comp_1);
1025 if (try_wait_for_completion(&crypt_comp_1.comp)) {
1026 rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
1027 reinit_completion(&crypt_comp_1.comp);
1028 crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
1029 encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_1);
1030 wait_for_completion_io(&crypt_comp_1.comp);
1032 crypt_comp_2.ic = ic;
1033 init_completion(&crypt_comp_2.comp);
1034 crypt_comp_2.in_flight = (atomic_t)ATOMIC_INIT(0);
1035 encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_2);
1036 wait_for_completion_io(&crypt_comp_1.comp);
1037 rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
1038 wait_for_completion_io(&crypt_comp_2.comp);
1041 for (i = 0; i < to_end; i++)
1042 rw_section_mac(ic, commit_start + i, true);
1043 rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
1044 for (i = 0; i < commit_sections - to_end; i++)
1045 rw_section_mac(ic, i, true);
1047 rw_journal(ic, REQ_OP_WRITE, REQ_FUA, 0, commit_sections - to_end, &io_comp);
1050 wait_for_completion_io(&io_comp.comp);
1053 static void copy_from_journal(struct dm_integrity_c *ic, unsigned section, unsigned offset,
1054 unsigned n_sectors, sector_t target, io_notify_fn fn, void *data)
1056 struct dm_io_request io_req;
1057 struct dm_io_region io_loc;
1059 unsigned sector, pl_index, pl_offset;
1061 BUG_ON((target | n_sectors | offset) & (unsigned)(ic->sectors_per_block - 1));
1063 if (unlikely(dm_integrity_failed(ic))) {
1068 sector = section * ic->journal_section_sectors + JOURNAL_BLOCK_SECTORS + offset;
1070 pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
1071 pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
1073 io_req.bi_op = REQ_OP_WRITE;
1074 io_req.bi_op_flags = 0;
1075 io_req.mem.type = DM_IO_PAGE_LIST;
1076 io_req.mem.ptr.pl = &ic->journal[pl_index];
1077 io_req.mem.offset = pl_offset;
1078 io_req.notify.fn = fn;
1079 io_req.notify.context = data;
1080 io_req.client = ic->io;
1081 io_loc.bdev = ic->dev->bdev;
1082 io_loc.sector = target;
1083 io_loc.count = n_sectors;
1085 r = dm_io(&io_req, 1, &io_loc, NULL);
1087 WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
1092 static bool ranges_overlap(struct dm_integrity_range *range1, struct dm_integrity_range *range2)
1094 return range1->logical_sector < range2->logical_sector + range2->n_sectors &&
1095 range1->logical_sector + range1->n_sectors > range2->logical_sector;
1098 static bool add_new_range(struct dm_integrity_c *ic, struct dm_integrity_range *new_range, bool check_waiting)
1100 struct rb_node **n = &ic->in_progress.rb_node;
1101 struct rb_node *parent;
1103 BUG_ON((new_range->logical_sector | new_range->n_sectors) & (unsigned)(ic->sectors_per_block - 1));
1105 if (likely(check_waiting)) {
1106 struct dm_integrity_range *range;
1107 list_for_each_entry(range, &ic->wait_list, wait_entry) {
1108 if (unlikely(ranges_overlap(range, new_range)))
1116 struct dm_integrity_range *range = container_of(*n, struct dm_integrity_range, node);
1119 if (new_range->logical_sector + new_range->n_sectors <= range->logical_sector) {
1120 n = &range->node.rb_left;
1121 } else if (new_range->logical_sector >= range->logical_sector + range->n_sectors) {
1122 n = &range->node.rb_right;
1128 rb_link_node(&new_range->node, parent, n);
1129 rb_insert_color(&new_range->node, &ic->in_progress);
1134 static void remove_range_unlocked(struct dm_integrity_c *ic, struct dm_integrity_range *range)
1136 rb_erase(&range->node, &ic->in_progress);
1137 while (unlikely(!list_empty(&ic->wait_list))) {
1138 struct dm_integrity_range *last_range =
1139 list_first_entry(&ic->wait_list, struct dm_integrity_range, wait_entry);
1140 struct task_struct *last_range_task;
1141 last_range_task = last_range->task;
1142 list_del(&last_range->wait_entry);
1143 if (!add_new_range(ic, last_range, false)) {
1144 last_range->task = last_range_task;
1145 list_add(&last_range->wait_entry, &ic->wait_list);
1148 last_range->waiting = false;
1149 wake_up_process(last_range_task);
1153 static void remove_range(struct dm_integrity_c *ic, struct dm_integrity_range *range)
1155 unsigned long flags;
1157 spin_lock_irqsave(&ic->endio_wait.lock, flags);
1158 remove_range_unlocked(ic, range);
1159 spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1162 static void wait_and_add_new_range(struct dm_integrity_c *ic, struct dm_integrity_range *new_range)
1164 new_range->waiting = true;
1165 list_add_tail(&new_range->wait_entry, &ic->wait_list);
1166 new_range->task = current;
1168 __set_current_state(TASK_UNINTERRUPTIBLE);
1169 spin_unlock_irq(&ic->endio_wait.lock);
1171 spin_lock_irq(&ic->endio_wait.lock);
1172 } while (unlikely(new_range->waiting));
1175 static void add_new_range_and_wait(struct dm_integrity_c *ic, struct dm_integrity_range *new_range)
1177 if (unlikely(!add_new_range(ic, new_range, true)))
1178 wait_and_add_new_range(ic, new_range);
1181 static void init_journal_node(struct journal_node *node)
1183 RB_CLEAR_NODE(&node->node);
1184 node->sector = (sector_t)-1;
1187 static void add_journal_node(struct dm_integrity_c *ic, struct journal_node *node, sector_t sector)
1189 struct rb_node **link;
1190 struct rb_node *parent;
1192 node->sector = sector;
1193 BUG_ON(!RB_EMPTY_NODE(&node->node));
1195 link = &ic->journal_tree_root.rb_node;
1199 struct journal_node *j;
1201 j = container_of(parent, struct journal_node, node);
1202 if (sector < j->sector)
1203 link = &j->node.rb_left;
1205 link = &j->node.rb_right;
1208 rb_link_node(&node->node, parent, link);
1209 rb_insert_color(&node->node, &ic->journal_tree_root);
1212 static void remove_journal_node(struct dm_integrity_c *ic, struct journal_node *node)
1214 BUG_ON(RB_EMPTY_NODE(&node->node));
1215 rb_erase(&node->node, &ic->journal_tree_root);
1216 init_journal_node(node);
1219 #define NOT_FOUND (-1U)
1221 static unsigned find_journal_node(struct dm_integrity_c *ic, sector_t sector, sector_t *next_sector)
1223 struct rb_node *n = ic->journal_tree_root.rb_node;
1224 unsigned found = NOT_FOUND;
1225 *next_sector = (sector_t)-1;
1227 struct journal_node *j = container_of(n, struct journal_node, node);
1228 if (sector == j->sector) {
1229 found = j - ic->journal_tree;
1231 if (sector < j->sector) {
1232 *next_sector = j->sector;
1233 n = j->node.rb_left;
1235 n = j->node.rb_right;
1242 static bool test_journal_node(struct dm_integrity_c *ic, unsigned pos, sector_t sector)
1244 struct journal_node *node, *next_node;
1245 struct rb_node *next;
1247 if (unlikely(pos >= ic->journal_entries))
1249 node = &ic->journal_tree[pos];
1250 if (unlikely(RB_EMPTY_NODE(&node->node)))
1252 if (unlikely(node->sector != sector))
1255 next = rb_next(&node->node);
1256 if (unlikely(!next))
1259 next_node = container_of(next, struct journal_node, node);
1260 return next_node->sector != sector;
1263 static bool find_newer_committed_node(struct dm_integrity_c *ic, struct journal_node *node)
1265 struct rb_node *next;
1266 struct journal_node *next_node;
1267 unsigned next_section;
1269 BUG_ON(RB_EMPTY_NODE(&node->node));
1271 next = rb_next(&node->node);
1272 if (unlikely(!next))
1275 next_node = container_of(next, struct journal_node, node);
1277 if (next_node->sector != node->sector)
1280 next_section = (unsigned)(next_node - ic->journal_tree) / ic->journal_section_entries;
1281 if (next_section >= ic->committed_section &&
1282 next_section < ic->committed_section + ic->n_committed_sections)
1284 if (next_section + ic->journal_sections < ic->committed_section + ic->n_committed_sections)
1294 static int dm_integrity_rw_tag(struct dm_integrity_c *ic, unsigned char *tag, sector_t *metadata_block,
1295 unsigned *metadata_offset, unsigned total_size, int op)
1298 unsigned char *data, *dp;
1299 struct dm_buffer *b;
1303 r = dm_integrity_failed(ic);
1307 data = dm_bufio_read(ic->bufio, *metadata_block, &b);
1309 return PTR_ERR(data);
1311 to_copy = min((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - *metadata_offset, total_size);
1312 dp = data + *metadata_offset;
1313 if (op == TAG_READ) {
1314 memcpy(tag, dp, to_copy);
1315 } else if (op == TAG_WRITE) {
1316 memcpy(dp, tag, to_copy);
1317 dm_bufio_mark_partial_buffer_dirty(b, *metadata_offset, *metadata_offset + to_copy);
1319 /* e.g.: op == TAG_CMP */
1320 if (unlikely(memcmp(dp, tag, to_copy))) {
1323 for (i = 0; i < to_copy; i++) {
1324 if (dp[i] != tag[i])
1328 dm_bufio_release(b);
1332 dm_bufio_release(b);
1335 *metadata_offset += to_copy;
1336 if (unlikely(*metadata_offset == 1U << SECTOR_SHIFT << ic->log2_buffer_sectors)) {
1337 (*metadata_block)++;
1338 *metadata_offset = 0;
1340 total_size -= to_copy;
1341 } while (unlikely(total_size));
1346 static void dm_integrity_flush_buffers(struct dm_integrity_c *ic)
1349 r = dm_bufio_write_dirty_buffers(ic->bufio);
1351 dm_integrity_io_error(ic, "writing tags", r);
1354 static void sleep_on_endio_wait(struct dm_integrity_c *ic)
1356 DECLARE_WAITQUEUE(wait, current);
1357 __add_wait_queue(&ic->endio_wait, &wait);
1358 __set_current_state(TASK_UNINTERRUPTIBLE);
1359 spin_unlock_irq(&ic->endio_wait.lock);
1361 spin_lock_irq(&ic->endio_wait.lock);
1362 __remove_wait_queue(&ic->endio_wait, &wait);
1365 static void autocommit_fn(struct timer_list *t)
1367 struct dm_integrity_c *ic = from_timer(ic, t, autocommit_timer);
1369 if (likely(!dm_integrity_failed(ic)))
1370 queue_work(ic->commit_wq, &ic->commit_work);
1373 static void schedule_autocommit(struct dm_integrity_c *ic)
1375 if (!timer_pending(&ic->autocommit_timer))
1376 mod_timer(&ic->autocommit_timer, jiffies + ic->autocommit_jiffies);
1379 static void submit_flush_bio(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
1382 unsigned long flags;
1384 spin_lock_irqsave(&ic->endio_wait.lock, flags);
1385 bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1386 bio_list_add(&ic->flush_bio_list, bio);
1387 spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1389 queue_work(ic->commit_wq, &ic->commit_work);
1392 static void do_endio(struct dm_integrity_c *ic, struct bio *bio)
1394 int r = dm_integrity_failed(ic);
1395 if (unlikely(r) && !bio->bi_status)
1396 bio->bi_status = errno_to_blk_status(r);
1397 if (unlikely(ic->synchronous_mode) && bio_op(bio) == REQ_OP_WRITE) {
1398 unsigned long flags;
1399 spin_lock_irqsave(&ic->endio_wait.lock, flags);
1400 bio_list_add(&ic->synchronous_bios, bio);
1401 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
1402 spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1408 static void do_endio_flush(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
1410 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1412 if (unlikely(dio->fua) && likely(!bio->bi_status) && likely(!dm_integrity_failed(ic)))
1413 submit_flush_bio(ic, dio);
1418 static void dec_in_flight(struct dm_integrity_io *dio)
1420 if (atomic_dec_and_test(&dio->in_flight)) {
1421 struct dm_integrity_c *ic = dio->ic;
1424 remove_range(ic, &dio->range);
1426 if (unlikely(dio->write))
1427 schedule_autocommit(ic);
1429 bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1431 if (unlikely(dio->bi_status) && !bio->bi_status)
1432 bio->bi_status = dio->bi_status;
1433 if (likely(!bio->bi_status) && unlikely(bio_sectors(bio) != dio->range.n_sectors)) {
1434 dio->range.logical_sector += dio->range.n_sectors;
1435 bio_advance(bio, dio->range.n_sectors << SECTOR_SHIFT);
1436 INIT_WORK(&dio->work, integrity_bio_wait);
1437 queue_work(ic->wait_wq, &dio->work);
1440 do_endio_flush(ic, dio);
1444 static void integrity_end_io(struct bio *bio)
1446 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
1448 bio->bi_iter = dio->orig_bi_iter;
1449 bio->bi_disk = dio->orig_bi_disk;
1450 bio->bi_partno = dio->orig_bi_partno;
1451 if (dio->orig_bi_integrity) {
1452 bio->bi_integrity = dio->orig_bi_integrity;
1453 bio->bi_opf |= REQ_INTEGRITY;
1455 bio->bi_end_io = dio->orig_bi_end_io;
1457 if (dio->completion)
1458 complete(dio->completion);
1463 static void integrity_sector_checksum(struct dm_integrity_c *ic, sector_t sector,
1464 const char *data, char *result)
1466 __u64 sector_le = cpu_to_le64(sector);
1467 SHASH_DESC_ON_STACK(req, ic->internal_hash);
1469 unsigned digest_size;
1471 req->tfm = ic->internal_hash;
1473 r = crypto_shash_init(req);
1474 if (unlikely(r < 0)) {
1475 dm_integrity_io_error(ic, "crypto_shash_init", r);
1479 r = crypto_shash_update(req, (const __u8 *)§or_le, sizeof sector_le);
1480 if (unlikely(r < 0)) {
1481 dm_integrity_io_error(ic, "crypto_shash_update", r);
1485 r = crypto_shash_update(req, data, ic->sectors_per_block << SECTOR_SHIFT);
1486 if (unlikely(r < 0)) {
1487 dm_integrity_io_error(ic, "crypto_shash_update", r);
1491 r = crypto_shash_final(req, result);
1492 if (unlikely(r < 0)) {
1493 dm_integrity_io_error(ic, "crypto_shash_final", r);
1497 digest_size = crypto_shash_digestsize(ic->internal_hash);
1498 if (unlikely(digest_size < ic->tag_size))
1499 memset(result + digest_size, 0, ic->tag_size - digest_size);
1504 /* this shouldn't happen anyway, the hash functions have no reason to fail */
1505 get_random_bytes(result, ic->tag_size);
1508 static void integrity_metadata(struct work_struct *w)
1510 struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
1511 struct dm_integrity_c *ic = dio->ic;
1515 if (ic->internal_hash) {
1516 struct bvec_iter iter;
1518 unsigned digest_size = crypto_shash_digestsize(ic->internal_hash);
1519 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1521 unsigned extra_space = unlikely(digest_size > ic->tag_size) ? digest_size - ic->tag_size : 0;
1522 char checksums_onstack[HASH_MAX_DIGESTSIZE];
1523 unsigned sectors_to_process = dio->range.n_sectors;
1524 sector_t sector = dio->range.logical_sector;
1526 if (unlikely(ic->mode == 'R'))
1529 checksums = kmalloc((PAGE_SIZE >> SECTOR_SHIFT >> ic->sb->log2_sectors_per_block) * ic->tag_size + extra_space,
1530 GFP_NOIO | __GFP_NORETRY | __GFP_NOWARN);
1532 checksums = checksums_onstack;
1533 if (WARN_ON(extra_space &&
1534 digest_size > sizeof(checksums_onstack))) {
1540 __bio_for_each_segment(bv, bio, iter, dio->orig_bi_iter) {
1542 char *mem, *checksums_ptr;
1545 mem = (char *)kmap_atomic(bv.bv_page) + bv.bv_offset;
1547 checksums_ptr = checksums;
1549 integrity_sector_checksum(ic, sector, mem + pos, checksums_ptr);
1550 checksums_ptr += ic->tag_size;
1551 sectors_to_process -= ic->sectors_per_block;
1552 pos += ic->sectors_per_block << SECTOR_SHIFT;
1553 sector += ic->sectors_per_block;
1554 } while (pos < bv.bv_len && sectors_to_process && checksums != checksums_onstack);
1557 r = dm_integrity_rw_tag(ic, checksums, &dio->metadata_block, &dio->metadata_offset,
1558 checksums_ptr - checksums, !dio->write ? TAG_CMP : TAG_WRITE);
1561 DMERR_LIMIT("Checksum failed at sector 0x%llx",
1562 (unsigned long long)(sector - ((r + ic->tag_size - 1) / ic->tag_size)));
1564 atomic64_inc(&ic->number_of_mismatches);
1566 if (likely(checksums != checksums_onstack))
1571 if (!sectors_to_process)
1574 if (unlikely(pos < bv.bv_len)) {
1575 bv.bv_offset += pos;
1581 if (likely(checksums != checksums_onstack))
1584 struct bio_integrity_payload *bip = dio->orig_bi_integrity;
1588 struct bvec_iter iter;
1589 unsigned data_to_process = dio->range.n_sectors;
1590 sector_to_block(ic, data_to_process);
1591 data_to_process *= ic->tag_size;
1593 bip_for_each_vec(biv, bip, iter) {
1597 BUG_ON(PageHighMem(biv.bv_page));
1598 tag = lowmem_page_address(biv.bv_page) + biv.bv_offset;
1599 this_len = min(biv.bv_len, data_to_process);
1600 r = dm_integrity_rw_tag(ic, tag, &dio->metadata_block, &dio->metadata_offset,
1601 this_len, !dio->write ? TAG_READ : TAG_WRITE);
1604 data_to_process -= this_len;
1605 if (!data_to_process)
1614 dio->bi_status = errno_to_blk_status(r);
1618 static int dm_integrity_map(struct dm_target *ti, struct bio *bio)
1620 struct dm_integrity_c *ic = ti->private;
1621 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
1622 struct bio_integrity_payload *bip;
1624 sector_t area, offset;
1629 if (unlikely(bio->bi_opf & REQ_PREFLUSH)) {
1630 submit_flush_bio(ic, dio);
1631 return DM_MAPIO_SUBMITTED;
1634 dio->range.logical_sector = dm_target_offset(ti, bio->bi_iter.bi_sector);
1635 dio->write = bio_op(bio) == REQ_OP_WRITE;
1636 dio->fua = dio->write && bio->bi_opf & REQ_FUA;
1637 if (unlikely(dio->fua)) {
1639 * Don't pass down the FUA flag because we have to flush
1640 * disk cache anyway.
1642 bio->bi_opf &= ~REQ_FUA;
1644 if (unlikely(dio->range.logical_sector + bio_sectors(bio) > ic->provided_data_sectors)) {
1645 DMERR("Too big sector number: 0x%llx + 0x%x > 0x%llx",
1646 (unsigned long long)dio->range.logical_sector, bio_sectors(bio),
1647 (unsigned long long)ic->provided_data_sectors);
1648 return DM_MAPIO_KILL;
1650 if (unlikely((dio->range.logical_sector | bio_sectors(bio)) & (unsigned)(ic->sectors_per_block - 1))) {
1651 DMERR("Bio not aligned on %u sectors: 0x%llx, 0x%x",
1652 ic->sectors_per_block,
1653 (unsigned long long)dio->range.logical_sector, bio_sectors(bio));
1654 return DM_MAPIO_KILL;
1657 if (ic->sectors_per_block > 1) {
1658 struct bvec_iter iter;
1660 bio_for_each_segment(bv, bio, iter) {
1661 if (unlikely(bv.bv_len & ((ic->sectors_per_block << SECTOR_SHIFT) - 1))) {
1662 DMERR("Bio vector (%u,%u) is not aligned on %u-sector boundary",
1663 bv.bv_offset, bv.bv_len, ic->sectors_per_block);
1664 return DM_MAPIO_KILL;
1669 bip = bio_integrity(bio);
1670 if (!ic->internal_hash) {
1672 unsigned wanted_tag_size = bio_sectors(bio) >> ic->sb->log2_sectors_per_block;
1673 if (ic->log2_tag_size >= 0)
1674 wanted_tag_size <<= ic->log2_tag_size;
1676 wanted_tag_size *= ic->tag_size;
1677 if (unlikely(wanted_tag_size != bip->bip_iter.bi_size)) {
1678 DMERR("Invalid integrity data size %u, expected %u",
1679 bip->bip_iter.bi_size, wanted_tag_size);
1680 return DM_MAPIO_KILL;
1684 if (unlikely(bip != NULL)) {
1685 DMERR("Unexpected integrity data when using internal hash");
1686 return DM_MAPIO_KILL;
1690 if (unlikely(ic->mode == 'R') && unlikely(dio->write))
1691 return DM_MAPIO_KILL;
1693 get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
1694 dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
1695 bio->bi_iter.bi_sector = get_data_sector(ic, area, offset);
1697 dm_integrity_map_continue(dio, true);
1698 return DM_MAPIO_SUBMITTED;
1701 static bool __journal_read_write(struct dm_integrity_io *dio, struct bio *bio,
1702 unsigned journal_section, unsigned journal_entry)
1704 struct dm_integrity_c *ic = dio->ic;
1705 sector_t logical_sector;
1708 logical_sector = dio->range.logical_sector;
1709 n_sectors = dio->range.n_sectors;
1711 struct bio_vec bv = bio_iovec(bio);
1714 if (unlikely(bv.bv_len >> SECTOR_SHIFT > n_sectors))
1715 bv.bv_len = n_sectors << SECTOR_SHIFT;
1716 n_sectors -= bv.bv_len >> SECTOR_SHIFT;
1717 bio_advance_iter(bio, &bio->bi_iter, bv.bv_len);
1719 mem = kmap_atomic(bv.bv_page);
1720 if (likely(dio->write))
1721 flush_dcache_page(bv.bv_page);
1724 struct journal_entry *je = access_journal_entry(ic, journal_section, journal_entry);
1726 if (unlikely(!dio->write)) {
1727 struct journal_sector *js;
1731 if (unlikely(journal_entry_is_inprogress(je))) {
1732 flush_dcache_page(bv.bv_page);
1735 __io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
1739 BUG_ON(journal_entry_get_sector(je) != logical_sector);
1740 js = access_journal_data(ic, journal_section, journal_entry);
1741 mem_ptr = mem + bv.bv_offset;
1744 memcpy(mem_ptr, js, JOURNAL_SECTOR_DATA);
1745 *(commit_id_t *)(mem_ptr + JOURNAL_SECTOR_DATA) = je->last_bytes[s];
1747 mem_ptr += 1 << SECTOR_SHIFT;
1748 } while (++s < ic->sectors_per_block);
1749 #ifdef INTERNAL_VERIFY
1750 if (ic->internal_hash) {
1751 char checksums_onstack[max(HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
1753 integrity_sector_checksum(ic, logical_sector, mem + bv.bv_offset, checksums_onstack);
1754 if (unlikely(memcmp(checksums_onstack, journal_entry_tag(ic, je), ic->tag_size))) {
1755 DMERR_LIMIT("Checksum failed when reading from journal, at sector 0x%llx",
1756 (unsigned long long)logical_sector);
1762 if (!ic->internal_hash) {
1763 struct bio_integrity_payload *bip = bio_integrity(bio);
1764 unsigned tag_todo = ic->tag_size;
1765 char *tag_ptr = journal_entry_tag(ic, je);
1768 struct bio_vec biv = bvec_iter_bvec(bip->bip_vec, bip->bip_iter);
1769 unsigned tag_now = min(biv.bv_len, tag_todo);
1771 BUG_ON(PageHighMem(biv.bv_page));
1772 tag_addr = lowmem_page_address(biv.bv_page) + biv.bv_offset;
1773 if (likely(dio->write))
1774 memcpy(tag_ptr, tag_addr, tag_now);
1776 memcpy(tag_addr, tag_ptr, tag_now);
1777 bvec_iter_advance(bip->bip_vec, &bip->bip_iter, tag_now);
1779 tag_todo -= tag_now;
1780 } while (unlikely(tag_todo)); else {
1781 if (likely(dio->write))
1782 memset(tag_ptr, 0, tag_todo);
1786 if (likely(dio->write)) {
1787 struct journal_sector *js;
1790 js = access_journal_data(ic, journal_section, journal_entry);
1791 memcpy(js, mem + bv.bv_offset, ic->sectors_per_block << SECTOR_SHIFT);
1795 je->last_bytes[s] = js[s].commit_id;
1796 } while (++s < ic->sectors_per_block);
1798 if (ic->internal_hash) {
1799 unsigned digest_size = crypto_shash_digestsize(ic->internal_hash);
1800 if (unlikely(digest_size > ic->tag_size)) {
1801 char checksums_onstack[HASH_MAX_DIGESTSIZE];
1802 integrity_sector_checksum(ic, logical_sector, (char *)js, checksums_onstack);
1803 memcpy(journal_entry_tag(ic, je), checksums_onstack, ic->tag_size);
1805 integrity_sector_checksum(ic, logical_sector, (char *)js, journal_entry_tag(ic, je));
1808 journal_entry_set_sector(je, logical_sector);
1810 logical_sector += ic->sectors_per_block;
1813 if (unlikely(journal_entry == ic->journal_section_entries)) {
1816 wraparound_section(ic, &journal_section);
1819 bv.bv_offset += ic->sectors_per_block << SECTOR_SHIFT;
1820 } while (bv.bv_len -= ic->sectors_per_block << SECTOR_SHIFT);
1822 if (unlikely(!dio->write))
1823 flush_dcache_page(bv.bv_page);
1825 } while (n_sectors);
1827 if (likely(dio->write)) {
1829 if (unlikely(waitqueue_active(&ic->copy_to_journal_wait)))
1830 wake_up(&ic->copy_to_journal_wait);
1831 if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold) {
1832 queue_work(ic->commit_wq, &ic->commit_work);
1834 schedule_autocommit(ic);
1837 remove_range(ic, &dio->range);
1840 if (unlikely(bio->bi_iter.bi_size)) {
1841 sector_t area, offset;
1843 dio->range.logical_sector = logical_sector;
1844 get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
1845 dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
1852 static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map)
1854 struct dm_integrity_c *ic = dio->ic;
1855 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1856 unsigned journal_section, journal_entry;
1857 unsigned journal_read_pos;
1858 struct completion read_comp;
1859 bool need_sync_io = ic->internal_hash && !dio->write;
1861 if (need_sync_io && from_map) {
1862 INIT_WORK(&dio->work, integrity_bio_wait);
1863 queue_work(ic->metadata_wq, &dio->work);
1868 spin_lock_irq(&ic->endio_wait.lock);
1870 if (unlikely(dm_integrity_failed(ic))) {
1871 spin_unlock_irq(&ic->endio_wait.lock);
1875 dio->range.n_sectors = bio_sectors(bio);
1876 journal_read_pos = NOT_FOUND;
1877 if (likely(ic->mode == 'J')) {
1879 unsigned next_entry, i, pos;
1880 unsigned ws, we, range_sectors;
1882 dio->range.n_sectors = min(dio->range.n_sectors,
1883 (sector_t)ic->free_sectors << ic->sb->log2_sectors_per_block);
1884 if (unlikely(!dio->range.n_sectors)) {
1886 goto offload_to_thread;
1887 sleep_on_endio_wait(ic);
1890 range_sectors = dio->range.n_sectors >> ic->sb->log2_sectors_per_block;
1891 ic->free_sectors -= range_sectors;
1892 journal_section = ic->free_section;
1893 journal_entry = ic->free_section_entry;
1895 next_entry = ic->free_section_entry + range_sectors;
1896 ic->free_section_entry = next_entry % ic->journal_section_entries;
1897 ic->free_section += next_entry / ic->journal_section_entries;
1898 ic->n_uncommitted_sections += next_entry / ic->journal_section_entries;
1899 wraparound_section(ic, &ic->free_section);
1901 pos = journal_section * ic->journal_section_entries + journal_entry;
1902 ws = journal_section;
1906 struct journal_entry *je;
1908 add_journal_node(ic, &ic->journal_tree[pos], dio->range.logical_sector + i);
1910 if (unlikely(pos >= ic->journal_entries))
1913 je = access_journal_entry(ic, ws, we);
1914 BUG_ON(!journal_entry_is_unused(je));
1915 journal_entry_set_inprogress(je);
1917 if (unlikely(we == ic->journal_section_entries)) {
1920 wraparound_section(ic, &ws);
1922 } while ((i += ic->sectors_per_block) < dio->range.n_sectors);
1924 spin_unlock_irq(&ic->endio_wait.lock);
1925 goto journal_read_write;
1927 sector_t next_sector;
1928 journal_read_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
1929 if (likely(journal_read_pos == NOT_FOUND)) {
1930 if (unlikely(dio->range.n_sectors > next_sector - dio->range.logical_sector))
1931 dio->range.n_sectors = next_sector - dio->range.logical_sector;
1934 unsigned jp = journal_read_pos + 1;
1935 for (i = ic->sectors_per_block; i < dio->range.n_sectors; i += ic->sectors_per_block, jp++) {
1936 if (!test_journal_node(ic, jp, dio->range.logical_sector + i))
1939 dio->range.n_sectors = i;
1943 if (unlikely(!add_new_range(ic, &dio->range, true))) {
1945 * We must not sleep in the request routine because it could
1946 * stall bios on current->bio_list.
1947 * So, we offload the bio to a workqueue if we have to sleep.
1951 spin_unlock_irq(&ic->endio_wait.lock);
1952 INIT_WORK(&dio->work, integrity_bio_wait);
1953 queue_work(ic->wait_wq, &dio->work);
1956 if (journal_read_pos != NOT_FOUND)
1957 dio->range.n_sectors = ic->sectors_per_block;
1958 wait_and_add_new_range(ic, &dio->range);
1960 * wait_and_add_new_range drops the spinlock, so the journal
1961 * may have been changed arbitrarily. We need to recheck.
1962 * To simplify the code, we restrict I/O size to just one block.
1964 if (journal_read_pos != NOT_FOUND) {
1965 sector_t next_sector;
1966 unsigned new_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
1967 if (unlikely(new_pos != journal_read_pos)) {
1968 remove_range_unlocked(ic, &dio->range);
1973 spin_unlock_irq(&ic->endio_wait.lock);
1975 if (unlikely(journal_read_pos != NOT_FOUND)) {
1976 journal_section = journal_read_pos / ic->journal_section_entries;
1977 journal_entry = journal_read_pos % ic->journal_section_entries;
1978 goto journal_read_write;
1981 if (ic->mode == 'B' && dio->write) {
1982 if (!block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
1983 dio->range.n_sectors, BITMAP_OP_TEST_ALL_SET)) {
1984 struct bitmap_block_status *bbs;
1986 bbs = sector_to_bitmap_block(ic, dio->range.logical_sector);
1987 spin_lock(&bbs->bio_queue_lock);
1988 bio_list_add(&bbs->bio_queue, bio);
1989 spin_unlock(&bbs->bio_queue_lock);
1990 queue_work(ic->writer_wq, &bbs->work);
1995 dio->in_flight = (atomic_t)ATOMIC_INIT(2);
1998 init_completion(&read_comp);
1999 dio->completion = &read_comp;
2001 dio->completion = NULL;
2003 dio->orig_bi_iter = bio->bi_iter;
2005 dio->orig_bi_disk = bio->bi_disk;
2006 dio->orig_bi_partno = bio->bi_partno;
2007 bio_set_dev(bio, ic->dev->bdev);
2009 dio->orig_bi_integrity = bio_integrity(bio);
2010 bio->bi_integrity = NULL;
2011 bio->bi_opf &= ~REQ_INTEGRITY;
2013 dio->orig_bi_end_io = bio->bi_end_io;
2014 bio->bi_end_io = integrity_end_io;
2016 bio->bi_iter.bi_size = dio->range.n_sectors << SECTOR_SHIFT;
2017 generic_make_request(bio);
2020 wait_for_completion_io(&read_comp);
2021 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
2022 dio->range.logical_sector + dio->range.n_sectors > le64_to_cpu(ic->sb->recalc_sector))
2024 if (ic->mode == 'B') {
2025 if (!block_bitmap_op(ic, ic->recalc_bitmap, dio->range.logical_sector,
2026 dio->range.n_sectors, BITMAP_OP_TEST_ALL_CLEAR))
2030 if (likely(!bio->bi_status))
2031 integrity_metadata(&dio->work);
2037 INIT_WORK(&dio->work, integrity_metadata);
2038 queue_work(ic->metadata_wq, &dio->work);
2044 if (unlikely(__journal_read_write(dio, bio, journal_section, journal_entry)))
2047 do_endio_flush(ic, dio);
2051 static void integrity_bio_wait(struct work_struct *w)
2053 struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
2055 dm_integrity_map_continue(dio, false);
2058 static void pad_uncommitted(struct dm_integrity_c *ic)
2060 if (ic->free_section_entry) {
2061 ic->free_sectors -= ic->journal_section_entries - ic->free_section_entry;
2062 ic->free_section_entry = 0;
2064 wraparound_section(ic, &ic->free_section);
2065 ic->n_uncommitted_sections++;
2067 if (WARN_ON(ic->journal_sections * ic->journal_section_entries !=
2068 (ic->n_uncommitted_sections + ic->n_committed_sections) *
2069 ic->journal_section_entries + ic->free_sectors)) {
2070 DMCRIT("journal_sections %u, journal_section_entries %u, "
2071 "n_uncommitted_sections %u, n_committed_sections %u, "
2072 "journal_section_entries %u, free_sectors %u",
2073 ic->journal_sections, ic->journal_section_entries,
2074 ic->n_uncommitted_sections, ic->n_committed_sections,
2075 ic->journal_section_entries, ic->free_sectors);
2079 static void integrity_commit(struct work_struct *w)
2081 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, commit_work);
2082 unsigned commit_start, commit_sections;
2084 struct bio *flushes;
2086 del_timer(&ic->autocommit_timer);
2088 spin_lock_irq(&ic->endio_wait.lock);
2089 flushes = bio_list_get(&ic->flush_bio_list);
2090 if (unlikely(ic->mode != 'J')) {
2091 spin_unlock_irq(&ic->endio_wait.lock);
2092 dm_integrity_flush_buffers(ic);
2093 goto release_flush_bios;
2096 pad_uncommitted(ic);
2097 commit_start = ic->uncommitted_section;
2098 commit_sections = ic->n_uncommitted_sections;
2099 spin_unlock_irq(&ic->endio_wait.lock);
2101 if (!commit_sections)
2102 goto release_flush_bios;
2105 for (n = 0; n < commit_sections; n++) {
2106 for (j = 0; j < ic->journal_section_entries; j++) {
2107 struct journal_entry *je;
2108 je = access_journal_entry(ic, i, j);
2109 io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
2111 for (j = 0; j < ic->journal_section_sectors; j++) {
2112 struct journal_sector *js;
2113 js = access_journal(ic, i, j);
2114 js->commit_id = dm_integrity_commit_id(ic, i, j, ic->commit_seq);
2117 if (unlikely(i >= ic->journal_sections))
2118 ic->commit_seq = next_commit_seq(ic->commit_seq);
2119 wraparound_section(ic, &i);
2123 write_journal(ic, commit_start, commit_sections);
2125 spin_lock_irq(&ic->endio_wait.lock);
2126 ic->uncommitted_section += commit_sections;
2127 wraparound_section(ic, &ic->uncommitted_section);
2128 ic->n_uncommitted_sections -= commit_sections;
2129 ic->n_committed_sections += commit_sections;
2130 spin_unlock_irq(&ic->endio_wait.lock);
2132 if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold)
2133 queue_work(ic->writer_wq, &ic->writer_work);
2137 struct bio *next = flushes->bi_next;
2138 flushes->bi_next = NULL;
2139 do_endio(ic, flushes);
2144 static void complete_copy_from_journal(unsigned long error, void *context)
2146 struct journal_io *io = context;
2147 struct journal_completion *comp = io->comp;
2148 struct dm_integrity_c *ic = comp->ic;
2149 remove_range(ic, &io->range);
2150 mempool_free(io, &ic->journal_io_mempool);
2151 if (unlikely(error != 0))
2152 dm_integrity_io_error(ic, "copying from journal", -EIO);
2153 complete_journal_op(comp);
2156 static void restore_last_bytes(struct dm_integrity_c *ic, struct journal_sector *js,
2157 struct journal_entry *je)
2161 js->commit_id = je->last_bytes[s];
2163 } while (++s < ic->sectors_per_block);
2166 static void do_journal_write(struct dm_integrity_c *ic, unsigned write_start,
2167 unsigned write_sections, bool from_replay)
2170 struct journal_completion comp;
2171 struct blk_plug plug;
2173 blk_start_plug(&plug);
2176 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
2177 init_completion(&comp.comp);
2180 for (n = 0; n < write_sections; n++, i++, wraparound_section(ic, &i)) {
2181 #ifndef INTERNAL_VERIFY
2182 if (unlikely(from_replay))
2184 rw_section_mac(ic, i, false);
2185 for (j = 0; j < ic->journal_section_entries; j++) {
2186 struct journal_entry *je = access_journal_entry(ic, i, j);
2187 sector_t sec, area, offset;
2188 unsigned k, l, next_loop;
2189 sector_t metadata_block;
2190 unsigned metadata_offset;
2191 struct journal_io *io;
2193 if (journal_entry_is_unused(je))
2195 BUG_ON(unlikely(journal_entry_is_inprogress(je)) && !from_replay);
2196 sec = journal_entry_get_sector(je);
2197 if (unlikely(from_replay)) {
2198 if (unlikely(sec & (unsigned)(ic->sectors_per_block - 1))) {
2199 dm_integrity_io_error(ic, "invalid sector in journal", -EIO);
2200 sec &= ~(sector_t)(ic->sectors_per_block - 1);
2203 get_area_and_offset(ic, sec, &area, &offset);
2204 restore_last_bytes(ic, access_journal_data(ic, i, j), je);
2205 for (k = j + 1; k < ic->journal_section_entries; k++) {
2206 struct journal_entry *je2 = access_journal_entry(ic, i, k);
2207 sector_t sec2, area2, offset2;
2208 if (journal_entry_is_unused(je2))
2210 BUG_ON(unlikely(journal_entry_is_inprogress(je2)) && !from_replay);
2211 sec2 = journal_entry_get_sector(je2);
2212 get_area_and_offset(ic, sec2, &area2, &offset2);
2213 if (area2 != area || offset2 != offset + ((k - j) << ic->sb->log2_sectors_per_block))
2215 restore_last_bytes(ic, access_journal_data(ic, i, k), je2);
2219 io = mempool_alloc(&ic->journal_io_mempool, GFP_NOIO);
2221 io->range.logical_sector = sec;
2222 io->range.n_sectors = (k - j) << ic->sb->log2_sectors_per_block;
2224 spin_lock_irq(&ic->endio_wait.lock);
2225 add_new_range_and_wait(ic, &io->range);
2227 if (likely(!from_replay)) {
2228 struct journal_node *section_node = &ic->journal_tree[i * ic->journal_section_entries];
2230 /* don't write if there is newer committed sector */
2231 while (j < k && find_newer_committed_node(ic, §ion_node[j])) {
2232 struct journal_entry *je2 = access_journal_entry(ic, i, j);
2234 journal_entry_set_unused(je2);
2235 remove_journal_node(ic, §ion_node[j]);
2237 sec += ic->sectors_per_block;
2238 offset += ic->sectors_per_block;
2240 while (j < k && find_newer_committed_node(ic, §ion_node[k - 1])) {
2241 struct journal_entry *je2 = access_journal_entry(ic, i, k - 1);
2243 journal_entry_set_unused(je2);
2244 remove_journal_node(ic, §ion_node[k - 1]);
2248 remove_range_unlocked(ic, &io->range);
2249 spin_unlock_irq(&ic->endio_wait.lock);
2250 mempool_free(io, &ic->journal_io_mempool);
2253 for (l = j; l < k; l++) {
2254 remove_journal_node(ic, §ion_node[l]);
2257 spin_unlock_irq(&ic->endio_wait.lock);
2259 metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
2260 for (l = j; l < k; l++) {
2262 struct journal_entry *je2 = access_journal_entry(ic, i, l);
2265 #ifndef INTERNAL_VERIFY
2266 unlikely(from_replay) &&
2268 ic->internal_hash) {
2269 char test_tag[max_t(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
2271 integrity_sector_checksum(ic, sec + ((l - j) << ic->sb->log2_sectors_per_block),
2272 (char *)access_journal_data(ic, i, l), test_tag);
2273 if (unlikely(memcmp(test_tag, journal_entry_tag(ic, je2), ic->tag_size)))
2274 dm_integrity_io_error(ic, "tag mismatch when replaying journal", -EILSEQ);
2277 journal_entry_set_unused(je2);
2278 r = dm_integrity_rw_tag(ic, journal_entry_tag(ic, je2), &metadata_block, &metadata_offset,
2279 ic->tag_size, TAG_WRITE);
2281 dm_integrity_io_error(ic, "reading tags", r);
2285 atomic_inc(&comp.in_flight);
2286 copy_from_journal(ic, i, j << ic->sb->log2_sectors_per_block,
2287 (k - j) << ic->sb->log2_sectors_per_block,
2288 get_data_sector(ic, area, offset),
2289 complete_copy_from_journal, io);
2295 dm_bufio_write_dirty_buffers_async(ic->bufio);
2297 blk_finish_plug(&plug);
2299 complete_journal_op(&comp);
2300 wait_for_completion_io(&comp.comp);
2302 dm_integrity_flush_buffers(ic);
2305 static void integrity_writer(struct work_struct *w)
2307 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, writer_work);
2308 unsigned write_start, write_sections;
2310 unsigned prev_free_sectors;
2312 /* the following test is not needed, but it tests the replay code */
2313 if (READ_ONCE(ic->suspending) && !ic->meta_dev)
2316 spin_lock_irq(&ic->endio_wait.lock);
2317 write_start = ic->committed_section;
2318 write_sections = ic->n_committed_sections;
2319 spin_unlock_irq(&ic->endio_wait.lock);
2321 if (!write_sections)
2324 do_journal_write(ic, write_start, write_sections, false);
2326 spin_lock_irq(&ic->endio_wait.lock);
2328 ic->committed_section += write_sections;
2329 wraparound_section(ic, &ic->committed_section);
2330 ic->n_committed_sections -= write_sections;
2332 prev_free_sectors = ic->free_sectors;
2333 ic->free_sectors += write_sections * ic->journal_section_entries;
2334 if (unlikely(!prev_free_sectors))
2335 wake_up_locked(&ic->endio_wait);
2337 spin_unlock_irq(&ic->endio_wait.lock);
2340 static void recalc_write_super(struct dm_integrity_c *ic)
2344 dm_integrity_flush_buffers(ic);
2345 if (dm_integrity_failed(ic))
2348 r = sync_rw_sb(ic, REQ_OP_WRITE, 0);
2350 dm_integrity_io_error(ic, "writing superblock", r);
2353 static void integrity_recalc(struct work_struct *w)
2355 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, recalc_work);
2356 struct dm_integrity_range range;
2357 struct dm_io_request io_req;
2358 struct dm_io_region io_loc;
2359 sector_t area, offset;
2360 sector_t metadata_block;
2361 unsigned metadata_offset;
2362 sector_t logical_sector, n_sectors;
2366 unsigned super_counter = 0;
2368 DEBUG_print("start recalculation... (position %llx)\n", le64_to_cpu(ic->sb->recalc_sector));
2370 spin_lock_irq(&ic->endio_wait.lock);
2374 if (unlikely(READ_ONCE(ic->suspending)))
2377 range.logical_sector = le64_to_cpu(ic->sb->recalc_sector);
2378 if (unlikely(range.logical_sector >= ic->provided_data_sectors)) {
2379 if (ic->mode == 'B') {
2380 DEBUG_print("queue_delayed_work: bitmap_flush_work\n");
2381 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
2386 get_area_and_offset(ic, range.logical_sector, &area, &offset);
2387 range.n_sectors = min((sector_t)RECALC_SECTORS, ic->provided_data_sectors - range.logical_sector);
2389 range.n_sectors = min(range.n_sectors, ((sector_t)1U << ic->sb->log2_interleave_sectors) - (unsigned)offset);
2391 add_new_range_and_wait(ic, &range);
2392 spin_unlock_irq(&ic->endio_wait.lock);
2393 logical_sector = range.logical_sector;
2394 n_sectors = range.n_sectors;
2396 if (ic->mode == 'B') {
2397 if (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector, n_sectors, BITMAP_OP_TEST_ALL_CLEAR)) {
2398 goto advance_and_next;
2400 while (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector,
2401 ic->sectors_per_block, BITMAP_OP_TEST_ALL_CLEAR)) {
2402 logical_sector += ic->sectors_per_block;
2403 n_sectors -= ic->sectors_per_block;
2406 while (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector + n_sectors - ic->sectors_per_block,
2407 ic->sectors_per_block, BITMAP_OP_TEST_ALL_CLEAR)) {
2408 n_sectors -= ic->sectors_per_block;
2411 get_area_and_offset(ic, logical_sector, &area, &offset);
2414 DEBUG_print("recalculating: %lx, %lx\n", logical_sector, n_sectors);
2416 if (unlikely(++super_counter == RECALC_WRITE_SUPER)) {
2417 recalc_write_super(ic);
2418 if (ic->mode == 'B') {
2419 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, ic->bitmap_flush_interval);
2424 if (unlikely(dm_integrity_failed(ic)))
2427 io_req.bi_op = REQ_OP_READ;
2428 io_req.bi_op_flags = 0;
2429 io_req.mem.type = DM_IO_VMA;
2430 io_req.mem.ptr.addr = ic->recalc_buffer;
2431 io_req.notify.fn = NULL;
2432 io_req.client = ic->io;
2433 io_loc.bdev = ic->dev->bdev;
2434 io_loc.sector = get_data_sector(ic, area, offset);
2435 io_loc.count = n_sectors;
2437 r = dm_io(&io_req, 1, &io_loc, NULL);
2439 dm_integrity_io_error(ic, "reading data", r);
2443 t = ic->recalc_tags;
2444 for (i = 0; i < n_sectors; i += ic->sectors_per_block) {
2445 integrity_sector_checksum(ic, logical_sector + i, ic->recalc_buffer + (i << SECTOR_SHIFT), t);
2449 metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
2451 r = dm_integrity_rw_tag(ic, ic->recalc_tags, &metadata_block, &metadata_offset, t - ic->recalc_tags, TAG_WRITE);
2453 dm_integrity_io_error(ic, "writing tags", r);
2460 spin_lock_irq(&ic->endio_wait.lock);
2461 remove_range_unlocked(ic, &range);
2462 ic->sb->recalc_sector = cpu_to_le64(range.logical_sector + range.n_sectors);
2466 remove_range(ic, &range);
2470 spin_unlock_irq(&ic->endio_wait.lock);
2472 recalc_write_super(ic);
2475 static void bitmap_block_work(struct work_struct *w)
2477 struct bitmap_block_status *bbs = container_of(w, struct bitmap_block_status, work);
2478 struct dm_integrity_c *ic = bbs->ic;
2480 struct bio_list bio_queue;
2481 struct bio_list waiting;
2483 bio_list_init(&waiting);
2485 spin_lock(&bbs->bio_queue_lock);
2486 bio_queue = bbs->bio_queue;
2487 bio_list_init(&bbs->bio_queue);
2488 spin_unlock(&bbs->bio_queue_lock);
2490 while ((bio = bio_list_pop(&bio_queue))) {
2491 struct dm_integrity_io *dio;
2493 dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
2495 if (block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
2496 dio->range.n_sectors, BITMAP_OP_TEST_ALL_SET)) {
2497 remove_range(ic, &dio->range);
2498 INIT_WORK(&dio->work, integrity_bio_wait);
2499 queue_work(ic->wait_wq, &dio->work);
2501 block_bitmap_op(ic, ic->journal, dio->range.logical_sector,
2502 dio->range.n_sectors, BITMAP_OP_SET);
2503 bio_list_add(&waiting, bio);
2507 if (bio_list_empty(&waiting))
2510 rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC,
2511 bbs->idx * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT),
2512 BITMAP_BLOCK_SIZE >> SECTOR_SHIFT, NULL);
2514 while ((bio = bio_list_pop(&waiting))) {
2515 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
2517 block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
2518 dio->range.n_sectors, BITMAP_OP_SET);
2520 remove_range(ic, &dio->range);
2521 INIT_WORK(&dio->work, integrity_bio_wait);
2522 queue_work(ic->wait_wq, &dio->work);
2525 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, ic->bitmap_flush_interval);
2528 static void bitmap_flush_work(struct work_struct *work)
2530 struct dm_integrity_c *ic = container_of(work, struct dm_integrity_c, bitmap_flush_work.work);
2531 struct dm_integrity_range range;
2532 unsigned long limit;
2535 dm_integrity_flush_buffers(ic);
2537 range.logical_sector = 0;
2538 range.n_sectors = ic->provided_data_sectors;
2540 spin_lock_irq(&ic->endio_wait.lock);
2541 add_new_range_and_wait(ic, &range);
2542 spin_unlock_irq(&ic->endio_wait.lock);
2544 dm_integrity_flush_buffers(ic);
2546 blkdev_issue_flush(ic->dev->bdev, GFP_NOIO, NULL);
2548 limit = ic->provided_data_sectors;
2549 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
2550 limit = le64_to_cpu(ic->sb->recalc_sector)
2551 >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit)
2552 << (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
2554 /*DEBUG_print("zeroing journal\n");*/
2555 block_bitmap_op(ic, ic->journal, 0, limit, BITMAP_OP_CLEAR);
2556 block_bitmap_op(ic, ic->may_write_bitmap, 0, limit, BITMAP_OP_CLEAR);
2558 rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, 0,
2559 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
2561 spin_lock_irq(&ic->endio_wait.lock);
2562 remove_range_unlocked(ic, &range);
2563 while (unlikely((bio = bio_list_pop(&ic->synchronous_bios)) != NULL)) {
2565 spin_unlock_irq(&ic->endio_wait.lock);
2566 spin_lock_irq(&ic->endio_wait.lock);
2568 spin_unlock_irq(&ic->endio_wait.lock);
2572 static void init_journal(struct dm_integrity_c *ic, unsigned start_section,
2573 unsigned n_sections, unsigned char commit_seq)
2580 for (n = 0; n < n_sections; n++) {
2581 i = start_section + n;
2582 wraparound_section(ic, &i);
2583 for (j = 0; j < ic->journal_section_sectors; j++) {
2584 struct journal_sector *js = access_journal(ic, i, j);
2585 memset(&js->entries, 0, JOURNAL_SECTOR_DATA);
2586 js->commit_id = dm_integrity_commit_id(ic, i, j, commit_seq);
2588 for (j = 0; j < ic->journal_section_entries; j++) {
2589 struct journal_entry *je = access_journal_entry(ic, i, j);
2590 journal_entry_set_unused(je);
2594 write_journal(ic, start_section, n_sections);
2597 static int find_commit_seq(struct dm_integrity_c *ic, unsigned i, unsigned j, commit_id_t id)
2600 for (k = 0; k < N_COMMIT_IDS; k++) {
2601 if (dm_integrity_commit_id(ic, i, j, k) == id)
2604 dm_integrity_io_error(ic, "journal commit id", -EIO);
2608 static void replay_journal(struct dm_integrity_c *ic)
2611 bool used_commit_ids[N_COMMIT_IDS];
2612 unsigned max_commit_id_sections[N_COMMIT_IDS];
2613 unsigned write_start, write_sections;
2614 unsigned continue_section;
2616 unsigned char unused, last_used, want_commit_seq;
2618 if (ic->mode == 'R')
2621 if (ic->journal_uptodate)
2627 if (!ic->just_formatted) {
2628 DEBUG_print("reading journal\n");
2629 rw_journal(ic, REQ_OP_READ, 0, 0, ic->journal_sections, NULL);
2631 DEBUG_bytes(lowmem_page_address(ic->journal_io[0].page), 64, "read journal");
2632 if (ic->journal_io) {
2633 struct journal_completion crypt_comp;
2635 init_completion(&crypt_comp.comp);
2636 crypt_comp.in_flight = (atomic_t)ATOMIC_INIT(0);
2637 encrypt_journal(ic, false, 0, ic->journal_sections, &crypt_comp);
2638 wait_for_completion(&crypt_comp.comp);
2640 DEBUG_bytes(lowmem_page_address(ic->journal[0].page), 64, "decrypted journal");
2643 if (dm_integrity_failed(ic))
2646 journal_empty = true;
2647 memset(used_commit_ids, 0, sizeof used_commit_ids);
2648 memset(max_commit_id_sections, 0, sizeof max_commit_id_sections);
2649 for (i = 0; i < ic->journal_sections; i++) {
2650 for (j = 0; j < ic->journal_section_sectors; j++) {
2652 struct journal_sector *js = access_journal(ic, i, j);
2653 k = find_commit_seq(ic, i, j, js->commit_id);
2656 used_commit_ids[k] = true;
2657 max_commit_id_sections[k] = i;
2659 if (journal_empty) {
2660 for (j = 0; j < ic->journal_section_entries; j++) {
2661 struct journal_entry *je = access_journal_entry(ic, i, j);
2662 if (!journal_entry_is_unused(je)) {
2663 journal_empty = false;
2670 if (!used_commit_ids[N_COMMIT_IDS - 1]) {
2671 unused = N_COMMIT_IDS - 1;
2672 while (unused && !used_commit_ids[unused - 1])
2675 for (unused = 0; unused < N_COMMIT_IDS; unused++)
2676 if (!used_commit_ids[unused])
2678 if (unused == N_COMMIT_IDS) {
2679 dm_integrity_io_error(ic, "journal commit ids", -EIO);
2683 DEBUG_print("first unused commit seq %d [%d,%d,%d,%d]\n",
2684 unused, used_commit_ids[0], used_commit_ids[1],
2685 used_commit_ids[2], used_commit_ids[3]);
2687 last_used = prev_commit_seq(unused);
2688 want_commit_seq = prev_commit_seq(last_used);
2690 if (!used_commit_ids[want_commit_seq] && used_commit_ids[prev_commit_seq(want_commit_seq)])
2691 journal_empty = true;
2693 write_start = max_commit_id_sections[last_used] + 1;
2694 if (unlikely(write_start >= ic->journal_sections))
2695 want_commit_seq = next_commit_seq(want_commit_seq);
2696 wraparound_section(ic, &write_start);
2699 for (write_sections = 0; write_sections < ic->journal_sections; write_sections++) {
2700 for (j = 0; j < ic->journal_section_sectors; j++) {
2701 struct journal_sector *js = access_journal(ic, i, j);
2703 if (js->commit_id != dm_integrity_commit_id(ic, i, j, want_commit_seq)) {
2705 * This could be caused by crash during writing.
2706 * We won't replay the inconsistent part of the
2709 DEBUG_print("commit id mismatch at position (%u, %u): %d != %d\n",
2710 i, j, find_commit_seq(ic, i, j, js->commit_id), want_commit_seq);
2715 if (unlikely(i >= ic->journal_sections))
2716 want_commit_seq = next_commit_seq(want_commit_seq);
2717 wraparound_section(ic, &i);
2721 if (!journal_empty) {
2722 DEBUG_print("replaying %u sections, starting at %u, commit seq %d\n",
2723 write_sections, write_start, want_commit_seq);
2724 do_journal_write(ic, write_start, write_sections, true);
2727 if (write_sections == ic->journal_sections && (ic->mode == 'J' || journal_empty)) {
2728 continue_section = write_start;
2729 ic->commit_seq = want_commit_seq;
2730 DEBUG_print("continuing from section %u, commit seq %d\n", write_start, ic->commit_seq);
2733 unsigned char erase_seq;
2735 DEBUG_print("clearing journal\n");
2737 erase_seq = prev_commit_seq(prev_commit_seq(last_used));
2739 init_journal(ic, s, 1, erase_seq);
2741 wraparound_section(ic, &s);
2742 if (ic->journal_sections >= 2) {
2743 init_journal(ic, s, ic->journal_sections - 2, erase_seq);
2744 s += ic->journal_sections - 2;
2745 wraparound_section(ic, &s);
2746 init_journal(ic, s, 1, erase_seq);
2749 continue_section = 0;
2750 ic->commit_seq = next_commit_seq(erase_seq);
2753 ic->committed_section = continue_section;
2754 ic->n_committed_sections = 0;
2756 ic->uncommitted_section = continue_section;
2757 ic->n_uncommitted_sections = 0;
2759 ic->free_section = continue_section;
2760 ic->free_section_entry = 0;
2761 ic->free_sectors = ic->journal_entries;
2763 ic->journal_tree_root = RB_ROOT;
2764 for (i = 0; i < ic->journal_entries; i++)
2765 init_journal_node(&ic->journal_tree[i]);
2768 static void dm_integrity_enter_synchronous_mode(struct dm_integrity_c *ic)
2770 DEBUG_print("dm_integrity_enter_synchronous_mode\n");
2772 if (ic->mode == 'B') {
2773 ic->bitmap_flush_interval = msecs_to_jiffies(10) + 1;
2774 ic->synchronous_mode = 1;
2776 cancel_delayed_work_sync(&ic->bitmap_flush_work);
2777 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
2778 flush_workqueue(ic->commit_wq);
2782 static int dm_integrity_reboot(struct notifier_block *n, unsigned long code, void *x)
2784 struct dm_integrity_c *ic = container_of(n, struct dm_integrity_c, reboot_notifier);
2786 DEBUG_print("dm_integrity_reboot\n");
2788 dm_integrity_enter_synchronous_mode(ic);
2793 static void dm_integrity_postsuspend(struct dm_target *ti)
2795 struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2798 WARN_ON(unregister_reboot_notifier(&ic->reboot_notifier));
2800 del_timer_sync(&ic->autocommit_timer);
2802 WRITE_ONCE(ic->suspending, 1);
2805 drain_workqueue(ic->recalc_wq);
2807 if (ic->mode == 'B')
2808 cancel_delayed_work_sync(&ic->bitmap_flush_work);
2810 queue_work(ic->commit_wq, &ic->commit_work);
2811 drain_workqueue(ic->commit_wq);
2813 if (ic->mode == 'J') {
2815 queue_work(ic->writer_wq, &ic->writer_work);
2816 drain_workqueue(ic->writer_wq);
2817 dm_integrity_flush_buffers(ic);
2820 if (ic->mode == 'B') {
2821 dm_integrity_flush_buffers(ic);
2823 /* set to 0 to test bitmap replay code */
2824 init_journal(ic, 0, ic->journal_sections, 0);
2825 ic->sb->flags &= ~cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
2826 r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
2828 dm_integrity_io_error(ic, "writing superblock", r);
2832 WRITE_ONCE(ic->suspending, 0);
2834 BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
2836 ic->journal_uptodate = true;
2839 static void dm_integrity_resume(struct dm_target *ti)
2841 struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2843 DEBUG_print("resume\n");
2845 if (ic->sb->flags & cpu_to_le32(SB_FLAG_DIRTY_BITMAP)) {
2846 DEBUG_print("resume dirty_bitmap\n");
2847 rw_journal_sectors(ic, REQ_OP_READ, 0, 0,
2848 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
2849 if (ic->mode == 'B') {
2850 if (ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit) {
2851 block_bitmap_copy(ic, ic->recalc_bitmap, ic->journal);
2852 block_bitmap_copy(ic, ic->may_write_bitmap, ic->journal);
2853 if (!block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors,
2854 BITMAP_OP_TEST_ALL_CLEAR)) {
2855 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
2856 ic->sb->recalc_sector = cpu_to_le64(0);
2859 DEBUG_print("non-matching blocks_per_bitmap_bit: %u, %u\n",
2860 ic->sb->log2_blocks_per_bitmap_bit, ic->log2_blocks_per_bitmap_bit);
2861 ic->sb->log2_blocks_per_bitmap_bit = ic->log2_blocks_per_bitmap_bit;
2862 block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_SET);
2863 block_bitmap_op(ic, ic->may_write_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_SET);
2864 block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_SET);
2865 rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, 0,
2866 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
2867 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
2868 ic->sb->recalc_sector = cpu_to_le64(0);
2871 if (!(ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit &&
2872 block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_TEST_ALL_CLEAR))) {
2873 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
2874 ic->sb->recalc_sector = cpu_to_le64(0);
2876 init_journal(ic, 0, ic->journal_sections, 0);
2878 ic->sb->flags &= ~cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
2880 r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
2882 dm_integrity_io_error(ic, "writing superblock", r);
2885 if (ic->mode == 'B') {
2887 ic->sb->flags |= cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
2888 ic->sb->log2_blocks_per_bitmap_bit = ic->log2_blocks_per_bitmap_bit;
2889 r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
2891 dm_integrity_io_error(ic, "writing superblock", r);
2893 mode = ic->recalculate_flag ? BITMAP_OP_SET : BITMAP_OP_CLEAR;
2894 block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, mode);
2895 block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, mode);
2896 block_bitmap_op(ic, ic->may_write_bitmap, 0, ic->provided_data_sectors, mode);
2897 rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, 0,
2898 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
2902 DEBUG_print("testing recalc: %x\n", ic->sb->flags);
2903 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
2904 __u64 recalc_pos = le64_to_cpu(ic->sb->recalc_sector);
2905 DEBUG_print("recalc pos: %lx / %lx\n", (long)recalc_pos, ic->provided_data_sectors);
2906 if (recalc_pos < ic->provided_data_sectors) {
2907 queue_work(ic->recalc_wq, &ic->recalc_work);
2908 } else if (recalc_pos > ic->provided_data_sectors) {
2909 ic->sb->recalc_sector = cpu_to_le64(ic->provided_data_sectors);
2910 recalc_write_super(ic);
2914 ic->reboot_notifier.notifier_call = dm_integrity_reboot;
2915 ic->reboot_notifier.next = NULL;
2916 ic->reboot_notifier.priority = INT_MAX - 1; /* be notified after md and before hardware drivers */
2917 WARN_ON(register_reboot_notifier(&ic->reboot_notifier));
2920 /* set to 1 to stress test synchronous mode */
2921 dm_integrity_enter_synchronous_mode(ic);
2925 static void dm_integrity_status(struct dm_target *ti, status_type_t type,
2926 unsigned status_flags, char *result, unsigned maxlen)
2928 struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2933 case STATUSTYPE_INFO:
2935 (unsigned long long)atomic64_read(&ic->number_of_mismatches),
2936 (unsigned long long)ic->provided_data_sectors);
2937 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
2938 DMEMIT(" %llu", (unsigned long long)le64_to_cpu(ic->sb->recalc_sector));
2943 case STATUSTYPE_TABLE: {
2944 __u64 watermark_percentage = (__u64)(ic->journal_entries - ic->free_sectors_threshold) * 100;
2945 watermark_percentage += ic->journal_entries / 2;
2946 do_div(watermark_percentage, ic->journal_entries);
2948 arg_count += !!ic->meta_dev;
2949 arg_count += ic->sectors_per_block != 1;
2950 arg_count += !!(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING));
2951 arg_count += ic->mode == 'J';
2952 arg_count += ic->mode == 'J';
2953 arg_count += ic->mode == 'B';
2954 arg_count += ic->mode == 'B';
2955 arg_count += !!ic->internal_hash_alg.alg_string;
2956 arg_count += !!ic->journal_crypt_alg.alg_string;
2957 arg_count += !!ic->journal_mac_alg.alg_string;
2958 DMEMIT("%s %llu %u %c %u", ic->dev->name, (unsigned long long)ic->start,
2959 ic->tag_size, ic->mode, arg_count);
2961 DMEMIT(" meta_device:%s", ic->meta_dev->name);
2962 if (ic->sectors_per_block != 1)
2963 DMEMIT(" block_size:%u", ic->sectors_per_block << SECTOR_SHIFT);
2964 if (ic->recalculate_flag)
2965 DMEMIT(" recalculate");
2966 DMEMIT(" journal_sectors:%u", ic->initial_sectors - SB_SECTORS);
2967 DMEMIT(" interleave_sectors:%u", 1U << ic->sb->log2_interleave_sectors);
2968 DMEMIT(" buffer_sectors:%u", 1U << ic->log2_buffer_sectors);
2969 if (ic->mode == 'J') {
2970 DMEMIT(" journal_watermark:%u", (unsigned)watermark_percentage);
2971 DMEMIT(" commit_time:%u", ic->autocommit_msec);
2973 if (ic->mode == 'B') {
2974 DMEMIT(" sectors_per_bit:%llu", (unsigned long long)ic->sectors_per_block << ic->log2_blocks_per_bitmap_bit);
2975 DMEMIT(" bitmap_flush_interval:%u", jiffies_to_msecs(ic->bitmap_flush_interval));
2978 #define EMIT_ALG(a, n) \
2980 if (ic->a.alg_string) { \
2981 DMEMIT(" %s:%s", n, ic->a.alg_string); \
2982 if (ic->a.key_string) \
2983 DMEMIT(":%s", ic->a.key_string);\
2986 EMIT_ALG(internal_hash_alg, "internal_hash");
2987 EMIT_ALG(journal_crypt_alg, "journal_crypt");
2988 EMIT_ALG(journal_mac_alg, "journal_mac");
2994 static int dm_integrity_iterate_devices(struct dm_target *ti,
2995 iterate_devices_callout_fn fn, void *data)
2997 struct dm_integrity_c *ic = ti->private;
3000 return fn(ti, ic->dev, ic->start + ic->initial_sectors + ic->metadata_run, ti->len, data);
3002 return fn(ti, ic->dev, 0, ti->len, data);
3005 static void dm_integrity_io_hints(struct dm_target *ti, struct queue_limits *limits)
3007 struct dm_integrity_c *ic = ti->private;
3009 if (ic->sectors_per_block > 1) {
3010 limits->logical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
3011 limits->physical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
3012 blk_limits_io_min(limits, ic->sectors_per_block << SECTOR_SHIFT);
3016 static void calculate_journal_section_size(struct dm_integrity_c *ic)
3018 unsigned sector_space = JOURNAL_SECTOR_DATA;
3020 ic->journal_sections = le32_to_cpu(ic->sb->journal_sections);
3021 ic->journal_entry_size = roundup(offsetof(struct journal_entry, last_bytes[ic->sectors_per_block]) + ic->tag_size,
3022 JOURNAL_ENTRY_ROUNDUP);
3024 if (ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC))
3025 sector_space -= JOURNAL_MAC_PER_SECTOR;
3026 ic->journal_entries_per_sector = sector_space / ic->journal_entry_size;
3027 ic->journal_section_entries = ic->journal_entries_per_sector * JOURNAL_BLOCK_SECTORS;
3028 ic->journal_section_sectors = (ic->journal_section_entries << ic->sb->log2_sectors_per_block) + JOURNAL_BLOCK_SECTORS;
3029 ic->journal_entries = ic->journal_section_entries * ic->journal_sections;
3032 static int calculate_device_limits(struct dm_integrity_c *ic)
3034 __u64 initial_sectors;
3036 calculate_journal_section_size(ic);
3037 initial_sectors = SB_SECTORS + (__u64)ic->journal_section_sectors * ic->journal_sections;
3038 if (initial_sectors + METADATA_PADDING_SECTORS >= ic->meta_device_sectors || initial_sectors > UINT_MAX)
3040 ic->initial_sectors = initial_sectors;
3042 if (!ic->meta_dev) {
3043 sector_t last_sector, last_area, last_offset;
3045 ic->metadata_run = roundup((__u64)ic->tag_size << (ic->sb->log2_interleave_sectors - ic->sb->log2_sectors_per_block),
3046 (__u64)(1 << SECTOR_SHIFT << METADATA_PADDING_SECTORS)) >> SECTOR_SHIFT;
3047 if (!(ic->metadata_run & (ic->metadata_run - 1)))
3048 ic->log2_metadata_run = __ffs(ic->metadata_run);
3050 ic->log2_metadata_run = -1;
3052 get_area_and_offset(ic, ic->provided_data_sectors - 1, &last_area, &last_offset);
3053 last_sector = get_data_sector(ic, last_area, last_offset);
3054 if (last_sector < ic->start || last_sector >= ic->meta_device_sectors)
3057 __u64 meta_size = (ic->provided_data_sectors >> ic->sb->log2_sectors_per_block) * ic->tag_size;
3058 meta_size = (meta_size + ((1U << (ic->log2_buffer_sectors + SECTOR_SHIFT)) - 1))
3059 >> (ic->log2_buffer_sectors + SECTOR_SHIFT);
3060 meta_size <<= ic->log2_buffer_sectors;
3061 if (ic->initial_sectors + meta_size < ic->initial_sectors ||
3062 ic->initial_sectors + meta_size > ic->meta_device_sectors)
3064 ic->metadata_run = 1;
3065 ic->log2_metadata_run = 0;
3071 static int initialize_superblock(struct dm_integrity_c *ic, unsigned journal_sectors, unsigned interleave_sectors)
3073 unsigned journal_sections;
3076 memset(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT);
3077 memcpy(ic->sb->magic, SB_MAGIC, 8);
3078 ic->sb->integrity_tag_size = cpu_to_le16(ic->tag_size);
3079 ic->sb->log2_sectors_per_block = __ffs(ic->sectors_per_block);
3080 if (ic->journal_mac_alg.alg_string)
3081 ic->sb->flags |= cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC);
3083 calculate_journal_section_size(ic);
3084 journal_sections = journal_sectors / ic->journal_section_sectors;
3085 if (!journal_sections)
3086 journal_sections = 1;
3088 if (!ic->meta_dev) {
3089 ic->sb->journal_sections = cpu_to_le32(journal_sections);
3090 if (!interleave_sectors)
3091 interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
3092 ic->sb->log2_interleave_sectors = __fls(interleave_sectors);
3093 ic->sb->log2_interleave_sectors = max((__u8)MIN_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
3094 ic->sb->log2_interleave_sectors = min((__u8)MAX_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
3096 ic->provided_data_sectors = 0;
3097 for (test_bit = fls64(ic->meta_device_sectors) - 1; test_bit >= 3; test_bit--) {
3098 __u64 prev_data_sectors = ic->provided_data_sectors;
3100 ic->provided_data_sectors |= (sector_t)1 << test_bit;
3101 if (calculate_device_limits(ic))
3102 ic->provided_data_sectors = prev_data_sectors;
3104 if (!ic->provided_data_sectors)
3107 ic->sb->log2_interleave_sectors = 0;
3108 ic->provided_data_sectors = ic->data_device_sectors;
3109 ic->provided_data_sectors &= ~(sector_t)(ic->sectors_per_block - 1);
3112 ic->sb->journal_sections = cpu_to_le32(0);
3113 for (test_bit = fls(journal_sections) - 1; test_bit >= 0; test_bit--) {
3114 __u32 prev_journal_sections = le32_to_cpu(ic->sb->journal_sections);
3115 __u32 test_journal_sections = prev_journal_sections | (1U << test_bit);
3116 if (test_journal_sections > journal_sections)
3118 ic->sb->journal_sections = cpu_to_le32(test_journal_sections);
3119 if (calculate_device_limits(ic))
3120 ic->sb->journal_sections = cpu_to_le32(prev_journal_sections);
3123 if (!le32_to_cpu(ic->sb->journal_sections)) {
3124 if (ic->log2_buffer_sectors > 3) {
3125 ic->log2_buffer_sectors--;
3126 goto try_smaller_buffer;
3132 ic->sb->provided_data_sectors = cpu_to_le64(ic->provided_data_sectors);
3139 static void dm_integrity_set(struct dm_target *ti, struct dm_integrity_c *ic)
3141 struct gendisk *disk = dm_disk(dm_table_get_md(ti->table));
3142 struct blk_integrity bi;
3144 memset(&bi, 0, sizeof(bi));
3145 bi.profile = &dm_integrity_profile;
3146 bi.tuple_size = ic->tag_size;
3147 bi.tag_size = bi.tuple_size;
3148 bi.interval_exp = ic->sb->log2_sectors_per_block + SECTOR_SHIFT;
3150 blk_integrity_register(disk, &bi);
3151 blk_queue_max_integrity_segments(disk->queue, UINT_MAX);
3154 static void dm_integrity_free_page_list(struct page_list *pl)
3160 for (i = 0; pl[i].page; i++)
3161 __free_page(pl[i].page);
3165 static struct page_list *dm_integrity_alloc_page_list(unsigned n_pages)
3167 struct page_list *pl;
3170 pl = kvmalloc_array(n_pages + 1, sizeof(struct page_list), GFP_KERNEL | __GFP_ZERO);
3174 for (i = 0; i < n_pages; i++) {
3175 pl[i].page = alloc_page(GFP_KERNEL);
3177 dm_integrity_free_page_list(pl);
3181 pl[i - 1].next = &pl[i];
3189 static void dm_integrity_free_journal_scatterlist(struct dm_integrity_c *ic, struct scatterlist **sl)
3192 for (i = 0; i < ic->journal_sections; i++)
3197 static struct scatterlist **dm_integrity_alloc_journal_scatterlist(struct dm_integrity_c *ic,
3198 struct page_list *pl)
3200 struct scatterlist **sl;
3203 sl = kvmalloc_array(ic->journal_sections,
3204 sizeof(struct scatterlist *),
3205 GFP_KERNEL | __GFP_ZERO);
3209 for (i = 0; i < ic->journal_sections; i++) {
3210 struct scatterlist *s;
3211 unsigned start_index, start_offset;
3212 unsigned end_index, end_offset;
3216 page_list_location(ic, i, 0, &start_index, &start_offset);
3217 page_list_location(ic, i, ic->journal_section_sectors - 1,
3218 &end_index, &end_offset);
3220 n_pages = (end_index - start_index + 1);
3222 s = kvmalloc_array(n_pages, sizeof(struct scatterlist),
3225 dm_integrity_free_journal_scatterlist(ic, sl);
3229 sg_init_table(s, n_pages);
3230 for (idx = start_index; idx <= end_index; idx++) {
3231 char *va = lowmem_page_address(pl[idx].page);
3232 unsigned start = 0, end = PAGE_SIZE;
3233 if (idx == start_index)
3234 start = start_offset;
3235 if (idx == end_index)
3236 end = end_offset + (1 << SECTOR_SHIFT);
3237 sg_set_buf(&s[idx - start_index], va + start, end - start);
3246 static void free_alg(struct alg_spec *a)
3248 kzfree(a->alg_string);
3250 memset(a, 0, sizeof *a);
3253 static int get_alg_and_key(const char *arg, struct alg_spec *a, char **error, char *error_inval)
3259 a->alg_string = kstrdup(strchr(arg, ':') + 1, GFP_KERNEL);
3263 k = strchr(a->alg_string, ':');
3266 a->key_string = k + 1;
3267 if (strlen(a->key_string) & 1)
3270 a->key_size = strlen(a->key_string) / 2;
3271 a->key = kmalloc(a->key_size, GFP_KERNEL);
3274 if (hex2bin(a->key, a->key_string, a->key_size))
3280 *error = error_inval;
3283 *error = "Out of memory for an argument";
3287 static int get_mac(struct crypto_shash **hash, struct alg_spec *a, char **error,
3288 char *error_alg, char *error_key)
3292 if (a->alg_string) {
3293 *hash = crypto_alloc_shash(a->alg_string, 0, 0);
3294 if (IS_ERR(*hash)) {
3302 r = crypto_shash_setkey(*hash, a->key, a->key_size);
3307 } else if (crypto_shash_get_flags(*hash) & CRYPTO_TFM_NEED_KEY) {
3316 static int create_journal(struct dm_integrity_c *ic, char **error)
3320 __u64 journal_pages, journal_desc_size, journal_tree_size;
3321 unsigned char *crypt_data = NULL, *crypt_iv = NULL;
3322 struct skcipher_request *req = NULL;
3324 ic->commit_ids[0] = cpu_to_le64(0x1111111111111111ULL);
3325 ic->commit_ids[1] = cpu_to_le64(0x2222222222222222ULL);
3326 ic->commit_ids[2] = cpu_to_le64(0x3333333333333333ULL);
3327 ic->commit_ids[3] = cpu_to_le64(0x4444444444444444ULL);
3329 journal_pages = roundup((__u64)ic->journal_sections * ic->journal_section_sectors,
3330 PAGE_SIZE >> SECTOR_SHIFT) >> (PAGE_SHIFT - SECTOR_SHIFT);
3331 journal_desc_size = journal_pages * sizeof(struct page_list);
3332 if (journal_pages >= totalram_pages() - totalhigh_pages() || journal_desc_size > ULONG_MAX) {
3333 *error = "Journal doesn't fit into memory";
3337 ic->journal_pages = journal_pages;
3339 ic->journal = dm_integrity_alloc_page_list(ic->journal_pages);
3341 *error = "Could not allocate memory for journal";
3345 if (ic->journal_crypt_alg.alg_string) {
3346 unsigned ivsize, blocksize;
3347 struct journal_completion comp;
3350 ic->journal_crypt = crypto_alloc_skcipher(ic->journal_crypt_alg.alg_string, 0, 0);
3351 if (IS_ERR(ic->journal_crypt)) {
3352 *error = "Invalid journal cipher";
3353 r = PTR_ERR(ic->journal_crypt);
3354 ic->journal_crypt = NULL;
3357 ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
3358 blocksize = crypto_skcipher_blocksize(ic->journal_crypt);
3360 if (ic->journal_crypt_alg.key) {
3361 r = crypto_skcipher_setkey(ic->journal_crypt, ic->journal_crypt_alg.key,
3362 ic->journal_crypt_alg.key_size);
3364 *error = "Error setting encryption key";
3368 DEBUG_print("cipher %s, block size %u iv size %u\n",
3369 ic->journal_crypt_alg.alg_string, blocksize, ivsize);
3371 ic->journal_io = dm_integrity_alloc_page_list(ic->journal_pages);
3372 if (!ic->journal_io) {
3373 *error = "Could not allocate memory for journal io";
3378 if (blocksize == 1) {
3379 struct scatterlist *sg;
3381 req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
3383 *error = "Could not allocate crypt request";
3388 crypt_iv = kzalloc(ivsize, GFP_KERNEL);
3390 *error = "Could not allocate iv";
3395 ic->journal_xor = dm_integrity_alloc_page_list(ic->journal_pages);
3396 if (!ic->journal_xor) {
3397 *error = "Could not allocate memory for journal xor";
3402 sg = kvmalloc_array(ic->journal_pages + 1,
3403 sizeof(struct scatterlist),
3406 *error = "Unable to allocate sg list";
3410 sg_init_table(sg, ic->journal_pages + 1);
3411 for (i = 0; i < ic->journal_pages; i++) {
3412 char *va = lowmem_page_address(ic->journal_xor[i].page);
3414 sg_set_buf(&sg[i], va, PAGE_SIZE);
3416 sg_set_buf(&sg[i], &ic->commit_ids, sizeof ic->commit_ids);
3418 skcipher_request_set_crypt(req, sg, sg,
3419 PAGE_SIZE * ic->journal_pages + sizeof ic->commit_ids, crypt_iv);
3420 init_completion(&comp.comp);
3421 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
3422 if (do_crypt(true, req, &comp))
3423 wait_for_completion(&comp.comp);
3425 r = dm_integrity_failed(ic);
3427 *error = "Unable to encrypt journal";
3430 DEBUG_bytes(lowmem_page_address(ic->journal_xor[0].page), 64, "xor data");
3432 crypto_free_skcipher(ic->journal_crypt);
3433 ic->journal_crypt = NULL;
3435 unsigned crypt_len = roundup(ivsize, blocksize);
3437 req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
3439 *error = "Could not allocate crypt request";
3444 crypt_iv = kmalloc(ivsize, GFP_KERNEL);
3446 *error = "Could not allocate iv";
3451 crypt_data = kmalloc(crypt_len, GFP_KERNEL);
3453 *error = "Unable to allocate crypt data";
3458 ic->journal_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal);
3459 if (!ic->journal_scatterlist) {
3460 *error = "Unable to allocate sg list";
3464 ic->journal_io_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal_io);
3465 if (!ic->journal_io_scatterlist) {
3466 *error = "Unable to allocate sg list";
3470 ic->sk_requests = kvmalloc_array(ic->journal_sections,
3471 sizeof(struct skcipher_request *),
3472 GFP_KERNEL | __GFP_ZERO);
3473 if (!ic->sk_requests) {
3474 *error = "Unable to allocate sk requests";
3478 for (i = 0; i < ic->journal_sections; i++) {
3479 struct scatterlist sg;
3480 struct skcipher_request *section_req;
3481 __u32 section_le = cpu_to_le32(i);
3483 memset(crypt_iv, 0x00, ivsize);
3484 memset(crypt_data, 0x00, crypt_len);
3485 memcpy(crypt_data, §ion_le, min((size_t)crypt_len, sizeof(section_le)));
3487 sg_init_one(&sg, crypt_data, crypt_len);
3488 skcipher_request_set_crypt(req, &sg, &sg, crypt_len, crypt_iv);
3489 init_completion(&comp.comp);
3490 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
3491 if (do_crypt(true, req, &comp))
3492 wait_for_completion(&comp.comp);
3494 r = dm_integrity_failed(ic);
3496 *error = "Unable to generate iv";
3500 section_req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
3502 *error = "Unable to allocate crypt request";
3506 section_req->iv = kmalloc_array(ivsize, 2,
3508 if (!section_req->iv) {
3509 skcipher_request_free(section_req);
3510 *error = "Unable to allocate iv";
3514 memcpy(section_req->iv + ivsize, crypt_data, ivsize);
3515 section_req->cryptlen = (size_t)ic->journal_section_sectors << SECTOR_SHIFT;
3516 ic->sk_requests[i] = section_req;
3517 DEBUG_bytes(crypt_data, ivsize, "iv(%u)", i);
3522 for (i = 0; i < N_COMMIT_IDS; i++) {
3525 for (j = 0; j < i; j++) {
3526 if (ic->commit_ids[j] == ic->commit_ids[i]) {
3527 ic->commit_ids[i] = cpu_to_le64(le64_to_cpu(ic->commit_ids[i]) + 1);
3528 goto retest_commit_id;
3531 DEBUG_print("commit id %u: %016llx\n", i, ic->commit_ids[i]);
3534 journal_tree_size = (__u64)ic->journal_entries * sizeof(struct journal_node);
3535 if (journal_tree_size > ULONG_MAX) {
3536 *error = "Journal doesn't fit into memory";
3540 ic->journal_tree = kvmalloc(journal_tree_size, GFP_KERNEL);
3541 if (!ic->journal_tree) {
3542 *error = "Could not allocate memory for journal tree";
3548 skcipher_request_free(req);
3554 * Construct a integrity mapping
3558 * offset from the start of the device
3560 * D - direct writes, J - journal writes, B - bitmap mode, R - recovery mode
3561 * number of optional arguments
3562 * optional arguments:
3564 * interleave_sectors
3571 * bitmap_flush_interval
3577 static int dm_integrity_ctr(struct dm_target *ti, unsigned argc, char **argv)
3579 struct dm_integrity_c *ic;
3582 unsigned extra_args;
3583 struct dm_arg_set as;
3584 static const struct dm_arg _args[] = {
3585 {0, 9, "Invalid number of feature args"},
3587 unsigned journal_sectors, interleave_sectors, buffer_sectors, journal_watermark, sync_msec;
3588 bool should_write_sb;
3590 unsigned long long start;
3591 __s8 log2_sectors_per_bitmap_bit = -1;
3592 __s8 log2_blocks_per_bitmap_bit;
3593 __u64 bits_in_journal;
3594 __u64 n_bitmap_bits;
3596 #define DIRECT_ARGUMENTS 4
3598 if (argc <= DIRECT_ARGUMENTS) {
3599 ti->error = "Invalid argument count";
3603 ic = kzalloc(sizeof(struct dm_integrity_c), GFP_KERNEL);
3605 ti->error = "Cannot allocate integrity context";
3609 ti->per_io_data_size = sizeof(struct dm_integrity_io);
3611 ic->in_progress = RB_ROOT;
3612 INIT_LIST_HEAD(&ic->wait_list);
3613 init_waitqueue_head(&ic->endio_wait);
3614 bio_list_init(&ic->flush_bio_list);
3615 init_waitqueue_head(&ic->copy_to_journal_wait);
3616 init_completion(&ic->crypto_backoff);
3617 atomic64_set(&ic->number_of_mismatches, 0);
3618 ic->bitmap_flush_interval = BITMAP_FLUSH_INTERVAL;
3620 r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &ic->dev);
3622 ti->error = "Device lookup failed";
3626 if (sscanf(argv[1], "%llu%c", &start, &dummy) != 1 || start != (sector_t)start) {
3627 ti->error = "Invalid starting offset";
3633 if (strcmp(argv[2], "-")) {
3634 if (sscanf(argv[2], "%u%c", &ic->tag_size, &dummy) != 1 || !ic->tag_size) {
3635 ti->error = "Invalid tag size";
3641 if (!strcmp(argv[3], "J") || !strcmp(argv[3], "B") ||
3642 !strcmp(argv[3], "D") || !strcmp(argv[3], "R")) {
3643 ic->mode = argv[3][0];
3645 ti->error = "Invalid mode (expecting J, B, D, R)";
3650 journal_sectors = 0;
3651 interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
3652 buffer_sectors = DEFAULT_BUFFER_SECTORS;
3653 journal_watermark = DEFAULT_JOURNAL_WATERMARK;
3654 sync_msec = DEFAULT_SYNC_MSEC;
3655 ic->sectors_per_block = 1;
3657 as.argc = argc - DIRECT_ARGUMENTS;
3658 as.argv = argv + DIRECT_ARGUMENTS;
3659 r = dm_read_arg_group(_args, &as, &extra_args, &ti->error);
3663 while (extra_args--) {
3664 const char *opt_string;
3666 unsigned long long llval;
3667 opt_string = dm_shift_arg(&as);
3670 ti->error = "Not enough feature arguments";
3673 if (sscanf(opt_string, "journal_sectors:%u%c", &val, &dummy) == 1)
3674 journal_sectors = val ? val : 1;
3675 else if (sscanf(opt_string, "interleave_sectors:%u%c", &val, &dummy) == 1)
3676 interleave_sectors = val;
3677 else if (sscanf(opt_string, "buffer_sectors:%u%c", &val, &dummy) == 1)
3678 buffer_sectors = val;
3679 else if (sscanf(opt_string, "journal_watermark:%u%c", &val, &dummy) == 1 && val <= 100)
3680 journal_watermark = val;
3681 else if (sscanf(opt_string, "commit_time:%u%c", &val, &dummy) == 1)
3683 else if (!strncmp(opt_string, "meta_device:", strlen("meta_device:"))) {
3685 dm_put_device(ti, ic->meta_dev);
3686 ic->meta_dev = NULL;
3688 r = dm_get_device(ti, strchr(opt_string, ':') + 1,
3689 dm_table_get_mode(ti->table), &ic->meta_dev);
3691 ti->error = "Device lookup failed";
3694 } else if (sscanf(opt_string, "block_size:%u%c", &val, &dummy) == 1) {
3695 if (val < 1 << SECTOR_SHIFT ||
3696 val > MAX_SECTORS_PER_BLOCK << SECTOR_SHIFT ||
3699 ti->error = "Invalid block_size argument";
3702 ic->sectors_per_block = val >> SECTOR_SHIFT;
3703 } else if (sscanf(opt_string, "sectors_per_bit:%llu%c", &llval, &dummy) == 1) {
3704 log2_sectors_per_bitmap_bit = !llval ? 0 : __ilog2_u64(llval);
3705 } else if (sscanf(opt_string, "bitmap_flush_interval:%u%c", &val, &dummy) == 1) {
3706 if (val >= (uint64_t)UINT_MAX * 1000 / HZ) {
3708 ti->error = "Invalid bitmap_flush_interval argument";
3710 ic->bitmap_flush_interval = msecs_to_jiffies(val);
3711 } else if (!strncmp(opt_string, "internal_hash:", strlen("internal_hash:"))) {
3712 r = get_alg_and_key(opt_string, &ic->internal_hash_alg, &ti->error,
3713 "Invalid internal_hash argument");
3716 } else if (!strncmp(opt_string, "journal_crypt:", strlen("journal_crypt:"))) {
3717 r = get_alg_and_key(opt_string, &ic->journal_crypt_alg, &ti->error,
3718 "Invalid journal_crypt argument");
3721 } else if (!strncmp(opt_string, "journal_mac:", strlen("journal_mac:"))) {
3722 r = get_alg_and_key(opt_string, &ic->journal_mac_alg, &ti->error,
3723 "Invalid journal_mac argument");
3726 } else if (!strcmp(opt_string, "recalculate")) {
3727 ic->recalculate_flag = true;
3730 ti->error = "Invalid argument";
3735 ic->data_device_sectors = i_size_read(ic->dev->bdev->bd_inode) >> SECTOR_SHIFT;
3737 ic->meta_device_sectors = ic->data_device_sectors;
3739 ic->meta_device_sectors = i_size_read(ic->meta_dev->bdev->bd_inode) >> SECTOR_SHIFT;
3741 if (!journal_sectors) {
3742 journal_sectors = min((sector_t)DEFAULT_MAX_JOURNAL_SECTORS,
3743 ic->data_device_sectors >> DEFAULT_JOURNAL_SIZE_FACTOR);
3746 if (!buffer_sectors)
3748 ic->log2_buffer_sectors = min((int)__fls(buffer_sectors), 31 - SECTOR_SHIFT);
3750 r = get_mac(&ic->internal_hash, &ic->internal_hash_alg, &ti->error,
3751 "Invalid internal hash", "Error setting internal hash key");
3755 r = get_mac(&ic->journal_mac, &ic->journal_mac_alg, &ti->error,
3756 "Invalid journal mac", "Error setting journal mac key");
3760 if (!ic->tag_size) {
3761 if (!ic->internal_hash) {
3762 ti->error = "Unknown tag size";
3766 ic->tag_size = crypto_shash_digestsize(ic->internal_hash);
3768 if (ic->tag_size > MAX_TAG_SIZE) {
3769 ti->error = "Too big tag size";
3773 if (!(ic->tag_size & (ic->tag_size - 1)))
3774 ic->log2_tag_size = __ffs(ic->tag_size);
3776 ic->log2_tag_size = -1;
3778 if (ic->mode == 'B' && !ic->internal_hash) {
3780 ti->error = "Bitmap mode can be only used with internal hash";
3784 ic->autocommit_jiffies = msecs_to_jiffies(sync_msec);
3785 ic->autocommit_msec = sync_msec;
3786 timer_setup(&ic->autocommit_timer, autocommit_fn, 0);
3788 ic->io = dm_io_client_create();
3789 if (IS_ERR(ic->io)) {
3790 r = PTR_ERR(ic->io);
3792 ti->error = "Cannot allocate dm io";
3796 r = mempool_init_slab_pool(&ic->journal_io_mempool, JOURNAL_IO_MEMPOOL, journal_io_cache);
3798 ti->error = "Cannot allocate mempool";
3802 ic->metadata_wq = alloc_workqueue("dm-integrity-metadata",
3803 WQ_MEM_RECLAIM, METADATA_WORKQUEUE_MAX_ACTIVE);
3804 if (!ic->metadata_wq) {
3805 ti->error = "Cannot allocate workqueue";
3811 * If this workqueue were percpu, it would cause bio reordering
3812 * and reduced performance.
3814 ic->wait_wq = alloc_workqueue("dm-integrity-wait", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
3816 ti->error = "Cannot allocate workqueue";
3821 ic->commit_wq = alloc_workqueue("dm-integrity-commit", WQ_MEM_RECLAIM, 1);
3822 if (!ic->commit_wq) {
3823 ti->error = "Cannot allocate workqueue";
3827 INIT_WORK(&ic->commit_work, integrity_commit);
3829 if (ic->mode == 'J' || ic->mode == 'B') {
3830 ic->writer_wq = alloc_workqueue("dm-integrity-writer", WQ_MEM_RECLAIM, 1);
3831 if (!ic->writer_wq) {
3832 ti->error = "Cannot allocate workqueue";
3836 INIT_WORK(&ic->writer_work, integrity_writer);
3839 ic->sb = alloc_pages_exact(SB_SECTORS << SECTOR_SHIFT, GFP_KERNEL);
3842 ti->error = "Cannot allocate superblock area";
3846 r = sync_rw_sb(ic, REQ_OP_READ, 0);
3848 ti->error = "Error reading superblock";
3851 should_write_sb = false;
3852 if (memcmp(ic->sb->magic, SB_MAGIC, 8)) {
3853 if (ic->mode != 'R') {
3854 if (memchr_inv(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT)) {
3856 ti->error = "The device is not initialized";
3861 r = initialize_superblock(ic, journal_sectors, interleave_sectors);
3863 ti->error = "Could not initialize superblock";
3866 if (ic->mode != 'R')
3867 should_write_sb = true;
3870 if (!ic->sb->version || ic->sb->version > SB_VERSION_3) {
3872 ti->error = "Unknown version";
3875 if (le16_to_cpu(ic->sb->integrity_tag_size) != ic->tag_size) {
3877 ti->error = "Tag size doesn't match the information in superblock";
3880 if (ic->sb->log2_sectors_per_block != __ffs(ic->sectors_per_block)) {
3882 ti->error = "Block size doesn't match the information in superblock";
3885 if (!le32_to_cpu(ic->sb->journal_sections)) {
3887 ti->error = "Corrupted superblock, journal_sections is 0";
3890 /* make sure that ti->max_io_len doesn't overflow */
3891 if (!ic->meta_dev) {
3892 if (ic->sb->log2_interleave_sectors < MIN_LOG2_INTERLEAVE_SECTORS ||
3893 ic->sb->log2_interleave_sectors > MAX_LOG2_INTERLEAVE_SECTORS) {
3895 ti->error = "Invalid interleave_sectors in the superblock";
3899 if (ic->sb->log2_interleave_sectors) {
3901 ti->error = "Invalid interleave_sectors in the superblock";
3905 ic->provided_data_sectors = le64_to_cpu(ic->sb->provided_data_sectors);
3906 if (ic->provided_data_sectors != le64_to_cpu(ic->sb->provided_data_sectors)) {
3907 /* test for overflow */
3909 ti->error = "The superblock has 64-bit device size, but the kernel was compiled with 32-bit sectors";
3912 if (!!(ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC)) != !!ic->journal_mac_alg.alg_string) {
3914 ti->error = "Journal mac mismatch";
3919 r = calculate_device_limits(ic);
3922 if (ic->log2_buffer_sectors > 3) {
3923 ic->log2_buffer_sectors--;
3924 goto try_smaller_buffer;
3927 ti->error = "The device is too small";
3931 if (log2_sectors_per_bitmap_bit < 0)
3932 log2_sectors_per_bitmap_bit = __fls(DEFAULT_SECTORS_PER_BITMAP_BIT);
3933 if (log2_sectors_per_bitmap_bit < ic->sb->log2_sectors_per_block)
3934 log2_sectors_per_bitmap_bit = ic->sb->log2_sectors_per_block;
3936 bits_in_journal = ((__u64)ic->journal_section_sectors * ic->journal_sections) << (SECTOR_SHIFT + 3);
3937 if (bits_in_journal > UINT_MAX)
3938 bits_in_journal = UINT_MAX;
3939 while (bits_in_journal < (ic->provided_data_sectors + ((sector_t)1 << log2_sectors_per_bitmap_bit) - 1) >> log2_sectors_per_bitmap_bit)
3940 log2_sectors_per_bitmap_bit++;
3942 log2_blocks_per_bitmap_bit = log2_sectors_per_bitmap_bit - ic->sb->log2_sectors_per_block;
3943 ic->log2_blocks_per_bitmap_bit = log2_blocks_per_bitmap_bit;
3944 if (should_write_sb) {
3945 ic->sb->log2_blocks_per_bitmap_bit = log2_blocks_per_bitmap_bit;
3947 n_bitmap_bits = ((ic->provided_data_sectors >> ic->sb->log2_sectors_per_block)
3948 + (((sector_t)1 << log2_blocks_per_bitmap_bit) - 1)) >> log2_blocks_per_bitmap_bit;
3949 ic->n_bitmap_blocks = DIV_ROUND_UP(n_bitmap_bits, BITMAP_BLOCK_SIZE * 8);
3952 ic->log2_buffer_sectors = min(ic->log2_buffer_sectors, (__u8)__ffs(ic->metadata_run));
3954 if (ti->len > ic->provided_data_sectors) {
3956 ti->error = "Not enough provided sectors for requested mapping size";
3961 threshold = (__u64)ic->journal_entries * (100 - journal_watermark);
3963 do_div(threshold, 100);
3964 ic->free_sectors_threshold = threshold;
3966 DEBUG_print("initialized:\n");
3967 DEBUG_print(" integrity_tag_size %u\n", le16_to_cpu(ic->sb->integrity_tag_size));
3968 DEBUG_print(" journal_entry_size %u\n", ic->journal_entry_size);
3969 DEBUG_print(" journal_entries_per_sector %u\n", ic->journal_entries_per_sector);
3970 DEBUG_print(" journal_section_entries %u\n", ic->journal_section_entries);
3971 DEBUG_print(" journal_section_sectors %u\n", ic->journal_section_sectors);
3972 DEBUG_print(" journal_sections %u\n", (unsigned)le32_to_cpu(ic->sb->journal_sections));
3973 DEBUG_print(" journal_entries %u\n", ic->journal_entries);
3974 DEBUG_print(" log2_interleave_sectors %d\n", ic->sb->log2_interleave_sectors);
3975 DEBUG_print(" data_device_sectors 0x%llx\n", i_size_read(ic->dev->bdev->bd_inode) >> SECTOR_SHIFT);
3976 DEBUG_print(" initial_sectors 0x%x\n", ic->initial_sectors);
3977 DEBUG_print(" metadata_run 0x%x\n", ic->metadata_run);
3978 DEBUG_print(" log2_metadata_run %d\n", ic->log2_metadata_run);
3979 DEBUG_print(" provided_data_sectors 0x%llx (%llu)\n", (unsigned long long)ic->provided_data_sectors,
3980 (unsigned long long)ic->provided_data_sectors);
3981 DEBUG_print(" log2_buffer_sectors %u\n", ic->log2_buffer_sectors);
3982 DEBUG_print(" bits_in_journal %llu\n", (unsigned long long)bits_in_journal);
3984 if (ic->recalculate_flag && !(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))) {
3985 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
3986 ic->sb->recalc_sector = cpu_to_le64(0);
3989 if (ic->internal_hash) {
3990 ic->recalc_wq = alloc_workqueue("dm-integrity-recalc", WQ_MEM_RECLAIM, 1);
3991 if (!ic->recalc_wq ) {
3992 ti->error = "Cannot allocate workqueue";
3996 INIT_WORK(&ic->recalc_work, integrity_recalc);
3997 ic->recalc_buffer = vmalloc(RECALC_SECTORS << SECTOR_SHIFT);
3998 if (!ic->recalc_buffer) {
3999 ti->error = "Cannot allocate buffer for recalculating";
4003 ic->recalc_tags = kvmalloc_array(RECALC_SECTORS >> ic->sb->log2_sectors_per_block,
4004 ic->tag_size, GFP_KERNEL);
4005 if (!ic->recalc_tags) {
4006 ti->error = "Cannot allocate tags for recalculating";
4012 ic->bufio = dm_bufio_client_create(ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev,
4013 1U << (SECTOR_SHIFT + ic->log2_buffer_sectors), 1, 0, NULL, NULL);
4014 if (IS_ERR(ic->bufio)) {
4015 r = PTR_ERR(ic->bufio);
4016 ti->error = "Cannot initialize dm-bufio";
4020 dm_bufio_set_sector_offset(ic->bufio, ic->start + ic->initial_sectors);
4022 if (ic->mode != 'R') {
4023 r = create_journal(ic, &ti->error);
4029 if (ic->mode == 'B') {
4031 unsigned n_bitmap_pages = DIV_ROUND_UP(ic->n_bitmap_blocks, PAGE_SIZE / BITMAP_BLOCK_SIZE);
4033 ic->recalc_bitmap = dm_integrity_alloc_page_list(n_bitmap_pages);
4034 if (!ic->recalc_bitmap) {
4038 ic->may_write_bitmap = dm_integrity_alloc_page_list(n_bitmap_pages);
4039 if (!ic->may_write_bitmap) {
4043 ic->bbs = kvmalloc_array(ic->n_bitmap_blocks, sizeof(struct bitmap_block_status), GFP_KERNEL);
4048 INIT_DELAYED_WORK(&ic->bitmap_flush_work, bitmap_flush_work);
4049 for (i = 0; i < ic->n_bitmap_blocks; i++) {
4050 struct bitmap_block_status *bbs = &ic->bbs[i];
4051 unsigned sector, pl_index, pl_offset;
4053 INIT_WORK(&bbs->work, bitmap_block_work);
4056 bio_list_init(&bbs->bio_queue);
4057 spin_lock_init(&bbs->bio_queue_lock);
4059 sector = i * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT);
4060 pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
4061 pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
4063 bbs->bitmap = lowmem_page_address(ic->journal[pl_index].page) + pl_offset;
4067 if (should_write_sb) {
4070 init_journal(ic, 0, ic->journal_sections, 0);
4071 r = dm_integrity_failed(ic);
4073 ti->error = "Error initializing journal";
4076 r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
4078 ti->error = "Error initializing superblock";
4081 ic->just_formatted = true;
4084 if (!ic->meta_dev) {
4085 r = dm_set_target_max_io_len(ti, 1U << ic->sb->log2_interleave_sectors);
4089 if (ic->mode == 'B') {
4090 unsigned max_io_len = ((sector_t)ic->sectors_per_block << ic->log2_blocks_per_bitmap_bit) * (BITMAP_BLOCK_SIZE * 8);
4092 max_io_len = 1U << 31;
4093 DEBUG_print("max_io_len: old %u, new %u\n", ti->max_io_len, max_io_len);
4094 if (!ti->max_io_len || ti->max_io_len > max_io_len) {
4095 r = dm_set_target_max_io_len(ti, max_io_len);
4101 if (!ic->internal_hash)
4102 dm_integrity_set(ti, ic);
4104 ti->num_flush_bios = 1;
4105 ti->flush_supported = true;
4110 dm_integrity_dtr(ti);
4114 static void dm_integrity_dtr(struct dm_target *ti)
4116 struct dm_integrity_c *ic = ti->private;
4118 BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
4119 BUG_ON(!list_empty(&ic->wait_list));
4121 if (ic->metadata_wq)
4122 destroy_workqueue(ic->metadata_wq);
4124 destroy_workqueue(ic->wait_wq);
4126 destroy_workqueue(ic->commit_wq);
4128 destroy_workqueue(ic->writer_wq);
4130 destroy_workqueue(ic->recalc_wq);
4131 vfree(ic->recalc_buffer);
4132 kvfree(ic->recalc_tags);
4135 dm_bufio_client_destroy(ic->bufio);
4136 mempool_exit(&ic->journal_io_mempool);
4138 dm_io_client_destroy(ic->io);
4140 dm_put_device(ti, ic->dev);
4142 dm_put_device(ti, ic->meta_dev);
4143 dm_integrity_free_page_list(ic->journal);
4144 dm_integrity_free_page_list(ic->journal_io);
4145 dm_integrity_free_page_list(ic->journal_xor);
4146 dm_integrity_free_page_list(ic->recalc_bitmap);
4147 dm_integrity_free_page_list(ic->may_write_bitmap);
4148 if (ic->journal_scatterlist)
4149 dm_integrity_free_journal_scatterlist(ic, ic->journal_scatterlist);
4150 if (ic->journal_io_scatterlist)
4151 dm_integrity_free_journal_scatterlist(ic, ic->journal_io_scatterlist);
4152 if (ic->sk_requests) {
4155 for (i = 0; i < ic->journal_sections; i++) {
4156 struct skcipher_request *req = ic->sk_requests[i];
4159 skcipher_request_free(req);
4162 kvfree(ic->sk_requests);
4164 kvfree(ic->journal_tree);
4166 free_pages_exact(ic->sb, SB_SECTORS << SECTOR_SHIFT);
4168 if (ic->internal_hash)
4169 crypto_free_shash(ic->internal_hash);
4170 free_alg(&ic->internal_hash_alg);
4172 if (ic->journal_crypt)
4173 crypto_free_skcipher(ic->journal_crypt);
4174 free_alg(&ic->journal_crypt_alg);
4176 if (ic->journal_mac)
4177 crypto_free_shash(ic->journal_mac);
4178 free_alg(&ic->journal_mac_alg);
4183 static struct target_type integrity_target = {
4184 .name = "integrity",
4185 .version = {1, 3, 0},
4186 .module = THIS_MODULE,
4187 .features = DM_TARGET_SINGLETON | DM_TARGET_INTEGRITY,
4188 .ctr = dm_integrity_ctr,
4189 .dtr = dm_integrity_dtr,
4190 .map = dm_integrity_map,
4191 .postsuspend = dm_integrity_postsuspend,
4192 .resume = dm_integrity_resume,
4193 .status = dm_integrity_status,
4194 .iterate_devices = dm_integrity_iterate_devices,
4195 .io_hints = dm_integrity_io_hints,
4198 static int __init dm_integrity_init(void)
4202 journal_io_cache = kmem_cache_create("integrity_journal_io",
4203 sizeof(struct journal_io), 0, 0, NULL);
4204 if (!journal_io_cache) {
4205 DMERR("can't allocate journal io cache");
4209 r = dm_register_target(&integrity_target);
4212 DMERR("register failed %d", r);
4217 static void __exit dm_integrity_exit(void)
4219 dm_unregister_target(&integrity_target);
4220 kmem_cache_destroy(journal_io_cache);
4223 module_init(dm_integrity_init);
4224 module_exit(dm_integrity_exit);
4226 MODULE_AUTHOR("Milan Broz");
4227 MODULE_AUTHOR("Mikulas Patocka");
4228 MODULE_DESCRIPTION(DM_NAME " target for integrity tags extension");
4229 MODULE_LICENSE("GPL");