2 * Copyright (C) 2016-2017 Red Hat, Inc. All rights reserved.
3 * Copyright (C) 2016-2017 Milan Broz
4 * Copyright (C) 2016-2017 Mikulas Patocka
6 * This file is released under the GPL.
9 #include "dm-bio-record.h"
11 #include <linux/compiler.h>
12 #include <linux/module.h>
13 #include <linux/device-mapper.h>
14 #include <linux/dm-io.h>
15 #include <linux/vmalloc.h>
16 #include <linux/sort.h>
17 #include <linux/rbtree.h>
18 #include <linux/delay.h>
19 #include <linux/random.h>
20 #include <linux/reboot.h>
21 #include <crypto/hash.h>
22 #include <crypto/skcipher.h>
23 #include <linux/async_tx.h>
24 #include <linux/dm-bufio.h>
26 #define DM_MSG_PREFIX "integrity"
28 #define DEFAULT_INTERLEAVE_SECTORS 32768
29 #define DEFAULT_JOURNAL_SIZE_FACTOR 7
30 #define DEFAULT_SECTORS_PER_BITMAP_BIT 32768
31 #define DEFAULT_BUFFER_SECTORS 128
32 #define DEFAULT_JOURNAL_WATERMARK 50
33 #define DEFAULT_SYNC_MSEC 10000
34 #define DEFAULT_MAX_JOURNAL_SECTORS 131072
35 #define MIN_LOG2_INTERLEAVE_SECTORS 3
36 #define MAX_LOG2_INTERLEAVE_SECTORS 31
37 #define METADATA_WORKQUEUE_MAX_ACTIVE 16
38 #define RECALC_SECTORS 8192
39 #define RECALC_WRITE_SUPER 16
40 #define BITMAP_BLOCK_SIZE 4096 /* don't change it */
41 #define BITMAP_FLUSH_INTERVAL (10 * HZ)
44 * Warning - DEBUG_PRINT prints security-sensitive data to the log,
45 * so it should not be enabled in the official kernel
48 //#define INTERNAL_VERIFY
54 #define SB_MAGIC "integrt"
55 #define SB_VERSION_1 1
56 #define SB_VERSION_2 2
57 #define SB_VERSION_3 3
59 #define MAX_SECTORS_PER_BLOCK 8
64 __u8 log2_interleave_sectors;
65 __u16 integrity_tag_size;
66 __u32 journal_sections;
67 __u64 provided_data_sectors; /* userspace uses this value */
69 __u8 log2_sectors_per_block;
70 __u8 log2_blocks_per_bitmap_bit;
75 #define SB_FLAG_HAVE_JOURNAL_MAC 0x1
76 #define SB_FLAG_RECALCULATING 0x2
77 #define SB_FLAG_DIRTY_BITMAP 0x4
79 #define JOURNAL_ENTRY_ROUNDUP 8
81 typedef __u64 commit_id_t;
82 #define JOURNAL_MAC_PER_SECTOR 8
84 struct journal_entry {
92 commit_id_t last_bytes[0];
96 #define journal_entry_tag(ic, je) ((__u8 *)&(je)->last_bytes[(ic)->sectors_per_block])
98 #if BITS_PER_LONG == 64
99 #define journal_entry_set_sector(je, x) do { smp_wmb(); WRITE_ONCE((je)->u.sector, cpu_to_le64(x)); } while (0)
101 #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)
103 #define journal_entry_get_sector(je) le64_to_cpu((je)->u.sector)
104 #define journal_entry_is_unused(je) ((je)->u.s.sector_hi == cpu_to_le32(-1))
105 #define journal_entry_set_unused(je) do { ((je)->u.s.sector_hi = cpu_to_le32(-1)); } while (0)
106 #define journal_entry_is_inprogress(je) ((je)->u.s.sector_hi == cpu_to_le32(-2))
107 #define journal_entry_set_inprogress(je) do { ((je)->u.s.sector_hi = cpu_to_le32(-2)); } while (0)
109 #define JOURNAL_BLOCK_SECTORS 8
110 #define JOURNAL_SECTOR_DATA ((1 << SECTOR_SHIFT) - sizeof(commit_id_t))
111 #define JOURNAL_MAC_SIZE (JOURNAL_MAC_PER_SECTOR * JOURNAL_BLOCK_SECTORS)
113 struct journal_sector {
114 __u8 entries[JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR];
115 __u8 mac[JOURNAL_MAC_PER_SECTOR];
116 commit_id_t commit_id;
119 #define MAX_TAG_SIZE (JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR - offsetof(struct journal_entry, last_bytes[MAX_SECTORS_PER_BLOCK]))
121 #define METADATA_PADDING_SECTORS 8
123 #define N_COMMIT_IDS 4
125 static unsigned char prev_commit_seq(unsigned char seq)
127 return (seq + N_COMMIT_IDS - 1) % N_COMMIT_IDS;
130 static unsigned char next_commit_seq(unsigned char seq)
132 return (seq + 1) % N_COMMIT_IDS;
136 * In-memory structures
139 struct journal_node {
151 struct dm_integrity_c {
153 struct dm_dev *meta_dev;
157 mempool_t journal_io_mempool;
158 struct dm_io_client *io;
159 struct dm_bufio_client *bufio;
160 struct workqueue_struct *metadata_wq;
161 struct superblock *sb;
162 unsigned journal_pages;
163 unsigned n_bitmap_blocks;
165 struct page_list *journal;
166 struct page_list *journal_io;
167 struct page_list *journal_xor;
168 struct page_list *recalc_bitmap;
169 struct page_list *may_write_bitmap;
170 struct bitmap_block_status *bbs;
171 unsigned bitmap_flush_interval;
172 int synchronous_mode;
173 struct bio_list synchronous_bios;
174 struct delayed_work bitmap_flush_work;
176 struct crypto_skcipher *journal_crypt;
177 struct scatterlist **journal_scatterlist;
178 struct scatterlist **journal_io_scatterlist;
179 struct skcipher_request **sk_requests;
181 struct crypto_shash *journal_mac;
183 struct journal_node *journal_tree;
184 struct rb_root journal_tree_root;
186 sector_t provided_data_sectors;
188 unsigned short journal_entry_size;
189 unsigned char journal_entries_per_sector;
190 unsigned char journal_section_entries;
191 unsigned short journal_section_sectors;
192 unsigned journal_sections;
193 unsigned journal_entries;
194 sector_t data_device_sectors;
195 sector_t meta_device_sectors;
196 unsigned initial_sectors;
197 unsigned metadata_run;
198 __s8 log2_metadata_run;
199 __u8 log2_buffer_sectors;
200 __u8 sectors_per_block;
201 __u8 log2_blocks_per_bitmap_bit;
207 struct crypto_shash *internal_hash;
209 struct dm_target *ti;
211 /* these variables are locked with endio_wait.lock */
212 struct rb_root in_progress;
213 struct list_head wait_list;
214 wait_queue_head_t endio_wait;
215 struct workqueue_struct *wait_wq;
216 struct workqueue_struct *offload_wq;
218 unsigned char commit_seq;
219 commit_id_t commit_ids[N_COMMIT_IDS];
221 unsigned committed_section;
222 unsigned n_committed_sections;
224 unsigned uncommitted_section;
225 unsigned n_uncommitted_sections;
227 unsigned free_section;
228 unsigned char free_section_entry;
229 unsigned free_sectors;
231 unsigned free_sectors_threshold;
233 struct workqueue_struct *commit_wq;
234 struct work_struct commit_work;
236 struct workqueue_struct *writer_wq;
237 struct work_struct writer_work;
239 struct workqueue_struct *recalc_wq;
240 struct work_struct recalc_work;
244 struct bio_list flush_bio_list;
246 unsigned long autocommit_jiffies;
247 struct timer_list autocommit_timer;
248 unsigned autocommit_msec;
250 wait_queue_head_t copy_to_journal_wait;
252 struct completion crypto_backoff;
254 bool journal_uptodate;
256 bool recalculate_flag;
258 struct alg_spec internal_hash_alg;
259 struct alg_spec journal_crypt_alg;
260 struct alg_spec journal_mac_alg;
262 atomic64_t number_of_mismatches;
264 struct notifier_block reboot_notifier;
267 struct dm_integrity_range {
268 sector_t logical_sector;
274 struct task_struct *task;
275 struct list_head wait_entry;
280 struct dm_integrity_io {
281 struct work_struct work;
283 struct dm_integrity_c *ic;
287 struct dm_integrity_range range;
289 sector_t metadata_block;
290 unsigned metadata_offset;
293 blk_status_t bi_status;
295 struct completion *completion;
297 struct dm_bio_details bio_details;
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->offload_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 dm_bio_restore(&dio->bio_details, bio);
1449 if (bio->bi_integrity)
1450 bio->bi_opf |= REQ_INTEGRITY;
1452 if (dio->completion)
1453 complete(dio->completion);
1458 static void integrity_sector_checksum(struct dm_integrity_c *ic, sector_t sector,
1459 const char *data, char *result)
1461 __u64 sector_le = cpu_to_le64(sector);
1462 SHASH_DESC_ON_STACK(req, ic->internal_hash);
1464 unsigned digest_size;
1466 req->tfm = ic->internal_hash;
1468 r = crypto_shash_init(req);
1469 if (unlikely(r < 0)) {
1470 dm_integrity_io_error(ic, "crypto_shash_init", r);
1474 r = crypto_shash_update(req, (const __u8 *)§or_le, sizeof sector_le);
1475 if (unlikely(r < 0)) {
1476 dm_integrity_io_error(ic, "crypto_shash_update", r);
1480 r = crypto_shash_update(req, data, ic->sectors_per_block << SECTOR_SHIFT);
1481 if (unlikely(r < 0)) {
1482 dm_integrity_io_error(ic, "crypto_shash_update", r);
1486 r = crypto_shash_final(req, result);
1487 if (unlikely(r < 0)) {
1488 dm_integrity_io_error(ic, "crypto_shash_final", r);
1492 digest_size = crypto_shash_digestsize(ic->internal_hash);
1493 if (unlikely(digest_size < ic->tag_size))
1494 memset(result + digest_size, 0, ic->tag_size - digest_size);
1499 /* this shouldn't happen anyway, the hash functions have no reason to fail */
1500 get_random_bytes(result, ic->tag_size);
1503 static void integrity_metadata(struct work_struct *w)
1505 struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
1506 struct dm_integrity_c *ic = dio->ic;
1510 if (ic->internal_hash) {
1511 struct bvec_iter iter;
1513 unsigned digest_size = crypto_shash_digestsize(ic->internal_hash);
1514 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1516 unsigned extra_space = unlikely(digest_size > ic->tag_size) ? digest_size - ic->tag_size : 0;
1517 char checksums_onstack[max((size_t)HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
1518 unsigned sectors_to_process = dio->range.n_sectors;
1519 sector_t sector = dio->range.logical_sector;
1521 if (unlikely(ic->mode == 'R'))
1524 checksums = kmalloc((PAGE_SIZE >> SECTOR_SHIFT >> ic->sb->log2_sectors_per_block) * ic->tag_size + extra_space,
1525 GFP_NOIO | __GFP_NORETRY | __GFP_NOWARN);
1527 checksums = checksums_onstack;
1528 if (WARN_ON(extra_space &&
1529 digest_size > sizeof(checksums_onstack))) {
1535 __bio_for_each_segment(bv, bio, iter, dio->bio_details.bi_iter) {
1537 char *mem, *checksums_ptr;
1540 mem = (char *)kmap_atomic(bv.bv_page) + bv.bv_offset;
1542 checksums_ptr = checksums;
1544 integrity_sector_checksum(ic, sector, mem + pos, checksums_ptr);
1545 checksums_ptr += ic->tag_size;
1546 sectors_to_process -= ic->sectors_per_block;
1547 pos += ic->sectors_per_block << SECTOR_SHIFT;
1548 sector += ic->sectors_per_block;
1549 } while (pos < bv.bv_len && sectors_to_process && checksums != checksums_onstack);
1552 r = dm_integrity_rw_tag(ic, checksums, &dio->metadata_block, &dio->metadata_offset,
1553 checksums_ptr - checksums, !dio->write ? TAG_CMP : TAG_WRITE);
1556 DMERR_LIMIT("Checksum failed at sector 0x%llx",
1557 (unsigned long long)(sector - ((r + ic->tag_size - 1) / ic->tag_size)));
1559 atomic64_inc(&ic->number_of_mismatches);
1561 if (likely(checksums != checksums_onstack))
1566 if (!sectors_to_process)
1569 if (unlikely(pos < bv.bv_len)) {
1570 bv.bv_offset += pos;
1576 if (likely(checksums != checksums_onstack))
1579 struct bio_integrity_payload *bip = dio->bio_details.bi_integrity;
1583 struct bvec_iter iter;
1584 unsigned data_to_process = dio->range.n_sectors;
1585 sector_to_block(ic, data_to_process);
1586 data_to_process *= ic->tag_size;
1588 bip_for_each_vec(biv, bip, iter) {
1592 BUG_ON(PageHighMem(biv.bv_page));
1593 tag = lowmem_page_address(biv.bv_page) + biv.bv_offset;
1594 this_len = min(biv.bv_len, data_to_process);
1595 r = dm_integrity_rw_tag(ic, tag, &dio->metadata_block, &dio->metadata_offset,
1596 this_len, !dio->write ? TAG_READ : TAG_WRITE);
1599 data_to_process -= this_len;
1600 if (!data_to_process)
1609 dio->bi_status = errno_to_blk_status(r);
1613 static int dm_integrity_map(struct dm_target *ti, struct bio *bio)
1615 struct dm_integrity_c *ic = ti->private;
1616 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
1617 struct bio_integrity_payload *bip;
1619 sector_t area, offset;
1624 if (unlikely(bio->bi_opf & REQ_PREFLUSH)) {
1625 submit_flush_bio(ic, dio);
1626 return DM_MAPIO_SUBMITTED;
1629 dio->range.logical_sector = dm_target_offset(ti, bio->bi_iter.bi_sector);
1630 dio->write = bio_op(bio) == REQ_OP_WRITE;
1631 dio->fua = dio->write && bio->bi_opf & REQ_FUA;
1632 if (unlikely(dio->fua)) {
1634 * Don't pass down the FUA flag because we have to flush
1635 * disk cache anyway.
1637 bio->bi_opf &= ~REQ_FUA;
1639 if (unlikely(dio->range.logical_sector + bio_sectors(bio) > ic->provided_data_sectors)) {
1640 DMERR("Too big sector number: 0x%llx + 0x%x > 0x%llx",
1641 (unsigned long long)dio->range.logical_sector, bio_sectors(bio),
1642 (unsigned long long)ic->provided_data_sectors);
1643 return DM_MAPIO_KILL;
1645 if (unlikely((dio->range.logical_sector | bio_sectors(bio)) & (unsigned)(ic->sectors_per_block - 1))) {
1646 DMERR("Bio not aligned on %u sectors: 0x%llx, 0x%x",
1647 ic->sectors_per_block,
1648 (unsigned long long)dio->range.logical_sector, bio_sectors(bio));
1649 return DM_MAPIO_KILL;
1652 if (ic->sectors_per_block > 1) {
1653 struct bvec_iter iter;
1655 bio_for_each_segment(bv, bio, iter) {
1656 if (unlikely(bv.bv_len & ((ic->sectors_per_block << SECTOR_SHIFT) - 1))) {
1657 DMERR("Bio vector (%u,%u) is not aligned on %u-sector boundary",
1658 bv.bv_offset, bv.bv_len, ic->sectors_per_block);
1659 return DM_MAPIO_KILL;
1664 bip = bio_integrity(bio);
1665 if (!ic->internal_hash) {
1667 unsigned wanted_tag_size = bio_sectors(bio) >> ic->sb->log2_sectors_per_block;
1668 if (ic->log2_tag_size >= 0)
1669 wanted_tag_size <<= ic->log2_tag_size;
1671 wanted_tag_size *= ic->tag_size;
1672 if (unlikely(wanted_tag_size != bip->bip_iter.bi_size)) {
1673 DMERR("Invalid integrity data size %u, expected %u",
1674 bip->bip_iter.bi_size, wanted_tag_size);
1675 return DM_MAPIO_KILL;
1679 if (unlikely(bip != NULL)) {
1680 DMERR("Unexpected integrity data when using internal hash");
1681 return DM_MAPIO_KILL;
1685 if (unlikely(ic->mode == 'R') && unlikely(dio->write))
1686 return DM_MAPIO_KILL;
1688 get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
1689 dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
1690 bio->bi_iter.bi_sector = get_data_sector(ic, area, offset);
1692 dm_integrity_map_continue(dio, true);
1693 return DM_MAPIO_SUBMITTED;
1696 static bool __journal_read_write(struct dm_integrity_io *dio, struct bio *bio,
1697 unsigned journal_section, unsigned journal_entry)
1699 struct dm_integrity_c *ic = dio->ic;
1700 sector_t logical_sector;
1703 logical_sector = dio->range.logical_sector;
1704 n_sectors = dio->range.n_sectors;
1706 struct bio_vec bv = bio_iovec(bio);
1709 if (unlikely(bv.bv_len >> SECTOR_SHIFT > n_sectors))
1710 bv.bv_len = n_sectors << SECTOR_SHIFT;
1711 n_sectors -= bv.bv_len >> SECTOR_SHIFT;
1712 bio_advance_iter(bio, &bio->bi_iter, bv.bv_len);
1714 mem = kmap_atomic(bv.bv_page);
1715 if (likely(dio->write))
1716 flush_dcache_page(bv.bv_page);
1719 struct journal_entry *je = access_journal_entry(ic, journal_section, journal_entry);
1721 if (unlikely(!dio->write)) {
1722 struct journal_sector *js;
1726 if (unlikely(journal_entry_is_inprogress(je))) {
1727 flush_dcache_page(bv.bv_page);
1730 __io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
1734 BUG_ON(journal_entry_get_sector(je) != logical_sector);
1735 js = access_journal_data(ic, journal_section, journal_entry);
1736 mem_ptr = mem + bv.bv_offset;
1739 memcpy(mem_ptr, js, JOURNAL_SECTOR_DATA);
1740 *(commit_id_t *)(mem_ptr + JOURNAL_SECTOR_DATA) = je->last_bytes[s];
1742 mem_ptr += 1 << SECTOR_SHIFT;
1743 } while (++s < ic->sectors_per_block);
1744 #ifdef INTERNAL_VERIFY
1745 if (ic->internal_hash) {
1746 char checksums_onstack[max((size_t)HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
1748 integrity_sector_checksum(ic, logical_sector, mem + bv.bv_offset, checksums_onstack);
1749 if (unlikely(memcmp(checksums_onstack, journal_entry_tag(ic, je), ic->tag_size))) {
1750 DMERR_LIMIT("Checksum failed when reading from journal, at sector 0x%llx",
1751 (unsigned long long)logical_sector);
1757 if (!ic->internal_hash) {
1758 struct bio_integrity_payload *bip = bio_integrity(bio);
1759 unsigned tag_todo = ic->tag_size;
1760 char *tag_ptr = journal_entry_tag(ic, je);
1763 struct bio_vec biv = bvec_iter_bvec(bip->bip_vec, bip->bip_iter);
1764 unsigned tag_now = min(biv.bv_len, tag_todo);
1766 BUG_ON(PageHighMem(biv.bv_page));
1767 tag_addr = lowmem_page_address(biv.bv_page) + biv.bv_offset;
1768 if (likely(dio->write))
1769 memcpy(tag_ptr, tag_addr, tag_now);
1771 memcpy(tag_addr, tag_ptr, tag_now);
1772 bvec_iter_advance(bip->bip_vec, &bip->bip_iter, tag_now);
1774 tag_todo -= tag_now;
1775 } while (unlikely(tag_todo)); else {
1776 if (likely(dio->write))
1777 memset(tag_ptr, 0, tag_todo);
1781 if (likely(dio->write)) {
1782 struct journal_sector *js;
1785 js = access_journal_data(ic, journal_section, journal_entry);
1786 memcpy(js, mem + bv.bv_offset, ic->sectors_per_block << SECTOR_SHIFT);
1790 je->last_bytes[s] = js[s].commit_id;
1791 } while (++s < ic->sectors_per_block);
1793 if (ic->internal_hash) {
1794 unsigned digest_size = crypto_shash_digestsize(ic->internal_hash);
1795 if (unlikely(digest_size > ic->tag_size)) {
1796 char checksums_onstack[HASH_MAX_DIGESTSIZE];
1797 integrity_sector_checksum(ic, logical_sector, (char *)js, checksums_onstack);
1798 memcpy(journal_entry_tag(ic, je), checksums_onstack, ic->tag_size);
1800 integrity_sector_checksum(ic, logical_sector, (char *)js, journal_entry_tag(ic, je));
1803 journal_entry_set_sector(je, logical_sector);
1805 logical_sector += ic->sectors_per_block;
1808 if (unlikely(journal_entry == ic->journal_section_entries)) {
1811 wraparound_section(ic, &journal_section);
1814 bv.bv_offset += ic->sectors_per_block << SECTOR_SHIFT;
1815 } while (bv.bv_len -= ic->sectors_per_block << SECTOR_SHIFT);
1817 if (unlikely(!dio->write))
1818 flush_dcache_page(bv.bv_page);
1820 } while (n_sectors);
1822 if (likely(dio->write)) {
1824 if (unlikely(waitqueue_active(&ic->copy_to_journal_wait)))
1825 wake_up(&ic->copy_to_journal_wait);
1826 if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold) {
1827 queue_work(ic->commit_wq, &ic->commit_work);
1829 schedule_autocommit(ic);
1832 remove_range(ic, &dio->range);
1835 if (unlikely(bio->bi_iter.bi_size)) {
1836 sector_t area, offset;
1838 dio->range.logical_sector = logical_sector;
1839 get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
1840 dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
1847 static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map)
1849 struct dm_integrity_c *ic = dio->ic;
1850 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1851 unsigned journal_section, journal_entry;
1852 unsigned journal_read_pos;
1853 struct completion read_comp;
1854 bool need_sync_io = ic->internal_hash && !dio->write;
1856 if (need_sync_io && from_map) {
1857 INIT_WORK(&dio->work, integrity_bio_wait);
1858 queue_work(ic->offload_wq, &dio->work);
1863 spin_lock_irq(&ic->endio_wait.lock);
1865 if (unlikely(dm_integrity_failed(ic))) {
1866 spin_unlock_irq(&ic->endio_wait.lock);
1870 dio->range.n_sectors = bio_sectors(bio);
1871 journal_read_pos = NOT_FOUND;
1872 if (likely(ic->mode == 'J')) {
1874 unsigned next_entry, i, pos;
1875 unsigned ws, we, range_sectors;
1877 dio->range.n_sectors = min(dio->range.n_sectors,
1878 (sector_t)ic->free_sectors << ic->sb->log2_sectors_per_block);
1879 if (unlikely(!dio->range.n_sectors)) {
1881 goto offload_to_thread;
1882 sleep_on_endio_wait(ic);
1885 range_sectors = dio->range.n_sectors >> ic->sb->log2_sectors_per_block;
1886 ic->free_sectors -= range_sectors;
1887 journal_section = ic->free_section;
1888 journal_entry = ic->free_section_entry;
1890 next_entry = ic->free_section_entry + range_sectors;
1891 ic->free_section_entry = next_entry % ic->journal_section_entries;
1892 ic->free_section += next_entry / ic->journal_section_entries;
1893 ic->n_uncommitted_sections += next_entry / ic->journal_section_entries;
1894 wraparound_section(ic, &ic->free_section);
1896 pos = journal_section * ic->journal_section_entries + journal_entry;
1897 ws = journal_section;
1901 struct journal_entry *je;
1903 add_journal_node(ic, &ic->journal_tree[pos], dio->range.logical_sector + i);
1905 if (unlikely(pos >= ic->journal_entries))
1908 je = access_journal_entry(ic, ws, we);
1909 BUG_ON(!journal_entry_is_unused(je));
1910 journal_entry_set_inprogress(je);
1912 if (unlikely(we == ic->journal_section_entries)) {
1915 wraparound_section(ic, &ws);
1917 } while ((i += ic->sectors_per_block) < dio->range.n_sectors);
1919 spin_unlock_irq(&ic->endio_wait.lock);
1920 goto journal_read_write;
1922 sector_t next_sector;
1923 journal_read_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
1924 if (likely(journal_read_pos == NOT_FOUND)) {
1925 if (unlikely(dio->range.n_sectors > next_sector - dio->range.logical_sector))
1926 dio->range.n_sectors = next_sector - dio->range.logical_sector;
1929 unsigned jp = journal_read_pos + 1;
1930 for (i = ic->sectors_per_block; i < dio->range.n_sectors; i += ic->sectors_per_block, jp++) {
1931 if (!test_journal_node(ic, jp, dio->range.logical_sector + i))
1934 dio->range.n_sectors = i;
1938 if (unlikely(!add_new_range(ic, &dio->range, true))) {
1940 * We must not sleep in the request routine because it could
1941 * stall bios on current->bio_list.
1942 * So, we offload the bio to a workqueue if we have to sleep.
1946 spin_unlock_irq(&ic->endio_wait.lock);
1947 INIT_WORK(&dio->work, integrity_bio_wait);
1948 queue_work(ic->wait_wq, &dio->work);
1951 if (journal_read_pos != NOT_FOUND)
1952 dio->range.n_sectors = ic->sectors_per_block;
1953 wait_and_add_new_range(ic, &dio->range);
1955 * wait_and_add_new_range drops the spinlock, so the journal
1956 * may have been changed arbitrarily. We need to recheck.
1957 * To simplify the code, we restrict I/O size to just one block.
1959 if (journal_read_pos != NOT_FOUND) {
1960 sector_t next_sector;
1961 unsigned new_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
1962 if (unlikely(new_pos != journal_read_pos)) {
1963 remove_range_unlocked(ic, &dio->range);
1968 spin_unlock_irq(&ic->endio_wait.lock);
1970 if (unlikely(journal_read_pos != NOT_FOUND)) {
1971 journal_section = journal_read_pos / ic->journal_section_entries;
1972 journal_entry = journal_read_pos % ic->journal_section_entries;
1973 goto journal_read_write;
1976 if (ic->mode == 'B' && dio->write) {
1977 if (!block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
1978 dio->range.n_sectors, BITMAP_OP_TEST_ALL_SET)) {
1979 struct bitmap_block_status *bbs;
1981 bbs = sector_to_bitmap_block(ic, dio->range.logical_sector);
1982 spin_lock(&bbs->bio_queue_lock);
1983 bio_list_add(&bbs->bio_queue, bio);
1984 spin_unlock(&bbs->bio_queue_lock);
1985 queue_work(ic->writer_wq, &bbs->work);
1990 dio->in_flight = (atomic_t)ATOMIC_INIT(2);
1993 init_completion(&read_comp);
1994 dio->completion = &read_comp;
1996 dio->completion = NULL;
1998 dm_bio_record(&dio->bio_details, bio);
1999 bio_set_dev(bio, ic->dev->bdev);
2000 bio->bi_integrity = NULL;
2001 bio->bi_opf &= ~REQ_INTEGRITY;
2002 bio->bi_end_io = integrity_end_io;
2003 bio->bi_iter.bi_size = dio->range.n_sectors << SECTOR_SHIFT;
2005 generic_make_request(bio);
2008 wait_for_completion_io(&read_comp);
2009 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
2010 dio->range.logical_sector + dio->range.n_sectors > le64_to_cpu(ic->sb->recalc_sector))
2012 if (ic->mode == 'B') {
2013 if (!block_bitmap_op(ic, ic->recalc_bitmap, dio->range.logical_sector,
2014 dio->range.n_sectors, BITMAP_OP_TEST_ALL_CLEAR))
2018 if (likely(!bio->bi_status))
2019 integrity_metadata(&dio->work);
2025 INIT_WORK(&dio->work, integrity_metadata);
2026 queue_work(ic->metadata_wq, &dio->work);
2032 if (unlikely(__journal_read_write(dio, bio, journal_section, journal_entry)))
2035 do_endio_flush(ic, dio);
2039 static void integrity_bio_wait(struct work_struct *w)
2041 struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
2043 dm_integrity_map_continue(dio, false);
2046 static void pad_uncommitted(struct dm_integrity_c *ic)
2048 if (ic->free_section_entry) {
2049 ic->free_sectors -= ic->journal_section_entries - ic->free_section_entry;
2050 ic->free_section_entry = 0;
2052 wraparound_section(ic, &ic->free_section);
2053 ic->n_uncommitted_sections++;
2055 if (WARN_ON(ic->journal_sections * ic->journal_section_entries !=
2056 (ic->n_uncommitted_sections + ic->n_committed_sections) *
2057 ic->journal_section_entries + ic->free_sectors)) {
2058 DMCRIT("journal_sections %u, journal_section_entries %u, "
2059 "n_uncommitted_sections %u, n_committed_sections %u, "
2060 "journal_section_entries %u, free_sectors %u",
2061 ic->journal_sections, ic->journal_section_entries,
2062 ic->n_uncommitted_sections, ic->n_committed_sections,
2063 ic->journal_section_entries, ic->free_sectors);
2067 static void integrity_commit(struct work_struct *w)
2069 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, commit_work);
2070 unsigned commit_start, commit_sections;
2072 struct bio *flushes;
2074 del_timer(&ic->autocommit_timer);
2076 spin_lock_irq(&ic->endio_wait.lock);
2077 flushes = bio_list_get(&ic->flush_bio_list);
2078 if (unlikely(ic->mode != 'J')) {
2079 spin_unlock_irq(&ic->endio_wait.lock);
2080 dm_integrity_flush_buffers(ic);
2081 goto release_flush_bios;
2084 pad_uncommitted(ic);
2085 commit_start = ic->uncommitted_section;
2086 commit_sections = ic->n_uncommitted_sections;
2087 spin_unlock_irq(&ic->endio_wait.lock);
2089 if (!commit_sections)
2090 goto release_flush_bios;
2093 for (n = 0; n < commit_sections; n++) {
2094 for (j = 0; j < ic->journal_section_entries; j++) {
2095 struct journal_entry *je;
2096 je = access_journal_entry(ic, i, j);
2097 io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
2099 for (j = 0; j < ic->journal_section_sectors; j++) {
2100 struct journal_sector *js;
2101 js = access_journal(ic, i, j);
2102 js->commit_id = dm_integrity_commit_id(ic, i, j, ic->commit_seq);
2105 if (unlikely(i >= ic->journal_sections))
2106 ic->commit_seq = next_commit_seq(ic->commit_seq);
2107 wraparound_section(ic, &i);
2111 write_journal(ic, commit_start, commit_sections);
2113 spin_lock_irq(&ic->endio_wait.lock);
2114 ic->uncommitted_section += commit_sections;
2115 wraparound_section(ic, &ic->uncommitted_section);
2116 ic->n_uncommitted_sections -= commit_sections;
2117 ic->n_committed_sections += commit_sections;
2118 spin_unlock_irq(&ic->endio_wait.lock);
2120 if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold)
2121 queue_work(ic->writer_wq, &ic->writer_work);
2125 struct bio *next = flushes->bi_next;
2126 flushes->bi_next = NULL;
2127 do_endio(ic, flushes);
2132 static void complete_copy_from_journal(unsigned long error, void *context)
2134 struct journal_io *io = context;
2135 struct journal_completion *comp = io->comp;
2136 struct dm_integrity_c *ic = comp->ic;
2137 remove_range(ic, &io->range);
2138 mempool_free(io, &ic->journal_io_mempool);
2139 if (unlikely(error != 0))
2140 dm_integrity_io_error(ic, "copying from journal", -EIO);
2141 complete_journal_op(comp);
2144 static void restore_last_bytes(struct dm_integrity_c *ic, struct journal_sector *js,
2145 struct journal_entry *je)
2149 js->commit_id = je->last_bytes[s];
2151 } while (++s < ic->sectors_per_block);
2154 static void do_journal_write(struct dm_integrity_c *ic, unsigned write_start,
2155 unsigned write_sections, bool from_replay)
2158 struct journal_completion comp;
2159 struct blk_plug plug;
2161 blk_start_plug(&plug);
2164 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
2165 init_completion(&comp.comp);
2168 for (n = 0; n < write_sections; n++, i++, wraparound_section(ic, &i)) {
2169 #ifndef INTERNAL_VERIFY
2170 if (unlikely(from_replay))
2172 rw_section_mac(ic, i, false);
2173 for (j = 0; j < ic->journal_section_entries; j++) {
2174 struct journal_entry *je = access_journal_entry(ic, i, j);
2175 sector_t sec, area, offset;
2176 unsigned k, l, next_loop;
2177 sector_t metadata_block;
2178 unsigned metadata_offset;
2179 struct journal_io *io;
2181 if (journal_entry_is_unused(je))
2183 BUG_ON(unlikely(journal_entry_is_inprogress(je)) && !from_replay);
2184 sec = journal_entry_get_sector(je);
2185 if (unlikely(from_replay)) {
2186 if (unlikely(sec & (unsigned)(ic->sectors_per_block - 1))) {
2187 dm_integrity_io_error(ic, "invalid sector in journal", -EIO);
2188 sec &= ~(sector_t)(ic->sectors_per_block - 1);
2191 get_area_and_offset(ic, sec, &area, &offset);
2192 restore_last_bytes(ic, access_journal_data(ic, i, j), je);
2193 for (k = j + 1; k < ic->journal_section_entries; k++) {
2194 struct journal_entry *je2 = access_journal_entry(ic, i, k);
2195 sector_t sec2, area2, offset2;
2196 if (journal_entry_is_unused(je2))
2198 BUG_ON(unlikely(journal_entry_is_inprogress(je2)) && !from_replay);
2199 sec2 = journal_entry_get_sector(je2);
2200 get_area_and_offset(ic, sec2, &area2, &offset2);
2201 if (area2 != area || offset2 != offset + ((k - j) << ic->sb->log2_sectors_per_block))
2203 restore_last_bytes(ic, access_journal_data(ic, i, k), je2);
2207 io = mempool_alloc(&ic->journal_io_mempool, GFP_NOIO);
2209 io->range.logical_sector = sec;
2210 io->range.n_sectors = (k - j) << ic->sb->log2_sectors_per_block;
2212 spin_lock_irq(&ic->endio_wait.lock);
2213 add_new_range_and_wait(ic, &io->range);
2215 if (likely(!from_replay)) {
2216 struct journal_node *section_node = &ic->journal_tree[i * ic->journal_section_entries];
2218 /* don't write if there is newer committed sector */
2219 while (j < k && find_newer_committed_node(ic, §ion_node[j])) {
2220 struct journal_entry *je2 = access_journal_entry(ic, i, j);
2222 journal_entry_set_unused(je2);
2223 remove_journal_node(ic, §ion_node[j]);
2225 sec += ic->sectors_per_block;
2226 offset += ic->sectors_per_block;
2228 while (j < k && find_newer_committed_node(ic, §ion_node[k - 1])) {
2229 struct journal_entry *je2 = access_journal_entry(ic, i, k - 1);
2231 journal_entry_set_unused(je2);
2232 remove_journal_node(ic, §ion_node[k - 1]);
2236 remove_range_unlocked(ic, &io->range);
2237 spin_unlock_irq(&ic->endio_wait.lock);
2238 mempool_free(io, &ic->journal_io_mempool);
2241 for (l = j; l < k; l++) {
2242 remove_journal_node(ic, §ion_node[l]);
2245 spin_unlock_irq(&ic->endio_wait.lock);
2247 metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
2248 for (l = j; l < k; l++) {
2250 struct journal_entry *je2 = access_journal_entry(ic, i, l);
2253 #ifndef INTERNAL_VERIFY
2254 unlikely(from_replay) &&
2256 ic->internal_hash) {
2257 char test_tag[max_t(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
2259 integrity_sector_checksum(ic, sec + ((l - j) << ic->sb->log2_sectors_per_block),
2260 (char *)access_journal_data(ic, i, l), test_tag);
2261 if (unlikely(memcmp(test_tag, journal_entry_tag(ic, je2), ic->tag_size)))
2262 dm_integrity_io_error(ic, "tag mismatch when replaying journal", -EILSEQ);
2265 journal_entry_set_unused(je2);
2266 r = dm_integrity_rw_tag(ic, journal_entry_tag(ic, je2), &metadata_block, &metadata_offset,
2267 ic->tag_size, TAG_WRITE);
2269 dm_integrity_io_error(ic, "reading tags", r);
2273 atomic_inc(&comp.in_flight);
2274 copy_from_journal(ic, i, j << ic->sb->log2_sectors_per_block,
2275 (k - j) << ic->sb->log2_sectors_per_block,
2276 get_data_sector(ic, area, offset),
2277 complete_copy_from_journal, io);
2283 dm_bufio_write_dirty_buffers_async(ic->bufio);
2285 blk_finish_plug(&plug);
2287 complete_journal_op(&comp);
2288 wait_for_completion_io(&comp.comp);
2290 dm_integrity_flush_buffers(ic);
2293 static void integrity_writer(struct work_struct *w)
2295 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, writer_work);
2296 unsigned write_start, write_sections;
2298 unsigned prev_free_sectors;
2300 /* the following test is not needed, but it tests the replay code */
2301 if (unlikely(dm_suspended(ic->ti)) && !ic->meta_dev)
2304 spin_lock_irq(&ic->endio_wait.lock);
2305 write_start = ic->committed_section;
2306 write_sections = ic->n_committed_sections;
2307 spin_unlock_irq(&ic->endio_wait.lock);
2309 if (!write_sections)
2312 do_journal_write(ic, write_start, write_sections, false);
2314 spin_lock_irq(&ic->endio_wait.lock);
2316 ic->committed_section += write_sections;
2317 wraparound_section(ic, &ic->committed_section);
2318 ic->n_committed_sections -= write_sections;
2320 prev_free_sectors = ic->free_sectors;
2321 ic->free_sectors += write_sections * ic->journal_section_entries;
2322 if (unlikely(!prev_free_sectors))
2323 wake_up_locked(&ic->endio_wait);
2325 spin_unlock_irq(&ic->endio_wait.lock);
2328 static void recalc_write_super(struct dm_integrity_c *ic)
2332 dm_integrity_flush_buffers(ic);
2333 if (dm_integrity_failed(ic))
2336 r = sync_rw_sb(ic, REQ_OP_WRITE, 0);
2338 dm_integrity_io_error(ic, "writing superblock", r);
2341 static void integrity_recalc(struct work_struct *w)
2343 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, recalc_work);
2344 struct dm_integrity_range range;
2345 struct dm_io_request io_req;
2346 struct dm_io_region io_loc;
2347 sector_t area, offset;
2348 sector_t metadata_block;
2349 unsigned metadata_offset;
2350 sector_t logical_sector, n_sectors;
2354 unsigned super_counter = 0;
2356 DEBUG_print("start recalculation... (position %llx)\n", le64_to_cpu(ic->sb->recalc_sector));
2358 spin_lock_irq(&ic->endio_wait.lock);
2362 if (unlikely(dm_suspended(ic->ti)))
2365 range.logical_sector = le64_to_cpu(ic->sb->recalc_sector);
2366 if (unlikely(range.logical_sector >= ic->provided_data_sectors)) {
2367 if (ic->mode == 'B') {
2368 DEBUG_print("queue_delayed_work: bitmap_flush_work\n");
2369 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
2374 get_area_and_offset(ic, range.logical_sector, &area, &offset);
2375 range.n_sectors = min((sector_t)RECALC_SECTORS, ic->provided_data_sectors - range.logical_sector);
2377 range.n_sectors = min(range.n_sectors, ((sector_t)1U << ic->sb->log2_interleave_sectors) - (unsigned)offset);
2379 add_new_range_and_wait(ic, &range);
2380 spin_unlock_irq(&ic->endio_wait.lock);
2381 logical_sector = range.logical_sector;
2382 n_sectors = range.n_sectors;
2384 if (ic->mode == 'B') {
2385 if (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector, n_sectors, BITMAP_OP_TEST_ALL_CLEAR)) {
2386 goto advance_and_next;
2388 while (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector,
2389 ic->sectors_per_block, BITMAP_OP_TEST_ALL_CLEAR)) {
2390 logical_sector += ic->sectors_per_block;
2391 n_sectors -= ic->sectors_per_block;
2394 while (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector + n_sectors - ic->sectors_per_block,
2395 ic->sectors_per_block, BITMAP_OP_TEST_ALL_CLEAR)) {
2396 n_sectors -= ic->sectors_per_block;
2399 get_area_and_offset(ic, logical_sector, &area, &offset);
2402 DEBUG_print("recalculating: %lx, %lx\n", logical_sector, n_sectors);
2404 if (unlikely(++super_counter == RECALC_WRITE_SUPER)) {
2405 recalc_write_super(ic);
2406 if (ic->mode == 'B') {
2407 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, ic->bitmap_flush_interval);
2412 if (unlikely(dm_integrity_failed(ic)))
2415 io_req.bi_op = REQ_OP_READ;
2416 io_req.bi_op_flags = 0;
2417 io_req.mem.type = DM_IO_VMA;
2418 io_req.mem.ptr.addr = ic->recalc_buffer;
2419 io_req.notify.fn = NULL;
2420 io_req.client = ic->io;
2421 io_loc.bdev = ic->dev->bdev;
2422 io_loc.sector = get_data_sector(ic, area, offset);
2423 io_loc.count = n_sectors;
2425 r = dm_io(&io_req, 1, &io_loc, NULL);
2427 dm_integrity_io_error(ic, "reading data", r);
2431 t = ic->recalc_tags;
2432 for (i = 0; i < n_sectors; i += ic->sectors_per_block) {
2433 integrity_sector_checksum(ic, logical_sector + i, ic->recalc_buffer + (i << SECTOR_SHIFT), t);
2437 metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
2439 r = dm_integrity_rw_tag(ic, ic->recalc_tags, &metadata_block, &metadata_offset, t - ic->recalc_tags, TAG_WRITE);
2441 dm_integrity_io_error(ic, "writing tags", r);
2448 spin_lock_irq(&ic->endio_wait.lock);
2449 remove_range_unlocked(ic, &range);
2450 ic->sb->recalc_sector = cpu_to_le64(range.logical_sector + range.n_sectors);
2454 remove_range(ic, &range);
2458 spin_unlock_irq(&ic->endio_wait.lock);
2460 recalc_write_super(ic);
2463 static void bitmap_block_work(struct work_struct *w)
2465 struct bitmap_block_status *bbs = container_of(w, struct bitmap_block_status, work);
2466 struct dm_integrity_c *ic = bbs->ic;
2468 struct bio_list bio_queue;
2469 struct bio_list waiting;
2471 bio_list_init(&waiting);
2473 spin_lock(&bbs->bio_queue_lock);
2474 bio_queue = bbs->bio_queue;
2475 bio_list_init(&bbs->bio_queue);
2476 spin_unlock(&bbs->bio_queue_lock);
2478 while ((bio = bio_list_pop(&bio_queue))) {
2479 struct dm_integrity_io *dio;
2481 dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
2483 if (block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
2484 dio->range.n_sectors, BITMAP_OP_TEST_ALL_SET)) {
2485 remove_range(ic, &dio->range);
2486 INIT_WORK(&dio->work, integrity_bio_wait);
2487 queue_work(ic->offload_wq, &dio->work);
2489 block_bitmap_op(ic, ic->journal, dio->range.logical_sector,
2490 dio->range.n_sectors, BITMAP_OP_SET);
2491 bio_list_add(&waiting, bio);
2495 if (bio_list_empty(&waiting))
2498 rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC,
2499 bbs->idx * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT),
2500 BITMAP_BLOCK_SIZE >> SECTOR_SHIFT, NULL);
2502 while ((bio = bio_list_pop(&waiting))) {
2503 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
2505 block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
2506 dio->range.n_sectors, BITMAP_OP_SET);
2508 remove_range(ic, &dio->range);
2509 INIT_WORK(&dio->work, integrity_bio_wait);
2510 queue_work(ic->offload_wq, &dio->work);
2513 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, ic->bitmap_flush_interval);
2516 static void bitmap_flush_work(struct work_struct *work)
2518 struct dm_integrity_c *ic = container_of(work, struct dm_integrity_c, bitmap_flush_work.work);
2519 struct dm_integrity_range range;
2520 unsigned long limit;
2523 dm_integrity_flush_buffers(ic);
2525 range.logical_sector = 0;
2526 range.n_sectors = ic->provided_data_sectors;
2528 spin_lock_irq(&ic->endio_wait.lock);
2529 add_new_range_and_wait(ic, &range);
2530 spin_unlock_irq(&ic->endio_wait.lock);
2532 dm_integrity_flush_buffers(ic);
2534 blkdev_issue_flush(ic->dev->bdev, GFP_NOIO, NULL);
2536 limit = ic->provided_data_sectors;
2537 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
2538 limit = le64_to_cpu(ic->sb->recalc_sector)
2539 >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit)
2540 << (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
2542 /*DEBUG_print("zeroing journal\n");*/
2543 block_bitmap_op(ic, ic->journal, 0, limit, BITMAP_OP_CLEAR);
2544 block_bitmap_op(ic, ic->may_write_bitmap, 0, limit, BITMAP_OP_CLEAR);
2546 rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, 0,
2547 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
2549 spin_lock_irq(&ic->endio_wait.lock);
2550 remove_range_unlocked(ic, &range);
2551 while (unlikely((bio = bio_list_pop(&ic->synchronous_bios)) != NULL)) {
2553 spin_unlock_irq(&ic->endio_wait.lock);
2554 spin_lock_irq(&ic->endio_wait.lock);
2556 spin_unlock_irq(&ic->endio_wait.lock);
2560 static void init_journal(struct dm_integrity_c *ic, unsigned start_section,
2561 unsigned n_sections, unsigned char commit_seq)
2568 for (n = 0; n < n_sections; n++) {
2569 i = start_section + n;
2570 wraparound_section(ic, &i);
2571 for (j = 0; j < ic->journal_section_sectors; j++) {
2572 struct journal_sector *js = access_journal(ic, i, j);
2573 memset(&js->entries, 0, JOURNAL_SECTOR_DATA);
2574 js->commit_id = dm_integrity_commit_id(ic, i, j, commit_seq);
2576 for (j = 0; j < ic->journal_section_entries; j++) {
2577 struct journal_entry *je = access_journal_entry(ic, i, j);
2578 journal_entry_set_unused(je);
2582 write_journal(ic, start_section, n_sections);
2585 static int find_commit_seq(struct dm_integrity_c *ic, unsigned i, unsigned j, commit_id_t id)
2588 for (k = 0; k < N_COMMIT_IDS; k++) {
2589 if (dm_integrity_commit_id(ic, i, j, k) == id)
2592 dm_integrity_io_error(ic, "journal commit id", -EIO);
2596 static void replay_journal(struct dm_integrity_c *ic)
2599 bool used_commit_ids[N_COMMIT_IDS];
2600 unsigned max_commit_id_sections[N_COMMIT_IDS];
2601 unsigned write_start, write_sections;
2602 unsigned continue_section;
2604 unsigned char unused, last_used, want_commit_seq;
2606 if (ic->mode == 'R')
2609 if (ic->journal_uptodate)
2615 if (!ic->just_formatted) {
2616 DEBUG_print("reading journal\n");
2617 rw_journal(ic, REQ_OP_READ, 0, 0, ic->journal_sections, NULL);
2619 DEBUG_bytes(lowmem_page_address(ic->journal_io[0].page), 64, "read journal");
2620 if (ic->journal_io) {
2621 struct journal_completion crypt_comp;
2623 init_completion(&crypt_comp.comp);
2624 crypt_comp.in_flight = (atomic_t)ATOMIC_INIT(0);
2625 encrypt_journal(ic, false, 0, ic->journal_sections, &crypt_comp);
2626 wait_for_completion(&crypt_comp.comp);
2628 DEBUG_bytes(lowmem_page_address(ic->journal[0].page), 64, "decrypted journal");
2631 if (dm_integrity_failed(ic))
2634 journal_empty = true;
2635 memset(used_commit_ids, 0, sizeof used_commit_ids);
2636 memset(max_commit_id_sections, 0, sizeof max_commit_id_sections);
2637 for (i = 0; i < ic->journal_sections; i++) {
2638 for (j = 0; j < ic->journal_section_sectors; j++) {
2640 struct journal_sector *js = access_journal(ic, i, j);
2641 k = find_commit_seq(ic, i, j, js->commit_id);
2644 used_commit_ids[k] = true;
2645 max_commit_id_sections[k] = i;
2647 if (journal_empty) {
2648 for (j = 0; j < ic->journal_section_entries; j++) {
2649 struct journal_entry *je = access_journal_entry(ic, i, j);
2650 if (!journal_entry_is_unused(je)) {
2651 journal_empty = false;
2658 if (!used_commit_ids[N_COMMIT_IDS - 1]) {
2659 unused = N_COMMIT_IDS - 1;
2660 while (unused && !used_commit_ids[unused - 1])
2663 for (unused = 0; unused < N_COMMIT_IDS; unused++)
2664 if (!used_commit_ids[unused])
2666 if (unused == N_COMMIT_IDS) {
2667 dm_integrity_io_error(ic, "journal commit ids", -EIO);
2671 DEBUG_print("first unused commit seq %d [%d,%d,%d,%d]\n",
2672 unused, used_commit_ids[0], used_commit_ids[1],
2673 used_commit_ids[2], used_commit_ids[3]);
2675 last_used = prev_commit_seq(unused);
2676 want_commit_seq = prev_commit_seq(last_used);
2678 if (!used_commit_ids[want_commit_seq] && used_commit_ids[prev_commit_seq(want_commit_seq)])
2679 journal_empty = true;
2681 write_start = max_commit_id_sections[last_used] + 1;
2682 if (unlikely(write_start >= ic->journal_sections))
2683 want_commit_seq = next_commit_seq(want_commit_seq);
2684 wraparound_section(ic, &write_start);
2687 for (write_sections = 0; write_sections < ic->journal_sections; write_sections++) {
2688 for (j = 0; j < ic->journal_section_sectors; j++) {
2689 struct journal_sector *js = access_journal(ic, i, j);
2691 if (js->commit_id != dm_integrity_commit_id(ic, i, j, want_commit_seq)) {
2693 * This could be caused by crash during writing.
2694 * We won't replay the inconsistent part of the
2697 DEBUG_print("commit id mismatch at position (%u, %u): %d != %d\n",
2698 i, j, find_commit_seq(ic, i, j, js->commit_id), want_commit_seq);
2703 if (unlikely(i >= ic->journal_sections))
2704 want_commit_seq = next_commit_seq(want_commit_seq);
2705 wraparound_section(ic, &i);
2709 if (!journal_empty) {
2710 DEBUG_print("replaying %u sections, starting at %u, commit seq %d\n",
2711 write_sections, write_start, want_commit_seq);
2712 do_journal_write(ic, write_start, write_sections, true);
2715 if (write_sections == ic->journal_sections && (ic->mode == 'J' || journal_empty)) {
2716 continue_section = write_start;
2717 ic->commit_seq = want_commit_seq;
2718 DEBUG_print("continuing from section %u, commit seq %d\n", write_start, ic->commit_seq);
2721 unsigned char erase_seq;
2723 DEBUG_print("clearing journal\n");
2725 erase_seq = prev_commit_seq(prev_commit_seq(last_used));
2727 init_journal(ic, s, 1, erase_seq);
2729 wraparound_section(ic, &s);
2730 if (ic->journal_sections >= 2) {
2731 init_journal(ic, s, ic->journal_sections - 2, erase_seq);
2732 s += ic->journal_sections - 2;
2733 wraparound_section(ic, &s);
2734 init_journal(ic, s, 1, erase_seq);
2737 continue_section = 0;
2738 ic->commit_seq = next_commit_seq(erase_seq);
2741 ic->committed_section = continue_section;
2742 ic->n_committed_sections = 0;
2744 ic->uncommitted_section = continue_section;
2745 ic->n_uncommitted_sections = 0;
2747 ic->free_section = continue_section;
2748 ic->free_section_entry = 0;
2749 ic->free_sectors = ic->journal_entries;
2751 ic->journal_tree_root = RB_ROOT;
2752 for (i = 0; i < ic->journal_entries; i++)
2753 init_journal_node(&ic->journal_tree[i]);
2756 static void dm_integrity_enter_synchronous_mode(struct dm_integrity_c *ic)
2758 DEBUG_print("dm_integrity_enter_synchronous_mode\n");
2760 if (ic->mode == 'B') {
2761 ic->bitmap_flush_interval = msecs_to_jiffies(10) + 1;
2762 ic->synchronous_mode = 1;
2764 cancel_delayed_work_sync(&ic->bitmap_flush_work);
2765 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
2766 flush_workqueue(ic->commit_wq);
2770 static int dm_integrity_reboot(struct notifier_block *n, unsigned long code, void *x)
2772 struct dm_integrity_c *ic = container_of(n, struct dm_integrity_c, reboot_notifier);
2774 DEBUG_print("dm_integrity_reboot\n");
2776 dm_integrity_enter_synchronous_mode(ic);
2781 static void dm_integrity_postsuspend(struct dm_target *ti)
2783 struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2786 WARN_ON(unregister_reboot_notifier(&ic->reboot_notifier));
2788 del_timer_sync(&ic->autocommit_timer);
2791 drain_workqueue(ic->recalc_wq);
2793 if (ic->mode == 'B')
2794 cancel_delayed_work_sync(&ic->bitmap_flush_work);
2796 queue_work(ic->commit_wq, &ic->commit_work);
2797 drain_workqueue(ic->commit_wq);
2799 if (ic->mode == 'J') {
2801 queue_work(ic->writer_wq, &ic->writer_work);
2802 drain_workqueue(ic->writer_wq);
2803 dm_integrity_flush_buffers(ic);
2806 if (ic->mode == 'B') {
2807 dm_integrity_flush_buffers(ic);
2809 /* set to 0 to test bitmap replay code */
2810 init_journal(ic, 0, ic->journal_sections, 0);
2811 ic->sb->flags &= ~cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
2812 r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
2814 dm_integrity_io_error(ic, "writing superblock", r);
2818 BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
2820 ic->journal_uptodate = true;
2823 static void dm_integrity_resume(struct dm_target *ti)
2825 struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2827 DEBUG_print("resume\n");
2829 if (ic->sb->flags & cpu_to_le32(SB_FLAG_DIRTY_BITMAP)) {
2830 DEBUG_print("resume dirty_bitmap\n");
2831 rw_journal_sectors(ic, REQ_OP_READ, 0, 0,
2832 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
2833 if (ic->mode == 'B') {
2834 if (ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit) {
2835 block_bitmap_copy(ic, ic->recalc_bitmap, ic->journal);
2836 block_bitmap_copy(ic, ic->may_write_bitmap, ic->journal);
2837 if (!block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors,
2838 BITMAP_OP_TEST_ALL_CLEAR)) {
2839 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
2840 ic->sb->recalc_sector = cpu_to_le64(0);
2843 DEBUG_print("non-matching blocks_per_bitmap_bit: %u, %u\n",
2844 ic->sb->log2_blocks_per_bitmap_bit, ic->log2_blocks_per_bitmap_bit);
2845 ic->sb->log2_blocks_per_bitmap_bit = ic->log2_blocks_per_bitmap_bit;
2846 block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_SET);
2847 block_bitmap_op(ic, ic->may_write_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_SET);
2848 block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_SET);
2849 rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, 0,
2850 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
2851 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
2852 ic->sb->recalc_sector = cpu_to_le64(0);
2855 if (!(ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit &&
2856 block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_TEST_ALL_CLEAR))) {
2857 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
2858 ic->sb->recalc_sector = cpu_to_le64(0);
2860 init_journal(ic, 0, ic->journal_sections, 0);
2862 ic->sb->flags &= ~cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
2864 r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
2866 dm_integrity_io_error(ic, "writing superblock", r);
2869 if (ic->mode == 'B') {
2870 ic->sb->flags |= cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
2871 ic->sb->log2_blocks_per_bitmap_bit = ic->log2_blocks_per_bitmap_bit;
2872 r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
2874 dm_integrity_io_error(ic, "writing superblock", r);
2876 block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
2877 block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
2878 block_bitmap_op(ic, ic->may_write_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
2879 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
2880 le64_to_cpu(ic->sb->recalc_sector) < ic->provided_data_sectors) {
2881 block_bitmap_op(ic, ic->journal, le64_to_cpu(ic->sb->recalc_sector),
2882 ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
2883 block_bitmap_op(ic, ic->recalc_bitmap, le64_to_cpu(ic->sb->recalc_sector),
2884 ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
2885 block_bitmap_op(ic, ic->may_write_bitmap, le64_to_cpu(ic->sb->recalc_sector),
2886 ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
2888 rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, 0,
2889 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
2893 DEBUG_print("testing recalc: %x\n", ic->sb->flags);
2894 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
2895 __u64 recalc_pos = le64_to_cpu(ic->sb->recalc_sector);
2896 DEBUG_print("recalc pos: %lx / %lx\n", (long)recalc_pos, ic->provided_data_sectors);
2897 if (recalc_pos < ic->provided_data_sectors) {
2898 queue_work(ic->recalc_wq, &ic->recalc_work);
2899 } else if (recalc_pos > ic->provided_data_sectors) {
2900 ic->sb->recalc_sector = cpu_to_le64(ic->provided_data_sectors);
2901 recalc_write_super(ic);
2905 ic->reboot_notifier.notifier_call = dm_integrity_reboot;
2906 ic->reboot_notifier.next = NULL;
2907 ic->reboot_notifier.priority = INT_MAX - 1; /* be notified after md and before hardware drivers */
2908 WARN_ON(register_reboot_notifier(&ic->reboot_notifier));
2911 /* set to 1 to stress test synchronous mode */
2912 dm_integrity_enter_synchronous_mode(ic);
2916 static void dm_integrity_status(struct dm_target *ti, status_type_t type,
2917 unsigned status_flags, char *result, unsigned maxlen)
2919 struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2924 case STATUSTYPE_INFO:
2926 (unsigned long long)atomic64_read(&ic->number_of_mismatches),
2927 (unsigned long long)ic->provided_data_sectors);
2928 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
2929 DMEMIT(" %llu", (unsigned long long)le64_to_cpu(ic->sb->recalc_sector));
2934 case STATUSTYPE_TABLE: {
2935 __u64 watermark_percentage = (__u64)(ic->journal_entries - ic->free_sectors_threshold) * 100;
2936 watermark_percentage += ic->journal_entries / 2;
2937 do_div(watermark_percentage, ic->journal_entries);
2939 arg_count += !!ic->meta_dev;
2940 arg_count += ic->sectors_per_block != 1;
2941 arg_count += !!(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING));
2942 arg_count += ic->mode == 'J';
2943 arg_count += ic->mode == 'J';
2944 arg_count += ic->mode == 'B';
2945 arg_count += ic->mode == 'B';
2946 arg_count += !!ic->internal_hash_alg.alg_string;
2947 arg_count += !!ic->journal_crypt_alg.alg_string;
2948 arg_count += !!ic->journal_mac_alg.alg_string;
2949 DMEMIT("%s %llu %u %c %u", ic->dev->name, (unsigned long long)ic->start,
2950 ic->tag_size, ic->mode, arg_count);
2952 DMEMIT(" meta_device:%s", ic->meta_dev->name);
2953 if (ic->sectors_per_block != 1)
2954 DMEMIT(" block_size:%u", ic->sectors_per_block << SECTOR_SHIFT);
2955 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
2956 DMEMIT(" recalculate");
2957 DMEMIT(" journal_sectors:%u", ic->initial_sectors - SB_SECTORS);
2958 DMEMIT(" interleave_sectors:%u", 1U << ic->sb->log2_interleave_sectors);
2959 DMEMIT(" buffer_sectors:%u", 1U << ic->log2_buffer_sectors);
2960 if (ic->mode == 'J') {
2961 DMEMIT(" journal_watermark:%u", (unsigned)watermark_percentage);
2962 DMEMIT(" commit_time:%u", ic->autocommit_msec);
2964 if (ic->mode == 'B') {
2965 DMEMIT(" sectors_per_bit:%llu", (unsigned long long)ic->sectors_per_block << ic->log2_blocks_per_bitmap_bit);
2966 DMEMIT(" bitmap_flush_interval:%u", jiffies_to_msecs(ic->bitmap_flush_interval));
2969 #define EMIT_ALG(a, n) \
2971 if (ic->a.alg_string) { \
2972 DMEMIT(" %s:%s", n, ic->a.alg_string); \
2973 if (ic->a.key_string) \
2974 DMEMIT(":%s", ic->a.key_string);\
2977 EMIT_ALG(internal_hash_alg, "internal_hash");
2978 EMIT_ALG(journal_crypt_alg, "journal_crypt");
2979 EMIT_ALG(journal_mac_alg, "journal_mac");
2985 static int dm_integrity_iterate_devices(struct dm_target *ti,
2986 iterate_devices_callout_fn fn, void *data)
2988 struct dm_integrity_c *ic = ti->private;
2991 return fn(ti, ic->dev, ic->start + ic->initial_sectors + ic->metadata_run, ti->len, data);
2993 return fn(ti, ic->dev, 0, ti->len, data);
2996 static void dm_integrity_io_hints(struct dm_target *ti, struct queue_limits *limits)
2998 struct dm_integrity_c *ic = ti->private;
3000 if (ic->sectors_per_block > 1) {
3001 limits->logical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
3002 limits->physical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
3003 blk_limits_io_min(limits, ic->sectors_per_block << SECTOR_SHIFT);
3007 static void calculate_journal_section_size(struct dm_integrity_c *ic)
3009 unsigned sector_space = JOURNAL_SECTOR_DATA;
3011 ic->journal_sections = le32_to_cpu(ic->sb->journal_sections);
3012 ic->journal_entry_size = roundup(offsetof(struct journal_entry, last_bytes[ic->sectors_per_block]) + ic->tag_size,
3013 JOURNAL_ENTRY_ROUNDUP);
3015 if (ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC))
3016 sector_space -= JOURNAL_MAC_PER_SECTOR;
3017 ic->journal_entries_per_sector = sector_space / ic->journal_entry_size;
3018 ic->journal_section_entries = ic->journal_entries_per_sector * JOURNAL_BLOCK_SECTORS;
3019 ic->journal_section_sectors = (ic->journal_section_entries << ic->sb->log2_sectors_per_block) + JOURNAL_BLOCK_SECTORS;
3020 ic->journal_entries = ic->journal_section_entries * ic->journal_sections;
3023 static int calculate_device_limits(struct dm_integrity_c *ic)
3025 __u64 initial_sectors;
3027 calculate_journal_section_size(ic);
3028 initial_sectors = SB_SECTORS + (__u64)ic->journal_section_sectors * ic->journal_sections;
3029 if (initial_sectors + METADATA_PADDING_SECTORS >= ic->meta_device_sectors || initial_sectors > UINT_MAX)
3031 ic->initial_sectors = initial_sectors;
3033 if (!ic->meta_dev) {
3034 sector_t last_sector, last_area, last_offset;
3036 ic->metadata_run = roundup((__u64)ic->tag_size << (ic->sb->log2_interleave_sectors - ic->sb->log2_sectors_per_block),
3037 (__u64)(1 << SECTOR_SHIFT << METADATA_PADDING_SECTORS)) >> SECTOR_SHIFT;
3038 if (!(ic->metadata_run & (ic->metadata_run - 1)))
3039 ic->log2_metadata_run = __ffs(ic->metadata_run);
3041 ic->log2_metadata_run = -1;
3043 get_area_and_offset(ic, ic->provided_data_sectors - 1, &last_area, &last_offset);
3044 last_sector = get_data_sector(ic, last_area, last_offset);
3045 if (last_sector < ic->start || last_sector >= ic->meta_device_sectors)
3048 __u64 meta_size = (ic->provided_data_sectors >> ic->sb->log2_sectors_per_block) * ic->tag_size;
3049 meta_size = (meta_size + ((1U << (ic->log2_buffer_sectors + SECTOR_SHIFT)) - 1))
3050 >> (ic->log2_buffer_sectors + SECTOR_SHIFT);
3051 meta_size <<= ic->log2_buffer_sectors;
3052 if (ic->initial_sectors + meta_size < ic->initial_sectors ||
3053 ic->initial_sectors + meta_size > ic->meta_device_sectors)
3055 ic->metadata_run = 1;
3056 ic->log2_metadata_run = 0;
3062 static int initialize_superblock(struct dm_integrity_c *ic, unsigned journal_sectors, unsigned interleave_sectors)
3064 unsigned journal_sections;
3067 memset(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT);
3068 memcpy(ic->sb->magic, SB_MAGIC, 8);
3069 ic->sb->integrity_tag_size = cpu_to_le16(ic->tag_size);
3070 ic->sb->log2_sectors_per_block = __ffs(ic->sectors_per_block);
3071 if (ic->journal_mac_alg.alg_string)
3072 ic->sb->flags |= cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC);
3074 calculate_journal_section_size(ic);
3075 journal_sections = journal_sectors / ic->journal_section_sectors;
3076 if (!journal_sections)
3077 journal_sections = 1;
3079 if (!ic->meta_dev) {
3080 ic->sb->journal_sections = cpu_to_le32(journal_sections);
3081 if (!interleave_sectors)
3082 interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
3083 ic->sb->log2_interleave_sectors = __fls(interleave_sectors);
3084 ic->sb->log2_interleave_sectors = max((__u8)MIN_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
3085 ic->sb->log2_interleave_sectors = min((__u8)MAX_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
3087 ic->provided_data_sectors = 0;
3088 for (test_bit = fls64(ic->meta_device_sectors) - 1; test_bit >= 3; test_bit--) {
3089 __u64 prev_data_sectors = ic->provided_data_sectors;
3091 ic->provided_data_sectors |= (sector_t)1 << test_bit;
3092 if (calculate_device_limits(ic))
3093 ic->provided_data_sectors = prev_data_sectors;
3095 if (!ic->provided_data_sectors)
3098 ic->sb->log2_interleave_sectors = 0;
3099 ic->provided_data_sectors = ic->data_device_sectors;
3100 ic->provided_data_sectors &= ~(sector_t)(ic->sectors_per_block - 1);
3103 ic->sb->journal_sections = cpu_to_le32(0);
3104 for (test_bit = fls(journal_sections) - 1; test_bit >= 0; test_bit--) {
3105 __u32 prev_journal_sections = le32_to_cpu(ic->sb->journal_sections);
3106 __u32 test_journal_sections = prev_journal_sections | (1U << test_bit);
3107 if (test_journal_sections > journal_sections)
3109 ic->sb->journal_sections = cpu_to_le32(test_journal_sections);
3110 if (calculate_device_limits(ic))
3111 ic->sb->journal_sections = cpu_to_le32(prev_journal_sections);
3114 if (!le32_to_cpu(ic->sb->journal_sections)) {
3115 if (ic->log2_buffer_sectors > 3) {
3116 ic->log2_buffer_sectors--;
3117 goto try_smaller_buffer;
3123 ic->sb->provided_data_sectors = cpu_to_le64(ic->provided_data_sectors);
3130 static void dm_integrity_set(struct dm_target *ti, struct dm_integrity_c *ic)
3132 struct gendisk *disk = dm_disk(dm_table_get_md(ti->table));
3133 struct blk_integrity bi;
3135 memset(&bi, 0, sizeof(bi));
3136 bi.profile = &dm_integrity_profile;
3137 bi.tuple_size = ic->tag_size;
3138 bi.tag_size = bi.tuple_size;
3139 bi.interval_exp = ic->sb->log2_sectors_per_block + SECTOR_SHIFT;
3141 blk_integrity_register(disk, &bi);
3142 blk_queue_max_integrity_segments(disk->queue, UINT_MAX);
3145 static void dm_integrity_free_page_list(struct page_list *pl)
3151 for (i = 0; pl[i].page; i++)
3152 __free_page(pl[i].page);
3156 static struct page_list *dm_integrity_alloc_page_list(unsigned n_pages)
3158 struct page_list *pl;
3161 pl = kvmalloc_array(n_pages + 1, sizeof(struct page_list), GFP_KERNEL | __GFP_ZERO);
3165 for (i = 0; i < n_pages; i++) {
3166 pl[i].page = alloc_page(GFP_KERNEL);
3168 dm_integrity_free_page_list(pl);
3172 pl[i - 1].next = &pl[i];
3180 static void dm_integrity_free_journal_scatterlist(struct dm_integrity_c *ic, struct scatterlist **sl)
3183 for (i = 0; i < ic->journal_sections; i++)
3188 static struct scatterlist **dm_integrity_alloc_journal_scatterlist(struct dm_integrity_c *ic,
3189 struct page_list *pl)
3191 struct scatterlist **sl;
3194 sl = kvmalloc_array(ic->journal_sections,
3195 sizeof(struct scatterlist *),
3196 GFP_KERNEL | __GFP_ZERO);
3200 for (i = 0; i < ic->journal_sections; i++) {
3201 struct scatterlist *s;
3202 unsigned start_index, start_offset;
3203 unsigned end_index, end_offset;
3207 page_list_location(ic, i, 0, &start_index, &start_offset);
3208 page_list_location(ic, i, ic->journal_section_sectors - 1,
3209 &end_index, &end_offset);
3211 n_pages = (end_index - start_index + 1);
3213 s = kvmalloc_array(n_pages, sizeof(struct scatterlist),
3216 dm_integrity_free_journal_scatterlist(ic, sl);
3220 sg_init_table(s, n_pages);
3221 for (idx = start_index; idx <= end_index; idx++) {
3222 char *va = lowmem_page_address(pl[idx].page);
3223 unsigned start = 0, end = PAGE_SIZE;
3224 if (idx == start_index)
3225 start = start_offset;
3226 if (idx == end_index)
3227 end = end_offset + (1 << SECTOR_SHIFT);
3228 sg_set_buf(&s[idx - start_index], va + start, end - start);
3237 static void free_alg(struct alg_spec *a)
3239 kzfree(a->alg_string);
3241 memset(a, 0, sizeof *a);
3244 static int get_alg_and_key(const char *arg, struct alg_spec *a, char **error, char *error_inval)
3250 a->alg_string = kstrdup(strchr(arg, ':') + 1, GFP_KERNEL);
3254 k = strchr(a->alg_string, ':');
3257 a->key_string = k + 1;
3258 if (strlen(a->key_string) & 1)
3261 a->key_size = strlen(a->key_string) / 2;
3262 a->key = kmalloc(a->key_size, GFP_KERNEL);
3265 if (hex2bin(a->key, a->key_string, a->key_size))
3271 *error = error_inval;
3274 *error = "Out of memory for an argument";
3278 static int get_mac(struct crypto_shash **hash, struct alg_spec *a, char **error,
3279 char *error_alg, char *error_key)
3283 if (a->alg_string) {
3284 *hash = crypto_alloc_shash(a->alg_string, 0, 0);
3285 if (IS_ERR(*hash)) {
3293 r = crypto_shash_setkey(*hash, a->key, a->key_size);
3298 } else if (crypto_shash_get_flags(*hash) & CRYPTO_TFM_NEED_KEY) {
3307 static int create_journal(struct dm_integrity_c *ic, char **error)
3311 __u64 journal_pages, journal_desc_size, journal_tree_size;
3312 unsigned char *crypt_data = NULL, *crypt_iv = NULL;
3313 struct skcipher_request *req = NULL;
3315 ic->commit_ids[0] = cpu_to_le64(0x1111111111111111ULL);
3316 ic->commit_ids[1] = cpu_to_le64(0x2222222222222222ULL);
3317 ic->commit_ids[2] = cpu_to_le64(0x3333333333333333ULL);
3318 ic->commit_ids[3] = cpu_to_le64(0x4444444444444444ULL);
3320 journal_pages = roundup((__u64)ic->journal_sections * ic->journal_section_sectors,
3321 PAGE_SIZE >> SECTOR_SHIFT) >> (PAGE_SHIFT - SECTOR_SHIFT);
3322 journal_desc_size = journal_pages * sizeof(struct page_list);
3323 if (journal_pages >= totalram_pages() - totalhigh_pages() || journal_desc_size > ULONG_MAX) {
3324 *error = "Journal doesn't fit into memory";
3328 ic->journal_pages = journal_pages;
3330 ic->journal = dm_integrity_alloc_page_list(ic->journal_pages);
3332 *error = "Could not allocate memory for journal";
3336 if (ic->journal_crypt_alg.alg_string) {
3337 unsigned ivsize, blocksize;
3338 struct journal_completion comp;
3341 ic->journal_crypt = crypto_alloc_skcipher(ic->journal_crypt_alg.alg_string, 0, 0);
3342 if (IS_ERR(ic->journal_crypt)) {
3343 *error = "Invalid journal cipher";
3344 r = PTR_ERR(ic->journal_crypt);
3345 ic->journal_crypt = NULL;
3348 ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
3349 blocksize = crypto_skcipher_blocksize(ic->journal_crypt);
3351 if (ic->journal_crypt_alg.key) {
3352 r = crypto_skcipher_setkey(ic->journal_crypt, ic->journal_crypt_alg.key,
3353 ic->journal_crypt_alg.key_size);
3355 *error = "Error setting encryption key";
3359 DEBUG_print("cipher %s, block size %u iv size %u\n",
3360 ic->journal_crypt_alg.alg_string, blocksize, ivsize);
3362 ic->journal_io = dm_integrity_alloc_page_list(ic->journal_pages);
3363 if (!ic->journal_io) {
3364 *error = "Could not allocate memory for journal io";
3369 if (blocksize == 1) {
3370 struct scatterlist *sg;
3372 req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
3374 *error = "Could not allocate crypt request";
3379 crypt_iv = kzalloc(ivsize, GFP_KERNEL);
3381 *error = "Could not allocate iv";
3386 ic->journal_xor = dm_integrity_alloc_page_list(ic->journal_pages);
3387 if (!ic->journal_xor) {
3388 *error = "Could not allocate memory for journal xor";
3393 sg = kvmalloc_array(ic->journal_pages + 1,
3394 sizeof(struct scatterlist),
3397 *error = "Unable to allocate sg list";
3401 sg_init_table(sg, ic->journal_pages + 1);
3402 for (i = 0; i < ic->journal_pages; i++) {
3403 char *va = lowmem_page_address(ic->journal_xor[i].page);
3405 sg_set_buf(&sg[i], va, PAGE_SIZE);
3407 sg_set_buf(&sg[i], &ic->commit_ids, sizeof ic->commit_ids);
3409 skcipher_request_set_crypt(req, sg, sg,
3410 PAGE_SIZE * ic->journal_pages + sizeof ic->commit_ids, crypt_iv);
3411 init_completion(&comp.comp);
3412 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
3413 if (do_crypt(true, req, &comp))
3414 wait_for_completion(&comp.comp);
3416 r = dm_integrity_failed(ic);
3418 *error = "Unable to encrypt journal";
3421 DEBUG_bytes(lowmem_page_address(ic->journal_xor[0].page), 64, "xor data");
3423 crypto_free_skcipher(ic->journal_crypt);
3424 ic->journal_crypt = NULL;
3426 unsigned crypt_len = roundup(ivsize, blocksize);
3428 req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
3430 *error = "Could not allocate crypt request";
3435 crypt_iv = kmalloc(ivsize, GFP_KERNEL);
3437 *error = "Could not allocate iv";
3442 crypt_data = kmalloc(crypt_len, GFP_KERNEL);
3444 *error = "Unable to allocate crypt data";
3449 ic->journal_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal);
3450 if (!ic->journal_scatterlist) {
3451 *error = "Unable to allocate sg list";
3455 ic->journal_io_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal_io);
3456 if (!ic->journal_io_scatterlist) {
3457 *error = "Unable to allocate sg list";
3461 ic->sk_requests = kvmalloc_array(ic->journal_sections,
3462 sizeof(struct skcipher_request *),
3463 GFP_KERNEL | __GFP_ZERO);
3464 if (!ic->sk_requests) {
3465 *error = "Unable to allocate sk requests";
3469 for (i = 0; i < ic->journal_sections; i++) {
3470 struct scatterlist sg;
3471 struct skcipher_request *section_req;
3472 __u32 section_le = cpu_to_le32(i);
3474 memset(crypt_iv, 0x00, ivsize);
3475 memset(crypt_data, 0x00, crypt_len);
3476 memcpy(crypt_data, §ion_le, min((size_t)crypt_len, sizeof(section_le)));
3478 sg_init_one(&sg, crypt_data, crypt_len);
3479 skcipher_request_set_crypt(req, &sg, &sg, crypt_len, crypt_iv);
3480 init_completion(&comp.comp);
3481 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
3482 if (do_crypt(true, req, &comp))
3483 wait_for_completion(&comp.comp);
3485 r = dm_integrity_failed(ic);
3487 *error = "Unable to generate iv";
3491 section_req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
3493 *error = "Unable to allocate crypt request";
3497 section_req->iv = kmalloc_array(ivsize, 2,
3499 if (!section_req->iv) {
3500 skcipher_request_free(section_req);
3501 *error = "Unable to allocate iv";
3505 memcpy(section_req->iv + ivsize, crypt_data, ivsize);
3506 section_req->cryptlen = (size_t)ic->journal_section_sectors << SECTOR_SHIFT;
3507 ic->sk_requests[i] = section_req;
3508 DEBUG_bytes(crypt_data, ivsize, "iv(%u)", i);
3513 for (i = 0; i < N_COMMIT_IDS; i++) {
3516 for (j = 0; j < i; j++) {
3517 if (ic->commit_ids[j] == ic->commit_ids[i]) {
3518 ic->commit_ids[i] = cpu_to_le64(le64_to_cpu(ic->commit_ids[i]) + 1);
3519 goto retest_commit_id;
3522 DEBUG_print("commit id %u: %016llx\n", i, ic->commit_ids[i]);
3525 journal_tree_size = (__u64)ic->journal_entries * sizeof(struct journal_node);
3526 if (journal_tree_size > ULONG_MAX) {
3527 *error = "Journal doesn't fit into memory";
3531 ic->journal_tree = kvmalloc(journal_tree_size, GFP_KERNEL);
3532 if (!ic->journal_tree) {
3533 *error = "Could not allocate memory for journal tree";
3539 skcipher_request_free(req);
3545 * Construct a integrity mapping
3549 * offset from the start of the device
3551 * D - direct writes, J - journal writes, B - bitmap mode, R - recovery mode
3552 * number of optional arguments
3553 * optional arguments:
3555 * interleave_sectors
3562 * bitmap_flush_interval
3568 static int dm_integrity_ctr(struct dm_target *ti, unsigned argc, char **argv)
3570 struct dm_integrity_c *ic;
3573 unsigned extra_args;
3574 struct dm_arg_set as;
3575 static const struct dm_arg _args[] = {
3576 {0, 9, "Invalid number of feature args"},
3578 unsigned journal_sectors, interleave_sectors, buffer_sectors, journal_watermark, sync_msec;
3579 bool should_write_sb;
3581 unsigned long long start;
3582 __s8 log2_sectors_per_bitmap_bit = -1;
3583 __s8 log2_blocks_per_bitmap_bit;
3584 __u64 bits_in_journal;
3585 __u64 n_bitmap_bits;
3587 #define DIRECT_ARGUMENTS 4
3589 if (argc <= DIRECT_ARGUMENTS) {
3590 ti->error = "Invalid argument count";
3594 ic = kzalloc(sizeof(struct dm_integrity_c), GFP_KERNEL);
3596 ti->error = "Cannot allocate integrity context";
3600 ti->per_io_data_size = sizeof(struct dm_integrity_io);
3603 ic->in_progress = RB_ROOT;
3604 INIT_LIST_HEAD(&ic->wait_list);
3605 init_waitqueue_head(&ic->endio_wait);
3606 bio_list_init(&ic->flush_bio_list);
3607 init_waitqueue_head(&ic->copy_to_journal_wait);
3608 init_completion(&ic->crypto_backoff);
3609 atomic64_set(&ic->number_of_mismatches, 0);
3610 ic->bitmap_flush_interval = BITMAP_FLUSH_INTERVAL;
3612 r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &ic->dev);
3614 ti->error = "Device lookup failed";
3618 if (sscanf(argv[1], "%llu%c", &start, &dummy) != 1 || start != (sector_t)start) {
3619 ti->error = "Invalid starting offset";
3625 if (strcmp(argv[2], "-")) {
3626 if (sscanf(argv[2], "%u%c", &ic->tag_size, &dummy) != 1 || !ic->tag_size) {
3627 ti->error = "Invalid tag size";
3633 if (!strcmp(argv[3], "J") || !strcmp(argv[3], "B") ||
3634 !strcmp(argv[3], "D") || !strcmp(argv[3], "R")) {
3635 ic->mode = argv[3][0];
3637 ti->error = "Invalid mode (expecting J, B, D, R)";
3642 journal_sectors = 0;
3643 interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
3644 buffer_sectors = DEFAULT_BUFFER_SECTORS;
3645 journal_watermark = DEFAULT_JOURNAL_WATERMARK;
3646 sync_msec = DEFAULT_SYNC_MSEC;
3647 ic->sectors_per_block = 1;
3649 as.argc = argc - DIRECT_ARGUMENTS;
3650 as.argv = argv + DIRECT_ARGUMENTS;
3651 r = dm_read_arg_group(_args, &as, &extra_args, &ti->error);
3655 while (extra_args--) {
3656 const char *opt_string;
3658 unsigned long long llval;
3659 opt_string = dm_shift_arg(&as);
3662 ti->error = "Not enough feature arguments";
3665 if (sscanf(opt_string, "journal_sectors:%u%c", &val, &dummy) == 1)
3666 journal_sectors = val ? val : 1;
3667 else if (sscanf(opt_string, "interleave_sectors:%u%c", &val, &dummy) == 1)
3668 interleave_sectors = val;
3669 else if (sscanf(opt_string, "buffer_sectors:%u%c", &val, &dummy) == 1)
3670 buffer_sectors = val;
3671 else if (sscanf(opt_string, "journal_watermark:%u%c", &val, &dummy) == 1 && val <= 100)
3672 journal_watermark = val;
3673 else if (sscanf(opt_string, "commit_time:%u%c", &val, &dummy) == 1)
3675 else if (!strncmp(opt_string, "meta_device:", strlen("meta_device:"))) {
3677 dm_put_device(ti, ic->meta_dev);
3678 ic->meta_dev = NULL;
3680 r = dm_get_device(ti, strchr(opt_string, ':') + 1,
3681 dm_table_get_mode(ti->table), &ic->meta_dev);
3683 ti->error = "Device lookup failed";
3686 } else if (sscanf(opt_string, "block_size:%u%c", &val, &dummy) == 1) {
3687 if (val < 1 << SECTOR_SHIFT ||
3688 val > MAX_SECTORS_PER_BLOCK << SECTOR_SHIFT ||
3691 ti->error = "Invalid block_size argument";
3694 ic->sectors_per_block = val >> SECTOR_SHIFT;
3695 } else if (sscanf(opt_string, "sectors_per_bit:%llu%c", &llval, &dummy) == 1) {
3696 log2_sectors_per_bitmap_bit = !llval ? 0 : __ilog2_u64(llval);
3697 } else if (sscanf(opt_string, "bitmap_flush_interval:%u%c", &val, &dummy) == 1) {
3698 if (val >= (uint64_t)UINT_MAX * 1000 / HZ) {
3700 ti->error = "Invalid bitmap_flush_interval argument";
3702 ic->bitmap_flush_interval = msecs_to_jiffies(val);
3703 } else if (!strncmp(opt_string, "internal_hash:", strlen("internal_hash:"))) {
3704 r = get_alg_and_key(opt_string, &ic->internal_hash_alg, &ti->error,
3705 "Invalid internal_hash argument");
3708 } else if (!strncmp(opt_string, "journal_crypt:", strlen("journal_crypt:"))) {
3709 r = get_alg_and_key(opt_string, &ic->journal_crypt_alg, &ti->error,
3710 "Invalid journal_crypt argument");
3713 } else if (!strncmp(opt_string, "journal_mac:", strlen("journal_mac:"))) {
3714 r = get_alg_and_key(opt_string, &ic->journal_mac_alg, &ti->error,
3715 "Invalid journal_mac argument");
3718 } else if (!strcmp(opt_string, "recalculate")) {
3719 ic->recalculate_flag = true;
3722 ti->error = "Invalid argument";
3727 ic->data_device_sectors = i_size_read(ic->dev->bdev->bd_inode) >> SECTOR_SHIFT;
3729 ic->meta_device_sectors = ic->data_device_sectors;
3731 ic->meta_device_sectors = i_size_read(ic->meta_dev->bdev->bd_inode) >> SECTOR_SHIFT;
3733 if (!journal_sectors) {
3734 journal_sectors = min((sector_t)DEFAULT_MAX_JOURNAL_SECTORS,
3735 ic->data_device_sectors >> DEFAULT_JOURNAL_SIZE_FACTOR);
3738 if (!buffer_sectors)
3740 ic->log2_buffer_sectors = min((int)__fls(buffer_sectors), 31 - SECTOR_SHIFT);
3742 r = get_mac(&ic->internal_hash, &ic->internal_hash_alg, &ti->error,
3743 "Invalid internal hash", "Error setting internal hash key");
3747 r = get_mac(&ic->journal_mac, &ic->journal_mac_alg, &ti->error,
3748 "Invalid journal mac", "Error setting journal mac key");
3752 if (!ic->tag_size) {
3753 if (!ic->internal_hash) {
3754 ti->error = "Unknown tag size";
3758 ic->tag_size = crypto_shash_digestsize(ic->internal_hash);
3760 if (ic->tag_size > MAX_TAG_SIZE) {
3761 ti->error = "Too big tag size";
3765 if (!(ic->tag_size & (ic->tag_size - 1)))
3766 ic->log2_tag_size = __ffs(ic->tag_size);
3768 ic->log2_tag_size = -1;
3770 if (ic->mode == 'B' && !ic->internal_hash) {
3772 ti->error = "Bitmap mode can be only used with internal hash";
3776 ic->autocommit_jiffies = msecs_to_jiffies(sync_msec);
3777 ic->autocommit_msec = sync_msec;
3778 timer_setup(&ic->autocommit_timer, autocommit_fn, 0);
3780 ic->io = dm_io_client_create();
3781 if (IS_ERR(ic->io)) {
3782 r = PTR_ERR(ic->io);
3784 ti->error = "Cannot allocate dm io";
3788 r = mempool_init_slab_pool(&ic->journal_io_mempool, JOURNAL_IO_MEMPOOL, journal_io_cache);
3790 ti->error = "Cannot allocate mempool";
3794 ic->metadata_wq = alloc_workqueue("dm-integrity-metadata",
3795 WQ_MEM_RECLAIM, METADATA_WORKQUEUE_MAX_ACTIVE);
3796 if (!ic->metadata_wq) {
3797 ti->error = "Cannot allocate workqueue";
3803 * If this workqueue were percpu, it would cause bio reordering
3804 * and reduced performance.
3806 ic->wait_wq = alloc_workqueue("dm-integrity-wait", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
3808 ti->error = "Cannot allocate workqueue";
3813 ic->offload_wq = alloc_workqueue("dm-integrity-offload", WQ_MEM_RECLAIM,
3814 METADATA_WORKQUEUE_MAX_ACTIVE);
3815 if (!ic->offload_wq) {
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->offload_wq);
4128 destroy_workqueue(ic->commit_wq);
4130 destroy_workqueue(ic->writer_wq);
4132 destroy_workqueue(ic->recalc_wq);
4133 vfree(ic->recalc_buffer);
4134 kvfree(ic->recalc_tags);
4137 dm_bufio_client_destroy(ic->bufio);
4138 mempool_exit(&ic->journal_io_mempool);
4140 dm_io_client_destroy(ic->io);
4142 dm_put_device(ti, ic->dev);
4144 dm_put_device(ti, ic->meta_dev);
4145 dm_integrity_free_page_list(ic->journal);
4146 dm_integrity_free_page_list(ic->journal_io);
4147 dm_integrity_free_page_list(ic->journal_xor);
4148 dm_integrity_free_page_list(ic->recalc_bitmap);
4149 dm_integrity_free_page_list(ic->may_write_bitmap);
4150 if (ic->journal_scatterlist)
4151 dm_integrity_free_journal_scatterlist(ic, ic->journal_scatterlist);
4152 if (ic->journal_io_scatterlist)
4153 dm_integrity_free_journal_scatterlist(ic, ic->journal_io_scatterlist);
4154 if (ic->sk_requests) {
4157 for (i = 0; i < ic->journal_sections; i++) {
4158 struct skcipher_request *req = ic->sk_requests[i];
4161 skcipher_request_free(req);
4164 kvfree(ic->sk_requests);
4166 kvfree(ic->journal_tree);
4168 free_pages_exact(ic->sb, SB_SECTORS << SECTOR_SHIFT);
4170 if (ic->internal_hash)
4171 crypto_free_shash(ic->internal_hash);
4172 free_alg(&ic->internal_hash_alg);
4174 if (ic->journal_crypt)
4175 crypto_free_skcipher(ic->journal_crypt);
4176 free_alg(&ic->journal_crypt_alg);
4178 if (ic->journal_mac)
4179 crypto_free_shash(ic->journal_mac);
4180 free_alg(&ic->journal_mac_alg);
4185 static struct target_type integrity_target = {
4186 .name = "integrity",
4187 .version = {1, 3, 0},
4188 .module = THIS_MODULE,
4189 .features = DM_TARGET_SINGLETON | DM_TARGET_INTEGRITY,
4190 .ctr = dm_integrity_ctr,
4191 .dtr = dm_integrity_dtr,
4192 .map = dm_integrity_map,
4193 .postsuspend = dm_integrity_postsuspend,
4194 .resume = dm_integrity_resume,
4195 .status = dm_integrity_status,
4196 .iterate_devices = dm_integrity_iterate_devices,
4197 .io_hints = dm_integrity_io_hints,
4200 static int __init dm_integrity_init(void)
4204 journal_io_cache = kmem_cache_create("integrity_journal_io",
4205 sizeof(struct journal_io), 0, 0, NULL);
4206 if (!journal_io_cache) {
4207 DMERR("can't allocate journal io cache");
4211 r = dm_register_target(&integrity_target);
4214 DMERR("register failed %d", r);
4219 static void __exit dm_integrity_exit(void)
4221 dm_unregister_target(&integrity_target);
4222 kmem_cache_destroy(journal_io_cache);
4225 module_init(dm_integrity_init);
4226 module_exit(dm_integrity_exit);
4228 MODULE_AUTHOR("Milan Broz");
4229 MODULE_AUTHOR("Mikulas Patocka");
4230 MODULE_DESCRIPTION(DM_NAME " target for integrity tags extension");
4231 MODULE_LICENSE("GPL");