2 * Copyright (C) 2016-2017 Red Hat, Inc. All rights reserved.
3 * Copyright (C) 2016-2017 Milan Broz
4 * Copyright (C) 2016-2017 Mikulas Patocka
6 * This file is released under the GPL.
9 #include <linux/compiler.h>
10 #include <linux/module.h>
11 #include <linux/device-mapper.h>
12 #include <linux/dm-io.h>
13 #include <linux/vmalloc.h>
14 #include <linux/sort.h>
15 #include <linux/rbtree.h>
16 #include <linux/delay.h>
17 #include <linux/random.h>
18 #include <crypto/hash.h>
19 #include <crypto/skcipher.h>
20 #include <linux/async_tx.h>
21 #include <linux/dm-bufio.h>
23 #define DM_MSG_PREFIX "integrity"
25 #define DEFAULT_INTERLEAVE_SECTORS 32768
26 #define DEFAULT_JOURNAL_SIZE_FACTOR 7
27 #define DEFAULT_BUFFER_SECTORS 128
28 #define DEFAULT_JOURNAL_WATERMARK 50
29 #define DEFAULT_SYNC_MSEC 10000
30 #define DEFAULT_MAX_JOURNAL_SECTORS 131072
31 #define MIN_LOG2_INTERLEAVE_SECTORS 3
32 #define MAX_LOG2_INTERLEAVE_SECTORS 31
33 #define METADATA_WORKQUEUE_MAX_ACTIVE 16
34 #define RECALC_SECTORS 8192
35 #define RECALC_WRITE_SUPER 16
38 * Warning - DEBUG_PRINT prints security-sensitive data to the log,
39 * so it should not be enabled in the official kernel
42 //#define INTERNAL_VERIFY
48 #define SB_MAGIC "integrt"
49 #define SB_VERSION_1 1
50 #define SB_VERSION_2 2
52 #define MAX_SECTORS_PER_BLOCK 8
57 __u8 log2_interleave_sectors;
58 __u16 integrity_tag_size;
59 __u32 journal_sections;
60 __u64 provided_data_sectors; /* userspace uses this value */
62 __u8 log2_sectors_per_block;
67 #define SB_FLAG_HAVE_JOURNAL_MAC 0x1
68 #define SB_FLAG_RECALCULATING 0x2
70 #define JOURNAL_ENTRY_ROUNDUP 8
72 typedef __u64 commit_id_t;
73 #define JOURNAL_MAC_PER_SECTOR 8
75 struct journal_entry {
83 commit_id_t last_bytes[0];
87 #define journal_entry_tag(ic, je) ((__u8 *)&(je)->last_bytes[(ic)->sectors_per_block])
89 #if BITS_PER_LONG == 64
90 #define journal_entry_set_sector(je, x) do { smp_wmb(); WRITE_ONCE((je)->u.sector, cpu_to_le64(x)); } while (0)
92 #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)
94 #define journal_entry_get_sector(je) le64_to_cpu((je)->u.sector)
95 #define journal_entry_is_unused(je) ((je)->u.s.sector_hi == cpu_to_le32(-1))
96 #define journal_entry_set_unused(je) do { ((je)->u.s.sector_hi = cpu_to_le32(-1)); } while (0)
97 #define journal_entry_is_inprogress(je) ((je)->u.s.sector_hi == cpu_to_le32(-2))
98 #define journal_entry_set_inprogress(je) do { ((je)->u.s.sector_hi = cpu_to_le32(-2)); } while (0)
100 #define JOURNAL_BLOCK_SECTORS 8
101 #define JOURNAL_SECTOR_DATA ((1 << SECTOR_SHIFT) - sizeof(commit_id_t))
102 #define JOURNAL_MAC_SIZE (JOURNAL_MAC_PER_SECTOR * JOURNAL_BLOCK_SECTORS)
104 struct journal_sector {
105 __u8 entries[JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR];
106 __u8 mac[JOURNAL_MAC_PER_SECTOR];
107 commit_id_t commit_id;
110 #define MAX_TAG_SIZE (JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR - offsetof(struct journal_entry, last_bytes[MAX_SECTORS_PER_BLOCK]))
112 #define METADATA_PADDING_SECTORS 8
114 #define N_COMMIT_IDS 4
116 static unsigned char prev_commit_seq(unsigned char seq)
118 return (seq + N_COMMIT_IDS - 1) % N_COMMIT_IDS;
121 static unsigned char next_commit_seq(unsigned char seq)
123 return (seq + 1) % N_COMMIT_IDS;
127 * In-memory structures
130 struct journal_node {
142 struct dm_integrity_c {
144 struct dm_dev *meta_dev;
148 mempool_t journal_io_mempool;
149 struct dm_io_client *io;
150 struct dm_bufio_client *bufio;
151 struct workqueue_struct *metadata_wq;
152 struct superblock *sb;
153 unsigned journal_pages;
154 struct page_list *journal;
155 struct page_list *journal_io;
156 struct page_list *journal_xor;
158 struct crypto_skcipher *journal_crypt;
159 struct scatterlist **journal_scatterlist;
160 struct scatterlist **journal_io_scatterlist;
161 struct skcipher_request **sk_requests;
163 struct crypto_shash *journal_mac;
165 struct journal_node *journal_tree;
166 struct rb_root journal_tree_root;
168 sector_t provided_data_sectors;
170 unsigned short journal_entry_size;
171 unsigned char journal_entries_per_sector;
172 unsigned char journal_section_entries;
173 unsigned short journal_section_sectors;
174 unsigned journal_sections;
175 unsigned journal_entries;
176 sector_t data_device_sectors;
177 sector_t meta_device_sectors;
178 unsigned initial_sectors;
179 unsigned metadata_run;
180 __s8 log2_metadata_run;
181 __u8 log2_buffer_sectors;
182 __u8 sectors_per_block;
189 struct crypto_shash *internal_hash;
191 /* these variables are locked with endio_wait.lock */
192 struct rb_root in_progress;
193 struct list_head wait_list;
194 wait_queue_head_t endio_wait;
195 struct workqueue_struct *wait_wq;
197 unsigned char commit_seq;
198 commit_id_t commit_ids[N_COMMIT_IDS];
200 unsigned committed_section;
201 unsigned n_committed_sections;
203 unsigned uncommitted_section;
204 unsigned n_uncommitted_sections;
206 unsigned free_section;
207 unsigned char free_section_entry;
208 unsigned free_sectors;
210 unsigned free_sectors_threshold;
212 struct workqueue_struct *commit_wq;
213 struct work_struct commit_work;
215 struct workqueue_struct *writer_wq;
216 struct work_struct writer_work;
218 struct workqueue_struct *recalc_wq;
219 struct work_struct recalc_work;
223 struct bio_list flush_bio_list;
225 unsigned long autocommit_jiffies;
226 struct timer_list autocommit_timer;
227 unsigned autocommit_msec;
229 wait_queue_head_t copy_to_journal_wait;
231 struct completion crypto_backoff;
233 bool journal_uptodate;
236 struct alg_spec internal_hash_alg;
237 struct alg_spec journal_crypt_alg;
238 struct alg_spec journal_mac_alg;
240 atomic64_t number_of_mismatches;
243 struct dm_integrity_range {
244 sector_t logical_sector;
250 struct task_struct *task;
251 struct list_head wait_entry;
256 struct dm_integrity_io {
257 struct work_struct work;
259 struct dm_integrity_c *ic;
263 struct dm_integrity_range range;
265 sector_t metadata_block;
266 unsigned metadata_offset;
269 blk_status_t bi_status;
271 struct completion *completion;
273 struct gendisk *orig_bi_disk;
275 bio_end_io_t *orig_bi_end_io;
276 struct bio_integrity_payload *orig_bi_integrity;
277 struct bvec_iter orig_bi_iter;
280 struct journal_completion {
281 struct dm_integrity_c *ic;
283 struct completion comp;
287 struct dm_integrity_range range;
288 struct journal_completion *comp;
291 static struct kmem_cache *journal_io_cache;
293 #define JOURNAL_IO_MEMPOOL 32
296 #define DEBUG_print(x, ...) printk(KERN_DEBUG x, ##__VA_ARGS__)
297 static void __DEBUG_bytes(__u8 *bytes, size_t len, const char *msg, ...)
306 pr_cont(" %02x", *bytes);
312 #define DEBUG_bytes(bytes, len, msg, ...) __DEBUG_bytes(bytes, len, KERN_DEBUG msg, ##__VA_ARGS__)
314 #define DEBUG_print(x, ...) do { } while (0)
315 #define DEBUG_bytes(bytes, len, msg, ...) do { } while (0)
319 * DM Integrity profile, protection is performed layer above (dm-crypt)
321 static const struct blk_integrity_profile dm_integrity_profile = {
322 .name = "DM-DIF-EXT-TAG",
327 static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map);
328 static void integrity_bio_wait(struct work_struct *w);
329 static void dm_integrity_dtr(struct dm_target *ti);
331 static void dm_integrity_io_error(struct dm_integrity_c *ic, const char *msg, int err)
334 atomic64_inc(&ic->number_of_mismatches);
335 if (!cmpxchg(&ic->failed, 0, err))
336 DMERR("Error on %s: %d", msg, err);
339 static int dm_integrity_failed(struct dm_integrity_c *ic)
341 return READ_ONCE(ic->failed);
344 static commit_id_t dm_integrity_commit_id(struct dm_integrity_c *ic, unsigned i,
345 unsigned j, unsigned char seq)
348 * Xor the number with section and sector, so that if a piece of
349 * journal is written at wrong place, it is detected.
351 return ic->commit_ids[seq] ^ cpu_to_le64(((__u64)i << 32) ^ j);
354 static void get_area_and_offset(struct dm_integrity_c *ic, sector_t data_sector,
355 sector_t *area, sector_t *offset)
358 __u8 log2_interleave_sectors = ic->sb->log2_interleave_sectors;
359 *area = data_sector >> log2_interleave_sectors;
360 *offset = (unsigned)data_sector & ((1U << log2_interleave_sectors) - 1);
363 *offset = data_sector;
367 #define sector_to_block(ic, n) \
369 BUG_ON((n) & (unsigned)((ic)->sectors_per_block - 1)); \
370 (n) >>= (ic)->sb->log2_sectors_per_block; \
373 static __u64 get_metadata_sector_and_offset(struct dm_integrity_c *ic, sector_t area,
374 sector_t offset, unsigned *metadata_offset)
379 ms = area << ic->sb->log2_interleave_sectors;
380 if (likely(ic->log2_metadata_run >= 0))
381 ms += area << ic->log2_metadata_run;
383 ms += area * ic->metadata_run;
384 ms >>= ic->log2_buffer_sectors;
386 sector_to_block(ic, offset);
388 if (likely(ic->log2_tag_size >= 0)) {
389 ms += offset >> (SECTOR_SHIFT + ic->log2_buffer_sectors - ic->log2_tag_size);
390 mo = (offset << ic->log2_tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
392 ms += (__u64)offset * ic->tag_size >> (SECTOR_SHIFT + ic->log2_buffer_sectors);
393 mo = (offset * ic->tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
395 *metadata_offset = mo;
399 static sector_t get_data_sector(struct dm_integrity_c *ic, sector_t area, sector_t offset)
406 result = area << ic->sb->log2_interleave_sectors;
407 if (likely(ic->log2_metadata_run >= 0))
408 result += (area + 1) << ic->log2_metadata_run;
410 result += (area + 1) * ic->metadata_run;
412 result += (sector_t)ic->initial_sectors + offset;
418 static void wraparound_section(struct dm_integrity_c *ic, unsigned *sec_ptr)
420 if (unlikely(*sec_ptr >= ic->journal_sections))
421 *sec_ptr -= ic->journal_sections;
424 static void sb_set_version(struct dm_integrity_c *ic)
426 if (ic->meta_dev || ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
427 ic->sb->version = SB_VERSION_2;
429 ic->sb->version = SB_VERSION_1;
432 static int sync_rw_sb(struct dm_integrity_c *ic, int op, int op_flags)
434 struct dm_io_request io_req;
435 struct dm_io_region io_loc;
438 io_req.bi_op_flags = op_flags;
439 io_req.mem.type = DM_IO_KMEM;
440 io_req.mem.ptr.addr = ic->sb;
441 io_req.notify.fn = NULL;
442 io_req.client = ic->io;
443 io_loc.bdev = ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev;
444 io_loc.sector = ic->start;
445 io_loc.count = SB_SECTORS;
447 return dm_io(&io_req, 1, &io_loc, NULL);
450 static void access_journal_check(struct dm_integrity_c *ic, unsigned section, unsigned offset,
451 bool e, const char *function)
453 #if defined(CONFIG_DM_DEBUG) || defined(INTERNAL_VERIFY)
454 unsigned limit = e ? ic->journal_section_entries : ic->journal_section_sectors;
456 if (unlikely(section >= ic->journal_sections) ||
457 unlikely(offset >= limit)) {
458 printk(KERN_CRIT "%s: invalid access at (%u,%u), limit (%u,%u)\n",
459 function, section, offset, ic->journal_sections, limit);
465 static void page_list_location(struct dm_integrity_c *ic, unsigned section, unsigned offset,
466 unsigned *pl_index, unsigned *pl_offset)
470 access_journal_check(ic, section, offset, false, "page_list_location");
472 sector = section * ic->journal_section_sectors + offset;
474 *pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
475 *pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
478 static struct journal_sector *access_page_list(struct dm_integrity_c *ic, struct page_list *pl,
479 unsigned section, unsigned offset, unsigned *n_sectors)
481 unsigned pl_index, pl_offset;
484 page_list_location(ic, section, offset, &pl_index, &pl_offset);
487 *n_sectors = (PAGE_SIZE - pl_offset) >> SECTOR_SHIFT;
489 va = lowmem_page_address(pl[pl_index].page);
491 return (struct journal_sector *)(va + pl_offset);
494 static struct journal_sector *access_journal(struct dm_integrity_c *ic, unsigned section, unsigned offset)
496 return access_page_list(ic, ic->journal, section, offset, NULL);
499 static struct journal_entry *access_journal_entry(struct dm_integrity_c *ic, unsigned section, unsigned n)
501 unsigned rel_sector, offset;
502 struct journal_sector *js;
504 access_journal_check(ic, section, n, true, "access_journal_entry");
506 rel_sector = n % JOURNAL_BLOCK_SECTORS;
507 offset = n / JOURNAL_BLOCK_SECTORS;
509 js = access_journal(ic, section, rel_sector);
510 return (struct journal_entry *)((char *)js + offset * ic->journal_entry_size);
513 static struct journal_sector *access_journal_data(struct dm_integrity_c *ic, unsigned section, unsigned n)
515 n <<= ic->sb->log2_sectors_per_block;
517 n += JOURNAL_BLOCK_SECTORS;
519 access_journal_check(ic, section, n, false, "access_journal_data");
521 return access_journal(ic, section, n);
524 static void section_mac(struct dm_integrity_c *ic, unsigned section, __u8 result[JOURNAL_MAC_SIZE])
526 SHASH_DESC_ON_STACK(desc, ic->journal_mac);
530 desc->tfm = ic->journal_mac;
532 r = crypto_shash_init(desc);
534 dm_integrity_io_error(ic, "crypto_shash_init", r);
538 for (j = 0; j < ic->journal_section_entries; j++) {
539 struct journal_entry *je = access_journal_entry(ic, section, j);
540 r = crypto_shash_update(desc, (__u8 *)&je->u.sector, sizeof je->u.sector);
542 dm_integrity_io_error(ic, "crypto_shash_update", r);
547 size = crypto_shash_digestsize(ic->journal_mac);
549 if (likely(size <= JOURNAL_MAC_SIZE)) {
550 r = crypto_shash_final(desc, result);
552 dm_integrity_io_error(ic, "crypto_shash_final", r);
555 memset(result + size, 0, JOURNAL_MAC_SIZE - size);
557 __u8 digest[HASH_MAX_DIGESTSIZE];
559 if (WARN_ON(size > sizeof(digest))) {
560 dm_integrity_io_error(ic, "digest_size", -EINVAL);
563 r = crypto_shash_final(desc, digest);
565 dm_integrity_io_error(ic, "crypto_shash_final", r);
568 memcpy(result, digest, JOURNAL_MAC_SIZE);
573 memset(result, 0, JOURNAL_MAC_SIZE);
576 static void rw_section_mac(struct dm_integrity_c *ic, unsigned section, bool wr)
578 __u8 result[JOURNAL_MAC_SIZE];
581 if (!ic->journal_mac)
584 section_mac(ic, section, result);
586 for (j = 0; j < JOURNAL_BLOCK_SECTORS; j++) {
587 struct journal_sector *js = access_journal(ic, section, j);
590 memcpy(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR);
592 if (memcmp(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR))
593 dm_integrity_io_error(ic, "journal mac", -EILSEQ);
598 static void complete_journal_op(void *context)
600 struct journal_completion *comp = context;
601 BUG_ON(!atomic_read(&comp->in_flight));
602 if (likely(atomic_dec_and_test(&comp->in_flight)))
603 complete(&comp->comp);
606 static void xor_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
607 unsigned n_sections, struct journal_completion *comp)
609 struct async_submit_ctl submit;
610 size_t n_bytes = (size_t)(n_sections * ic->journal_section_sectors) << SECTOR_SHIFT;
611 unsigned pl_index, pl_offset, section_index;
612 struct page_list *source_pl, *target_pl;
614 if (likely(encrypt)) {
615 source_pl = ic->journal;
616 target_pl = ic->journal_io;
618 source_pl = ic->journal_io;
619 target_pl = ic->journal;
622 page_list_location(ic, section, 0, &pl_index, &pl_offset);
624 atomic_add(roundup(pl_offset + n_bytes, PAGE_SIZE) >> PAGE_SHIFT, &comp->in_flight);
626 init_async_submit(&submit, ASYNC_TX_XOR_ZERO_DST, NULL, complete_journal_op, comp, NULL);
628 section_index = pl_index;
632 struct page *src_pages[2];
633 struct page *dst_page;
635 while (unlikely(pl_index == section_index)) {
638 rw_section_mac(ic, section, true);
643 page_list_location(ic, section, 0, §ion_index, &dummy);
646 this_step = min(n_bytes, (size_t)PAGE_SIZE - pl_offset);
647 dst_page = target_pl[pl_index].page;
648 src_pages[0] = source_pl[pl_index].page;
649 src_pages[1] = ic->journal_xor[pl_index].page;
651 async_xor(dst_page, src_pages, pl_offset, 2, this_step, &submit);
655 n_bytes -= this_step;
660 async_tx_issue_pending_all();
663 static void complete_journal_encrypt(struct crypto_async_request *req, int err)
665 struct journal_completion *comp = req->data;
667 if (likely(err == -EINPROGRESS)) {
668 complete(&comp->ic->crypto_backoff);
671 dm_integrity_io_error(comp->ic, "asynchronous encrypt", err);
673 complete_journal_op(comp);
676 static bool do_crypt(bool encrypt, struct skcipher_request *req, struct journal_completion *comp)
679 skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
680 complete_journal_encrypt, comp);
682 r = crypto_skcipher_encrypt(req);
684 r = crypto_skcipher_decrypt(req);
687 if (likely(r == -EINPROGRESS))
689 if (likely(r == -EBUSY)) {
690 wait_for_completion(&comp->ic->crypto_backoff);
691 reinit_completion(&comp->ic->crypto_backoff);
694 dm_integrity_io_error(comp->ic, "encrypt", r);
698 static void crypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
699 unsigned n_sections, struct journal_completion *comp)
701 struct scatterlist **source_sg;
702 struct scatterlist **target_sg;
704 atomic_add(2, &comp->in_flight);
706 if (likely(encrypt)) {
707 source_sg = ic->journal_scatterlist;
708 target_sg = ic->journal_io_scatterlist;
710 source_sg = ic->journal_io_scatterlist;
711 target_sg = ic->journal_scatterlist;
715 struct skcipher_request *req;
720 rw_section_mac(ic, section, true);
722 req = ic->sk_requests[section];
723 ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
726 memcpy(iv, iv + ivsize, ivsize);
728 req->src = source_sg[section];
729 req->dst = target_sg[section];
731 if (unlikely(do_crypt(encrypt, req, comp)))
732 atomic_inc(&comp->in_flight);
736 } while (n_sections);
738 atomic_dec(&comp->in_flight);
739 complete_journal_op(comp);
742 static void encrypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
743 unsigned n_sections, struct journal_completion *comp)
746 return xor_journal(ic, encrypt, section, n_sections, comp);
748 return crypt_journal(ic, encrypt, section, n_sections, comp);
751 static void complete_journal_io(unsigned long error, void *context)
753 struct journal_completion *comp = context;
754 if (unlikely(error != 0))
755 dm_integrity_io_error(comp->ic, "writing journal", -EIO);
756 complete_journal_op(comp);
759 static void rw_journal(struct dm_integrity_c *ic, int op, int op_flags, unsigned section,
760 unsigned n_sections, struct journal_completion *comp)
762 struct dm_io_request io_req;
763 struct dm_io_region io_loc;
764 unsigned sector, n_sectors, pl_index, pl_offset;
767 if (unlikely(dm_integrity_failed(ic))) {
769 complete_journal_io(-1UL, comp);
773 sector = section * ic->journal_section_sectors;
774 n_sectors = n_sections * ic->journal_section_sectors;
776 pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
777 pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
780 io_req.bi_op_flags = op_flags;
781 io_req.mem.type = DM_IO_PAGE_LIST;
783 io_req.mem.ptr.pl = &ic->journal_io[pl_index];
785 io_req.mem.ptr.pl = &ic->journal[pl_index];
786 io_req.mem.offset = pl_offset;
787 if (likely(comp != NULL)) {
788 io_req.notify.fn = complete_journal_io;
789 io_req.notify.context = comp;
791 io_req.notify.fn = NULL;
793 io_req.client = ic->io;
794 io_loc.bdev = ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev;
795 io_loc.sector = ic->start + SB_SECTORS + sector;
796 io_loc.count = n_sectors;
798 r = dm_io(&io_req, 1, &io_loc, NULL);
800 dm_integrity_io_error(ic, op == REQ_OP_READ ? "reading journal" : "writing journal", r);
802 WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
803 complete_journal_io(-1UL, comp);
808 static void write_journal(struct dm_integrity_c *ic, unsigned commit_start, unsigned commit_sections)
810 struct journal_completion io_comp;
811 struct journal_completion crypt_comp_1;
812 struct journal_completion crypt_comp_2;
816 init_completion(&io_comp.comp);
818 if (commit_start + commit_sections <= ic->journal_sections) {
819 io_comp.in_flight = (atomic_t)ATOMIC_INIT(1);
820 if (ic->journal_io) {
821 crypt_comp_1.ic = ic;
822 init_completion(&crypt_comp_1.comp);
823 crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
824 encrypt_journal(ic, true, commit_start, commit_sections, &crypt_comp_1);
825 wait_for_completion_io(&crypt_comp_1.comp);
827 for (i = 0; i < commit_sections; i++)
828 rw_section_mac(ic, commit_start + i, true);
830 rw_journal(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, commit_start,
831 commit_sections, &io_comp);
834 io_comp.in_flight = (atomic_t)ATOMIC_INIT(2);
835 to_end = ic->journal_sections - commit_start;
836 if (ic->journal_io) {
837 crypt_comp_1.ic = ic;
838 init_completion(&crypt_comp_1.comp);
839 crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
840 encrypt_journal(ic, true, commit_start, to_end, &crypt_comp_1);
841 if (try_wait_for_completion(&crypt_comp_1.comp)) {
842 rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
843 reinit_completion(&crypt_comp_1.comp);
844 crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
845 encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_1);
846 wait_for_completion_io(&crypt_comp_1.comp);
848 crypt_comp_2.ic = ic;
849 init_completion(&crypt_comp_2.comp);
850 crypt_comp_2.in_flight = (atomic_t)ATOMIC_INIT(0);
851 encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_2);
852 wait_for_completion_io(&crypt_comp_1.comp);
853 rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
854 wait_for_completion_io(&crypt_comp_2.comp);
857 for (i = 0; i < to_end; i++)
858 rw_section_mac(ic, commit_start + i, true);
859 rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
860 for (i = 0; i < commit_sections - to_end; i++)
861 rw_section_mac(ic, i, true);
863 rw_journal(ic, REQ_OP_WRITE, REQ_FUA, 0, commit_sections - to_end, &io_comp);
866 wait_for_completion_io(&io_comp.comp);
869 static void copy_from_journal(struct dm_integrity_c *ic, unsigned section, unsigned offset,
870 unsigned n_sectors, sector_t target, io_notify_fn fn, void *data)
872 struct dm_io_request io_req;
873 struct dm_io_region io_loc;
875 unsigned sector, pl_index, pl_offset;
877 BUG_ON((target | n_sectors | offset) & (unsigned)(ic->sectors_per_block - 1));
879 if (unlikely(dm_integrity_failed(ic))) {
884 sector = section * ic->journal_section_sectors + JOURNAL_BLOCK_SECTORS + offset;
886 pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
887 pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
889 io_req.bi_op = REQ_OP_WRITE;
890 io_req.bi_op_flags = 0;
891 io_req.mem.type = DM_IO_PAGE_LIST;
892 io_req.mem.ptr.pl = &ic->journal[pl_index];
893 io_req.mem.offset = pl_offset;
894 io_req.notify.fn = fn;
895 io_req.notify.context = data;
896 io_req.client = ic->io;
897 io_loc.bdev = ic->dev->bdev;
898 io_loc.sector = target;
899 io_loc.count = n_sectors;
901 r = dm_io(&io_req, 1, &io_loc, NULL);
903 WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
908 static bool ranges_overlap(struct dm_integrity_range *range1, struct dm_integrity_range *range2)
910 return range1->logical_sector < range2->logical_sector + range2->n_sectors &&
911 range1->logical_sector + range1->n_sectors > range2->logical_sector;
914 static bool add_new_range(struct dm_integrity_c *ic, struct dm_integrity_range *new_range, bool check_waiting)
916 struct rb_node **n = &ic->in_progress.rb_node;
917 struct rb_node *parent;
919 BUG_ON((new_range->logical_sector | new_range->n_sectors) & (unsigned)(ic->sectors_per_block - 1));
921 if (likely(check_waiting)) {
922 struct dm_integrity_range *range;
923 list_for_each_entry(range, &ic->wait_list, wait_entry) {
924 if (unlikely(ranges_overlap(range, new_range)))
932 struct dm_integrity_range *range = container_of(*n, struct dm_integrity_range, node);
935 if (new_range->logical_sector + new_range->n_sectors <= range->logical_sector) {
936 n = &range->node.rb_left;
937 } else if (new_range->logical_sector >= range->logical_sector + range->n_sectors) {
938 n = &range->node.rb_right;
944 rb_link_node(&new_range->node, parent, n);
945 rb_insert_color(&new_range->node, &ic->in_progress);
950 static void remove_range_unlocked(struct dm_integrity_c *ic, struct dm_integrity_range *range)
952 rb_erase(&range->node, &ic->in_progress);
953 while (unlikely(!list_empty(&ic->wait_list))) {
954 struct dm_integrity_range *last_range =
955 list_first_entry(&ic->wait_list, struct dm_integrity_range, wait_entry);
956 struct task_struct *last_range_task;
957 last_range_task = last_range->task;
958 list_del(&last_range->wait_entry);
959 if (!add_new_range(ic, last_range, false)) {
960 last_range->task = last_range_task;
961 list_add(&last_range->wait_entry, &ic->wait_list);
964 last_range->waiting = false;
965 wake_up_process(last_range_task);
969 static void remove_range(struct dm_integrity_c *ic, struct dm_integrity_range *range)
973 spin_lock_irqsave(&ic->endio_wait.lock, flags);
974 remove_range_unlocked(ic, range);
975 spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
978 static void wait_and_add_new_range(struct dm_integrity_c *ic, struct dm_integrity_range *new_range)
980 new_range->waiting = true;
981 list_add_tail(&new_range->wait_entry, &ic->wait_list);
982 new_range->task = current;
984 __set_current_state(TASK_UNINTERRUPTIBLE);
985 spin_unlock_irq(&ic->endio_wait.lock);
987 spin_lock_irq(&ic->endio_wait.lock);
988 } while (unlikely(new_range->waiting));
991 static void init_journal_node(struct journal_node *node)
993 RB_CLEAR_NODE(&node->node);
994 node->sector = (sector_t)-1;
997 static void add_journal_node(struct dm_integrity_c *ic, struct journal_node *node, sector_t sector)
999 struct rb_node **link;
1000 struct rb_node *parent;
1002 node->sector = sector;
1003 BUG_ON(!RB_EMPTY_NODE(&node->node));
1005 link = &ic->journal_tree_root.rb_node;
1009 struct journal_node *j;
1011 j = container_of(parent, struct journal_node, node);
1012 if (sector < j->sector)
1013 link = &j->node.rb_left;
1015 link = &j->node.rb_right;
1018 rb_link_node(&node->node, parent, link);
1019 rb_insert_color(&node->node, &ic->journal_tree_root);
1022 static void remove_journal_node(struct dm_integrity_c *ic, struct journal_node *node)
1024 BUG_ON(RB_EMPTY_NODE(&node->node));
1025 rb_erase(&node->node, &ic->journal_tree_root);
1026 init_journal_node(node);
1029 #define NOT_FOUND (-1U)
1031 static unsigned find_journal_node(struct dm_integrity_c *ic, sector_t sector, sector_t *next_sector)
1033 struct rb_node *n = ic->journal_tree_root.rb_node;
1034 unsigned found = NOT_FOUND;
1035 *next_sector = (sector_t)-1;
1037 struct journal_node *j = container_of(n, struct journal_node, node);
1038 if (sector == j->sector) {
1039 found = j - ic->journal_tree;
1041 if (sector < j->sector) {
1042 *next_sector = j->sector;
1043 n = j->node.rb_left;
1045 n = j->node.rb_right;
1052 static bool test_journal_node(struct dm_integrity_c *ic, unsigned pos, sector_t sector)
1054 struct journal_node *node, *next_node;
1055 struct rb_node *next;
1057 if (unlikely(pos >= ic->journal_entries))
1059 node = &ic->journal_tree[pos];
1060 if (unlikely(RB_EMPTY_NODE(&node->node)))
1062 if (unlikely(node->sector != sector))
1065 next = rb_next(&node->node);
1066 if (unlikely(!next))
1069 next_node = container_of(next, struct journal_node, node);
1070 return next_node->sector != sector;
1073 static bool find_newer_committed_node(struct dm_integrity_c *ic, struct journal_node *node)
1075 struct rb_node *next;
1076 struct journal_node *next_node;
1077 unsigned next_section;
1079 BUG_ON(RB_EMPTY_NODE(&node->node));
1081 next = rb_next(&node->node);
1082 if (unlikely(!next))
1085 next_node = container_of(next, struct journal_node, node);
1087 if (next_node->sector != node->sector)
1090 next_section = (unsigned)(next_node - ic->journal_tree) / ic->journal_section_entries;
1091 if (next_section >= ic->committed_section &&
1092 next_section < ic->committed_section + ic->n_committed_sections)
1094 if (next_section + ic->journal_sections < ic->committed_section + ic->n_committed_sections)
1104 static int dm_integrity_rw_tag(struct dm_integrity_c *ic, unsigned char *tag, sector_t *metadata_block,
1105 unsigned *metadata_offset, unsigned total_size, int op)
1108 unsigned char *data, *dp;
1109 struct dm_buffer *b;
1113 r = dm_integrity_failed(ic);
1117 data = dm_bufio_read(ic->bufio, *metadata_block, &b);
1119 return PTR_ERR(data);
1121 to_copy = min((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - *metadata_offset, total_size);
1122 dp = data + *metadata_offset;
1123 if (op == TAG_READ) {
1124 memcpy(tag, dp, to_copy);
1125 } else if (op == TAG_WRITE) {
1126 memcpy(dp, tag, to_copy);
1127 dm_bufio_mark_partial_buffer_dirty(b, *metadata_offset, *metadata_offset + to_copy);
1129 /* e.g.: op == TAG_CMP */
1130 if (unlikely(memcmp(dp, tag, to_copy))) {
1133 for (i = 0; i < to_copy; i++) {
1134 if (dp[i] != tag[i])
1138 dm_bufio_release(b);
1142 dm_bufio_release(b);
1145 *metadata_offset += to_copy;
1146 if (unlikely(*metadata_offset == 1U << SECTOR_SHIFT << ic->log2_buffer_sectors)) {
1147 (*metadata_block)++;
1148 *metadata_offset = 0;
1150 total_size -= to_copy;
1151 } while (unlikely(total_size));
1156 static void dm_integrity_flush_buffers(struct dm_integrity_c *ic)
1159 r = dm_bufio_write_dirty_buffers(ic->bufio);
1161 dm_integrity_io_error(ic, "writing tags", r);
1164 static void sleep_on_endio_wait(struct dm_integrity_c *ic)
1166 DECLARE_WAITQUEUE(wait, current);
1167 __add_wait_queue(&ic->endio_wait, &wait);
1168 __set_current_state(TASK_UNINTERRUPTIBLE);
1169 spin_unlock_irq(&ic->endio_wait.lock);
1171 spin_lock_irq(&ic->endio_wait.lock);
1172 __remove_wait_queue(&ic->endio_wait, &wait);
1175 static void autocommit_fn(struct timer_list *t)
1177 struct dm_integrity_c *ic = from_timer(ic, t, autocommit_timer);
1179 if (likely(!dm_integrity_failed(ic)))
1180 queue_work(ic->commit_wq, &ic->commit_work);
1183 static void schedule_autocommit(struct dm_integrity_c *ic)
1185 if (!timer_pending(&ic->autocommit_timer))
1186 mod_timer(&ic->autocommit_timer, jiffies + ic->autocommit_jiffies);
1189 static void submit_flush_bio(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
1192 unsigned long flags;
1194 spin_lock_irqsave(&ic->endio_wait.lock, flags);
1195 bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1196 bio_list_add(&ic->flush_bio_list, bio);
1197 spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1199 queue_work(ic->commit_wq, &ic->commit_work);
1202 static void do_endio(struct dm_integrity_c *ic, struct bio *bio)
1204 int r = dm_integrity_failed(ic);
1205 if (unlikely(r) && !bio->bi_status)
1206 bio->bi_status = errno_to_blk_status(r);
1210 static void do_endio_flush(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
1212 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1214 if (unlikely(dio->fua) && likely(!bio->bi_status) && likely(!dm_integrity_failed(ic)))
1215 submit_flush_bio(ic, dio);
1220 static void dec_in_flight(struct dm_integrity_io *dio)
1222 if (atomic_dec_and_test(&dio->in_flight)) {
1223 struct dm_integrity_c *ic = dio->ic;
1226 remove_range(ic, &dio->range);
1228 if (unlikely(dio->write))
1229 schedule_autocommit(ic);
1231 bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1233 if (unlikely(dio->bi_status) && !bio->bi_status)
1234 bio->bi_status = dio->bi_status;
1235 if (likely(!bio->bi_status) && unlikely(bio_sectors(bio) != dio->range.n_sectors)) {
1236 dio->range.logical_sector += dio->range.n_sectors;
1237 bio_advance(bio, dio->range.n_sectors << SECTOR_SHIFT);
1238 INIT_WORK(&dio->work, integrity_bio_wait);
1239 queue_work(ic->wait_wq, &dio->work);
1242 do_endio_flush(ic, dio);
1246 static void integrity_end_io(struct bio *bio)
1248 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
1250 bio->bi_iter = dio->orig_bi_iter;
1251 bio->bi_disk = dio->orig_bi_disk;
1252 bio->bi_partno = dio->orig_bi_partno;
1253 if (dio->orig_bi_integrity) {
1254 bio->bi_integrity = dio->orig_bi_integrity;
1255 bio->bi_opf |= REQ_INTEGRITY;
1257 bio->bi_end_io = dio->orig_bi_end_io;
1259 if (dio->completion)
1260 complete(dio->completion);
1265 static void integrity_sector_checksum(struct dm_integrity_c *ic, sector_t sector,
1266 const char *data, char *result)
1268 __u64 sector_le = cpu_to_le64(sector);
1269 SHASH_DESC_ON_STACK(req, ic->internal_hash);
1271 unsigned digest_size;
1273 req->tfm = ic->internal_hash;
1275 r = crypto_shash_init(req);
1276 if (unlikely(r < 0)) {
1277 dm_integrity_io_error(ic, "crypto_shash_init", r);
1281 r = crypto_shash_update(req, (const __u8 *)§or_le, sizeof sector_le);
1282 if (unlikely(r < 0)) {
1283 dm_integrity_io_error(ic, "crypto_shash_update", r);
1287 r = crypto_shash_update(req, data, ic->sectors_per_block << SECTOR_SHIFT);
1288 if (unlikely(r < 0)) {
1289 dm_integrity_io_error(ic, "crypto_shash_update", r);
1293 r = crypto_shash_final(req, result);
1294 if (unlikely(r < 0)) {
1295 dm_integrity_io_error(ic, "crypto_shash_final", r);
1299 digest_size = crypto_shash_digestsize(ic->internal_hash);
1300 if (unlikely(digest_size < ic->tag_size))
1301 memset(result + digest_size, 0, ic->tag_size - digest_size);
1306 /* this shouldn't happen anyway, the hash functions have no reason to fail */
1307 get_random_bytes(result, ic->tag_size);
1310 static void integrity_metadata(struct work_struct *w)
1312 struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
1313 struct dm_integrity_c *ic = dio->ic;
1317 if (ic->internal_hash) {
1318 struct bvec_iter iter;
1320 unsigned digest_size = crypto_shash_digestsize(ic->internal_hash);
1321 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1323 unsigned extra_space = unlikely(digest_size > ic->tag_size) ? digest_size - ic->tag_size : 0;
1324 char checksums_onstack[HASH_MAX_DIGESTSIZE];
1325 unsigned sectors_to_process = dio->range.n_sectors;
1326 sector_t sector = dio->range.logical_sector;
1328 if (unlikely(ic->mode == 'R'))
1331 checksums = kmalloc((PAGE_SIZE >> SECTOR_SHIFT >> ic->sb->log2_sectors_per_block) * ic->tag_size + extra_space,
1332 GFP_NOIO | __GFP_NORETRY | __GFP_NOWARN);
1334 checksums = checksums_onstack;
1335 if (WARN_ON(extra_space &&
1336 digest_size > sizeof(checksums_onstack))) {
1342 __bio_for_each_segment(bv, bio, iter, dio->orig_bi_iter) {
1344 char *mem, *checksums_ptr;
1347 mem = (char *)kmap_atomic(bv.bv_page) + bv.bv_offset;
1349 checksums_ptr = checksums;
1351 integrity_sector_checksum(ic, sector, mem + pos, checksums_ptr);
1352 checksums_ptr += ic->tag_size;
1353 sectors_to_process -= ic->sectors_per_block;
1354 pos += ic->sectors_per_block << SECTOR_SHIFT;
1355 sector += ic->sectors_per_block;
1356 } while (pos < bv.bv_len && sectors_to_process && checksums != checksums_onstack);
1359 r = dm_integrity_rw_tag(ic, checksums, &dio->metadata_block, &dio->metadata_offset,
1360 checksums_ptr - checksums, !dio->write ? TAG_CMP : TAG_WRITE);
1363 DMERR_LIMIT("Checksum failed at sector 0x%llx",
1364 (unsigned long long)(sector - ((r + ic->tag_size - 1) / ic->tag_size)));
1366 atomic64_inc(&ic->number_of_mismatches);
1368 if (likely(checksums != checksums_onstack))
1373 if (!sectors_to_process)
1376 if (unlikely(pos < bv.bv_len)) {
1377 bv.bv_offset += pos;
1383 if (likely(checksums != checksums_onstack))
1386 struct bio_integrity_payload *bip = dio->orig_bi_integrity;
1390 struct bvec_iter iter;
1391 unsigned data_to_process = dio->range.n_sectors;
1392 sector_to_block(ic, data_to_process);
1393 data_to_process *= ic->tag_size;
1395 bip_for_each_vec(biv, bip, iter) {
1399 BUG_ON(PageHighMem(biv.bv_page));
1400 tag = lowmem_page_address(biv.bv_page) + biv.bv_offset;
1401 this_len = min(biv.bv_len, data_to_process);
1402 r = dm_integrity_rw_tag(ic, tag, &dio->metadata_block, &dio->metadata_offset,
1403 this_len, !dio->write ? TAG_READ : TAG_WRITE);
1406 data_to_process -= this_len;
1407 if (!data_to_process)
1416 dio->bi_status = errno_to_blk_status(r);
1420 static int dm_integrity_map(struct dm_target *ti, struct bio *bio)
1422 struct dm_integrity_c *ic = ti->private;
1423 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
1424 struct bio_integrity_payload *bip;
1426 sector_t area, offset;
1431 if (unlikely(bio->bi_opf & REQ_PREFLUSH)) {
1432 submit_flush_bio(ic, dio);
1433 return DM_MAPIO_SUBMITTED;
1436 dio->range.logical_sector = dm_target_offset(ti, bio->bi_iter.bi_sector);
1437 dio->write = bio_op(bio) == REQ_OP_WRITE;
1438 dio->fua = dio->write && bio->bi_opf & REQ_FUA;
1439 if (unlikely(dio->fua)) {
1441 * Don't pass down the FUA flag because we have to flush
1442 * disk cache anyway.
1444 bio->bi_opf &= ~REQ_FUA;
1446 if (unlikely(dio->range.logical_sector + bio_sectors(bio) > ic->provided_data_sectors)) {
1447 DMERR("Too big sector number: 0x%llx + 0x%x > 0x%llx",
1448 (unsigned long long)dio->range.logical_sector, bio_sectors(bio),
1449 (unsigned long long)ic->provided_data_sectors);
1450 return DM_MAPIO_KILL;
1452 if (unlikely((dio->range.logical_sector | bio_sectors(bio)) & (unsigned)(ic->sectors_per_block - 1))) {
1453 DMERR("Bio not aligned on %u sectors: 0x%llx, 0x%x",
1454 ic->sectors_per_block,
1455 (unsigned long long)dio->range.logical_sector, bio_sectors(bio));
1456 return DM_MAPIO_KILL;
1459 if (ic->sectors_per_block > 1) {
1460 struct bvec_iter iter;
1462 bio_for_each_segment(bv, bio, iter) {
1463 if (unlikely(bv.bv_len & ((ic->sectors_per_block << SECTOR_SHIFT) - 1))) {
1464 DMERR("Bio vector (%u,%u) is not aligned on %u-sector boundary",
1465 bv.bv_offset, bv.bv_len, ic->sectors_per_block);
1466 return DM_MAPIO_KILL;
1471 bip = bio_integrity(bio);
1472 if (!ic->internal_hash) {
1474 unsigned wanted_tag_size = bio_sectors(bio) >> ic->sb->log2_sectors_per_block;
1475 if (ic->log2_tag_size >= 0)
1476 wanted_tag_size <<= ic->log2_tag_size;
1478 wanted_tag_size *= ic->tag_size;
1479 if (unlikely(wanted_tag_size != bip->bip_iter.bi_size)) {
1480 DMERR("Invalid integrity data size %u, expected %u", bip->bip_iter.bi_size, wanted_tag_size);
1481 return DM_MAPIO_KILL;
1485 if (unlikely(bip != NULL)) {
1486 DMERR("Unexpected integrity data when using internal hash");
1487 return DM_MAPIO_KILL;
1491 if (unlikely(ic->mode == 'R') && unlikely(dio->write))
1492 return DM_MAPIO_KILL;
1494 get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
1495 dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
1496 bio->bi_iter.bi_sector = get_data_sector(ic, area, offset);
1498 dm_integrity_map_continue(dio, true);
1499 return DM_MAPIO_SUBMITTED;
1502 static bool __journal_read_write(struct dm_integrity_io *dio, struct bio *bio,
1503 unsigned journal_section, unsigned journal_entry)
1505 struct dm_integrity_c *ic = dio->ic;
1506 sector_t logical_sector;
1509 logical_sector = dio->range.logical_sector;
1510 n_sectors = dio->range.n_sectors;
1512 struct bio_vec bv = bio_iovec(bio);
1515 if (unlikely(bv.bv_len >> SECTOR_SHIFT > n_sectors))
1516 bv.bv_len = n_sectors << SECTOR_SHIFT;
1517 n_sectors -= bv.bv_len >> SECTOR_SHIFT;
1518 bio_advance_iter(bio, &bio->bi_iter, bv.bv_len);
1520 mem = kmap_atomic(bv.bv_page);
1521 if (likely(dio->write))
1522 flush_dcache_page(bv.bv_page);
1525 struct journal_entry *je = access_journal_entry(ic, journal_section, journal_entry);
1527 if (unlikely(!dio->write)) {
1528 struct journal_sector *js;
1532 if (unlikely(journal_entry_is_inprogress(je))) {
1533 flush_dcache_page(bv.bv_page);
1536 __io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
1540 BUG_ON(journal_entry_get_sector(je) != logical_sector);
1541 js = access_journal_data(ic, journal_section, journal_entry);
1542 mem_ptr = mem + bv.bv_offset;
1545 memcpy(mem_ptr, js, JOURNAL_SECTOR_DATA);
1546 *(commit_id_t *)(mem_ptr + JOURNAL_SECTOR_DATA) = je->last_bytes[s];
1548 mem_ptr += 1 << SECTOR_SHIFT;
1549 } while (++s < ic->sectors_per_block);
1550 #ifdef INTERNAL_VERIFY
1551 if (ic->internal_hash) {
1552 char checksums_onstack[max(HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
1554 integrity_sector_checksum(ic, logical_sector, mem + bv.bv_offset, checksums_onstack);
1555 if (unlikely(memcmp(checksums_onstack, journal_entry_tag(ic, je), ic->tag_size))) {
1556 DMERR_LIMIT("Checksum failed when reading from journal, at sector 0x%llx",
1557 (unsigned long long)logical_sector);
1563 if (!ic->internal_hash) {
1564 struct bio_integrity_payload *bip = bio_integrity(bio);
1565 unsigned tag_todo = ic->tag_size;
1566 char *tag_ptr = journal_entry_tag(ic, je);
1569 struct bio_vec biv = bvec_iter_bvec(bip->bip_vec, bip->bip_iter);
1570 unsigned tag_now = min(biv.bv_len, tag_todo);
1572 BUG_ON(PageHighMem(biv.bv_page));
1573 tag_addr = lowmem_page_address(biv.bv_page) + biv.bv_offset;
1574 if (likely(dio->write))
1575 memcpy(tag_ptr, tag_addr, tag_now);
1577 memcpy(tag_addr, tag_ptr, tag_now);
1578 bvec_iter_advance(bip->bip_vec, &bip->bip_iter, tag_now);
1580 tag_todo -= tag_now;
1581 } while (unlikely(tag_todo)); else {
1582 if (likely(dio->write))
1583 memset(tag_ptr, 0, tag_todo);
1587 if (likely(dio->write)) {
1588 struct journal_sector *js;
1591 js = access_journal_data(ic, journal_section, journal_entry);
1592 memcpy(js, mem + bv.bv_offset, ic->sectors_per_block << SECTOR_SHIFT);
1596 je->last_bytes[s] = js[s].commit_id;
1597 } while (++s < ic->sectors_per_block);
1599 if (ic->internal_hash) {
1600 unsigned digest_size = crypto_shash_digestsize(ic->internal_hash);
1601 if (unlikely(digest_size > ic->tag_size)) {
1602 char checksums_onstack[HASH_MAX_DIGESTSIZE];
1603 integrity_sector_checksum(ic, logical_sector, (char *)js, checksums_onstack);
1604 memcpy(journal_entry_tag(ic, je), checksums_onstack, ic->tag_size);
1606 integrity_sector_checksum(ic, logical_sector, (char *)js, journal_entry_tag(ic, je));
1609 journal_entry_set_sector(je, logical_sector);
1611 logical_sector += ic->sectors_per_block;
1614 if (unlikely(journal_entry == ic->journal_section_entries)) {
1617 wraparound_section(ic, &journal_section);
1620 bv.bv_offset += ic->sectors_per_block << SECTOR_SHIFT;
1621 } while (bv.bv_len -= ic->sectors_per_block << SECTOR_SHIFT);
1623 if (unlikely(!dio->write))
1624 flush_dcache_page(bv.bv_page);
1626 } while (n_sectors);
1628 if (likely(dio->write)) {
1630 if (unlikely(waitqueue_active(&ic->copy_to_journal_wait)))
1631 wake_up(&ic->copy_to_journal_wait);
1632 if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold) {
1633 queue_work(ic->commit_wq, &ic->commit_work);
1635 schedule_autocommit(ic);
1638 remove_range(ic, &dio->range);
1641 if (unlikely(bio->bi_iter.bi_size)) {
1642 sector_t area, offset;
1644 dio->range.logical_sector = logical_sector;
1645 get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
1646 dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
1653 static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map)
1655 struct dm_integrity_c *ic = dio->ic;
1656 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1657 unsigned journal_section, journal_entry;
1658 unsigned journal_read_pos;
1659 struct completion read_comp;
1660 bool need_sync_io = ic->internal_hash && !dio->write;
1662 if (need_sync_io && from_map) {
1663 INIT_WORK(&dio->work, integrity_bio_wait);
1664 queue_work(ic->metadata_wq, &dio->work);
1669 spin_lock_irq(&ic->endio_wait.lock);
1671 if (unlikely(dm_integrity_failed(ic))) {
1672 spin_unlock_irq(&ic->endio_wait.lock);
1676 dio->range.n_sectors = bio_sectors(bio);
1677 journal_read_pos = NOT_FOUND;
1678 if (likely(ic->mode == 'J')) {
1680 unsigned next_entry, i, pos;
1681 unsigned ws, we, range_sectors;
1683 dio->range.n_sectors = min(dio->range.n_sectors,
1684 ic->free_sectors << ic->sb->log2_sectors_per_block);
1685 if (unlikely(!dio->range.n_sectors)) {
1687 goto offload_to_thread;
1688 sleep_on_endio_wait(ic);
1691 range_sectors = dio->range.n_sectors >> ic->sb->log2_sectors_per_block;
1692 ic->free_sectors -= range_sectors;
1693 journal_section = ic->free_section;
1694 journal_entry = ic->free_section_entry;
1696 next_entry = ic->free_section_entry + range_sectors;
1697 ic->free_section_entry = next_entry % ic->journal_section_entries;
1698 ic->free_section += next_entry / ic->journal_section_entries;
1699 ic->n_uncommitted_sections += next_entry / ic->journal_section_entries;
1700 wraparound_section(ic, &ic->free_section);
1702 pos = journal_section * ic->journal_section_entries + journal_entry;
1703 ws = journal_section;
1707 struct journal_entry *je;
1709 add_journal_node(ic, &ic->journal_tree[pos], dio->range.logical_sector + i);
1711 if (unlikely(pos >= ic->journal_entries))
1714 je = access_journal_entry(ic, ws, we);
1715 BUG_ON(!journal_entry_is_unused(je));
1716 journal_entry_set_inprogress(je);
1718 if (unlikely(we == ic->journal_section_entries)) {
1721 wraparound_section(ic, &ws);
1723 } while ((i += ic->sectors_per_block) < dio->range.n_sectors);
1725 spin_unlock_irq(&ic->endio_wait.lock);
1726 goto journal_read_write;
1728 sector_t next_sector;
1729 journal_read_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
1730 if (likely(journal_read_pos == NOT_FOUND)) {
1731 if (unlikely(dio->range.n_sectors > next_sector - dio->range.logical_sector))
1732 dio->range.n_sectors = next_sector - dio->range.logical_sector;
1735 unsigned jp = journal_read_pos + 1;
1736 for (i = ic->sectors_per_block; i < dio->range.n_sectors; i += ic->sectors_per_block, jp++) {
1737 if (!test_journal_node(ic, jp, dio->range.logical_sector + i))
1740 dio->range.n_sectors = i;
1744 if (unlikely(!add_new_range(ic, &dio->range, true))) {
1746 * We must not sleep in the request routine because it could
1747 * stall bios on current->bio_list.
1748 * So, we offload the bio to a workqueue if we have to sleep.
1752 spin_unlock_irq(&ic->endio_wait.lock);
1753 INIT_WORK(&dio->work, integrity_bio_wait);
1754 queue_work(ic->wait_wq, &dio->work);
1757 wait_and_add_new_range(ic, &dio->range);
1759 spin_unlock_irq(&ic->endio_wait.lock);
1761 if (unlikely(journal_read_pos != NOT_FOUND)) {
1762 journal_section = journal_read_pos / ic->journal_section_entries;
1763 journal_entry = journal_read_pos % ic->journal_section_entries;
1764 goto journal_read_write;
1767 dio->in_flight = (atomic_t)ATOMIC_INIT(2);
1770 init_completion(&read_comp);
1771 dio->completion = &read_comp;
1773 dio->completion = NULL;
1775 dio->orig_bi_iter = bio->bi_iter;
1777 dio->orig_bi_disk = bio->bi_disk;
1778 dio->orig_bi_partno = bio->bi_partno;
1779 bio_set_dev(bio, ic->dev->bdev);
1781 dio->orig_bi_integrity = bio_integrity(bio);
1782 bio->bi_integrity = NULL;
1783 bio->bi_opf &= ~REQ_INTEGRITY;
1785 dio->orig_bi_end_io = bio->bi_end_io;
1786 bio->bi_end_io = integrity_end_io;
1788 bio->bi_iter.bi_size = dio->range.n_sectors << SECTOR_SHIFT;
1789 generic_make_request(bio);
1792 wait_for_completion_io(&read_comp);
1793 if (unlikely(ic->recalc_wq != NULL) &&
1794 ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
1795 dio->range.logical_sector + dio->range.n_sectors > le64_to_cpu(ic->sb->recalc_sector))
1797 if (likely(!bio->bi_status))
1798 integrity_metadata(&dio->work);
1804 INIT_WORK(&dio->work, integrity_metadata);
1805 queue_work(ic->metadata_wq, &dio->work);
1811 if (unlikely(__journal_read_write(dio, bio, journal_section, journal_entry)))
1814 do_endio_flush(ic, dio);
1818 static void integrity_bio_wait(struct work_struct *w)
1820 struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
1822 dm_integrity_map_continue(dio, false);
1825 static void pad_uncommitted(struct dm_integrity_c *ic)
1827 if (ic->free_section_entry) {
1828 ic->free_sectors -= ic->journal_section_entries - ic->free_section_entry;
1829 ic->free_section_entry = 0;
1831 wraparound_section(ic, &ic->free_section);
1832 ic->n_uncommitted_sections++;
1834 WARN_ON(ic->journal_sections * ic->journal_section_entries !=
1835 (ic->n_uncommitted_sections + ic->n_committed_sections) * ic->journal_section_entries + ic->free_sectors);
1838 static void integrity_commit(struct work_struct *w)
1840 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, commit_work);
1841 unsigned commit_start, commit_sections;
1843 struct bio *flushes;
1845 del_timer(&ic->autocommit_timer);
1847 spin_lock_irq(&ic->endio_wait.lock);
1848 flushes = bio_list_get(&ic->flush_bio_list);
1849 if (unlikely(ic->mode != 'J')) {
1850 spin_unlock_irq(&ic->endio_wait.lock);
1851 dm_integrity_flush_buffers(ic);
1852 goto release_flush_bios;
1855 pad_uncommitted(ic);
1856 commit_start = ic->uncommitted_section;
1857 commit_sections = ic->n_uncommitted_sections;
1858 spin_unlock_irq(&ic->endio_wait.lock);
1860 if (!commit_sections)
1861 goto release_flush_bios;
1864 for (n = 0; n < commit_sections; n++) {
1865 for (j = 0; j < ic->journal_section_entries; j++) {
1866 struct journal_entry *je;
1867 je = access_journal_entry(ic, i, j);
1868 io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
1870 for (j = 0; j < ic->journal_section_sectors; j++) {
1871 struct journal_sector *js;
1872 js = access_journal(ic, i, j);
1873 js->commit_id = dm_integrity_commit_id(ic, i, j, ic->commit_seq);
1876 if (unlikely(i >= ic->journal_sections))
1877 ic->commit_seq = next_commit_seq(ic->commit_seq);
1878 wraparound_section(ic, &i);
1882 write_journal(ic, commit_start, commit_sections);
1884 spin_lock_irq(&ic->endio_wait.lock);
1885 ic->uncommitted_section += commit_sections;
1886 wraparound_section(ic, &ic->uncommitted_section);
1887 ic->n_uncommitted_sections -= commit_sections;
1888 ic->n_committed_sections += commit_sections;
1889 spin_unlock_irq(&ic->endio_wait.lock);
1891 if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold)
1892 queue_work(ic->writer_wq, &ic->writer_work);
1896 struct bio *next = flushes->bi_next;
1897 flushes->bi_next = NULL;
1898 do_endio(ic, flushes);
1903 static void complete_copy_from_journal(unsigned long error, void *context)
1905 struct journal_io *io = context;
1906 struct journal_completion *comp = io->comp;
1907 struct dm_integrity_c *ic = comp->ic;
1908 remove_range(ic, &io->range);
1909 mempool_free(io, &ic->journal_io_mempool);
1910 if (unlikely(error != 0))
1911 dm_integrity_io_error(ic, "copying from journal", -EIO);
1912 complete_journal_op(comp);
1915 static void restore_last_bytes(struct dm_integrity_c *ic, struct journal_sector *js,
1916 struct journal_entry *je)
1920 js->commit_id = je->last_bytes[s];
1922 } while (++s < ic->sectors_per_block);
1925 static void do_journal_write(struct dm_integrity_c *ic, unsigned write_start,
1926 unsigned write_sections, bool from_replay)
1929 struct journal_completion comp;
1930 struct blk_plug plug;
1932 blk_start_plug(&plug);
1935 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
1936 init_completion(&comp.comp);
1939 for (n = 0; n < write_sections; n++, i++, wraparound_section(ic, &i)) {
1940 #ifndef INTERNAL_VERIFY
1941 if (unlikely(from_replay))
1943 rw_section_mac(ic, i, false);
1944 for (j = 0; j < ic->journal_section_entries; j++) {
1945 struct journal_entry *je = access_journal_entry(ic, i, j);
1946 sector_t sec, area, offset;
1947 unsigned k, l, next_loop;
1948 sector_t metadata_block;
1949 unsigned metadata_offset;
1950 struct journal_io *io;
1952 if (journal_entry_is_unused(je))
1954 BUG_ON(unlikely(journal_entry_is_inprogress(je)) && !from_replay);
1955 sec = journal_entry_get_sector(je);
1956 if (unlikely(from_replay)) {
1957 if (unlikely(sec & (unsigned)(ic->sectors_per_block - 1))) {
1958 dm_integrity_io_error(ic, "invalid sector in journal", -EIO);
1959 sec &= ~(sector_t)(ic->sectors_per_block - 1);
1962 get_area_and_offset(ic, sec, &area, &offset);
1963 restore_last_bytes(ic, access_journal_data(ic, i, j), je);
1964 for (k = j + 1; k < ic->journal_section_entries; k++) {
1965 struct journal_entry *je2 = access_journal_entry(ic, i, k);
1966 sector_t sec2, area2, offset2;
1967 if (journal_entry_is_unused(je2))
1969 BUG_ON(unlikely(journal_entry_is_inprogress(je2)) && !from_replay);
1970 sec2 = journal_entry_get_sector(je2);
1971 get_area_and_offset(ic, sec2, &area2, &offset2);
1972 if (area2 != area || offset2 != offset + ((k - j) << ic->sb->log2_sectors_per_block))
1974 restore_last_bytes(ic, access_journal_data(ic, i, k), je2);
1978 io = mempool_alloc(&ic->journal_io_mempool, GFP_NOIO);
1980 io->range.logical_sector = sec;
1981 io->range.n_sectors = (k - j) << ic->sb->log2_sectors_per_block;
1983 spin_lock_irq(&ic->endio_wait.lock);
1984 if (unlikely(!add_new_range(ic, &io->range, true)))
1985 wait_and_add_new_range(ic, &io->range);
1987 if (likely(!from_replay)) {
1988 struct journal_node *section_node = &ic->journal_tree[i * ic->journal_section_entries];
1990 /* don't write if there is newer committed sector */
1991 while (j < k && find_newer_committed_node(ic, §ion_node[j])) {
1992 struct journal_entry *je2 = access_journal_entry(ic, i, j);
1994 journal_entry_set_unused(je2);
1995 remove_journal_node(ic, §ion_node[j]);
1997 sec += ic->sectors_per_block;
1998 offset += ic->sectors_per_block;
2000 while (j < k && find_newer_committed_node(ic, §ion_node[k - 1])) {
2001 struct journal_entry *je2 = access_journal_entry(ic, i, k - 1);
2003 journal_entry_set_unused(je2);
2004 remove_journal_node(ic, §ion_node[k - 1]);
2008 remove_range_unlocked(ic, &io->range);
2009 spin_unlock_irq(&ic->endio_wait.lock);
2010 mempool_free(io, &ic->journal_io_mempool);
2013 for (l = j; l < k; l++) {
2014 remove_journal_node(ic, §ion_node[l]);
2017 spin_unlock_irq(&ic->endio_wait.lock);
2019 metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
2020 for (l = j; l < k; l++) {
2022 struct journal_entry *je2 = access_journal_entry(ic, i, l);
2025 #ifndef INTERNAL_VERIFY
2026 unlikely(from_replay) &&
2028 ic->internal_hash) {
2029 char test_tag[max_t(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
2031 integrity_sector_checksum(ic, sec + ((l - j) << ic->sb->log2_sectors_per_block),
2032 (char *)access_journal_data(ic, i, l), test_tag);
2033 if (unlikely(memcmp(test_tag, journal_entry_tag(ic, je2), ic->tag_size)))
2034 dm_integrity_io_error(ic, "tag mismatch when replaying journal", -EILSEQ);
2037 journal_entry_set_unused(je2);
2038 r = dm_integrity_rw_tag(ic, journal_entry_tag(ic, je2), &metadata_block, &metadata_offset,
2039 ic->tag_size, TAG_WRITE);
2041 dm_integrity_io_error(ic, "reading tags", r);
2045 atomic_inc(&comp.in_flight);
2046 copy_from_journal(ic, i, j << ic->sb->log2_sectors_per_block,
2047 (k - j) << ic->sb->log2_sectors_per_block,
2048 get_data_sector(ic, area, offset),
2049 complete_copy_from_journal, io);
2055 dm_bufio_write_dirty_buffers_async(ic->bufio);
2057 blk_finish_plug(&plug);
2059 complete_journal_op(&comp);
2060 wait_for_completion_io(&comp.comp);
2062 dm_integrity_flush_buffers(ic);
2065 static void integrity_writer(struct work_struct *w)
2067 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, writer_work);
2068 unsigned write_start, write_sections;
2070 unsigned prev_free_sectors;
2072 /* the following test is not needed, but it tests the replay code */
2073 if (READ_ONCE(ic->suspending) && !ic->meta_dev)
2076 spin_lock_irq(&ic->endio_wait.lock);
2077 write_start = ic->committed_section;
2078 write_sections = ic->n_committed_sections;
2079 spin_unlock_irq(&ic->endio_wait.lock);
2081 if (!write_sections)
2084 do_journal_write(ic, write_start, write_sections, false);
2086 spin_lock_irq(&ic->endio_wait.lock);
2088 ic->committed_section += write_sections;
2089 wraparound_section(ic, &ic->committed_section);
2090 ic->n_committed_sections -= write_sections;
2092 prev_free_sectors = ic->free_sectors;
2093 ic->free_sectors += write_sections * ic->journal_section_entries;
2094 if (unlikely(!prev_free_sectors))
2095 wake_up_locked(&ic->endio_wait);
2097 spin_unlock_irq(&ic->endio_wait.lock);
2100 static void recalc_write_super(struct dm_integrity_c *ic)
2104 dm_integrity_flush_buffers(ic);
2105 if (dm_integrity_failed(ic))
2109 r = sync_rw_sb(ic, REQ_OP_WRITE, 0);
2111 dm_integrity_io_error(ic, "writing superblock", r);
2114 static void integrity_recalc(struct work_struct *w)
2116 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, recalc_work);
2117 struct dm_integrity_range range;
2118 struct dm_io_request io_req;
2119 struct dm_io_region io_loc;
2120 sector_t area, offset;
2121 sector_t metadata_block;
2122 unsigned metadata_offset;
2126 unsigned super_counter = 0;
2128 spin_lock_irq(&ic->endio_wait.lock);
2132 if (unlikely(READ_ONCE(ic->suspending)))
2135 range.logical_sector = le64_to_cpu(ic->sb->recalc_sector);
2136 if (unlikely(range.logical_sector >= ic->provided_data_sectors))
2139 get_area_and_offset(ic, range.logical_sector, &area, &offset);
2140 range.n_sectors = min((sector_t)RECALC_SECTORS, ic->provided_data_sectors - range.logical_sector);
2142 range.n_sectors = min(range.n_sectors, (1U << ic->sb->log2_interleave_sectors) - (unsigned)offset);
2144 if (unlikely(!add_new_range(ic, &range, true)))
2145 wait_and_add_new_range(ic, &range);
2147 spin_unlock_irq(&ic->endio_wait.lock);
2149 if (unlikely(++super_counter == RECALC_WRITE_SUPER)) {
2150 recalc_write_super(ic);
2154 if (unlikely(dm_integrity_failed(ic)))
2157 io_req.bi_op = REQ_OP_READ;
2158 io_req.bi_op_flags = 0;
2159 io_req.mem.type = DM_IO_VMA;
2160 io_req.mem.ptr.addr = ic->recalc_buffer;
2161 io_req.notify.fn = NULL;
2162 io_req.client = ic->io;
2163 io_loc.bdev = ic->dev->bdev;
2164 io_loc.sector = get_data_sector(ic, area, offset);
2165 io_loc.count = range.n_sectors;
2167 r = dm_io(&io_req, 1, &io_loc, NULL);
2169 dm_integrity_io_error(ic, "reading data", r);
2173 t = ic->recalc_tags;
2174 for (i = 0; i < range.n_sectors; i += ic->sectors_per_block) {
2175 integrity_sector_checksum(ic, range.logical_sector + i, ic->recalc_buffer + (i << SECTOR_SHIFT), t);
2179 metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
2181 r = dm_integrity_rw_tag(ic, ic->recalc_tags, &metadata_block, &metadata_offset, t - ic->recalc_tags, TAG_WRITE);
2183 dm_integrity_io_error(ic, "writing tags", r);
2187 spin_lock_irq(&ic->endio_wait.lock);
2188 remove_range_unlocked(ic, &range);
2189 ic->sb->recalc_sector = cpu_to_le64(range.logical_sector + range.n_sectors);
2193 remove_range(ic, &range);
2197 spin_unlock_irq(&ic->endio_wait.lock);
2199 recalc_write_super(ic);
2202 static void init_journal(struct dm_integrity_c *ic, unsigned start_section,
2203 unsigned n_sections, unsigned char commit_seq)
2210 for (n = 0; n < n_sections; n++) {
2211 i = start_section + n;
2212 wraparound_section(ic, &i);
2213 for (j = 0; j < ic->journal_section_sectors; j++) {
2214 struct journal_sector *js = access_journal(ic, i, j);
2215 memset(&js->entries, 0, JOURNAL_SECTOR_DATA);
2216 js->commit_id = dm_integrity_commit_id(ic, i, j, commit_seq);
2218 for (j = 0; j < ic->journal_section_entries; j++) {
2219 struct journal_entry *je = access_journal_entry(ic, i, j);
2220 journal_entry_set_unused(je);
2224 write_journal(ic, start_section, n_sections);
2227 static int find_commit_seq(struct dm_integrity_c *ic, unsigned i, unsigned j, commit_id_t id)
2230 for (k = 0; k < N_COMMIT_IDS; k++) {
2231 if (dm_integrity_commit_id(ic, i, j, k) == id)
2234 dm_integrity_io_error(ic, "journal commit id", -EIO);
2238 static void replay_journal(struct dm_integrity_c *ic)
2241 bool used_commit_ids[N_COMMIT_IDS];
2242 unsigned max_commit_id_sections[N_COMMIT_IDS];
2243 unsigned write_start, write_sections;
2244 unsigned continue_section;
2246 unsigned char unused, last_used, want_commit_seq;
2248 if (ic->mode == 'R')
2251 if (ic->journal_uptodate)
2257 if (!ic->just_formatted) {
2258 DEBUG_print("reading journal\n");
2259 rw_journal(ic, REQ_OP_READ, 0, 0, ic->journal_sections, NULL);
2261 DEBUG_bytes(lowmem_page_address(ic->journal_io[0].page), 64, "read journal");
2262 if (ic->journal_io) {
2263 struct journal_completion crypt_comp;
2265 init_completion(&crypt_comp.comp);
2266 crypt_comp.in_flight = (atomic_t)ATOMIC_INIT(0);
2267 encrypt_journal(ic, false, 0, ic->journal_sections, &crypt_comp);
2268 wait_for_completion(&crypt_comp.comp);
2270 DEBUG_bytes(lowmem_page_address(ic->journal[0].page), 64, "decrypted journal");
2273 if (dm_integrity_failed(ic))
2276 journal_empty = true;
2277 memset(used_commit_ids, 0, sizeof used_commit_ids);
2278 memset(max_commit_id_sections, 0, sizeof max_commit_id_sections);
2279 for (i = 0; i < ic->journal_sections; i++) {
2280 for (j = 0; j < ic->journal_section_sectors; j++) {
2282 struct journal_sector *js = access_journal(ic, i, j);
2283 k = find_commit_seq(ic, i, j, js->commit_id);
2286 used_commit_ids[k] = true;
2287 max_commit_id_sections[k] = i;
2289 if (journal_empty) {
2290 for (j = 0; j < ic->journal_section_entries; j++) {
2291 struct journal_entry *je = access_journal_entry(ic, i, j);
2292 if (!journal_entry_is_unused(je)) {
2293 journal_empty = false;
2300 if (!used_commit_ids[N_COMMIT_IDS - 1]) {
2301 unused = N_COMMIT_IDS - 1;
2302 while (unused && !used_commit_ids[unused - 1])
2305 for (unused = 0; unused < N_COMMIT_IDS; unused++)
2306 if (!used_commit_ids[unused])
2308 if (unused == N_COMMIT_IDS) {
2309 dm_integrity_io_error(ic, "journal commit ids", -EIO);
2313 DEBUG_print("first unused commit seq %d [%d,%d,%d,%d]\n",
2314 unused, used_commit_ids[0], used_commit_ids[1],
2315 used_commit_ids[2], used_commit_ids[3]);
2317 last_used = prev_commit_seq(unused);
2318 want_commit_seq = prev_commit_seq(last_used);
2320 if (!used_commit_ids[want_commit_seq] && used_commit_ids[prev_commit_seq(want_commit_seq)])
2321 journal_empty = true;
2323 write_start = max_commit_id_sections[last_used] + 1;
2324 if (unlikely(write_start >= ic->journal_sections))
2325 want_commit_seq = next_commit_seq(want_commit_seq);
2326 wraparound_section(ic, &write_start);
2329 for (write_sections = 0; write_sections < ic->journal_sections; write_sections++) {
2330 for (j = 0; j < ic->journal_section_sectors; j++) {
2331 struct journal_sector *js = access_journal(ic, i, j);
2333 if (js->commit_id != dm_integrity_commit_id(ic, i, j, want_commit_seq)) {
2335 * This could be caused by crash during writing.
2336 * We won't replay the inconsistent part of the
2339 DEBUG_print("commit id mismatch at position (%u, %u): %d != %d\n",
2340 i, j, find_commit_seq(ic, i, j, js->commit_id), want_commit_seq);
2345 if (unlikely(i >= ic->journal_sections))
2346 want_commit_seq = next_commit_seq(want_commit_seq);
2347 wraparound_section(ic, &i);
2351 if (!journal_empty) {
2352 DEBUG_print("replaying %u sections, starting at %u, commit seq %d\n",
2353 write_sections, write_start, want_commit_seq);
2354 do_journal_write(ic, write_start, write_sections, true);
2357 if (write_sections == ic->journal_sections && (ic->mode == 'J' || journal_empty)) {
2358 continue_section = write_start;
2359 ic->commit_seq = want_commit_seq;
2360 DEBUG_print("continuing from section %u, commit seq %d\n", write_start, ic->commit_seq);
2363 unsigned char erase_seq;
2365 DEBUG_print("clearing journal\n");
2367 erase_seq = prev_commit_seq(prev_commit_seq(last_used));
2369 init_journal(ic, s, 1, erase_seq);
2371 wraparound_section(ic, &s);
2372 if (ic->journal_sections >= 2) {
2373 init_journal(ic, s, ic->journal_sections - 2, erase_seq);
2374 s += ic->journal_sections - 2;
2375 wraparound_section(ic, &s);
2376 init_journal(ic, s, 1, erase_seq);
2379 continue_section = 0;
2380 ic->commit_seq = next_commit_seq(erase_seq);
2383 ic->committed_section = continue_section;
2384 ic->n_committed_sections = 0;
2386 ic->uncommitted_section = continue_section;
2387 ic->n_uncommitted_sections = 0;
2389 ic->free_section = continue_section;
2390 ic->free_section_entry = 0;
2391 ic->free_sectors = ic->journal_entries;
2393 ic->journal_tree_root = RB_ROOT;
2394 for (i = 0; i < ic->journal_entries; i++)
2395 init_journal_node(&ic->journal_tree[i]);
2398 static void dm_integrity_postsuspend(struct dm_target *ti)
2400 struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2402 del_timer_sync(&ic->autocommit_timer);
2404 WRITE_ONCE(ic->suspending, 1);
2407 drain_workqueue(ic->recalc_wq);
2409 queue_work(ic->commit_wq, &ic->commit_work);
2410 drain_workqueue(ic->commit_wq);
2412 if (ic->mode == 'J') {
2414 queue_work(ic->writer_wq, &ic->writer_work);
2415 drain_workqueue(ic->writer_wq);
2416 dm_integrity_flush_buffers(ic);
2419 WRITE_ONCE(ic->suspending, 0);
2421 BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
2423 ic->journal_uptodate = true;
2426 static void dm_integrity_resume(struct dm_target *ti)
2428 struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2432 if (ic->recalc_wq && ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
2433 __u64 recalc_pos = le64_to_cpu(ic->sb->recalc_sector);
2434 if (recalc_pos < ic->provided_data_sectors) {
2435 queue_work(ic->recalc_wq, &ic->recalc_work);
2436 } else if (recalc_pos > ic->provided_data_sectors) {
2437 ic->sb->recalc_sector = cpu_to_le64(ic->provided_data_sectors);
2438 recalc_write_super(ic);
2443 static void dm_integrity_status(struct dm_target *ti, status_type_t type,
2444 unsigned status_flags, char *result, unsigned maxlen)
2446 struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2451 case STATUSTYPE_INFO:
2453 (unsigned long long)atomic64_read(&ic->number_of_mismatches),
2454 (unsigned long long)ic->provided_data_sectors);
2455 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
2456 DMEMIT(" %llu", (unsigned long long)le64_to_cpu(ic->sb->recalc_sector));
2461 case STATUSTYPE_TABLE: {
2462 __u64 watermark_percentage = (__u64)(ic->journal_entries - ic->free_sectors_threshold) * 100;
2463 watermark_percentage += ic->journal_entries / 2;
2464 do_div(watermark_percentage, ic->journal_entries);
2466 arg_count += !!ic->meta_dev;
2467 arg_count += ic->sectors_per_block != 1;
2468 arg_count += !!(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING));
2469 arg_count += !!ic->internal_hash_alg.alg_string;
2470 arg_count += !!ic->journal_crypt_alg.alg_string;
2471 arg_count += !!ic->journal_mac_alg.alg_string;
2472 DMEMIT("%s %llu %u %c %u", ic->dev->name, (unsigned long long)ic->start,
2473 ic->tag_size, ic->mode, arg_count);
2475 DMEMIT(" meta_device:%s", ic->meta_dev->name);
2476 if (ic->sectors_per_block != 1)
2477 DMEMIT(" block_size:%u", ic->sectors_per_block << SECTOR_SHIFT);
2478 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
2479 DMEMIT(" recalculate");
2480 DMEMIT(" journal_sectors:%u", ic->initial_sectors - SB_SECTORS);
2481 DMEMIT(" interleave_sectors:%u", 1U << ic->sb->log2_interleave_sectors);
2482 DMEMIT(" buffer_sectors:%u", 1U << ic->log2_buffer_sectors);
2483 DMEMIT(" journal_watermark:%u", (unsigned)watermark_percentage);
2484 DMEMIT(" commit_time:%u", ic->autocommit_msec);
2486 #define EMIT_ALG(a, n) \
2488 if (ic->a.alg_string) { \
2489 DMEMIT(" %s:%s", n, ic->a.alg_string); \
2490 if (ic->a.key_string) \
2491 DMEMIT(":%s", ic->a.key_string);\
2494 EMIT_ALG(internal_hash_alg, "internal_hash");
2495 EMIT_ALG(journal_crypt_alg, "journal_crypt");
2496 EMIT_ALG(journal_mac_alg, "journal_mac");
2502 static int dm_integrity_iterate_devices(struct dm_target *ti,
2503 iterate_devices_callout_fn fn, void *data)
2505 struct dm_integrity_c *ic = ti->private;
2508 return fn(ti, ic->dev, ic->start + ic->initial_sectors + ic->metadata_run, ti->len, data);
2510 return fn(ti, ic->dev, 0, ti->len, data);
2513 static void dm_integrity_io_hints(struct dm_target *ti, struct queue_limits *limits)
2515 struct dm_integrity_c *ic = ti->private;
2517 if (ic->sectors_per_block > 1) {
2518 limits->logical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
2519 limits->physical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
2520 blk_limits_io_min(limits, ic->sectors_per_block << SECTOR_SHIFT);
2524 static void calculate_journal_section_size(struct dm_integrity_c *ic)
2526 unsigned sector_space = JOURNAL_SECTOR_DATA;
2528 ic->journal_sections = le32_to_cpu(ic->sb->journal_sections);
2529 ic->journal_entry_size = roundup(offsetof(struct journal_entry, last_bytes[ic->sectors_per_block]) + ic->tag_size,
2530 JOURNAL_ENTRY_ROUNDUP);
2532 if (ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC))
2533 sector_space -= JOURNAL_MAC_PER_SECTOR;
2534 ic->journal_entries_per_sector = sector_space / ic->journal_entry_size;
2535 ic->journal_section_entries = ic->journal_entries_per_sector * JOURNAL_BLOCK_SECTORS;
2536 ic->journal_section_sectors = (ic->journal_section_entries << ic->sb->log2_sectors_per_block) + JOURNAL_BLOCK_SECTORS;
2537 ic->journal_entries = ic->journal_section_entries * ic->journal_sections;
2540 static int calculate_device_limits(struct dm_integrity_c *ic)
2542 __u64 initial_sectors;
2544 calculate_journal_section_size(ic);
2545 initial_sectors = SB_SECTORS + (__u64)ic->journal_section_sectors * ic->journal_sections;
2546 if (initial_sectors + METADATA_PADDING_SECTORS >= ic->meta_device_sectors || initial_sectors > UINT_MAX)
2548 ic->initial_sectors = initial_sectors;
2550 if (!ic->meta_dev) {
2551 sector_t last_sector, last_area, last_offset;
2553 ic->metadata_run = roundup((__u64)ic->tag_size << (ic->sb->log2_interleave_sectors - ic->sb->log2_sectors_per_block),
2554 (__u64)(1 << SECTOR_SHIFT << METADATA_PADDING_SECTORS)) >> SECTOR_SHIFT;
2555 if (!(ic->metadata_run & (ic->metadata_run - 1)))
2556 ic->log2_metadata_run = __ffs(ic->metadata_run);
2558 ic->log2_metadata_run = -1;
2560 get_area_and_offset(ic, ic->provided_data_sectors - 1, &last_area, &last_offset);
2561 last_sector = get_data_sector(ic, last_area, last_offset);
2562 if (last_sector < ic->start || last_sector >= ic->meta_device_sectors)
2565 __u64 meta_size = ic->provided_data_sectors * ic->tag_size;
2566 meta_size = (meta_size + ((1U << (ic->log2_buffer_sectors + SECTOR_SHIFT)) - 1))
2567 >> (ic->log2_buffer_sectors + SECTOR_SHIFT);
2568 meta_size <<= ic->log2_buffer_sectors;
2569 if (ic->initial_sectors + meta_size < ic->initial_sectors ||
2570 ic->initial_sectors + meta_size > ic->meta_device_sectors)
2572 ic->metadata_run = 1;
2573 ic->log2_metadata_run = 0;
2579 static int initialize_superblock(struct dm_integrity_c *ic, unsigned journal_sectors, unsigned interleave_sectors)
2581 unsigned journal_sections;
2584 memset(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT);
2585 memcpy(ic->sb->magic, SB_MAGIC, 8);
2586 ic->sb->integrity_tag_size = cpu_to_le16(ic->tag_size);
2587 ic->sb->log2_sectors_per_block = __ffs(ic->sectors_per_block);
2588 if (ic->journal_mac_alg.alg_string)
2589 ic->sb->flags |= cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC);
2591 calculate_journal_section_size(ic);
2592 journal_sections = journal_sectors / ic->journal_section_sectors;
2593 if (!journal_sections)
2594 journal_sections = 1;
2596 if (!ic->meta_dev) {
2597 ic->sb->journal_sections = cpu_to_le32(journal_sections);
2598 if (!interleave_sectors)
2599 interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
2600 ic->sb->log2_interleave_sectors = __fls(interleave_sectors);
2601 ic->sb->log2_interleave_sectors = max((__u8)MIN_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
2602 ic->sb->log2_interleave_sectors = min((__u8)MAX_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
2604 ic->provided_data_sectors = 0;
2605 for (test_bit = fls64(ic->meta_device_sectors) - 1; test_bit >= 3; test_bit--) {
2606 __u64 prev_data_sectors = ic->provided_data_sectors;
2608 ic->provided_data_sectors |= (sector_t)1 << test_bit;
2609 if (calculate_device_limits(ic))
2610 ic->provided_data_sectors = prev_data_sectors;
2612 if (!ic->provided_data_sectors)
2615 ic->sb->log2_interleave_sectors = 0;
2616 ic->provided_data_sectors = ic->data_device_sectors;
2617 ic->provided_data_sectors &= ~(sector_t)(ic->sectors_per_block - 1);
2620 ic->sb->journal_sections = cpu_to_le32(0);
2621 for (test_bit = fls(journal_sections) - 1; test_bit >= 0; test_bit--) {
2622 __u32 prev_journal_sections = le32_to_cpu(ic->sb->journal_sections);
2623 __u32 test_journal_sections = prev_journal_sections | (1U << test_bit);
2624 if (test_journal_sections > journal_sections)
2626 ic->sb->journal_sections = cpu_to_le32(test_journal_sections);
2627 if (calculate_device_limits(ic))
2628 ic->sb->journal_sections = cpu_to_le32(prev_journal_sections);
2631 if (!le32_to_cpu(ic->sb->journal_sections)) {
2632 if (ic->log2_buffer_sectors > 3) {
2633 ic->log2_buffer_sectors--;
2634 goto try_smaller_buffer;
2640 ic->sb->provided_data_sectors = cpu_to_le64(ic->provided_data_sectors);
2647 static void dm_integrity_set(struct dm_target *ti, struct dm_integrity_c *ic)
2649 struct gendisk *disk = dm_disk(dm_table_get_md(ti->table));
2650 struct blk_integrity bi;
2652 memset(&bi, 0, sizeof(bi));
2653 bi.profile = &dm_integrity_profile;
2654 bi.tuple_size = ic->tag_size;
2655 bi.tag_size = bi.tuple_size;
2656 bi.interval_exp = ic->sb->log2_sectors_per_block + SECTOR_SHIFT;
2658 blk_integrity_register(disk, &bi);
2659 blk_queue_max_integrity_segments(disk->queue, UINT_MAX);
2662 static void dm_integrity_free_page_list(struct dm_integrity_c *ic, struct page_list *pl)
2668 for (i = 0; i < ic->journal_pages; i++)
2670 __free_page(pl[i].page);
2674 static struct page_list *dm_integrity_alloc_page_list(struct dm_integrity_c *ic)
2676 size_t page_list_desc_size = ic->journal_pages * sizeof(struct page_list);
2677 struct page_list *pl;
2680 pl = kvmalloc(page_list_desc_size, GFP_KERNEL | __GFP_ZERO);
2684 for (i = 0; i < ic->journal_pages; i++) {
2685 pl[i].page = alloc_page(GFP_KERNEL);
2687 dm_integrity_free_page_list(ic, pl);
2691 pl[i - 1].next = &pl[i];
2697 static void dm_integrity_free_journal_scatterlist(struct dm_integrity_c *ic, struct scatterlist **sl)
2700 for (i = 0; i < ic->journal_sections; i++)
2705 static struct scatterlist **dm_integrity_alloc_journal_scatterlist(struct dm_integrity_c *ic, struct page_list *pl)
2707 struct scatterlist **sl;
2710 sl = kvmalloc_array(ic->journal_sections,
2711 sizeof(struct scatterlist *),
2712 GFP_KERNEL | __GFP_ZERO);
2716 for (i = 0; i < ic->journal_sections; i++) {
2717 struct scatterlist *s;
2718 unsigned start_index, start_offset;
2719 unsigned end_index, end_offset;
2723 page_list_location(ic, i, 0, &start_index, &start_offset);
2724 page_list_location(ic, i, ic->journal_section_sectors - 1, &end_index, &end_offset);
2726 n_pages = (end_index - start_index + 1);
2728 s = kvmalloc_array(n_pages, sizeof(struct scatterlist),
2731 dm_integrity_free_journal_scatterlist(ic, sl);
2735 sg_init_table(s, n_pages);
2736 for (idx = start_index; idx <= end_index; idx++) {
2737 char *va = lowmem_page_address(pl[idx].page);
2738 unsigned start = 0, end = PAGE_SIZE;
2739 if (idx == start_index)
2740 start = start_offset;
2741 if (idx == end_index)
2742 end = end_offset + (1 << SECTOR_SHIFT);
2743 sg_set_buf(&s[idx - start_index], va + start, end - start);
2752 static void free_alg(struct alg_spec *a)
2754 kzfree(a->alg_string);
2756 memset(a, 0, sizeof *a);
2759 static int get_alg_and_key(const char *arg, struct alg_spec *a, char **error, char *error_inval)
2765 a->alg_string = kstrdup(strchr(arg, ':') + 1, GFP_KERNEL);
2769 k = strchr(a->alg_string, ':');
2772 a->key_string = k + 1;
2773 if (strlen(a->key_string) & 1)
2776 a->key_size = strlen(a->key_string) / 2;
2777 a->key = kmalloc(a->key_size, GFP_KERNEL);
2780 if (hex2bin(a->key, a->key_string, a->key_size))
2786 *error = error_inval;
2789 *error = "Out of memory for an argument";
2793 static int get_mac(struct crypto_shash **hash, struct alg_spec *a, char **error,
2794 char *error_alg, char *error_key)
2798 if (a->alg_string) {
2799 *hash = crypto_alloc_shash(a->alg_string, 0, 0);
2800 if (IS_ERR(*hash)) {
2808 r = crypto_shash_setkey(*hash, a->key, a->key_size);
2813 } else if (crypto_shash_get_flags(*hash) & CRYPTO_TFM_NEED_KEY) {
2822 static int create_journal(struct dm_integrity_c *ic, char **error)
2826 __u64 journal_pages, journal_desc_size, journal_tree_size;
2827 unsigned char *crypt_data = NULL, *crypt_iv = NULL;
2828 struct skcipher_request *req = NULL;
2830 ic->commit_ids[0] = cpu_to_le64(0x1111111111111111ULL);
2831 ic->commit_ids[1] = cpu_to_le64(0x2222222222222222ULL);
2832 ic->commit_ids[2] = cpu_to_le64(0x3333333333333333ULL);
2833 ic->commit_ids[3] = cpu_to_le64(0x4444444444444444ULL);
2835 journal_pages = roundup((__u64)ic->journal_sections * ic->journal_section_sectors,
2836 PAGE_SIZE >> SECTOR_SHIFT) >> (PAGE_SHIFT - SECTOR_SHIFT);
2837 journal_desc_size = journal_pages * sizeof(struct page_list);
2838 if (journal_pages >= totalram_pages() - totalhigh_pages() || journal_desc_size > ULONG_MAX) {
2839 *error = "Journal doesn't fit into memory";
2843 ic->journal_pages = journal_pages;
2845 ic->journal = dm_integrity_alloc_page_list(ic);
2847 *error = "Could not allocate memory for journal";
2851 if (ic->journal_crypt_alg.alg_string) {
2852 unsigned ivsize, blocksize;
2853 struct journal_completion comp;
2856 ic->journal_crypt = crypto_alloc_skcipher(ic->journal_crypt_alg.alg_string, 0, 0);
2857 if (IS_ERR(ic->journal_crypt)) {
2858 *error = "Invalid journal cipher";
2859 r = PTR_ERR(ic->journal_crypt);
2860 ic->journal_crypt = NULL;
2863 ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
2864 blocksize = crypto_skcipher_blocksize(ic->journal_crypt);
2866 if (ic->journal_crypt_alg.key) {
2867 r = crypto_skcipher_setkey(ic->journal_crypt, ic->journal_crypt_alg.key,
2868 ic->journal_crypt_alg.key_size);
2870 *error = "Error setting encryption key";
2874 DEBUG_print("cipher %s, block size %u iv size %u\n",
2875 ic->journal_crypt_alg.alg_string, blocksize, ivsize);
2877 ic->journal_io = dm_integrity_alloc_page_list(ic);
2878 if (!ic->journal_io) {
2879 *error = "Could not allocate memory for journal io";
2884 if (blocksize == 1) {
2885 struct scatterlist *sg;
2887 req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
2889 *error = "Could not allocate crypt request";
2894 crypt_iv = kmalloc(ivsize, GFP_KERNEL);
2896 *error = "Could not allocate iv";
2901 ic->journal_xor = dm_integrity_alloc_page_list(ic);
2902 if (!ic->journal_xor) {
2903 *error = "Could not allocate memory for journal xor";
2908 sg = kvmalloc_array(ic->journal_pages + 1,
2909 sizeof(struct scatterlist),
2912 *error = "Unable to allocate sg list";
2916 sg_init_table(sg, ic->journal_pages + 1);
2917 for (i = 0; i < ic->journal_pages; i++) {
2918 char *va = lowmem_page_address(ic->journal_xor[i].page);
2920 sg_set_buf(&sg[i], va, PAGE_SIZE);
2922 sg_set_buf(&sg[i], &ic->commit_ids, sizeof ic->commit_ids);
2923 memset(crypt_iv, 0x00, ivsize);
2925 skcipher_request_set_crypt(req, sg, sg, PAGE_SIZE * ic->journal_pages + sizeof ic->commit_ids, crypt_iv);
2926 init_completion(&comp.comp);
2927 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
2928 if (do_crypt(true, req, &comp))
2929 wait_for_completion(&comp.comp);
2931 r = dm_integrity_failed(ic);
2933 *error = "Unable to encrypt journal";
2936 DEBUG_bytes(lowmem_page_address(ic->journal_xor[0].page), 64, "xor data");
2938 crypto_free_skcipher(ic->journal_crypt);
2939 ic->journal_crypt = NULL;
2941 unsigned crypt_len = roundup(ivsize, blocksize);
2943 req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
2945 *error = "Could not allocate crypt request";
2950 crypt_iv = kmalloc(ivsize, GFP_KERNEL);
2952 *error = "Could not allocate iv";
2957 crypt_data = kmalloc(crypt_len, GFP_KERNEL);
2959 *error = "Unable to allocate crypt data";
2964 ic->journal_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal);
2965 if (!ic->journal_scatterlist) {
2966 *error = "Unable to allocate sg list";
2970 ic->journal_io_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal_io);
2971 if (!ic->journal_io_scatterlist) {
2972 *error = "Unable to allocate sg list";
2976 ic->sk_requests = kvmalloc_array(ic->journal_sections,
2977 sizeof(struct skcipher_request *),
2978 GFP_KERNEL | __GFP_ZERO);
2979 if (!ic->sk_requests) {
2980 *error = "Unable to allocate sk requests";
2984 for (i = 0; i < ic->journal_sections; i++) {
2985 struct scatterlist sg;
2986 struct skcipher_request *section_req;
2987 __u32 section_le = cpu_to_le32(i);
2989 memset(crypt_iv, 0x00, ivsize);
2990 memset(crypt_data, 0x00, crypt_len);
2991 memcpy(crypt_data, §ion_le, min((size_t)crypt_len, sizeof(section_le)));
2993 sg_init_one(&sg, crypt_data, crypt_len);
2994 skcipher_request_set_crypt(req, &sg, &sg, crypt_len, crypt_iv);
2995 init_completion(&comp.comp);
2996 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
2997 if (do_crypt(true, req, &comp))
2998 wait_for_completion(&comp.comp);
3000 r = dm_integrity_failed(ic);
3002 *error = "Unable to generate iv";
3006 section_req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
3008 *error = "Unable to allocate crypt request";
3012 section_req->iv = kmalloc_array(ivsize, 2,
3014 if (!section_req->iv) {
3015 skcipher_request_free(section_req);
3016 *error = "Unable to allocate iv";
3020 memcpy(section_req->iv + ivsize, crypt_data, ivsize);
3021 section_req->cryptlen = (size_t)ic->journal_section_sectors << SECTOR_SHIFT;
3022 ic->sk_requests[i] = section_req;
3023 DEBUG_bytes(crypt_data, ivsize, "iv(%u)", i);
3028 for (i = 0; i < N_COMMIT_IDS; i++) {
3031 for (j = 0; j < i; j++) {
3032 if (ic->commit_ids[j] == ic->commit_ids[i]) {
3033 ic->commit_ids[i] = cpu_to_le64(le64_to_cpu(ic->commit_ids[i]) + 1);
3034 goto retest_commit_id;
3037 DEBUG_print("commit id %u: %016llx\n", i, ic->commit_ids[i]);
3040 journal_tree_size = (__u64)ic->journal_entries * sizeof(struct journal_node);
3041 if (journal_tree_size > ULONG_MAX) {
3042 *error = "Journal doesn't fit into memory";
3046 ic->journal_tree = kvmalloc(journal_tree_size, GFP_KERNEL);
3047 if (!ic->journal_tree) {
3048 *error = "Could not allocate memory for journal tree";
3054 skcipher_request_free(req);
3060 * Construct a integrity mapping
3064 * offset from the start of the device
3066 * D - direct writes, J - journal writes, R - recovery mode
3067 * number of optional arguments
3068 * optional arguments:
3070 * interleave_sectors
3079 static int dm_integrity_ctr(struct dm_target *ti, unsigned argc, char **argv)
3081 struct dm_integrity_c *ic;
3084 unsigned extra_args;
3085 struct dm_arg_set as;
3086 static const struct dm_arg _args[] = {
3087 {0, 9, "Invalid number of feature args"},
3089 unsigned journal_sectors, interleave_sectors, buffer_sectors, journal_watermark, sync_msec;
3091 bool should_write_sb;
3093 unsigned long long start;
3095 #define DIRECT_ARGUMENTS 4
3097 if (argc <= DIRECT_ARGUMENTS) {
3098 ti->error = "Invalid argument count";
3102 ic = kzalloc(sizeof(struct dm_integrity_c), GFP_KERNEL);
3104 ti->error = "Cannot allocate integrity context";
3108 ti->per_io_data_size = sizeof(struct dm_integrity_io);
3110 ic->in_progress = RB_ROOT;
3111 INIT_LIST_HEAD(&ic->wait_list);
3112 init_waitqueue_head(&ic->endio_wait);
3113 bio_list_init(&ic->flush_bio_list);
3114 init_waitqueue_head(&ic->copy_to_journal_wait);
3115 init_completion(&ic->crypto_backoff);
3116 atomic64_set(&ic->number_of_mismatches, 0);
3118 r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &ic->dev);
3120 ti->error = "Device lookup failed";
3124 if (sscanf(argv[1], "%llu%c", &start, &dummy) != 1 || start != (sector_t)start) {
3125 ti->error = "Invalid starting offset";
3131 if (strcmp(argv[2], "-")) {
3132 if (sscanf(argv[2], "%u%c", &ic->tag_size, &dummy) != 1 || !ic->tag_size) {
3133 ti->error = "Invalid tag size";
3139 if (!strcmp(argv[3], "J") || !strcmp(argv[3], "D") || !strcmp(argv[3], "R"))
3140 ic->mode = argv[3][0];
3142 ti->error = "Invalid mode (expecting J, D, R)";
3147 journal_sectors = 0;
3148 interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
3149 buffer_sectors = DEFAULT_BUFFER_SECTORS;
3150 journal_watermark = DEFAULT_JOURNAL_WATERMARK;
3151 sync_msec = DEFAULT_SYNC_MSEC;
3152 recalculate = false;
3153 ic->sectors_per_block = 1;
3155 as.argc = argc - DIRECT_ARGUMENTS;
3156 as.argv = argv + DIRECT_ARGUMENTS;
3157 r = dm_read_arg_group(_args, &as, &extra_args, &ti->error);
3161 while (extra_args--) {
3162 const char *opt_string;
3164 opt_string = dm_shift_arg(&as);
3167 ti->error = "Not enough feature arguments";
3170 if (sscanf(opt_string, "journal_sectors:%u%c", &val, &dummy) == 1)
3171 journal_sectors = val ? val : 1;
3172 else if (sscanf(opt_string, "interleave_sectors:%u%c", &val, &dummy) == 1)
3173 interleave_sectors = val;
3174 else if (sscanf(opt_string, "buffer_sectors:%u%c", &val, &dummy) == 1)
3175 buffer_sectors = val;
3176 else if (sscanf(opt_string, "journal_watermark:%u%c", &val, &dummy) == 1 && val <= 100)
3177 journal_watermark = val;
3178 else if (sscanf(opt_string, "commit_time:%u%c", &val, &dummy) == 1)
3180 else if (!strncmp(opt_string, "meta_device:", strlen("meta_device:"))) {
3182 dm_put_device(ti, ic->meta_dev);
3183 ic->meta_dev = NULL;
3185 r = dm_get_device(ti, strchr(opt_string, ':') + 1, dm_table_get_mode(ti->table), &ic->meta_dev);
3187 ti->error = "Device lookup failed";
3190 } else if (sscanf(opt_string, "block_size:%u%c", &val, &dummy) == 1) {
3191 if (val < 1 << SECTOR_SHIFT ||
3192 val > MAX_SECTORS_PER_BLOCK << SECTOR_SHIFT ||
3195 ti->error = "Invalid block_size argument";
3198 ic->sectors_per_block = val >> SECTOR_SHIFT;
3199 } else if (!strncmp(opt_string, "internal_hash:", strlen("internal_hash:"))) {
3200 r = get_alg_and_key(opt_string, &ic->internal_hash_alg, &ti->error,
3201 "Invalid internal_hash argument");
3204 } else if (!strncmp(opt_string, "journal_crypt:", strlen("journal_crypt:"))) {
3205 r = get_alg_and_key(opt_string, &ic->journal_crypt_alg, &ti->error,
3206 "Invalid journal_crypt argument");
3209 } else if (!strncmp(opt_string, "journal_mac:", strlen("journal_mac:"))) {
3210 r = get_alg_and_key(opt_string, &ic->journal_mac_alg, &ti->error,
3211 "Invalid journal_mac argument");
3214 } else if (!strcmp(opt_string, "recalculate")) {
3218 ti->error = "Invalid argument";
3223 ic->data_device_sectors = i_size_read(ic->dev->bdev->bd_inode) >> SECTOR_SHIFT;
3225 ic->meta_device_sectors = ic->data_device_sectors;
3227 ic->meta_device_sectors = i_size_read(ic->meta_dev->bdev->bd_inode) >> SECTOR_SHIFT;
3229 if (!journal_sectors) {
3230 journal_sectors = min((sector_t)DEFAULT_MAX_JOURNAL_SECTORS,
3231 ic->data_device_sectors >> DEFAULT_JOURNAL_SIZE_FACTOR);
3234 if (!buffer_sectors)
3236 ic->log2_buffer_sectors = min((int)__fls(buffer_sectors), 31 - SECTOR_SHIFT);
3238 r = get_mac(&ic->internal_hash, &ic->internal_hash_alg, &ti->error,
3239 "Invalid internal hash", "Error setting internal hash key");
3243 r = get_mac(&ic->journal_mac, &ic->journal_mac_alg, &ti->error,
3244 "Invalid journal mac", "Error setting journal mac key");
3248 if (!ic->tag_size) {
3249 if (!ic->internal_hash) {
3250 ti->error = "Unknown tag size";
3254 ic->tag_size = crypto_shash_digestsize(ic->internal_hash);
3256 if (ic->tag_size > MAX_TAG_SIZE) {
3257 ti->error = "Too big tag size";
3261 if (!(ic->tag_size & (ic->tag_size - 1)))
3262 ic->log2_tag_size = __ffs(ic->tag_size);
3264 ic->log2_tag_size = -1;
3266 ic->autocommit_jiffies = msecs_to_jiffies(sync_msec);
3267 ic->autocommit_msec = sync_msec;
3268 timer_setup(&ic->autocommit_timer, autocommit_fn, 0);
3270 ic->io = dm_io_client_create();
3271 if (IS_ERR(ic->io)) {
3272 r = PTR_ERR(ic->io);
3274 ti->error = "Cannot allocate dm io";
3278 r = mempool_init_slab_pool(&ic->journal_io_mempool, JOURNAL_IO_MEMPOOL, journal_io_cache);
3280 ti->error = "Cannot allocate mempool";
3284 ic->metadata_wq = alloc_workqueue("dm-integrity-metadata",
3285 WQ_MEM_RECLAIM, METADATA_WORKQUEUE_MAX_ACTIVE);
3286 if (!ic->metadata_wq) {
3287 ti->error = "Cannot allocate workqueue";
3293 * If this workqueue were percpu, it would cause bio reordering
3294 * and reduced performance.
3296 ic->wait_wq = alloc_workqueue("dm-integrity-wait", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
3298 ti->error = "Cannot allocate workqueue";
3303 ic->commit_wq = alloc_workqueue("dm-integrity-commit", WQ_MEM_RECLAIM, 1);
3304 if (!ic->commit_wq) {
3305 ti->error = "Cannot allocate workqueue";
3309 INIT_WORK(&ic->commit_work, integrity_commit);
3311 if (ic->mode == 'J') {
3312 ic->writer_wq = alloc_workqueue("dm-integrity-writer", WQ_MEM_RECLAIM, 1);
3313 if (!ic->writer_wq) {
3314 ti->error = "Cannot allocate workqueue";
3318 INIT_WORK(&ic->writer_work, integrity_writer);
3321 ic->sb = alloc_pages_exact(SB_SECTORS << SECTOR_SHIFT, GFP_KERNEL);
3324 ti->error = "Cannot allocate superblock area";
3328 r = sync_rw_sb(ic, REQ_OP_READ, 0);
3330 ti->error = "Error reading superblock";
3333 should_write_sb = false;
3334 if (memcmp(ic->sb->magic, SB_MAGIC, 8)) {
3335 if (ic->mode != 'R') {
3336 if (memchr_inv(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT)) {
3338 ti->error = "The device is not initialized";
3343 r = initialize_superblock(ic, journal_sectors, interleave_sectors);
3345 ti->error = "Could not initialize superblock";
3348 if (ic->mode != 'R')
3349 should_write_sb = true;
3352 if (!ic->sb->version || ic->sb->version > SB_VERSION_2) {
3354 ti->error = "Unknown version";
3357 if (le16_to_cpu(ic->sb->integrity_tag_size) != ic->tag_size) {
3359 ti->error = "Tag size doesn't match the information in superblock";
3362 if (ic->sb->log2_sectors_per_block != __ffs(ic->sectors_per_block)) {
3364 ti->error = "Block size doesn't match the information in superblock";
3367 if (!le32_to_cpu(ic->sb->journal_sections)) {
3369 ti->error = "Corrupted superblock, journal_sections is 0";
3372 /* make sure that ti->max_io_len doesn't overflow */
3373 if (!ic->meta_dev) {
3374 if (ic->sb->log2_interleave_sectors < MIN_LOG2_INTERLEAVE_SECTORS ||
3375 ic->sb->log2_interleave_sectors > MAX_LOG2_INTERLEAVE_SECTORS) {
3377 ti->error = "Invalid interleave_sectors in the superblock";
3381 if (ic->sb->log2_interleave_sectors) {
3383 ti->error = "Invalid interleave_sectors in the superblock";
3387 ic->provided_data_sectors = le64_to_cpu(ic->sb->provided_data_sectors);
3388 if (ic->provided_data_sectors != le64_to_cpu(ic->sb->provided_data_sectors)) {
3389 /* test for overflow */
3391 ti->error = "The superblock has 64-bit device size, but the kernel was compiled with 32-bit sectors";
3394 if (!!(ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC)) != !!ic->journal_mac_alg.alg_string) {
3396 ti->error = "Journal mac mismatch";
3401 r = calculate_device_limits(ic);
3404 if (ic->log2_buffer_sectors > 3) {
3405 ic->log2_buffer_sectors--;
3406 goto try_smaller_buffer;
3409 ti->error = "The device is too small";
3413 ic->log2_buffer_sectors = min(ic->log2_buffer_sectors, (__u8)__ffs(ic->metadata_run));
3415 if (ti->len > ic->provided_data_sectors) {
3417 ti->error = "Not enough provided sectors for requested mapping size";
3422 threshold = (__u64)ic->journal_entries * (100 - journal_watermark);
3424 do_div(threshold, 100);
3425 ic->free_sectors_threshold = threshold;
3427 DEBUG_print("initialized:\n");
3428 DEBUG_print(" integrity_tag_size %u\n", le16_to_cpu(ic->sb->integrity_tag_size));
3429 DEBUG_print(" journal_entry_size %u\n", ic->journal_entry_size);
3430 DEBUG_print(" journal_entries_per_sector %u\n", ic->journal_entries_per_sector);
3431 DEBUG_print(" journal_section_entries %u\n", ic->journal_section_entries);
3432 DEBUG_print(" journal_section_sectors %u\n", ic->journal_section_sectors);
3433 DEBUG_print(" journal_sections %u\n", (unsigned)le32_to_cpu(ic->sb->journal_sections));
3434 DEBUG_print(" journal_entries %u\n", ic->journal_entries);
3435 DEBUG_print(" log2_interleave_sectors %d\n", ic->sb->log2_interleave_sectors);
3436 DEBUG_print(" device_sectors 0x%llx\n", (unsigned long long)ic->device_sectors);
3437 DEBUG_print(" initial_sectors 0x%x\n", ic->initial_sectors);
3438 DEBUG_print(" metadata_run 0x%x\n", ic->metadata_run);
3439 DEBUG_print(" log2_metadata_run %d\n", ic->log2_metadata_run);
3440 DEBUG_print(" provided_data_sectors 0x%llx (%llu)\n", (unsigned long long)ic->provided_data_sectors,
3441 (unsigned long long)ic->provided_data_sectors);
3442 DEBUG_print(" log2_buffer_sectors %u\n", ic->log2_buffer_sectors);
3444 if (recalculate && !(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))) {
3445 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
3446 ic->sb->recalc_sector = cpu_to_le64(0);
3449 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
3450 if (!ic->internal_hash) {
3452 ti->error = "Recalculate is only valid with internal hash";
3455 ic->recalc_wq = alloc_workqueue("dm-integrity-recalc", WQ_MEM_RECLAIM, 1);
3456 if (!ic->recalc_wq ) {
3457 ti->error = "Cannot allocate workqueue";
3461 INIT_WORK(&ic->recalc_work, integrity_recalc);
3462 ic->recalc_buffer = vmalloc(RECALC_SECTORS << SECTOR_SHIFT);
3463 if (!ic->recalc_buffer) {
3464 ti->error = "Cannot allocate buffer for recalculating";
3468 ic->recalc_tags = kvmalloc_array(RECALC_SECTORS >> ic->sb->log2_sectors_per_block,
3469 ic->tag_size, GFP_KERNEL);
3470 if (!ic->recalc_tags) {
3471 ti->error = "Cannot allocate tags for recalculating";
3477 ic->bufio = dm_bufio_client_create(ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev,
3478 1U << (SECTOR_SHIFT + ic->log2_buffer_sectors), 1, 0, NULL, NULL);
3479 if (IS_ERR(ic->bufio)) {
3480 r = PTR_ERR(ic->bufio);
3481 ti->error = "Cannot initialize dm-bufio";
3485 dm_bufio_set_sector_offset(ic->bufio, ic->start + ic->initial_sectors);
3487 if (ic->mode != 'R') {
3488 r = create_journal(ic, &ti->error);
3493 if (should_write_sb) {
3496 init_journal(ic, 0, ic->journal_sections, 0);
3497 r = dm_integrity_failed(ic);
3499 ti->error = "Error initializing journal";
3502 r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
3504 ti->error = "Error initializing superblock";
3507 ic->just_formatted = true;
3510 if (!ic->meta_dev) {
3511 r = dm_set_target_max_io_len(ti, 1U << ic->sb->log2_interleave_sectors);
3516 if (!ic->internal_hash)
3517 dm_integrity_set(ti, ic);
3519 ti->num_flush_bios = 1;
3520 ti->flush_supported = true;
3524 dm_integrity_dtr(ti);
3528 static void dm_integrity_dtr(struct dm_target *ti)
3530 struct dm_integrity_c *ic = ti->private;
3532 BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
3533 BUG_ON(!list_empty(&ic->wait_list));
3535 if (ic->metadata_wq)
3536 destroy_workqueue(ic->metadata_wq);
3538 destroy_workqueue(ic->wait_wq);
3540 destroy_workqueue(ic->commit_wq);
3542 destroy_workqueue(ic->writer_wq);
3544 destroy_workqueue(ic->recalc_wq);
3545 if (ic->recalc_buffer)
3546 vfree(ic->recalc_buffer);
3547 if (ic->recalc_tags)
3548 kvfree(ic->recalc_tags);
3550 dm_bufio_client_destroy(ic->bufio);
3551 mempool_exit(&ic->journal_io_mempool);
3553 dm_io_client_destroy(ic->io);
3555 dm_put_device(ti, ic->dev);
3557 dm_put_device(ti, ic->meta_dev);
3558 dm_integrity_free_page_list(ic, ic->journal);
3559 dm_integrity_free_page_list(ic, ic->journal_io);
3560 dm_integrity_free_page_list(ic, ic->journal_xor);
3561 if (ic->journal_scatterlist)
3562 dm_integrity_free_journal_scatterlist(ic, ic->journal_scatterlist);
3563 if (ic->journal_io_scatterlist)
3564 dm_integrity_free_journal_scatterlist(ic, ic->journal_io_scatterlist);
3565 if (ic->sk_requests) {
3568 for (i = 0; i < ic->journal_sections; i++) {
3569 struct skcipher_request *req = ic->sk_requests[i];
3572 skcipher_request_free(req);
3575 kvfree(ic->sk_requests);
3577 kvfree(ic->journal_tree);
3579 free_pages_exact(ic->sb, SB_SECTORS << SECTOR_SHIFT);
3581 if (ic->internal_hash)
3582 crypto_free_shash(ic->internal_hash);
3583 free_alg(&ic->internal_hash_alg);
3585 if (ic->journal_crypt)
3586 crypto_free_skcipher(ic->journal_crypt);
3587 free_alg(&ic->journal_crypt_alg);
3589 if (ic->journal_mac)
3590 crypto_free_shash(ic->journal_mac);
3591 free_alg(&ic->journal_mac_alg);
3596 static struct target_type integrity_target = {
3597 .name = "integrity",
3598 .version = {1, 2, 0},
3599 .module = THIS_MODULE,
3600 .features = DM_TARGET_SINGLETON | DM_TARGET_INTEGRITY,
3601 .ctr = dm_integrity_ctr,
3602 .dtr = dm_integrity_dtr,
3603 .map = dm_integrity_map,
3604 .postsuspend = dm_integrity_postsuspend,
3605 .resume = dm_integrity_resume,
3606 .status = dm_integrity_status,
3607 .iterate_devices = dm_integrity_iterate_devices,
3608 .io_hints = dm_integrity_io_hints,
3611 static int __init dm_integrity_init(void)
3615 journal_io_cache = kmem_cache_create("integrity_journal_io",
3616 sizeof(struct journal_io), 0, 0, NULL);
3617 if (!journal_io_cache) {
3618 DMERR("can't allocate journal io cache");
3622 r = dm_register_target(&integrity_target);
3625 DMERR("register failed %d", r);
3630 static void __exit dm_integrity_exit(void)
3632 dm_unregister_target(&integrity_target);
3633 kmem_cache_destroy(journal_io_cache);
3636 module_init(dm_integrity_init);
3637 module_exit(dm_integrity_exit);
3639 MODULE_AUTHOR("Milan Broz");
3640 MODULE_AUTHOR("Mikulas Patocka");
3641 MODULE_DESCRIPTION(DM_NAME " target for integrity tags extension");
3642 MODULE_LICENSE("GPL");