]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blame - drivers/md/dm-integrity.c
UBUNTU: Ubuntu-4.13.0-45.50
[mirror_ubuntu-artful-kernel.git] / drivers / md / dm-integrity.c
CommitLineData
7eada909
MP
1/*
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
5 *
6 * This file is released under the GPL.
7 */
8
9#include <linux/module.h>
10#include <linux/device-mapper.h>
11#include <linux/dm-io.h>
12#include <linux/vmalloc.h>
13#include <linux/sort.h>
14#include <linux/rbtree.h>
15#include <linux/delay.h>
16#include <linux/random.h>
17#include <crypto/hash.h>
18#include <crypto/skcipher.h>
19#include <linux/async_tx.h>
20#include "dm-bufio.h"
21
22#define DM_MSG_PREFIX "integrity"
23
24#define DEFAULT_INTERLEAVE_SECTORS 32768
25#define DEFAULT_JOURNAL_SIZE_FACTOR 7
26#define DEFAULT_BUFFER_SECTORS 128
27#define DEFAULT_JOURNAL_WATERMARK 50
28#define DEFAULT_SYNC_MSEC 10000
29#define DEFAULT_MAX_JOURNAL_SECTORS 131072
56b67a4f
MP
30#define MIN_LOG2_INTERLEAVE_SECTORS 3
31#define MAX_LOG2_INTERLEAVE_SECTORS 31
7eada909
MP
32#define METADATA_WORKQUEUE_MAX_ACTIVE 16
33
34/*
35 * Warning - DEBUG_PRINT prints security-sensitive data to the log,
36 * so it should not be enabled in the official kernel
37 */
38//#define DEBUG_PRINT
39//#define INTERNAL_VERIFY
40
41/*
42 * On disk structures
43 */
44
45#define SB_MAGIC "integrt"
46#define SB_VERSION 1
47#define SB_SECTORS 8
9d609f85 48#define MAX_SECTORS_PER_BLOCK 8
7eada909
MP
49
50struct superblock {
51 __u8 magic[8];
52 __u8 version;
53 __u8 log2_interleave_sectors;
54 __u16 integrity_tag_size;
55 __u32 journal_sections;
56 __u64 provided_data_sectors; /* userspace uses this value */
57 __u32 flags;
9d609f85 58 __u8 log2_sectors_per_block;
7eada909
MP
59};
60
61#define SB_FLAG_HAVE_JOURNAL_MAC 0x1
62
63#define JOURNAL_ENTRY_ROUNDUP 8
64
65typedef __u64 commit_id_t;
66#define JOURNAL_MAC_PER_SECTOR 8
67
68struct journal_entry {
69 union {
70 struct {
71 __u32 sector_lo;
72 __u32 sector_hi;
73 } s;
74 __u64 sector;
75 } u;
9d609f85
MP
76 commit_id_t last_bytes[0];
77 /* __u8 tag[0]; */
7eada909
MP
78};
79
9d609f85
MP
80#define journal_entry_tag(ic, je) ((__u8 *)&(je)->last_bytes[(ic)->sectors_per_block])
81
7eada909
MP
82#if BITS_PER_LONG == 64
83#define journal_entry_set_sector(je, x) do { smp_wmb(); ACCESS_ONCE((je)->u.sector) = cpu_to_le64(x); } while (0)
84#define journal_entry_get_sector(je) le64_to_cpu((je)->u.sector)
85#elif defined(CONFIG_LBDAF)
86#define journal_entry_set_sector(je, x) do { (je)->u.s.sector_lo = cpu_to_le32(x); smp_wmb(); ACCESS_ONCE((je)->u.s.sector_hi) = cpu_to_le32((x) >> 32); } while (0)
87#define journal_entry_get_sector(je) le64_to_cpu((je)->u.sector)
88#else
89#define journal_entry_set_sector(je, x) do { (je)->u.s.sector_lo = cpu_to_le32(x); smp_wmb(); ACCESS_ONCE((je)->u.s.sector_hi) = cpu_to_le32(0); } while (0)
90#define journal_entry_get_sector(je) le32_to_cpu((je)->u.s.sector_lo)
91#endif
92#define journal_entry_is_unused(je) ((je)->u.s.sector_hi == cpu_to_le32(-1))
93#define journal_entry_set_unused(je) do { ((je)->u.s.sector_hi = cpu_to_le32(-1)); } while (0)
94#define journal_entry_is_inprogress(je) ((je)->u.s.sector_hi == cpu_to_le32(-2))
95#define journal_entry_set_inprogress(je) do { ((je)->u.s.sector_hi = cpu_to_le32(-2)); } while (0)
96
97#define JOURNAL_BLOCK_SECTORS 8
98#define JOURNAL_SECTOR_DATA ((1 << SECTOR_SHIFT) - sizeof(commit_id_t))
99#define JOURNAL_MAC_SIZE (JOURNAL_MAC_PER_SECTOR * JOURNAL_BLOCK_SECTORS)
100
101struct journal_sector {
102 __u8 entries[JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR];
103 __u8 mac[JOURNAL_MAC_PER_SECTOR];
104 commit_id_t commit_id;
105};
106
9d609f85 107#define MAX_TAG_SIZE (JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR - offsetof(struct journal_entry, last_bytes[MAX_SECTORS_PER_BLOCK]))
7eada909
MP
108
109#define METADATA_PADDING_SECTORS 8
110
111#define N_COMMIT_IDS 4
112
113static unsigned char prev_commit_seq(unsigned char seq)
114{
115 return (seq + N_COMMIT_IDS - 1) % N_COMMIT_IDS;
116}
117
118static unsigned char next_commit_seq(unsigned char seq)
119{
120 return (seq + 1) % N_COMMIT_IDS;
121}
122
123/*
124 * In-memory structures
125 */
126
127struct journal_node {
128 struct rb_node node;
129 sector_t sector;
130};
131
132struct alg_spec {
133 char *alg_string;
134 char *key_string;
135 __u8 *key;
136 unsigned key_size;
137};
138
139struct dm_integrity_c {
140 struct dm_dev *dev;
141 unsigned tag_size;
142 __s8 log2_tag_size;
143 sector_t start;
144 mempool_t *journal_io_mempool;
145 struct dm_io_client *io;
146 struct dm_bufio_client *bufio;
147 struct workqueue_struct *metadata_wq;
148 struct superblock *sb;
149 unsigned journal_pages;
150 struct page_list *journal;
151 struct page_list *journal_io;
152 struct page_list *journal_xor;
153
154 struct crypto_skcipher *journal_crypt;
155 struct scatterlist **journal_scatterlist;
156 struct scatterlist **journal_io_scatterlist;
157 struct skcipher_request **sk_requests;
158
159 struct crypto_shash *journal_mac;
160
161 struct journal_node *journal_tree;
162 struct rb_root journal_tree_root;
163
164 sector_t provided_data_sectors;
165
166 unsigned short journal_entry_size;
167 unsigned char journal_entries_per_sector;
168 unsigned char journal_section_entries;
9d609f85 169 unsigned short journal_section_sectors;
7eada909
MP
170 unsigned journal_sections;
171 unsigned journal_entries;
172 sector_t device_sectors;
173 unsigned initial_sectors;
174 unsigned metadata_run;
175 __s8 log2_metadata_run;
176 __u8 log2_buffer_sectors;
9d609f85 177 __u8 sectors_per_block;
7eada909
MP
178
179 unsigned char mode;
180 bool suspending;
181
182 int failed;
183
184 struct crypto_shash *internal_hash;
185
186 /* these variables are locked with endio_wait.lock */
187 struct rb_root in_progress;
188 wait_queue_head_t endio_wait;
189 struct workqueue_struct *wait_wq;
190
191 unsigned char commit_seq;
192 commit_id_t commit_ids[N_COMMIT_IDS];
193
194 unsigned committed_section;
195 unsigned n_committed_sections;
196
197 unsigned uncommitted_section;
198 unsigned n_uncommitted_sections;
199
200 unsigned free_section;
201 unsigned char free_section_entry;
202 unsigned free_sectors;
203
204 unsigned free_sectors_threshold;
205
206 struct workqueue_struct *commit_wq;
207 struct work_struct commit_work;
208
209 struct workqueue_struct *writer_wq;
210 struct work_struct writer_work;
211
212 struct bio_list flush_bio_list;
213
214 unsigned long autocommit_jiffies;
215 struct timer_list autocommit_timer;
216 unsigned autocommit_msec;
217
218 wait_queue_head_t copy_to_journal_wait;
219
220 struct completion crypto_backoff;
221
222 bool journal_uptodate;
223 bool just_formatted;
224
225 struct alg_spec internal_hash_alg;
226 struct alg_spec journal_crypt_alg;
227 struct alg_spec journal_mac_alg;
228};
229
230struct dm_integrity_range {
231 sector_t logical_sector;
232 unsigned n_sectors;
233 struct rb_node node;
234};
235
236struct dm_integrity_io {
237 struct work_struct work;
238
239 struct dm_integrity_c *ic;
240 bool write;
241 bool fua;
242
243 struct dm_integrity_range range;
244
245 sector_t metadata_block;
246 unsigned metadata_offset;
247
248 atomic_t in_flight;
4e4cbee9 249 blk_status_t bi_status;
7eada909
MP
250
251 struct completion *completion;
252
253 struct block_device *orig_bi_bdev;
254 bio_end_io_t *orig_bi_end_io;
255 struct bio_integrity_payload *orig_bi_integrity;
256 struct bvec_iter orig_bi_iter;
257};
258
259struct journal_completion {
260 struct dm_integrity_c *ic;
261 atomic_t in_flight;
262 struct completion comp;
263};
264
265struct journal_io {
266 struct dm_integrity_range range;
267 struct journal_completion *comp;
268};
269
270static struct kmem_cache *journal_io_cache;
271
272#define JOURNAL_IO_MEMPOOL 32
273
274#ifdef DEBUG_PRINT
275#define DEBUG_print(x, ...) printk(KERN_DEBUG x, ##__VA_ARGS__)
276static void __DEBUG_bytes(__u8 *bytes, size_t len, const char *msg, ...)
277{
278 va_list args;
279 va_start(args, msg);
280 vprintk(msg, args);
281 va_end(args);
282 if (len)
283 pr_cont(":");
284 while (len) {
285 pr_cont(" %02x", *bytes);
286 bytes++;
287 len--;
288 }
289 pr_cont("\n");
290}
291#define DEBUG_bytes(bytes, len, msg, ...) __DEBUG_bytes(bytes, len, KERN_DEBUG msg, ##__VA_ARGS__)
292#else
293#define DEBUG_print(x, ...) do { } while (0)
294#define DEBUG_bytes(bytes, len, msg, ...) do { } while (0)
295#endif
296
297/*
298 * DM Integrity profile, protection is performed layer above (dm-crypt)
299 */
300static struct blk_integrity_profile dm_integrity_profile = {
301 .name = "DM-DIF-EXT-TAG",
302 .generate_fn = NULL,
303 .verify_fn = NULL,
304};
305
306static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map);
307static void integrity_bio_wait(struct work_struct *w);
308static void dm_integrity_dtr(struct dm_target *ti);
309
310static void dm_integrity_io_error(struct dm_integrity_c *ic, const char *msg, int err)
311{
312 if (!cmpxchg(&ic->failed, 0, err))
313 DMERR("Error on %s: %d", msg, err);
314}
315
316static int dm_integrity_failed(struct dm_integrity_c *ic)
317{
318 return ACCESS_ONCE(ic->failed);
319}
320
321static commit_id_t dm_integrity_commit_id(struct dm_integrity_c *ic, unsigned i,
322 unsigned j, unsigned char seq)
323{
324 /*
325 * Xor the number with section and sector, so that if a piece of
326 * journal is written at wrong place, it is detected.
327 */
328 return ic->commit_ids[seq] ^ cpu_to_le64(((__u64)i << 32) ^ j);
329}
330
331static void get_area_and_offset(struct dm_integrity_c *ic, sector_t data_sector,
332 sector_t *area, sector_t *offset)
333{
334 __u8 log2_interleave_sectors = ic->sb->log2_interleave_sectors;
335
336 *area = data_sector >> log2_interleave_sectors;
337 *offset = (unsigned)data_sector & ((1U << log2_interleave_sectors) - 1);
338}
339
9d609f85
MP
340#define sector_to_block(ic, n) \
341do { \
342 BUG_ON((n) & (unsigned)((ic)->sectors_per_block - 1)); \
343 (n) >>= (ic)->sb->log2_sectors_per_block; \
344} while (0)
345
7eada909
MP
346static __u64 get_metadata_sector_and_offset(struct dm_integrity_c *ic, sector_t area,
347 sector_t offset, unsigned *metadata_offset)
348{
349 __u64 ms;
350 unsigned mo;
351
352 ms = area << ic->sb->log2_interleave_sectors;
353 if (likely(ic->log2_metadata_run >= 0))
354 ms += area << ic->log2_metadata_run;
355 else
356 ms += area * ic->metadata_run;
357 ms >>= ic->log2_buffer_sectors;
358
9d609f85
MP
359 sector_to_block(ic, offset);
360
7eada909
MP
361 if (likely(ic->log2_tag_size >= 0)) {
362 ms += offset >> (SECTOR_SHIFT + ic->log2_buffer_sectors - ic->log2_tag_size);
363 mo = (offset << ic->log2_tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
364 } else {
365 ms += (__u64)offset * ic->tag_size >> (SECTOR_SHIFT + ic->log2_buffer_sectors);
366 mo = (offset * ic->tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
367 }
368 *metadata_offset = mo;
369 return ms;
370}
371
372static sector_t get_data_sector(struct dm_integrity_c *ic, sector_t area, sector_t offset)
373{
374 sector_t result;
375
376 result = area << ic->sb->log2_interleave_sectors;
377 if (likely(ic->log2_metadata_run >= 0))
378 result += (area + 1) << ic->log2_metadata_run;
379 else
380 result += (area + 1) * ic->metadata_run;
381
382 result += (sector_t)ic->initial_sectors + offset;
383 return result;
384}
385
386static void wraparound_section(struct dm_integrity_c *ic, unsigned *sec_ptr)
387{
388 if (unlikely(*sec_ptr >= ic->journal_sections))
389 *sec_ptr -= ic->journal_sections;
390}
391
392static int sync_rw_sb(struct dm_integrity_c *ic, int op, int op_flags)
393{
394 struct dm_io_request io_req;
395 struct dm_io_region io_loc;
396
397 io_req.bi_op = op;
398 io_req.bi_op_flags = op_flags;
399 io_req.mem.type = DM_IO_KMEM;
400 io_req.mem.ptr.addr = ic->sb;
401 io_req.notify.fn = NULL;
402 io_req.client = ic->io;
403 io_loc.bdev = ic->dev->bdev;
404 io_loc.sector = ic->start;
405 io_loc.count = SB_SECTORS;
406
407 return dm_io(&io_req, 1, &io_loc, NULL);
408}
409
410static void access_journal_check(struct dm_integrity_c *ic, unsigned section, unsigned offset,
411 bool e, const char *function)
412{
413#if defined(CONFIG_DM_DEBUG) || defined(INTERNAL_VERIFY)
414 unsigned limit = e ? ic->journal_section_entries : ic->journal_section_sectors;
415
416 if (unlikely(section >= ic->journal_sections) ||
417 unlikely(offset >= limit)) {
418 printk(KERN_CRIT "%s: invalid access at (%u,%u), limit (%u,%u)\n",
419 function, section, offset, ic->journal_sections, limit);
420 BUG();
421 }
422#endif
423}
424
425static void page_list_location(struct dm_integrity_c *ic, unsigned section, unsigned offset,
426 unsigned *pl_index, unsigned *pl_offset)
427{
428 unsigned sector;
429
56b67a4f 430 access_journal_check(ic, section, offset, false, "page_list_location");
7eada909
MP
431
432 sector = section * ic->journal_section_sectors + offset;
433
434 *pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
435 *pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
436}
437
438static struct journal_sector *access_page_list(struct dm_integrity_c *ic, struct page_list *pl,
439 unsigned section, unsigned offset, unsigned *n_sectors)
440{
441 unsigned pl_index, pl_offset;
442 char *va;
443
444 page_list_location(ic, section, offset, &pl_index, &pl_offset);
445
446 if (n_sectors)
447 *n_sectors = (PAGE_SIZE - pl_offset) >> SECTOR_SHIFT;
448
449 va = lowmem_page_address(pl[pl_index].page);
450
451 return (struct journal_sector *)(va + pl_offset);
452}
453
454static struct journal_sector *access_journal(struct dm_integrity_c *ic, unsigned section, unsigned offset)
455{
456 return access_page_list(ic, ic->journal, section, offset, NULL);
457}
458
459static struct journal_entry *access_journal_entry(struct dm_integrity_c *ic, unsigned section, unsigned n)
460{
461 unsigned rel_sector, offset;
462 struct journal_sector *js;
463
464 access_journal_check(ic, section, n, true, "access_journal_entry");
465
466 rel_sector = n % JOURNAL_BLOCK_SECTORS;
467 offset = n / JOURNAL_BLOCK_SECTORS;
468
469 js = access_journal(ic, section, rel_sector);
470 return (struct journal_entry *)((char *)js + offset * ic->journal_entry_size);
471}
472
473static struct journal_sector *access_journal_data(struct dm_integrity_c *ic, unsigned section, unsigned n)
474{
9d609f85 475 n <<= ic->sb->log2_sectors_per_block;
7eada909 476
9d609f85
MP
477 n += JOURNAL_BLOCK_SECTORS;
478
479 access_journal_check(ic, section, n, false, "access_journal_data");
480
481 return access_journal(ic, section, n);
7eada909
MP
482}
483
484static void section_mac(struct dm_integrity_c *ic, unsigned section, __u8 result[JOURNAL_MAC_SIZE])
485{
486 SHASH_DESC_ON_STACK(desc, ic->journal_mac);
487 int r;
488 unsigned j, size;
489
490 desc->tfm = ic->journal_mac;
491 desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
492
493 r = crypto_shash_init(desc);
494 if (unlikely(r)) {
495 dm_integrity_io_error(ic, "crypto_shash_init", r);
496 goto err;
497 }
498
499 for (j = 0; j < ic->journal_section_entries; j++) {
500 struct journal_entry *je = access_journal_entry(ic, section, j);
501 r = crypto_shash_update(desc, (__u8 *)&je->u.sector, sizeof je->u.sector);
502 if (unlikely(r)) {
503 dm_integrity_io_error(ic, "crypto_shash_update", r);
504 goto err;
505 }
506 }
507
508 size = crypto_shash_digestsize(ic->journal_mac);
509
510 if (likely(size <= JOURNAL_MAC_SIZE)) {
511 r = crypto_shash_final(desc, result);
512 if (unlikely(r)) {
513 dm_integrity_io_error(ic, "crypto_shash_final", r);
514 goto err;
515 }
516 memset(result + size, 0, JOURNAL_MAC_SIZE - size);
517 } else {
518 __u8 digest[size];
519 r = crypto_shash_final(desc, digest);
520 if (unlikely(r)) {
521 dm_integrity_io_error(ic, "crypto_shash_final", r);
522 goto err;
523 }
524 memcpy(result, digest, JOURNAL_MAC_SIZE);
525 }
526
527 return;
528err:
529 memset(result, 0, JOURNAL_MAC_SIZE);
530}
531
532static void rw_section_mac(struct dm_integrity_c *ic, unsigned section, bool wr)
533{
534 __u8 result[JOURNAL_MAC_SIZE];
535 unsigned j;
536
537 if (!ic->journal_mac)
538 return;
539
540 section_mac(ic, section, result);
541
542 for (j = 0; j < JOURNAL_BLOCK_SECTORS; j++) {
543 struct journal_sector *js = access_journal(ic, section, j);
544
545 if (likely(wr))
546 memcpy(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR);
547 else {
548 if (memcmp(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR))
549 dm_integrity_io_error(ic, "journal mac", -EILSEQ);
550 }
551 }
552}
553
554static void complete_journal_op(void *context)
555{
556 struct journal_completion *comp = context;
557 BUG_ON(!atomic_read(&comp->in_flight));
558 if (likely(atomic_dec_and_test(&comp->in_flight)))
559 complete(&comp->comp);
560}
561
562static void xor_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
563 unsigned n_sections, struct journal_completion *comp)
564{
565 struct async_submit_ctl submit;
566 size_t n_bytes = (size_t)(n_sections * ic->journal_section_sectors) << SECTOR_SHIFT;
567 unsigned pl_index, pl_offset, section_index;
568 struct page_list *source_pl, *target_pl;
569
570 if (likely(encrypt)) {
571 source_pl = ic->journal;
572 target_pl = ic->journal_io;
573 } else {
574 source_pl = ic->journal_io;
575 target_pl = ic->journal;
576 }
577
578 page_list_location(ic, section, 0, &pl_index, &pl_offset);
579
580 atomic_add(roundup(pl_offset + n_bytes, PAGE_SIZE) >> PAGE_SHIFT, &comp->in_flight);
581
582 init_async_submit(&submit, ASYNC_TX_XOR_ZERO_DST, NULL, complete_journal_op, comp, NULL);
583
584 section_index = pl_index;
585
586 do {
587 size_t this_step;
588 struct page *src_pages[2];
589 struct page *dst_page;
590
591 while (unlikely(pl_index == section_index)) {
592 unsigned dummy;
593 if (likely(encrypt))
594 rw_section_mac(ic, section, true);
595 section++;
596 n_sections--;
597 if (!n_sections)
598 break;
599 page_list_location(ic, section, 0, &section_index, &dummy);
600 }
601
602 this_step = min(n_bytes, (size_t)PAGE_SIZE - pl_offset);
603 dst_page = target_pl[pl_index].page;
604 src_pages[0] = source_pl[pl_index].page;
605 src_pages[1] = ic->journal_xor[pl_index].page;
606
607 async_xor(dst_page, src_pages, pl_offset, 2, this_step, &submit);
608
609 pl_index++;
610 pl_offset = 0;
611 n_bytes -= this_step;
612 } while (n_bytes);
613
614 BUG_ON(n_sections);
615
616 async_tx_issue_pending_all();
617}
618
619static void complete_journal_encrypt(struct crypto_async_request *req, int err)
620{
621 struct journal_completion *comp = req->data;
622 if (unlikely(err)) {
623 if (likely(err == -EINPROGRESS)) {
624 complete(&comp->ic->crypto_backoff);
625 return;
626 }
627 dm_integrity_io_error(comp->ic, "asynchronous encrypt", err);
628 }
629 complete_journal_op(comp);
630}
631
632static bool do_crypt(bool encrypt, struct skcipher_request *req, struct journal_completion *comp)
633{
634 int r;
635 skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
636 complete_journal_encrypt, comp);
637 if (likely(encrypt))
638 r = crypto_skcipher_encrypt(req);
639 else
640 r = crypto_skcipher_decrypt(req);
641 if (likely(!r))
642 return false;
643 if (likely(r == -EINPROGRESS))
644 return true;
645 if (likely(r == -EBUSY)) {
646 wait_for_completion(&comp->ic->crypto_backoff);
647 reinit_completion(&comp->ic->crypto_backoff);
648 return true;
649 }
650 dm_integrity_io_error(comp->ic, "encrypt", r);
651 return false;
652}
653
654static void crypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
655 unsigned n_sections, struct journal_completion *comp)
656{
657 struct scatterlist **source_sg;
658 struct scatterlist **target_sg;
659
660 atomic_add(2, &comp->in_flight);
661
662 if (likely(encrypt)) {
663 source_sg = ic->journal_scatterlist;
664 target_sg = ic->journal_io_scatterlist;
665 } else {
666 source_sg = ic->journal_io_scatterlist;
667 target_sg = ic->journal_scatterlist;
668 }
669
670 do {
671 struct skcipher_request *req;
672 unsigned ivsize;
673 char *iv;
674
675 if (likely(encrypt))
676 rw_section_mac(ic, section, true);
677
678 req = ic->sk_requests[section];
679 ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
680 iv = req->iv;
681
682 memcpy(iv, iv + ivsize, ivsize);
683
684 req->src = source_sg[section];
685 req->dst = target_sg[section];
686
687 if (unlikely(do_crypt(encrypt, req, comp)))
688 atomic_inc(&comp->in_flight);
689
690 section++;
691 n_sections--;
692 } while (n_sections);
693
694 atomic_dec(&comp->in_flight);
695 complete_journal_op(comp);
696}
697
698static void encrypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
699 unsigned n_sections, struct journal_completion *comp)
700{
701 if (ic->journal_xor)
702 return xor_journal(ic, encrypt, section, n_sections, comp);
703 else
704 return crypt_journal(ic, encrypt, section, n_sections, comp);
705}
706
707static void complete_journal_io(unsigned long error, void *context)
708{
709 struct journal_completion *comp = context;
710 if (unlikely(error != 0))
711 dm_integrity_io_error(comp->ic, "writing journal", -EIO);
712 complete_journal_op(comp);
713}
714
715static void rw_journal(struct dm_integrity_c *ic, int op, int op_flags, unsigned section,
716 unsigned n_sections, struct journal_completion *comp)
717{
718 struct dm_io_request io_req;
719 struct dm_io_region io_loc;
720 unsigned sector, n_sectors, pl_index, pl_offset;
721 int r;
722
723 if (unlikely(dm_integrity_failed(ic))) {
724 if (comp)
725 complete_journal_io(-1UL, comp);
726 return;
727 }
728
729 sector = section * ic->journal_section_sectors;
730 n_sectors = n_sections * ic->journal_section_sectors;
731
732 pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
733 pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
734
735 io_req.bi_op = op;
736 io_req.bi_op_flags = op_flags;
737 io_req.mem.type = DM_IO_PAGE_LIST;
738 if (ic->journal_io)
739 io_req.mem.ptr.pl = &ic->journal_io[pl_index];
740 else
741 io_req.mem.ptr.pl = &ic->journal[pl_index];
742 io_req.mem.offset = pl_offset;
743 if (likely(comp != NULL)) {
744 io_req.notify.fn = complete_journal_io;
745 io_req.notify.context = comp;
746 } else {
747 io_req.notify.fn = NULL;
748 }
749 io_req.client = ic->io;
750 io_loc.bdev = ic->dev->bdev;
751 io_loc.sector = ic->start + SB_SECTORS + sector;
752 io_loc.count = n_sectors;
753
754 r = dm_io(&io_req, 1, &io_loc, NULL);
755 if (unlikely(r)) {
756 dm_integrity_io_error(ic, op == REQ_OP_READ ? "reading journal" : "writing journal", r);
757 if (comp) {
758 WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
759 complete_journal_io(-1UL, comp);
760 }
761 }
762}
763
764static void write_journal(struct dm_integrity_c *ic, unsigned commit_start, unsigned commit_sections)
765{
766 struct journal_completion io_comp;
767 struct journal_completion crypt_comp_1;
768 struct journal_completion crypt_comp_2;
769 unsigned i;
770
771 io_comp.ic = ic;
772 io_comp.comp = COMPLETION_INITIALIZER_ONSTACK(io_comp.comp);
773
774 if (commit_start + commit_sections <= ic->journal_sections) {
775 io_comp.in_flight = (atomic_t)ATOMIC_INIT(1);
776 if (ic->journal_io) {
777 crypt_comp_1.ic = ic;
778 crypt_comp_1.comp = COMPLETION_INITIALIZER_ONSTACK(crypt_comp_1.comp);
779 crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
780 encrypt_journal(ic, true, commit_start, commit_sections, &crypt_comp_1);
781 wait_for_completion_io(&crypt_comp_1.comp);
782 } else {
783 for (i = 0; i < commit_sections; i++)
784 rw_section_mac(ic, commit_start + i, true);
785 }
ff0361b3
JK
786 rw_journal(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, commit_start,
787 commit_sections, &io_comp);
7eada909
MP
788 } else {
789 unsigned to_end;
790 io_comp.in_flight = (atomic_t)ATOMIC_INIT(2);
791 to_end = ic->journal_sections - commit_start;
792 if (ic->journal_io) {
793 crypt_comp_1.ic = ic;
794 crypt_comp_1.comp = COMPLETION_INITIALIZER_ONSTACK(crypt_comp_1.comp);
795 crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
796 encrypt_journal(ic, true, commit_start, to_end, &crypt_comp_1);
797 if (try_wait_for_completion(&crypt_comp_1.comp)) {
798 rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
799 crypt_comp_1.comp = COMPLETION_INITIALIZER_ONSTACK(crypt_comp_1.comp);
800 crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
801 encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_1);
802 wait_for_completion_io(&crypt_comp_1.comp);
803 } else {
804 crypt_comp_2.ic = ic;
805 crypt_comp_2.comp = COMPLETION_INITIALIZER_ONSTACK(crypt_comp_2.comp);
806 crypt_comp_2.in_flight = (atomic_t)ATOMIC_INIT(0);
807 encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_2);
808 wait_for_completion_io(&crypt_comp_1.comp);
809 rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
810 wait_for_completion_io(&crypt_comp_2.comp);
811 }
812 } else {
813 for (i = 0; i < to_end; i++)
814 rw_section_mac(ic, commit_start + i, true);
815 rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
816 for (i = 0; i < commit_sections - to_end; i++)
817 rw_section_mac(ic, i, true);
818 }
819 rw_journal(ic, REQ_OP_WRITE, REQ_FUA, 0, commit_sections - to_end, &io_comp);
820 }
821
822 wait_for_completion_io(&io_comp.comp);
823}
824
825static void copy_from_journal(struct dm_integrity_c *ic, unsigned section, unsigned offset,
826 unsigned n_sectors, sector_t target, io_notify_fn fn, void *data)
827{
828 struct dm_io_request io_req;
829 struct dm_io_region io_loc;
830 int r;
831 unsigned sector, pl_index, pl_offset;
832
9d609f85
MP
833 BUG_ON((target | n_sectors | offset) & (unsigned)(ic->sectors_per_block - 1));
834
7eada909
MP
835 if (unlikely(dm_integrity_failed(ic))) {
836 fn(-1UL, data);
837 return;
838 }
839
840 sector = section * ic->journal_section_sectors + JOURNAL_BLOCK_SECTORS + offset;
841
842 pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
843 pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
844
845 io_req.bi_op = REQ_OP_WRITE;
846 io_req.bi_op_flags = 0;
847 io_req.mem.type = DM_IO_PAGE_LIST;
848 io_req.mem.ptr.pl = &ic->journal[pl_index];
849 io_req.mem.offset = pl_offset;
850 io_req.notify.fn = fn;
851 io_req.notify.context = data;
852 io_req.client = ic->io;
853 io_loc.bdev = ic->dev->bdev;
854 io_loc.sector = ic->start + target;
855 io_loc.count = n_sectors;
856
857 r = dm_io(&io_req, 1, &io_loc, NULL);
858 if (unlikely(r)) {
859 WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
860 fn(-1UL, data);
861 }
862}
863
864static bool add_new_range(struct dm_integrity_c *ic, struct dm_integrity_range *new_range)
865{
866 struct rb_node **n = &ic->in_progress.rb_node;
867 struct rb_node *parent;
868
9d609f85
MP
869 BUG_ON((new_range->logical_sector | new_range->n_sectors) & (unsigned)(ic->sectors_per_block - 1));
870
7eada909
MP
871 parent = NULL;
872
873 while (*n) {
874 struct dm_integrity_range *range = container_of(*n, struct dm_integrity_range, node);
875
876 parent = *n;
877 if (new_range->logical_sector + new_range->n_sectors <= range->logical_sector) {
878 n = &range->node.rb_left;
879 } else if (new_range->logical_sector >= range->logical_sector + range->n_sectors) {
880 n = &range->node.rb_right;
881 } else {
882 return false;
883 }
884 }
885
886 rb_link_node(&new_range->node, parent, n);
887 rb_insert_color(&new_range->node, &ic->in_progress);
888
889 return true;
890}
891
892static void remove_range_unlocked(struct dm_integrity_c *ic, struct dm_integrity_range *range)
893{
894 rb_erase(&range->node, &ic->in_progress);
895 wake_up_locked(&ic->endio_wait);
896}
897
898static void remove_range(struct dm_integrity_c *ic, struct dm_integrity_range *range)
899{
900 unsigned long flags;
901
902 spin_lock_irqsave(&ic->endio_wait.lock, flags);
903 remove_range_unlocked(ic, range);
904 spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
905}
906
907static void init_journal_node(struct journal_node *node)
908{
909 RB_CLEAR_NODE(&node->node);
910 node->sector = (sector_t)-1;
911}
912
913static void add_journal_node(struct dm_integrity_c *ic, struct journal_node *node, sector_t sector)
914{
915 struct rb_node **link;
916 struct rb_node *parent;
917
918 node->sector = sector;
919 BUG_ON(!RB_EMPTY_NODE(&node->node));
920
921 link = &ic->journal_tree_root.rb_node;
922 parent = NULL;
923
924 while (*link) {
925 struct journal_node *j;
926 parent = *link;
927 j = container_of(parent, struct journal_node, node);
928 if (sector < j->sector)
929 link = &j->node.rb_left;
930 else
931 link = &j->node.rb_right;
932 }
933
934 rb_link_node(&node->node, parent, link);
935 rb_insert_color(&node->node, &ic->journal_tree_root);
936}
937
938static void remove_journal_node(struct dm_integrity_c *ic, struct journal_node *node)
939{
940 BUG_ON(RB_EMPTY_NODE(&node->node));
941 rb_erase(&node->node, &ic->journal_tree_root);
942 init_journal_node(node);
943}
944
945#define NOT_FOUND (-1U)
946
947static unsigned find_journal_node(struct dm_integrity_c *ic, sector_t sector, sector_t *next_sector)
948{
949 struct rb_node *n = ic->journal_tree_root.rb_node;
950 unsigned found = NOT_FOUND;
951 *next_sector = (sector_t)-1;
952 while (n) {
953 struct journal_node *j = container_of(n, struct journal_node, node);
954 if (sector == j->sector) {
955 found = j - ic->journal_tree;
956 }
957 if (sector < j->sector) {
958 *next_sector = j->sector;
959 n = j->node.rb_left;
960 } else {
961 n = j->node.rb_right;
962 }
963 }
964
965 return found;
966}
967
968static bool test_journal_node(struct dm_integrity_c *ic, unsigned pos, sector_t sector)
969{
970 struct journal_node *node, *next_node;
971 struct rb_node *next;
972
973 if (unlikely(pos >= ic->journal_entries))
974 return false;
975 node = &ic->journal_tree[pos];
976 if (unlikely(RB_EMPTY_NODE(&node->node)))
977 return false;
978 if (unlikely(node->sector != sector))
979 return false;
980
981 next = rb_next(&node->node);
982 if (unlikely(!next))
983 return true;
984
985 next_node = container_of(next, struct journal_node, node);
986 return next_node->sector != sector;
987}
988
989static bool find_newer_committed_node(struct dm_integrity_c *ic, struct journal_node *node)
990{
991 struct rb_node *next;
992 struct journal_node *next_node;
993 unsigned next_section;
994
995 BUG_ON(RB_EMPTY_NODE(&node->node));
996
997 next = rb_next(&node->node);
998 if (unlikely(!next))
999 return false;
1000
1001 next_node = container_of(next, struct journal_node, node);
1002
1003 if (next_node->sector != node->sector)
1004 return false;
1005
1006 next_section = (unsigned)(next_node - ic->journal_tree) / ic->journal_section_entries;
1007 if (next_section >= ic->committed_section &&
1008 next_section < ic->committed_section + ic->n_committed_sections)
1009 return true;
1010 if (next_section + ic->journal_sections < ic->committed_section + ic->n_committed_sections)
1011 return true;
1012
1013 return false;
1014}
1015
1016#define TAG_READ 0
1017#define TAG_WRITE 1
1018#define TAG_CMP 2
1019
1020static int dm_integrity_rw_tag(struct dm_integrity_c *ic, unsigned char *tag, sector_t *metadata_block,
1021 unsigned *metadata_offset, unsigned total_size, int op)
1022{
1023 do {
1024 unsigned char *data, *dp;
1025 struct dm_buffer *b;
1026 unsigned to_copy;
1027 int r;
1028
1029 r = dm_integrity_failed(ic);
1030 if (unlikely(r))
1031 return r;
1032
1033 data = dm_bufio_read(ic->bufio, *metadata_block, &b);
1034 if (unlikely(IS_ERR(data)))
1035 return PTR_ERR(data);
1036
1037 to_copy = min((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - *metadata_offset, total_size);
1038 dp = data + *metadata_offset;
1039 if (op == TAG_READ) {
1040 memcpy(tag, dp, to_copy);
1041 } else if (op == TAG_WRITE) {
1042 memcpy(dp, tag, to_copy);
1043 dm_bufio_mark_buffer_dirty(b);
1044 } else {
1045 /* e.g.: op == TAG_CMP */
1046 if (unlikely(memcmp(dp, tag, to_copy))) {
1047 unsigned i;
1048
1049 for (i = 0; i < to_copy; i++) {
1050 if (dp[i] != tag[i])
1051 break;
1052 total_size--;
1053 }
1054 dm_bufio_release(b);
1055 return total_size;
1056 }
1057 }
1058 dm_bufio_release(b);
1059
1060 tag += to_copy;
1061 *metadata_offset += to_copy;
1062 if (unlikely(*metadata_offset == 1U << SECTOR_SHIFT << ic->log2_buffer_sectors)) {
1063 (*metadata_block)++;
1064 *metadata_offset = 0;
1065 }
1066 total_size -= to_copy;
1067 } while (unlikely(total_size));
1068
1069 return 0;
1070}
1071
1072static void dm_integrity_flush_buffers(struct dm_integrity_c *ic)
1073{
1074 int r;
1075 r = dm_bufio_write_dirty_buffers(ic->bufio);
1076 if (unlikely(r))
1077 dm_integrity_io_error(ic, "writing tags", r);
1078}
1079
1080static void sleep_on_endio_wait(struct dm_integrity_c *ic)
1081{
1082 DECLARE_WAITQUEUE(wait, current);
1083 __add_wait_queue(&ic->endio_wait, &wait);
1084 __set_current_state(TASK_UNINTERRUPTIBLE);
1085 spin_unlock_irq(&ic->endio_wait.lock);
1086 io_schedule();
1087 spin_lock_irq(&ic->endio_wait.lock);
1088 __remove_wait_queue(&ic->endio_wait, &wait);
1089}
1090
1091static void autocommit_fn(unsigned long data)
1092{
1093 struct dm_integrity_c *ic = (struct dm_integrity_c *)data;
1094
1095 if (likely(!dm_integrity_failed(ic)))
1096 queue_work(ic->commit_wq, &ic->commit_work);
1097}
1098
1099static void schedule_autocommit(struct dm_integrity_c *ic)
1100{
1101 if (!timer_pending(&ic->autocommit_timer))
1102 mod_timer(&ic->autocommit_timer, jiffies + ic->autocommit_jiffies);
1103}
1104
1105static void submit_flush_bio(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
1106{
1107 struct bio *bio;
7def52b7
MS
1108 unsigned long flags;
1109
1110 spin_lock_irqsave(&ic->endio_wait.lock, flags);
7eada909
MP
1111 bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1112 bio_list_add(&ic->flush_bio_list, bio);
7def52b7
MS
1113 spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1114
7eada909
MP
1115 queue_work(ic->commit_wq, &ic->commit_work);
1116}
1117
1118static void do_endio(struct dm_integrity_c *ic, struct bio *bio)
1119{
1120 int r = dm_integrity_failed(ic);
4e4cbee9
CH
1121 if (unlikely(r) && !bio->bi_status)
1122 bio->bi_status = errno_to_blk_status(r);
7eada909
MP
1123 bio_endio(bio);
1124}
1125
1126static void do_endio_flush(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
1127{
1128 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1129
4e4cbee9 1130 if (unlikely(dio->fua) && likely(!bio->bi_status) && likely(!dm_integrity_failed(ic)))
7eada909
MP
1131 submit_flush_bio(ic, dio);
1132 else
1133 do_endio(ic, bio);
1134}
1135
1136static void dec_in_flight(struct dm_integrity_io *dio)
1137{
1138 if (atomic_dec_and_test(&dio->in_flight)) {
1139 struct dm_integrity_c *ic = dio->ic;
1140 struct bio *bio;
1141
1142 remove_range(ic, &dio->range);
1143
1144 if (unlikely(dio->write))
1145 schedule_autocommit(ic);
1146
1147 bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1148
4e4cbee9
CH
1149 if (unlikely(dio->bi_status) && !bio->bi_status)
1150 bio->bi_status = dio->bi_status;
1151 if (likely(!bio->bi_status) && unlikely(bio_sectors(bio) != dio->range.n_sectors)) {
7eada909
MP
1152 dio->range.logical_sector += dio->range.n_sectors;
1153 bio_advance(bio, dio->range.n_sectors << SECTOR_SHIFT);
1154 INIT_WORK(&dio->work, integrity_bio_wait);
1155 queue_work(ic->wait_wq, &dio->work);
1156 return;
1157 }
1158 do_endio_flush(ic, dio);
1159 }
1160}
1161
1162static void integrity_end_io(struct bio *bio)
1163{
1164 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
1165
1166 bio->bi_iter = dio->orig_bi_iter;
1167 bio->bi_bdev = dio->orig_bi_bdev;
1168 if (dio->orig_bi_integrity) {
1169 bio->bi_integrity = dio->orig_bi_integrity;
1170 bio->bi_opf |= REQ_INTEGRITY;
1171 }
1172 bio->bi_end_io = dio->orig_bi_end_io;
1173
1174 if (dio->completion)
1175 complete(dio->completion);
1176
1177 dec_in_flight(dio);
1178}
1179
1180static void integrity_sector_checksum(struct dm_integrity_c *ic, sector_t sector,
1181 const char *data, char *result)
1182{
1183 __u64 sector_le = cpu_to_le64(sector);
1184 SHASH_DESC_ON_STACK(req, ic->internal_hash);
1185 int r;
1186 unsigned digest_size;
1187
1188 req->tfm = ic->internal_hash;
1189 req->flags = 0;
1190
1191 r = crypto_shash_init(req);
1192 if (unlikely(r < 0)) {
1193 dm_integrity_io_error(ic, "crypto_shash_init", r);
1194 goto failed;
1195 }
1196
1197 r = crypto_shash_update(req, (const __u8 *)&sector_le, sizeof sector_le);
1198 if (unlikely(r < 0)) {
1199 dm_integrity_io_error(ic, "crypto_shash_update", r);
1200 goto failed;
1201 }
1202
9d609f85 1203 r = crypto_shash_update(req, data, ic->sectors_per_block << SECTOR_SHIFT);
7eada909
MP
1204 if (unlikely(r < 0)) {
1205 dm_integrity_io_error(ic, "crypto_shash_update", r);
1206 goto failed;
1207 }
1208
1209 r = crypto_shash_final(req, result);
1210 if (unlikely(r < 0)) {
1211 dm_integrity_io_error(ic, "crypto_shash_final", r);
1212 goto failed;
1213 }
1214
1215 digest_size = crypto_shash_digestsize(ic->internal_hash);
1216 if (unlikely(digest_size < ic->tag_size))
1217 memset(result + digest_size, 0, ic->tag_size - digest_size);
1218
1219 return;
1220
1221failed:
1222 /* this shouldn't happen anyway, the hash functions have no reason to fail */
1223 get_random_bytes(result, ic->tag_size);
1224}
1225
1226static void integrity_metadata(struct work_struct *w)
1227{
1228 struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
1229 struct dm_integrity_c *ic = dio->ic;
1230
1231 int r;
1232
1233 if (ic->internal_hash) {
1234 struct bvec_iter iter;
1235 struct bio_vec bv;
1236 unsigned digest_size = crypto_shash_digestsize(ic->internal_hash);
1237 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1238 char *checksums;
56b67a4f 1239 unsigned extra_space = unlikely(digest_size > ic->tag_size) ? digest_size - ic->tag_size : 0;
7eada909
MP
1240 char checksums_onstack[ic->tag_size + extra_space];
1241 unsigned sectors_to_process = dio->range.n_sectors;
1242 sector_t sector = dio->range.logical_sector;
1243
c2bcb2b7
MP
1244 if (unlikely(ic->mode == 'R'))
1245 goto skip_io;
1246
9d609f85 1247 checksums = kmalloc((PAGE_SIZE >> SECTOR_SHIFT >> ic->sb->log2_sectors_per_block) * ic->tag_size + extra_space,
7eada909
MP
1248 GFP_NOIO | __GFP_NORETRY | __GFP_NOWARN);
1249 if (!checksums)
1250 checksums = checksums_onstack;
1251
1252 __bio_for_each_segment(bv, bio, iter, dio->orig_bi_iter) {
1253 unsigned pos;
1254 char *mem, *checksums_ptr;
1255
1256again:
1257 mem = (char *)kmap_atomic(bv.bv_page) + bv.bv_offset;
1258 pos = 0;
1259 checksums_ptr = checksums;
1260 do {
1261 integrity_sector_checksum(ic, sector, mem + pos, checksums_ptr);
1262 checksums_ptr += ic->tag_size;
9d609f85
MP
1263 sectors_to_process -= ic->sectors_per_block;
1264 pos += ic->sectors_per_block << SECTOR_SHIFT;
1265 sector += ic->sectors_per_block;
7eada909
MP
1266 } while (pos < bv.bv_len && sectors_to_process && checksums != checksums_onstack);
1267 kunmap_atomic(mem);
1268
1269 r = dm_integrity_rw_tag(ic, checksums, &dio->metadata_block, &dio->metadata_offset,
1270 checksums_ptr - checksums, !dio->write ? TAG_CMP : TAG_WRITE);
1271 if (unlikely(r)) {
1272 if (r > 0) {
1273 DMERR("Checksum failed at sector 0x%llx",
1274 (unsigned long long)(sector - ((r + ic->tag_size - 1) / ic->tag_size)));
1275 r = -EILSEQ;
1276 }
1277 if (likely(checksums != checksums_onstack))
1278 kfree(checksums);
1279 goto error;
1280 }
1281
1282 if (!sectors_to_process)
1283 break;
1284
1285 if (unlikely(pos < bv.bv_len)) {
1286 bv.bv_offset += pos;
1287 bv.bv_len -= pos;
1288 goto again;
1289 }
1290 }
1291
1292 if (likely(checksums != checksums_onstack))
1293 kfree(checksums);
1294 } else {
1295 struct bio_integrity_payload *bip = dio->orig_bi_integrity;
1296
1297 if (bip) {
1298 struct bio_vec biv;
1299 struct bvec_iter iter;
9d609f85
MP
1300 unsigned data_to_process = dio->range.n_sectors;
1301 sector_to_block(ic, data_to_process);
1302 data_to_process *= ic->tag_size;
7eada909
MP
1303
1304 bip_for_each_vec(biv, bip, iter) {
1305 unsigned char *tag;
1306 unsigned this_len;
1307
1308 BUG_ON(PageHighMem(biv.bv_page));
1309 tag = lowmem_page_address(biv.bv_page) + biv.bv_offset;
1310 this_len = min(biv.bv_len, data_to_process);
1311 r = dm_integrity_rw_tag(ic, tag, &dio->metadata_block, &dio->metadata_offset,
1312 this_len, !dio->write ? TAG_READ : TAG_WRITE);
1313 if (unlikely(r))
1314 goto error;
1315 data_to_process -= this_len;
1316 if (!data_to_process)
1317 break;
1318 }
1319 }
1320 }
c2bcb2b7 1321skip_io:
7eada909
MP
1322 dec_in_flight(dio);
1323 return;
1324error:
4e4cbee9 1325 dio->bi_status = errno_to_blk_status(r);
7eada909
MP
1326 dec_in_flight(dio);
1327}
1328
1329static int dm_integrity_map(struct dm_target *ti, struct bio *bio)
1330{
1331 struct dm_integrity_c *ic = ti->private;
1332 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
9d609f85 1333 struct bio_integrity_payload *bip;
7eada909
MP
1334
1335 sector_t area, offset;
1336
1337 dio->ic = ic;
4e4cbee9 1338 dio->bi_status = 0;
7eada909
MP
1339
1340 if (unlikely(bio->bi_opf & REQ_PREFLUSH)) {
1341 submit_flush_bio(ic, dio);
1342 return DM_MAPIO_SUBMITTED;
1343 }
1344
1345 dio->range.logical_sector = dm_target_offset(ti, bio->bi_iter.bi_sector);
1346 dio->write = bio_op(bio) == REQ_OP_WRITE;
1347 dio->fua = dio->write && bio->bi_opf & REQ_FUA;
1348 if (unlikely(dio->fua)) {
1349 /*
1350 * Don't pass down the FUA flag because we have to flush
1351 * disk cache anyway.
1352 */
1353 bio->bi_opf &= ~REQ_FUA;
1354 }
1355 if (unlikely(dio->range.logical_sector + bio_sectors(bio) > ic->provided_data_sectors)) {
1356 DMERR("Too big sector number: 0x%llx + 0x%x > 0x%llx",
1357 (unsigned long long)dio->range.logical_sector, bio_sectors(bio),
1358 (unsigned long long)ic->provided_data_sectors);
846785e6 1359 return DM_MAPIO_KILL;
7eada909 1360 }
9d609f85
MP
1361 if (unlikely((dio->range.logical_sector | bio_sectors(bio)) & (unsigned)(ic->sectors_per_block - 1))) {
1362 DMERR("Bio not aligned on %u sectors: 0x%llx, 0x%x",
1363 ic->sectors_per_block,
1364 (unsigned long long)dio->range.logical_sector, bio_sectors(bio));
846785e6 1365 return DM_MAPIO_KILL;
9d609f85
MP
1366 }
1367
1368 if (ic->sectors_per_block > 1) {
1369 struct bvec_iter iter;
1370 struct bio_vec bv;
1371 bio_for_each_segment(bv, bio, iter) {
1372 if (unlikely((bv.bv_offset | bv.bv_len) & ((ic->sectors_per_block << SECTOR_SHIFT) - 1))) {
1373 DMERR("Bio vector (%u,%u) is not aligned on %u-sector boundary",
1374 bv.bv_offset, bv.bv_len, ic->sectors_per_block);
846785e6 1375 return DM_MAPIO_KILL;
9d609f85
MP
1376 }
1377 }
1378 }
1379
1380 bip = bio_integrity(bio);
1381 if (!ic->internal_hash) {
1382 if (bip) {
1383 unsigned wanted_tag_size = bio_sectors(bio) >> ic->sb->log2_sectors_per_block;
1384 if (ic->log2_tag_size >= 0)
1385 wanted_tag_size <<= ic->log2_tag_size;
1386 else
1387 wanted_tag_size *= ic->tag_size;
1388 if (unlikely(wanted_tag_size != bip->bip_iter.bi_size)) {
1389 DMERR("Invalid integrity data size %u, expected %u", bip->bip_iter.bi_size, wanted_tag_size);
846785e6 1390 return DM_MAPIO_KILL;
9d609f85
MP
1391 }
1392 }
1393 } else {
1394 if (unlikely(bip != NULL)) {
1395 DMERR("Unexpected integrity data when using internal hash");
846785e6 1396 return DM_MAPIO_KILL;
9d609f85
MP
1397 }
1398 }
7eada909 1399
c2bcb2b7 1400 if (unlikely(ic->mode == 'R') && unlikely(dio->write))
846785e6 1401 return DM_MAPIO_KILL;
c2bcb2b7 1402
7eada909
MP
1403 get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
1404 dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
1405 bio->bi_iter.bi_sector = get_data_sector(ic, area, offset);
1406
1407 dm_integrity_map_continue(dio, true);
1408 return DM_MAPIO_SUBMITTED;
1409}
1410
1411static bool __journal_read_write(struct dm_integrity_io *dio, struct bio *bio,
1412 unsigned journal_section, unsigned journal_entry)
1413{
1414 struct dm_integrity_c *ic = dio->ic;
1415 sector_t logical_sector;
1416 unsigned n_sectors;
1417
1418 logical_sector = dio->range.logical_sector;
1419 n_sectors = dio->range.n_sectors;
1420 do {
1421 struct bio_vec bv = bio_iovec(bio);
1422 char *mem;
1423
1424 if (unlikely(bv.bv_len >> SECTOR_SHIFT > n_sectors))
1425 bv.bv_len = n_sectors << SECTOR_SHIFT;
1426 n_sectors -= bv.bv_len >> SECTOR_SHIFT;
1427 bio_advance_iter(bio, &bio->bi_iter, bv.bv_len);
1428retry_kmap:
1429 mem = kmap_atomic(bv.bv_page);
1430 if (likely(dio->write))
1431 flush_dcache_page(bv.bv_page);
1432
1433 do {
1434 struct journal_entry *je = access_journal_entry(ic, journal_section, journal_entry);
1435
1436 if (unlikely(!dio->write)) {
1437 struct journal_sector *js;
9d609f85
MP
1438 char *mem_ptr;
1439 unsigned s;
7eada909
MP
1440
1441 if (unlikely(journal_entry_is_inprogress(je))) {
1442 flush_dcache_page(bv.bv_page);
1443 kunmap_atomic(mem);
1444
1445 __io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
1446 goto retry_kmap;
1447 }
1448 smp_rmb();
1449 BUG_ON(journal_entry_get_sector(je) != logical_sector);
1450 js = access_journal_data(ic, journal_section, journal_entry);
9d609f85
MP
1451 mem_ptr = mem + bv.bv_offset;
1452 s = 0;
1453 do {
1454 memcpy(mem_ptr, js, JOURNAL_SECTOR_DATA);
1455 *(commit_id_t *)(mem_ptr + JOURNAL_SECTOR_DATA) = je->last_bytes[s];
1456 js++;
1457 mem_ptr += 1 << SECTOR_SHIFT;
1458 } while (++s < ic->sectors_per_block);
7eada909
MP
1459#ifdef INTERNAL_VERIFY
1460 if (ic->internal_hash) {
1461 char checksums_onstack[max(crypto_shash_digestsize(ic->internal_hash), ic->tag_size)];
1462
1463 integrity_sector_checksum(ic, logical_sector, mem + bv.bv_offset, checksums_onstack);
9d609f85 1464 if (unlikely(memcmp(checksums_onstack, journal_entry_tag(ic, je), ic->tag_size))) {
7eada909
MP
1465 DMERR("Checksum failed when reading from journal, at sector 0x%llx",
1466 (unsigned long long)logical_sector);
1467 }
1468 }
1469#endif
1470 }
1471
1472 if (!ic->internal_hash) {
1473 struct bio_integrity_payload *bip = bio_integrity(bio);
1474 unsigned tag_todo = ic->tag_size;
9d609f85 1475 char *tag_ptr = journal_entry_tag(ic, je);
7eada909
MP
1476
1477 if (bip) do {
1478 struct bio_vec biv = bvec_iter_bvec(bip->bip_vec, bip->bip_iter);
1479 unsigned tag_now = min(biv.bv_len, tag_todo);
1480 char *tag_addr;
1481 BUG_ON(PageHighMem(biv.bv_page));
1482 tag_addr = lowmem_page_address(biv.bv_page) + biv.bv_offset;
1483 if (likely(dio->write))
1484 memcpy(tag_ptr, tag_addr, tag_now);
1485 else
1486 memcpy(tag_addr, tag_ptr, tag_now);
1487 bvec_iter_advance(bip->bip_vec, &bip->bip_iter, tag_now);
1488 tag_ptr += tag_now;
1489 tag_todo -= tag_now;
1490 } while (unlikely(tag_todo)); else {
1491 if (likely(dio->write))
1492 memset(tag_ptr, 0, tag_todo);
1493 }
1494 }
1495
1496 if (likely(dio->write)) {
1497 struct journal_sector *js;
9d609f85 1498 unsigned s;
7eada909
MP
1499
1500 js = access_journal_data(ic, journal_section, journal_entry);
9d609f85
MP
1501 memcpy(js, mem + bv.bv_offset, ic->sectors_per_block << SECTOR_SHIFT);
1502
1503 s = 0;
1504 do {
1505 je->last_bytes[s] = js[s].commit_id;
1506 } while (++s < ic->sectors_per_block);
7eada909
MP
1507
1508 if (ic->internal_hash) {
1509 unsigned digest_size = crypto_shash_digestsize(ic->internal_hash);
1510 if (unlikely(digest_size > ic->tag_size)) {
1511 char checksums_onstack[digest_size];
1512 integrity_sector_checksum(ic, logical_sector, (char *)js, checksums_onstack);
9d609f85 1513 memcpy(journal_entry_tag(ic, je), checksums_onstack, ic->tag_size);
7eada909 1514 } else
9d609f85 1515 integrity_sector_checksum(ic, logical_sector, (char *)js, journal_entry_tag(ic, je));
7eada909
MP
1516 }
1517
1518 journal_entry_set_sector(je, logical_sector);
1519 }
9d609f85 1520 logical_sector += ic->sectors_per_block;
7eada909
MP
1521
1522 journal_entry++;
1523 if (unlikely(journal_entry == ic->journal_section_entries)) {
1524 journal_entry = 0;
1525 journal_section++;
1526 wraparound_section(ic, &journal_section);
1527 }
1528
9d609f85
MP
1529 bv.bv_offset += ic->sectors_per_block << SECTOR_SHIFT;
1530 } while (bv.bv_len -= ic->sectors_per_block << SECTOR_SHIFT);
7eada909
MP
1531
1532 if (unlikely(!dio->write))
1533 flush_dcache_page(bv.bv_page);
1534 kunmap_atomic(mem);
1535 } while (n_sectors);
1536
1537 if (likely(dio->write)) {
1538 smp_mb();
1539 if (unlikely(waitqueue_active(&ic->copy_to_journal_wait)))
1540 wake_up(&ic->copy_to_journal_wait);
1541 if (ACCESS_ONCE(ic->free_sectors) <= ic->free_sectors_threshold) {
1542 queue_work(ic->commit_wq, &ic->commit_work);
1543 } else {
1544 schedule_autocommit(ic);
1545 }
1546 } else {
1547 remove_range(ic, &dio->range);
1548 }
1549
1550 if (unlikely(bio->bi_iter.bi_size)) {
1551 sector_t area, offset;
1552
1553 dio->range.logical_sector = logical_sector;
1554 get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
1555 dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
1556 return true;
1557 }
1558
1559 return false;
1560}
1561
1562static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map)
1563{
1564 struct dm_integrity_c *ic = dio->ic;
1565 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1566 unsigned journal_section, journal_entry;
1567 unsigned journal_read_pos;
1568 struct completion read_comp;
1569 bool need_sync_io = ic->internal_hash && !dio->write;
1570
1571 if (need_sync_io && from_map) {
1572 INIT_WORK(&dio->work, integrity_bio_wait);
1573 queue_work(ic->metadata_wq, &dio->work);
1574 return;
1575 }
1576
1577lock_retry:
1578 spin_lock_irq(&ic->endio_wait.lock);
1579retry:
1580 if (unlikely(dm_integrity_failed(ic))) {
1581 spin_unlock_irq(&ic->endio_wait.lock);
1582 do_endio(ic, bio);
1583 return;
1584 }
1585 dio->range.n_sectors = bio_sectors(bio);
1586 journal_read_pos = NOT_FOUND;
1587 if (likely(ic->mode == 'J')) {
1588 if (dio->write) {
1589 unsigned next_entry, i, pos;
9dd59727 1590 unsigned ws, we, range_sectors;
7eada909 1591
9dd59727
MP
1592 dio->range.n_sectors = min(dio->range.n_sectors,
1593 ic->free_sectors << ic->sb->log2_sectors_per_block);
7eada909
MP
1594 if (unlikely(!dio->range.n_sectors))
1595 goto sleep;
9dd59727
MP
1596 range_sectors = dio->range.n_sectors >> ic->sb->log2_sectors_per_block;
1597 ic->free_sectors -= range_sectors;
7eada909
MP
1598 journal_section = ic->free_section;
1599 journal_entry = ic->free_section_entry;
1600
9dd59727 1601 next_entry = ic->free_section_entry + range_sectors;
7eada909
MP
1602 ic->free_section_entry = next_entry % ic->journal_section_entries;
1603 ic->free_section += next_entry / ic->journal_section_entries;
1604 ic->n_uncommitted_sections += next_entry / ic->journal_section_entries;
1605 wraparound_section(ic, &ic->free_section);
1606
1607 pos = journal_section * ic->journal_section_entries + journal_entry;
1608 ws = journal_section;
1609 we = journal_entry;
9d609f85
MP
1610 i = 0;
1611 do {
7eada909
MP
1612 struct journal_entry *je;
1613
1614 add_journal_node(ic, &ic->journal_tree[pos], dio->range.logical_sector + i);
1615 pos++;
1616 if (unlikely(pos >= ic->journal_entries))
1617 pos = 0;
1618
1619 je = access_journal_entry(ic, ws, we);
1620 BUG_ON(!journal_entry_is_unused(je));
1621 journal_entry_set_inprogress(je);
1622 we++;
1623 if (unlikely(we == ic->journal_section_entries)) {
1624 we = 0;
1625 ws++;
1626 wraparound_section(ic, &ws);
1627 }
9d609f85 1628 } while ((i += ic->sectors_per_block) < dio->range.n_sectors);
7eada909
MP
1629
1630 spin_unlock_irq(&ic->endio_wait.lock);
1631 goto journal_read_write;
1632 } else {
1633 sector_t next_sector;
1634 journal_read_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
1635 if (likely(journal_read_pos == NOT_FOUND)) {
1636 if (unlikely(dio->range.n_sectors > next_sector - dio->range.logical_sector))
1637 dio->range.n_sectors = next_sector - dio->range.logical_sector;
1638 } else {
1639 unsigned i;
9d609f85
MP
1640 unsigned jp = journal_read_pos + 1;
1641 for (i = ic->sectors_per_block; i < dio->range.n_sectors; i += ic->sectors_per_block, jp++) {
1642 if (!test_journal_node(ic, jp, dio->range.logical_sector + i))
7eada909
MP
1643 break;
1644 }
1645 dio->range.n_sectors = i;
1646 }
1647 }
1648 }
1649 if (unlikely(!add_new_range(ic, &dio->range))) {
1650 /*
1651 * We must not sleep in the request routine because it could
1652 * stall bios on current->bio_list.
1653 * So, we offload the bio to a workqueue if we have to sleep.
1654 */
1655sleep:
1656 if (from_map) {
1657 spin_unlock_irq(&ic->endio_wait.lock);
1658 INIT_WORK(&dio->work, integrity_bio_wait);
1659 queue_work(ic->wait_wq, &dio->work);
1660 return;
1661 } else {
1662 sleep_on_endio_wait(ic);
1663 goto retry;
1664 }
1665 }
1666 spin_unlock_irq(&ic->endio_wait.lock);
1667
1668 if (unlikely(journal_read_pos != NOT_FOUND)) {
1669 journal_section = journal_read_pos / ic->journal_section_entries;
1670 journal_entry = journal_read_pos % ic->journal_section_entries;
1671 goto journal_read_write;
1672 }
1673
1674 dio->in_flight = (atomic_t)ATOMIC_INIT(2);
1675
1676 if (need_sync_io) {
1677 read_comp = COMPLETION_INITIALIZER_ONSTACK(read_comp);
1678 dio->completion = &read_comp;
1679 } else
1680 dio->completion = NULL;
1681
1682 dio->orig_bi_iter = bio->bi_iter;
1683
1684 dio->orig_bi_bdev = bio->bi_bdev;
1685 bio->bi_bdev = ic->dev->bdev;
1686
1687 dio->orig_bi_integrity = bio_integrity(bio);
1688 bio->bi_integrity = NULL;
1689 bio->bi_opf &= ~REQ_INTEGRITY;
1690
1691 dio->orig_bi_end_io = bio->bi_end_io;
1692 bio->bi_end_io = integrity_end_io;
1693
1694 bio->bi_iter.bi_size = dio->range.n_sectors << SECTOR_SHIFT;
1695 bio->bi_iter.bi_sector += ic->start;
1696 generic_make_request(bio);
1697
1698 if (need_sync_io) {
1699 wait_for_completion_io(&read_comp);
95bab525
HL
1700 if (likely(!bio->bi_status))
1701 integrity_metadata(&dio->work);
1702 else
1703 dec_in_flight(dio);
1704
7eada909
MP
1705 } else {
1706 INIT_WORK(&dio->work, integrity_metadata);
1707 queue_work(ic->metadata_wq, &dio->work);
1708 }
1709
1710 return;
1711
1712journal_read_write:
1713 if (unlikely(__journal_read_write(dio, bio, journal_section, journal_entry)))
1714 goto lock_retry;
1715
1716 do_endio_flush(ic, dio);
1717}
1718
1719
1720static void integrity_bio_wait(struct work_struct *w)
1721{
1722 struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
1723
1724 dm_integrity_map_continue(dio, false);
1725}
1726
1727static void pad_uncommitted(struct dm_integrity_c *ic)
1728{
1729 if (ic->free_section_entry) {
1730 ic->free_sectors -= ic->journal_section_entries - ic->free_section_entry;
1731 ic->free_section_entry = 0;
1732 ic->free_section++;
1733 wraparound_section(ic, &ic->free_section);
1734 ic->n_uncommitted_sections++;
1735 }
aa03a91f
MP
1736 WARN_ON(ic->journal_sections * ic->journal_section_entries !=
1737 (ic->n_uncommitted_sections + ic->n_committed_sections) * ic->journal_section_entries + ic->free_sectors);
7eada909
MP
1738}
1739
1740static void integrity_commit(struct work_struct *w)
1741{
1742 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, commit_work);
1743 unsigned commit_start, commit_sections;
1744 unsigned i, j, n;
1745 struct bio *flushes;
1746
1747 del_timer(&ic->autocommit_timer);
1748
1749 spin_lock_irq(&ic->endio_wait.lock);
1750 flushes = bio_list_get(&ic->flush_bio_list);
1751 if (unlikely(ic->mode != 'J')) {
1752 spin_unlock_irq(&ic->endio_wait.lock);
1753 dm_integrity_flush_buffers(ic);
1754 goto release_flush_bios;
1755 }
1756
1757 pad_uncommitted(ic);
1758 commit_start = ic->uncommitted_section;
1759 commit_sections = ic->n_uncommitted_sections;
1760 spin_unlock_irq(&ic->endio_wait.lock);
1761
1762 if (!commit_sections)
1763 goto release_flush_bios;
1764
1765 i = commit_start;
1766 for (n = 0; n < commit_sections; n++) {
1767 for (j = 0; j < ic->journal_section_entries; j++) {
1768 struct journal_entry *je;
1769 je = access_journal_entry(ic, i, j);
1770 io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
1771 }
1772 for (j = 0; j < ic->journal_section_sectors; j++) {
1773 struct journal_sector *js;
1774 js = access_journal(ic, i, j);
1775 js->commit_id = dm_integrity_commit_id(ic, i, j, ic->commit_seq);
1776 }
1777 i++;
1778 if (unlikely(i >= ic->journal_sections))
1779 ic->commit_seq = next_commit_seq(ic->commit_seq);
1780 wraparound_section(ic, &i);
1781 }
1782 smp_rmb();
1783
1784 write_journal(ic, commit_start, commit_sections);
1785
1786 spin_lock_irq(&ic->endio_wait.lock);
1787 ic->uncommitted_section += commit_sections;
1788 wraparound_section(ic, &ic->uncommitted_section);
1789 ic->n_uncommitted_sections -= commit_sections;
1790 ic->n_committed_sections += commit_sections;
1791 spin_unlock_irq(&ic->endio_wait.lock);
1792
1793 if (ACCESS_ONCE(ic->free_sectors) <= ic->free_sectors_threshold)
1794 queue_work(ic->writer_wq, &ic->writer_work);
1795
1796release_flush_bios:
1797 while (flushes) {
1798 struct bio *next = flushes->bi_next;
1799 flushes->bi_next = NULL;
1800 do_endio(ic, flushes);
1801 flushes = next;
1802 }
1803}
1804
1805static void complete_copy_from_journal(unsigned long error, void *context)
1806{
1807 struct journal_io *io = context;
1808 struct journal_completion *comp = io->comp;
1809 struct dm_integrity_c *ic = comp->ic;
1810 remove_range(ic, &io->range);
1811 mempool_free(io, ic->journal_io_mempool);
1812 if (unlikely(error != 0))
1813 dm_integrity_io_error(ic, "copying from journal", -EIO);
1814 complete_journal_op(comp);
1815}
1816
9d609f85
MP
1817static void restore_last_bytes(struct dm_integrity_c *ic, struct journal_sector *js,
1818 struct journal_entry *je)
1819{
1820 unsigned s = 0;
1821 do {
1822 js->commit_id = je->last_bytes[s];
1823 js++;
1824 } while (++s < ic->sectors_per_block);
1825}
1826
7eada909
MP
1827static void do_journal_write(struct dm_integrity_c *ic, unsigned write_start,
1828 unsigned write_sections, bool from_replay)
1829{
1830 unsigned i, j, n;
1831 struct journal_completion comp;
a7c3e62b
MP
1832 struct blk_plug plug;
1833
1834 blk_start_plug(&plug);
7eada909
MP
1835
1836 comp.ic = ic;
1837 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
1838 comp.comp = COMPLETION_INITIALIZER_ONSTACK(comp.comp);
1839
1840 i = write_start;
1841 for (n = 0; n < write_sections; n++, i++, wraparound_section(ic, &i)) {
1842#ifndef INTERNAL_VERIFY
1843 if (unlikely(from_replay))
1844#endif
1845 rw_section_mac(ic, i, false);
1846 for (j = 0; j < ic->journal_section_entries; j++) {
1847 struct journal_entry *je = access_journal_entry(ic, i, j);
1848 sector_t sec, area, offset;
1849 unsigned k, l, next_loop;
1850 sector_t metadata_block;
1851 unsigned metadata_offset;
1852 struct journal_io *io;
1853
1854 if (journal_entry_is_unused(je))
1855 continue;
1856 BUG_ON(unlikely(journal_entry_is_inprogress(je)) && !from_replay);
1857 sec = journal_entry_get_sector(je);
9d609f85
MP
1858 if (unlikely(from_replay)) {
1859 if (unlikely(sec & (unsigned)(ic->sectors_per_block - 1))) {
1860 dm_integrity_io_error(ic, "invalid sector in journal", -EIO);
1861 sec &= ~(sector_t)(ic->sectors_per_block - 1);
1862 }
1863 }
7eada909 1864 get_area_and_offset(ic, sec, &area, &offset);
9d609f85 1865 restore_last_bytes(ic, access_journal_data(ic, i, j), je);
7eada909
MP
1866 for (k = j + 1; k < ic->journal_section_entries; k++) {
1867 struct journal_entry *je2 = access_journal_entry(ic, i, k);
1868 sector_t sec2, area2, offset2;
1869 if (journal_entry_is_unused(je2))
1870 break;
1871 BUG_ON(unlikely(journal_entry_is_inprogress(je2)) && !from_replay);
1872 sec2 = journal_entry_get_sector(je2);
1873 get_area_and_offset(ic, sec2, &area2, &offset2);
9d609f85 1874 if (area2 != area || offset2 != offset + ((k - j) << ic->sb->log2_sectors_per_block))
7eada909 1875 break;
9d609f85 1876 restore_last_bytes(ic, access_journal_data(ic, i, k), je2);
7eada909
MP
1877 }
1878 next_loop = k - 1;
1879
1880 io = mempool_alloc(ic->journal_io_mempool, GFP_NOIO);
1881 io->comp = &comp;
1882 io->range.logical_sector = sec;
9d609f85 1883 io->range.n_sectors = (k - j) << ic->sb->log2_sectors_per_block;
7eada909
MP
1884
1885 spin_lock_irq(&ic->endio_wait.lock);
1886 while (unlikely(!add_new_range(ic, &io->range)))
1887 sleep_on_endio_wait(ic);
1888
1889 if (likely(!from_replay)) {
1890 struct journal_node *section_node = &ic->journal_tree[i * ic->journal_section_entries];
1891
1892 /* don't write if there is newer committed sector */
1893 while (j < k && find_newer_committed_node(ic, &section_node[j])) {
1894 struct journal_entry *je2 = access_journal_entry(ic, i, j);
1895
1896 journal_entry_set_unused(je2);
1897 remove_journal_node(ic, &section_node[j]);
1898 j++;
9d609f85
MP
1899 sec += ic->sectors_per_block;
1900 offset += ic->sectors_per_block;
7eada909
MP
1901 }
1902 while (j < k && find_newer_committed_node(ic, &section_node[k - 1])) {
1903 struct journal_entry *je2 = access_journal_entry(ic, i, k - 1);
1904
1905 journal_entry_set_unused(je2);
1906 remove_journal_node(ic, &section_node[k - 1]);
1907 k--;
1908 }
1909 if (j == k) {
1910 remove_range_unlocked(ic, &io->range);
1911 spin_unlock_irq(&ic->endio_wait.lock);
1912 mempool_free(io, ic->journal_io_mempool);
1913 goto skip_io;
1914 }
1915 for (l = j; l < k; l++) {
1916 remove_journal_node(ic, &section_node[l]);
1917 }
1918 }
1919 spin_unlock_irq(&ic->endio_wait.lock);
1920
1921 metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
1922 for (l = j; l < k; l++) {
1923 int r;
1924 struct journal_entry *je2 = access_journal_entry(ic, i, l);
1925
1926 if (
1927#ifndef INTERNAL_VERIFY
1928 unlikely(from_replay) &&
1929#endif
1930 ic->internal_hash) {
56b67a4f 1931 char test_tag[max(crypto_shash_digestsize(ic->internal_hash), ic->tag_size)];
7eada909 1932
9d609f85 1933 integrity_sector_checksum(ic, sec + ((l - j) << ic->sb->log2_sectors_per_block),
7eada909 1934 (char *)access_journal_data(ic, i, l), test_tag);
9d609f85 1935 if (unlikely(memcmp(test_tag, journal_entry_tag(ic, je2), ic->tag_size)))
7eada909
MP
1936 dm_integrity_io_error(ic, "tag mismatch when replaying journal", -EILSEQ);
1937 }
1938
1939 journal_entry_set_unused(je2);
9d609f85 1940 r = dm_integrity_rw_tag(ic, journal_entry_tag(ic, je2), &metadata_block, &metadata_offset,
7eada909
MP
1941 ic->tag_size, TAG_WRITE);
1942 if (unlikely(r)) {
1943 dm_integrity_io_error(ic, "reading tags", r);
1944 }
1945 }
1946
1947 atomic_inc(&comp.in_flight);
9d609f85
MP
1948 copy_from_journal(ic, i, j << ic->sb->log2_sectors_per_block,
1949 (k - j) << ic->sb->log2_sectors_per_block,
1950 get_data_sector(ic, area, offset),
7eada909
MP
1951 complete_copy_from_journal, io);
1952skip_io:
1953 j = next_loop;
1954 }
1955 }
1956
1957 dm_bufio_write_dirty_buffers_async(ic->bufio);
1958
a7c3e62b
MP
1959 blk_finish_plug(&plug);
1960
7eada909
MP
1961 complete_journal_op(&comp);
1962 wait_for_completion_io(&comp.comp);
1963
1964 dm_integrity_flush_buffers(ic);
1965}
1966
1967static void integrity_writer(struct work_struct *w)
1968{
1969 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, writer_work);
1970 unsigned write_start, write_sections;
1971
1972 unsigned prev_free_sectors;
1973
1974 /* the following test is not needed, but it tests the replay code */
1975 if (ACCESS_ONCE(ic->suspending))
1976 return;
1977
1978 spin_lock_irq(&ic->endio_wait.lock);
1979 write_start = ic->committed_section;
1980 write_sections = ic->n_committed_sections;
1981 spin_unlock_irq(&ic->endio_wait.lock);
1982
1983 if (!write_sections)
1984 return;
1985
1986 do_journal_write(ic, write_start, write_sections, false);
1987
1988 spin_lock_irq(&ic->endio_wait.lock);
1989
1990 ic->committed_section += write_sections;
1991 wraparound_section(ic, &ic->committed_section);
1992 ic->n_committed_sections -= write_sections;
1993
1994 prev_free_sectors = ic->free_sectors;
1995 ic->free_sectors += write_sections * ic->journal_section_entries;
1996 if (unlikely(!prev_free_sectors))
1997 wake_up_locked(&ic->endio_wait);
1998
1999 spin_unlock_irq(&ic->endio_wait.lock);
2000}
2001
2002static void init_journal(struct dm_integrity_c *ic, unsigned start_section,
2003 unsigned n_sections, unsigned char commit_seq)
2004{
2005 unsigned i, j, n;
2006
2007 if (!n_sections)
2008 return;
2009
2010 for (n = 0; n < n_sections; n++) {
2011 i = start_section + n;
2012 wraparound_section(ic, &i);
2013 for (j = 0; j < ic->journal_section_sectors; j++) {
2014 struct journal_sector *js = access_journal(ic, i, j);
2015 memset(&js->entries, 0, JOURNAL_SECTOR_DATA);
2016 js->commit_id = dm_integrity_commit_id(ic, i, j, commit_seq);
2017 }
2018 for (j = 0; j < ic->journal_section_entries; j++) {
2019 struct journal_entry *je = access_journal_entry(ic, i, j);
2020 journal_entry_set_unused(je);
2021 }
2022 }
2023
2024 write_journal(ic, start_section, n_sections);
2025}
2026
2027static int find_commit_seq(struct dm_integrity_c *ic, unsigned i, unsigned j, commit_id_t id)
2028{
2029 unsigned char k;
2030 for (k = 0; k < N_COMMIT_IDS; k++) {
2031 if (dm_integrity_commit_id(ic, i, j, k) == id)
2032 return k;
2033 }
2034 dm_integrity_io_error(ic, "journal commit id", -EIO);
2035 return -EIO;
2036}
2037
2038static void replay_journal(struct dm_integrity_c *ic)
2039{
2040 unsigned i, j;
2041 bool used_commit_ids[N_COMMIT_IDS];
2042 unsigned max_commit_id_sections[N_COMMIT_IDS];
2043 unsigned write_start, write_sections;
2044 unsigned continue_section;
2045 bool journal_empty;
2046 unsigned char unused, last_used, want_commit_seq;
2047
c2bcb2b7
MP
2048 if (ic->mode == 'R')
2049 return;
2050
7eada909
MP
2051 if (ic->journal_uptodate)
2052 return;
2053
2054 last_used = 0;
2055 write_start = 0;
2056
2057 if (!ic->just_formatted) {
2058 DEBUG_print("reading journal\n");
2059 rw_journal(ic, REQ_OP_READ, 0, 0, ic->journal_sections, NULL);
2060 if (ic->journal_io)
2061 DEBUG_bytes(lowmem_page_address(ic->journal_io[0].page), 64, "read journal");
2062 if (ic->journal_io) {
2063 struct journal_completion crypt_comp;
2064 crypt_comp.ic = ic;
2065 crypt_comp.comp = COMPLETION_INITIALIZER_ONSTACK(crypt_comp.comp);
2066 crypt_comp.in_flight = (atomic_t)ATOMIC_INIT(0);
2067 encrypt_journal(ic, false, 0, ic->journal_sections, &crypt_comp);
2068 wait_for_completion(&crypt_comp.comp);
2069 }
2070 DEBUG_bytes(lowmem_page_address(ic->journal[0].page), 64, "decrypted journal");
2071 }
2072
2073 if (dm_integrity_failed(ic))
2074 goto clear_journal;
2075
2076 journal_empty = true;
2077 memset(used_commit_ids, 0, sizeof used_commit_ids);
2078 memset(max_commit_id_sections, 0, sizeof max_commit_id_sections);
2079 for (i = 0; i < ic->journal_sections; i++) {
2080 for (j = 0; j < ic->journal_section_sectors; j++) {
2081 int k;
2082 struct journal_sector *js = access_journal(ic, i, j);
2083 k = find_commit_seq(ic, i, j, js->commit_id);
2084 if (k < 0)
2085 goto clear_journal;
2086 used_commit_ids[k] = true;
2087 max_commit_id_sections[k] = i;
2088 }
2089 if (journal_empty) {
2090 for (j = 0; j < ic->journal_section_entries; j++) {
2091 struct journal_entry *je = access_journal_entry(ic, i, j);
2092 if (!journal_entry_is_unused(je)) {
2093 journal_empty = false;
2094 break;
2095 }
2096 }
2097 }
2098 }
2099
2100 if (!used_commit_ids[N_COMMIT_IDS - 1]) {
2101 unused = N_COMMIT_IDS - 1;
2102 while (unused && !used_commit_ids[unused - 1])
2103 unused--;
2104 } else {
2105 for (unused = 0; unused < N_COMMIT_IDS; unused++)
2106 if (!used_commit_ids[unused])
2107 break;
2108 if (unused == N_COMMIT_IDS) {
2109 dm_integrity_io_error(ic, "journal commit ids", -EIO);
2110 goto clear_journal;
2111 }
2112 }
2113 DEBUG_print("first unused commit seq %d [%d,%d,%d,%d]\n",
2114 unused, used_commit_ids[0], used_commit_ids[1],
2115 used_commit_ids[2], used_commit_ids[3]);
2116
2117 last_used = prev_commit_seq(unused);
2118 want_commit_seq = prev_commit_seq(last_used);
2119
2120 if (!used_commit_ids[want_commit_seq] && used_commit_ids[prev_commit_seq(want_commit_seq)])
2121 journal_empty = true;
2122
2123 write_start = max_commit_id_sections[last_used] + 1;
2124 if (unlikely(write_start >= ic->journal_sections))
2125 want_commit_seq = next_commit_seq(want_commit_seq);
2126 wraparound_section(ic, &write_start);
2127
2128 i = write_start;
2129 for (write_sections = 0; write_sections < ic->journal_sections; write_sections++) {
2130 for (j = 0; j < ic->journal_section_sectors; j++) {
2131 struct journal_sector *js = access_journal(ic, i, j);
2132
2133 if (js->commit_id != dm_integrity_commit_id(ic, i, j, want_commit_seq)) {
2134 /*
2135 * This could be caused by crash during writing.
2136 * We won't replay the inconsistent part of the
2137 * journal.
2138 */
2139 DEBUG_print("commit id mismatch at position (%u, %u): %d != %d\n",
2140 i, j, find_commit_seq(ic, i, j, js->commit_id), want_commit_seq);
2141 goto brk;
2142 }
2143 }
2144 i++;
2145 if (unlikely(i >= ic->journal_sections))
2146 want_commit_seq = next_commit_seq(want_commit_seq);
2147 wraparound_section(ic, &i);
2148 }
2149brk:
2150
2151 if (!journal_empty) {
2152 DEBUG_print("replaying %u sections, starting at %u, commit seq %d\n",
2153 write_sections, write_start, want_commit_seq);
2154 do_journal_write(ic, write_start, write_sections, true);
2155 }
2156
2157 if (write_sections == ic->journal_sections && (ic->mode == 'J' || journal_empty)) {
2158 continue_section = write_start;
2159 ic->commit_seq = want_commit_seq;
2160 DEBUG_print("continuing from section %u, commit seq %d\n", write_start, ic->commit_seq);
2161 } else {
2162 unsigned s;
2163 unsigned char erase_seq;
2164clear_journal:
2165 DEBUG_print("clearing journal\n");
2166
2167 erase_seq = prev_commit_seq(prev_commit_seq(last_used));
2168 s = write_start;
2169 init_journal(ic, s, 1, erase_seq);
2170 s++;
2171 wraparound_section(ic, &s);
2172 if (ic->journal_sections >= 2) {
2173 init_journal(ic, s, ic->journal_sections - 2, erase_seq);
2174 s += ic->journal_sections - 2;
2175 wraparound_section(ic, &s);
2176 init_journal(ic, s, 1, erase_seq);
2177 }
2178
2179 continue_section = 0;
2180 ic->commit_seq = next_commit_seq(erase_seq);
2181 }
2182
2183 ic->committed_section = continue_section;
2184 ic->n_committed_sections = 0;
2185
2186 ic->uncommitted_section = continue_section;
2187 ic->n_uncommitted_sections = 0;
2188
2189 ic->free_section = continue_section;
2190 ic->free_section_entry = 0;
2191 ic->free_sectors = ic->journal_entries;
2192
2193 ic->journal_tree_root = RB_ROOT;
2194 for (i = 0; i < ic->journal_entries; i++)
2195 init_journal_node(&ic->journal_tree[i]);
2196}
2197
2198static void dm_integrity_postsuspend(struct dm_target *ti)
2199{
2200 struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2201
2202 del_timer_sync(&ic->autocommit_timer);
2203
2204 ic->suspending = true;
2205
2206 queue_work(ic->commit_wq, &ic->commit_work);
2207 drain_workqueue(ic->commit_wq);
2208
2209 if (ic->mode == 'J') {
2210 drain_workqueue(ic->writer_wq);
2211 dm_integrity_flush_buffers(ic);
2212 }
2213
2214 ic->suspending = false;
2215
2216 BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
2217
2218 ic->journal_uptodate = true;
2219}
2220
2221static void dm_integrity_resume(struct dm_target *ti)
2222{
2223 struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2224
2225 replay_journal(ic);
2226}
2227
2228static void dm_integrity_status(struct dm_target *ti, status_type_t type,
2229 unsigned status_flags, char *result, unsigned maxlen)
2230{
2231 struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2232 unsigned arg_count;
2233 size_t sz = 0;
2234
2235 switch (type) {
2236 case STATUSTYPE_INFO:
2237 result[0] = '\0';
2238 break;
2239
2240 case STATUSTYPE_TABLE: {
2241 __u64 watermark_percentage = (__u64)(ic->journal_entries - ic->free_sectors_threshold) * 100;
2242 watermark_percentage += ic->journal_entries / 2;
2243 do_div(watermark_percentage, ic->journal_entries);
2244 arg_count = 5;
9d609f85 2245 arg_count += ic->sectors_per_block != 1;
7eada909
MP
2246 arg_count += !!ic->internal_hash_alg.alg_string;
2247 arg_count += !!ic->journal_crypt_alg.alg_string;
2248 arg_count += !!ic->journal_mac_alg.alg_string;
2249 DMEMIT("%s %llu %u %c %u", ic->dev->name, (unsigned long long)ic->start,
2250 ic->tag_size, ic->mode, arg_count);
56b67a4f
MP
2251 DMEMIT(" journal_sectors:%u", ic->initial_sectors - SB_SECTORS);
2252 DMEMIT(" interleave_sectors:%u", 1U << ic->sb->log2_interleave_sectors);
2253 DMEMIT(" buffer_sectors:%u", 1U << ic->log2_buffer_sectors);
2254 DMEMIT(" journal_watermark:%u", (unsigned)watermark_percentage);
2255 DMEMIT(" commit_time:%u", ic->autocommit_msec);
9d609f85
MP
2256 if (ic->sectors_per_block != 1)
2257 DMEMIT(" block_size:%u", ic->sectors_per_block << SECTOR_SHIFT);
7eada909
MP
2258
2259#define EMIT_ALG(a, n) \
2260 do { \
2261 if (ic->a.alg_string) { \
2262 DMEMIT(" %s:%s", n, ic->a.alg_string); \
2263 if (ic->a.key_string) \
2264 DMEMIT(":%s", ic->a.key_string);\
2265 } \
2266 } while (0)
56b67a4f
MP
2267 EMIT_ALG(internal_hash_alg, "internal_hash");
2268 EMIT_ALG(journal_crypt_alg, "journal_crypt");
2269 EMIT_ALG(journal_mac_alg, "journal_mac");
7eada909
MP
2270 break;
2271 }
2272 }
2273}
2274
2275static int dm_integrity_iterate_devices(struct dm_target *ti,
2276 iterate_devices_callout_fn fn, void *data)
2277{
2278 struct dm_integrity_c *ic = ti->private;
2279
2280 return fn(ti, ic->dev, ic->start + ic->initial_sectors + ic->metadata_run, ti->len, data);
2281}
2282
9d609f85
MP
2283static void dm_integrity_io_hints(struct dm_target *ti, struct queue_limits *limits)
2284{
2285 struct dm_integrity_c *ic = ti->private;
2286
2287 if (ic->sectors_per_block > 1) {
2288 limits->logical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
2289 limits->physical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
2290 blk_limits_io_min(limits, ic->sectors_per_block << SECTOR_SHIFT);
2291 }
2292}
2293
7eada909
MP
2294static void calculate_journal_section_size(struct dm_integrity_c *ic)
2295{
2296 unsigned sector_space = JOURNAL_SECTOR_DATA;
2297
2298 ic->journal_sections = le32_to_cpu(ic->sb->journal_sections);
9d609f85 2299 ic->journal_entry_size = roundup(offsetof(struct journal_entry, last_bytes[ic->sectors_per_block]) + ic->tag_size,
7eada909
MP
2300 JOURNAL_ENTRY_ROUNDUP);
2301
2302 if (ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC))
2303 sector_space -= JOURNAL_MAC_PER_SECTOR;
2304 ic->journal_entries_per_sector = sector_space / ic->journal_entry_size;
2305 ic->journal_section_entries = ic->journal_entries_per_sector * JOURNAL_BLOCK_SECTORS;
9d609f85 2306 ic->journal_section_sectors = (ic->journal_section_entries << ic->sb->log2_sectors_per_block) + JOURNAL_BLOCK_SECTORS;
7eada909
MP
2307 ic->journal_entries = ic->journal_section_entries * ic->journal_sections;
2308}
2309
2310static int calculate_device_limits(struct dm_integrity_c *ic)
2311{
2312 __u64 initial_sectors;
2313 sector_t last_sector, last_area, last_offset;
2314
2315 calculate_journal_section_size(ic);
2316 initial_sectors = SB_SECTORS + (__u64)ic->journal_section_sectors * ic->journal_sections;
2317 if (initial_sectors + METADATA_PADDING_SECTORS >= ic->device_sectors || initial_sectors > UINT_MAX)
2318 return -EINVAL;
2319 ic->initial_sectors = initial_sectors;
2320
9d609f85 2321 ic->metadata_run = roundup((__u64)ic->tag_size << (ic->sb->log2_interleave_sectors - ic->sb->log2_sectors_per_block),
7eada909
MP
2322 (__u64)(1 << SECTOR_SHIFT << METADATA_PADDING_SECTORS)) >> SECTOR_SHIFT;
2323 if (!(ic->metadata_run & (ic->metadata_run - 1)))
2324 ic->log2_metadata_run = __ffs(ic->metadata_run);
2325 else
2326 ic->log2_metadata_run = -1;
2327
2328 get_area_and_offset(ic, ic->provided_data_sectors - 1, &last_area, &last_offset);
2329 last_sector = get_data_sector(ic, last_area, last_offset);
2330
2331 if (ic->start + last_sector < last_sector || ic->start + last_sector >= ic->device_sectors)
2332 return -EINVAL;
2333
2334 return 0;
2335}
2336
2337static int initialize_superblock(struct dm_integrity_c *ic, unsigned journal_sectors, unsigned interleave_sectors)
2338{
2339 unsigned journal_sections;
2340 int test_bit;
2341
56b67a4f 2342 memset(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT);
7eada909
MP
2343 memcpy(ic->sb->magic, SB_MAGIC, 8);
2344 ic->sb->version = SB_VERSION;
2345 ic->sb->integrity_tag_size = cpu_to_le16(ic->tag_size);
9d609f85 2346 ic->sb->log2_sectors_per_block = __ffs(ic->sectors_per_block);
7eada909
MP
2347 if (ic->journal_mac_alg.alg_string)
2348 ic->sb->flags |= cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC);
2349
2350 calculate_journal_section_size(ic);
2351 journal_sections = journal_sectors / ic->journal_section_sectors;
2352 if (!journal_sections)
2353 journal_sections = 1;
2354 ic->sb->journal_sections = cpu_to_le32(journal_sections);
2355
56b67a4f
MP
2356 if (!interleave_sectors)
2357 interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
7eada909 2358 ic->sb->log2_interleave_sectors = __fls(interleave_sectors);
56b67a4f
MP
2359 ic->sb->log2_interleave_sectors = max((__u8)MIN_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
2360 ic->sb->log2_interleave_sectors = min((__u8)MAX_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
7eada909
MP
2361
2362 ic->provided_data_sectors = 0;
2363 for (test_bit = fls64(ic->device_sectors) - 1; test_bit >= 3; test_bit--) {
2364 __u64 prev_data_sectors = ic->provided_data_sectors;
2365
2366 ic->provided_data_sectors |= (sector_t)1 << test_bit;
2367 if (calculate_device_limits(ic))
2368 ic->provided_data_sectors = prev_data_sectors;
2369 }
2370
56b67a4f 2371 if (!ic->provided_data_sectors)
7eada909
MP
2372 return -EINVAL;
2373
2374 ic->sb->provided_data_sectors = cpu_to_le64(ic->provided_data_sectors);
2375
2376 return 0;
2377}
2378
2379static void dm_integrity_set(struct dm_target *ti, struct dm_integrity_c *ic)
2380{
2381 struct gendisk *disk = dm_disk(dm_table_get_md(ti->table));
2382 struct blk_integrity bi;
2383
2384 memset(&bi, 0, sizeof(bi));
2385 bi.profile = &dm_integrity_profile;
9d609f85
MP
2386 bi.tuple_size = ic->tag_size;
2387 bi.tag_size = bi.tuple_size;
84ff1bcc 2388 bi.interval_exp = ic->sb->log2_sectors_per_block + SECTOR_SHIFT;
7eada909
MP
2389
2390 blk_integrity_register(disk, &bi);
2391 blk_queue_max_integrity_segments(disk->queue, UINT_MAX);
2392}
2393
7eada909
MP
2394static void dm_integrity_free_page_list(struct dm_integrity_c *ic, struct page_list *pl)
2395{
2396 unsigned i;
2397
2398 if (!pl)
2399 return;
2400 for (i = 0; i < ic->journal_pages; i++)
2401 if (pl[i].page)
2402 __free_page(pl[i].page);
2403 kvfree(pl);
2404}
2405
2406static struct page_list *dm_integrity_alloc_page_list(struct dm_integrity_c *ic)
2407{
2408 size_t page_list_desc_size = ic->journal_pages * sizeof(struct page_list);
2409 struct page_list *pl;
2410 unsigned i;
2411
702a6204 2412 pl = kvmalloc(page_list_desc_size, GFP_KERNEL | __GFP_ZERO);
7eada909
MP
2413 if (!pl)
2414 return NULL;
2415
2416 for (i = 0; i < ic->journal_pages; i++) {
2417 pl[i].page = alloc_page(GFP_KERNEL);
2418 if (!pl[i].page) {
2419 dm_integrity_free_page_list(ic, pl);
2420 return NULL;
2421 }
2422 if (i)
2423 pl[i - 1].next = &pl[i];
2424 }
2425
2426 return pl;
2427}
2428
2429static void dm_integrity_free_journal_scatterlist(struct dm_integrity_c *ic, struct scatterlist **sl)
2430{
2431 unsigned i;
2432 for (i = 0; i < ic->journal_sections; i++)
2433 kvfree(sl[i]);
2434 kfree(sl);
2435}
2436
2437static struct scatterlist **dm_integrity_alloc_journal_scatterlist(struct dm_integrity_c *ic, struct page_list *pl)
2438{
2439 struct scatterlist **sl;
2440 unsigned i;
2441
702a6204 2442 sl = kvmalloc(ic->journal_sections * sizeof(struct scatterlist *), GFP_KERNEL | __GFP_ZERO);
7eada909
MP
2443 if (!sl)
2444 return NULL;
2445
2446 for (i = 0; i < ic->journal_sections; i++) {
2447 struct scatterlist *s;
2448 unsigned start_index, start_offset;
2449 unsigned end_index, end_offset;
2450 unsigned n_pages;
2451 unsigned idx;
2452
2453 page_list_location(ic, i, 0, &start_index, &start_offset);
2454 page_list_location(ic, i, ic->journal_section_sectors - 1, &end_index, &end_offset);
2455
2456 n_pages = (end_index - start_index + 1);
2457
702a6204 2458 s = kvmalloc(n_pages * sizeof(struct scatterlist), GFP_KERNEL);
7eada909
MP
2459 if (!s) {
2460 dm_integrity_free_journal_scatterlist(ic, sl);
2461 return NULL;
2462 }
2463
2464 sg_init_table(s, n_pages);
2465 for (idx = start_index; idx <= end_index; idx++) {
2466 char *va = lowmem_page_address(pl[idx].page);
2467 unsigned start = 0, end = PAGE_SIZE;
2468 if (idx == start_index)
2469 start = start_offset;
2470 if (idx == end_index)
2471 end = end_offset + (1 << SECTOR_SHIFT);
2472 sg_set_buf(&s[idx - start_index], va + start, end - start);
2473 }
2474
2475 sl[i] = s;
2476 }
2477
2478 return sl;
2479}
2480
2481static void free_alg(struct alg_spec *a)
2482{
2483 kzfree(a->alg_string);
2484 kzfree(a->key);
2485 memset(a, 0, sizeof *a);
2486}
2487
2488static int get_alg_and_key(const char *arg, struct alg_spec *a, char **error, char *error_inval)
2489{
2490 char *k;
2491
2492 free_alg(a);
2493
2494 a->alg_string = kstrdup(strchr(arg, ':') + 1, GFP_KERNEL);
2495 if (!a->alg_string)
2496 goto nomem;
2497
2498 k = strchr(a->alg_string, ':');
2499 if (k) {
7eada909
MP
2500 *k = 0;
2501 a->key_string = k + 1;
2502 if (strlen(a->key_string) & 1)
2503 goto inval;
2504
2505 a->key_size = strlen(a->key_string) / 2;
2506 a->key = kmalloc(a->key_size, GFP_KERNEL);
2507 if (!a->key)
2508 goto nomem;
6625d903
MP
2509 if (hex2bin(a->key, a->key_string, a->key_size))
2510 goto inval;
7eada909
MP
2511 }
2512
2513 return 0;
2514inval:
2515 *error = error_inval;
2516 return -EINVAL;
2517nomem:
2518 *error = "Out of memory for an argument";
2519 return -ENOMEM;
2520}
2521
2522static int get_mac(struct crypto_shash **hash, struct alg_spec *a, char **error,
2523 char *error_alg, char *error_key)
2524{
2525 int r;
2526
2527 if (a->alg_string) {
2528 *hash = crypto_alloc_shash(a->alg_string, 0, CRYPTO_ALG_ASYNC);
2529 if (IS_ERR(*hash)) {
2530 *error = error_alg;
2531 r = PTR_ERR(*hash);
2532 *hash = NULL;
2533 return r;
2534 }
2535
2536 if (a->key) {
2537 r = crypto_shash_setkey(*hash, a->key, a->key_size);
2538 if (r) {
2539 *error = error_key;
2540 return r;
2541 }
2542 }
2543 }
2544
2545 return 0;
2546}
2547
1aa0efd4
MS
2548static int create_journal(struct dm_integrity_c *ic, char **error)
2549{
2550 int r = 0;
2551 unsigned i;
2552 __u64 journal_pages, journal_desc_size, journal_tree_size;
56b67a4f
MP
2553 unsigned char *crypt_data = NULL;
2554
2555 ic->commit_ids[0] = cpu_to_le64(0x1111111111111111ULL);
2556 ic->commit_ids[1] = cpu_to_le64(0x2222222222222222ULL);
2557 ic->commit_ids[2] = cpu_to_le64(0x3333333333333333ULL);
2558 ic->commit_ids[3] = cpu_to_le64(0x4444444444444444ULL);
1aa0efd4
MS
2559
2560 journal_pages = roundup((__u64)ic->journal_sections * ic->journal_section_sectors,
2561 PAGE_SIZE >> SECTOR_SHIFT) >> (PAGE_SHIFT - SECTOR_SHIFT);
2562 journal_desc_size = journal_pages * sizeof(struct page_list);
2563 if (journal_pages >= totalram_pages - totalhigh_pages || journal_desc_size > ULONG_MAX) {
2564 *error = "Journal doesn't fit into memory";
2565 r = -ENOMEM;
2566 goto bad;
2567 }
2568 ic->journal_pages = journal_pages;
2569
2570 ic->journal = dm_integrity_alloc_page_list(ic);
2571 if (!ic->journal) {
2572 *error = "Could not allocate memory for journal";
2573 r = -ENOMEM;
2574 goto bad;
2575 }
2576 if (ic->journal_crypt_alg.alg_string) {
2577 unsigned ivsize, blocksize;
2578 struct journal_completion comp;
2579
2580 comp.ic = ic;
2581 ic->journal_crypt = crypto_alloc_skcipher(ic->journal_crypt_alg.alg_string, 0, 0);
2582 if (IS_ERR(ic->journal_crypt)) {
2583 *error = "Invalid journal cipher";
2584 r = PTR_ERR(ic->journal_crypt);
2585 ic->journal_crypt = NULL;
2586 goto bad;
2587 }
2588 ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
2589 blocksize = crypto_skcipher_blocksize(ic->journal_crypt);
2590
2591 if (ic->journal_crypt_alg.key) {
2592 r = crypto_skcipher_setkey(ic->journal_crypt, ic->journal_crypt_alg.key,
2593 ic->journal_crypt_alg.key_size);
2594 if (r) {
2595 *error = "Error setting encryption key";
2596 goto bad;
2597 }
2598 }
2599 DEBUG_print("cipher %s, block size %u iv size %u\n",
2600 ic->journal_crypt_alg.alg_string, blocksize, ivsize);
2601
2602 ic->journal_io = dm_integrity_alloc_page_list(ic);
2603 if (!ic->journal_io) {
2604 *error = "Could not allocate memory for journal io";
2605 r = -ENOMEM;
2606 goto bad;
2607 }
2608
2609 if (blocksize == 1) {
2610 struct scatterlist *sg;
2611 SKCIPHER_REQUEST_ON_STACK(req, ic->journal_crypt);
2612 unsigned char iv[ivsize];
2613 skcipher_request_set_tfm(req, ic->journal_crypt);
2614
2615 ic->journal_xor = dm_integrity_alloc_page_list(ic);
2616 if (!ic->journal_xor) {
2617 *error = "Could not allocate memory for journal xor";
2618 r = -ENOMEM;
2619 goto bad;
2620 }
2621
702a6204 2622 sg = kvmalloc((ic->journal_pages + 1) * sizeof(struct scatterlist), GFP_KERNEL);
1aa0efd4
MS
2623 if (!sg) {
2624 *error = "Unable to allocate sg list";
2625 r = -ENOMEM;
2626 goto bad;
2627 }
2628 sg_init_table(sg, ic->journal_pages + 1);
2629 for (i = 0; i < ic->journal_pages; i++) {
2630 char *va = lowmem_page_address(ic->journal_xor[i].page);
2631 clear_page(va);
2632 sg_set_buf(&sg[i], va, PAGE_SIZE);
2633 }
2634 sg_set_buf(&sg[i], &ic->commit_ids, sizeof ic->commit_ids);
2635 memset(iv, 0x00, ivsize);
2636
2637 skcipher_request_set_crypt(req, sg, sg, PAGE_SIZE * ic->journal_pages + sizeof ic->commit_ids, iv);
2638 comp.comp = COMPLETION_INITIALIZER_ONSTACK(comp.comp);
2639 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
2640 if (do_crypt(true, req, &comp))
2641 wait_for_completion(&comp.comp);
2642 kvfree(sg);
2643 r = dm_integrity_failed(ic);
2644 if (r) {
2645 *error = "Unable to encrypt journal";
2646 goto bad;
2647 }
2648 DEBUG_bytes(lowmem_page_address(ic->journal_xor[0].page), 64, "xor data");
2649
2650 crypto_free_skcipher(ic->journal_crypt);
2651 ic->journal_crypt = NULL;
2652 } else {
2653 SKCIPHER_REQUEST_ON_STACK(req, ic->journal_crypt);
2654 unsigned char iv[ivsize];
2655 unsigned crypt_len = roundup(ivsize, blocksize);
56b67a4f
MP
2656
2657 crypt_data = kmalloc(crypt_len, GFP_KERNEL);
2658 if (!crypt_data) {
2659 *error = "Unable to allocate crypt data";
2660 r = -ENOMEM;
2661 goto bad;
2662 }
1aa0efd4
MS
2663
2664 skcipher_request_set_tfm(req, ic->journal_crypt);
2665
2666 ic->journal_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal);
2667 if (!ic->journal_scatterlist) {
2668 *error = "Unable to allocate sg list";
2669 r = -ENOMEM;
2670 goto bad;
2671 }
2672 ic->journal_io_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal_io);
2673 if (!ic->journal_io_scatterlist) {
2674 *error = "Unable to allocate sg list";
2675 r = -ENOMEM;
2676 goto bad;
2677 }
702a6204 2678 ic->sk_requests = kvmalloc(ic->journal_sections * sizeof(struct skcipher_request *), GFP_KERNEL | __GFP_ZERO);
1aa0efd4
MS
2679 if (!ic->sk_requests) {
2680 *error = "Unable to allocate sk requests";
2681 r = -ENOMEM;
2682 goto bad;
2683 }
2684 for (i = 0; i < ic->journal_sections; i++) {
2685 struct scatterlist sg;
2686 struct skcipher_request *section_req;
2687 __u32 section_le = cpu_to_le32(i);
2688
2689 memset(iv, 0x00, ivsize);
2690 memset(crypt_data, 0x00, crypt_len);
2691 memcpy(crypt_data, &section_le, min((size_t)crypt_len, sizeof(section_le)));
2692
2693 sg_init_one(&sg, crypt_data, crypt_len);
2694 skcipher_request_set_crypt(req, &sg, &sg, crypt_len, iv);
2695 comp.comp = COMPLETION_INITIALIZER_ONSTACK(comp.comp);
2696 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
2697 if (do_crypt(true, req, &comp))
2698 wait_for_completion(&comp.comp);
2699
2700 r = dm_integrity_failed(ic);
2701 if (r) {
2702 *error = "Unable to generate iv";
2703 goto bad;
2704 }
2705
2706 section_req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
2707 if (!section_req) {
2708 *error = "Unable to allocate crypt request";
2709 r = -ENOMEM;
2710 goto bad;
2711 }
2712 section_req->iv = kmalloc(ivsize * 2, GFP_KERNEL);
2713 if (!section_req->iv) {
2714 skcipher_request_free(section_req);
2715 *error = "Unable to allocate iv";
2716 r = -ENOMEM;
2717 goto bad;
2718 }
2719 memcpy(section_req->iv + ivsize, crypt_data, ivsize);
2720 section_req->cryptlen = (size_t)ic->journal_section_sectors << SECTOR_SHIFT;
2721 ic->sk_requests[i] = section_req;
2722 DEBUG_bytes(crypt_data, ivsize, "iv(%u)", i);
2723 }
2724 }
2725 }
2726
2727 for (i = 0; i < N_COMMIT_IDS; i++) {
2728 unsigned j;
2729retest_commit_id:
2730 for (j = 0; j < i; j++) {
2731 if (ic->commit_ids[j] == ic->commit_ids[i]) {
2732 ic->commit_ids[i] = cpu_to_le64(le64_to_cpu(ic->commit_ids[i]) + 1);
2733 goto retest_commit_id;
2734 }
2735 }
2736 DEBUG_print("commit id %u: %016llx\n", i, ic->commit_ids[i]);
2737 }
2738
2739 journal_tree_size = (__u64)ic->journal_entries * sizeof(struct journal_node);
2740 if (journal_tree_size > ULONG_MAX) {
2741 *error = "Journal doesn't fit into memory";
2742 r = -ENOMEM;
2743 goto bad;
2744 }
702a6204 2745 ic->journal_tree = kvmalloc(journal_tree_size, GFP_KERNEL);
1aa0efd4
MS
2746 if (!ic->journal_tree) {
2747 *error = "Could not allocate memory for journal tree";
2748 r = -ENOMEM;
2749 }
2750bad:
56b67a4f 2751 kfree(crypt_data);
1aa0efd4
MS
2752 return r;
2753}
2754
7eada909 2755/*
56b67a4f 2756 * Construct a integrity mapping
7eada909
MP
2757 *
2758 * Arguments:
2759 * device
2760 * offset from the start of the device
2761 * tag size
56b67a4f 2762 * D - direct writes, J - journal writes, R - recovery mode
7eada909
MP
2763 * number of optional arguments
2764 * optional arguments:
56b67a4f
MP
2765 * journal_sectors
2766 * interleave_sectors
2767 * buffer_sectors
2768 * journal_watermark
2769 * commit_time
2770 * internal_hash
2771 * journal_crypt
2772 * journal_mac
9d609f85 2773 * block_size
7eada909
MP
2774 */
2775static int dm_integrity_ctr(struct dm_target *ti, unsigned argc, char **argv)
2776{
2777 struct dm_integrity_c *ic;
2778 char dummy;
2779 int r;
7eada909
MP
2780 unsigned extra_args;
2781 struct dm_arg_set as;
2782 static struct dm_arg _args[] = {
9d609f85 2783 {0, 9, "Invalid number of feature args"},
7eada909
MP
2784 };
2785 unsigned journal_sectors, interleave_sectors, buffer_sectors, journal_watermark, sync_msec;
2786 bool should_write_sb;
7eada909
MP
2787 __u64 threshold;
2788 unsigned long long start;
2789
2790#define DIRECT_ARGUMENTS 4
2791
2792 if (argc <= DIRECT_ARGUMENTS) {
2793 ti->error = "Invalid argument count";
2794 return -EINVAL;
2795 }
2796
2797 ic = kzalloc(sizeof(struct dm_integrity_c), GFP_KERNEL);
2798 if (!ic) {
2799 ti->error = "Cannot allocate integrity context";
2800 return -ENOMEM;
2801 }
2802 ti->private = ic;
2803 ti->per_io_data_size = sizeof(struct dm_integrity_io);
2804
7eada909
MP
2805 ic->in_progress = RB_ROOT;
2806 init_waitqueue_head(&ic->endio_wait);
2807 bio_list_init(&ic->flush_bio_list);
2808 init_waitqueue_head(&ic->copy_to_journal_wait);
2809 init_completion(&ic->crypto_backoff);
2810
2811 r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &ic->dev);
2812 if (r) {
2813 ti->error = "Device lookup failed";
2814 goto bad;
2815 }
2816
2817 if (sscanf(argv[1], "%llu%c", &start, &dummy) != 1 || start != (sector_t)start) {
2818 ti->error = "Invalid starting offset";
2819 r = -EINVAL;
2820 goto bad;
2821 }
2822 ic->start = start;
2823
2824 if (strcmp(argv[2], "-")) {
2825 if (sscanf(argv[2], "%u%c", &ic->tag_size, &dummy) != 1 || !ic->tag_size) {
2826 ti->error = "Invalid tag size";
2827 r = -EINVAL;
2828 goto bad;
2829 }
2830 }
2831
c2bcb2b7 2832 if (!strcmp(argv[3], "J") || !strcmp(argv[3], "D") || !strcmp(argv[3], "R"))
7eada909
MP
2833 ic->mode = argv[3][0];
2834 else {
56b67a4f 2835 ti->error = "Invalid mode (expecting J, D, R)";
7eada909
MP
2836 r = -EINVAL;
2837 goto bad;
2838 }
2839
2840 ic->device_sectors = i_size_read(ic->dev->bdev->bd_inode) >> SECTOR_SHIFT;
2841 journal_sectors = min((sector_t)DEFAULT_MAX_JOURNAL_SECTORS,
2842 ic->device_sectors >> DEFAULT_JOURNAL_SIZE_FACTOR);
2843 interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
2844 buffer_sectors = DEFAULT_BUFFER_SECTORS;
2845 journal_watermark = DEFAULT_JOURNAL_WATERMARK;
2846 sync_msec = DEFAULT_SYNC_MSEC;
9d609f85 2847 ic->sectors_per_block = 1;
7eada909
MP
2848
2849 as.argc = argc - DIRECT_ARGUMENTS;
2850 as.argv = argv + DIRECT_ARGUMENTS;
2851 r = dm_read_arg_group(_args, &as, &extra_args, &ti->error);
2852 if (r)
2853 goto bad;
2854
2855 while (extra_args--) {
2856 const char *opt_string;
2857 unsigned val;
2858 opt_string = dm_shift_arg(&as);
2859 if (!opt_string) {
2860 r = -EINVAL;
2861 ti->error = "Not enough feature arguments";
2862 goto bad;
2863 }
56b67a4f 2864 if (sscanf(opt_string, "journal_sectors:%u%c", &val, &dummy) == 1)
7eada909 2865 journal_sectors = val;
56b67a4f 2866 else if (sscanf(opt_string, "interleave_sectors:%u%c", &val, &dummy) == 1)
7eada909 2867 interleave_sectors = val;
56b67a4f 2868 else if (sscanf(opt_string, "buffer_sectors:%u%c", &val, &dummy) == 1)
7eada909 2869 buffer_sectors = val;
56b67a4f 2870 else if (sscanf(opt_string, "journal_watermark:%u%c", &val, &dummy) == 1 && val <= 100)
7eada909 2871 journal_watermark = val;
56b67a4f 2872 else if (sscanf(opt_string, "commit_time:%u%c", &val, &dummy) == 1)
7eada909 2873 sync_msec = val;
9d609f85
MP
2874 else if (sscanf(opt_string, "block_size:%u%c", &val, &dummy) == 1) {
2875 if (val < 1 << SECTOR_SHIFT ||
2876 val > MAX_SECTORS_PER_BLOCK << SECTOR_SHIFT ||
2877 (val & (val -1))) {
2878 r = -EINVAL;
2879 ti->error = "Invalid block_size argument";
2880 goto bad;
2881 }
2882 ic->sectors_per_block = val >> SECTOR_SHIFT;
2883 } else if (!memcmp(opt_string, "internal_hash:", strlen("internal_hash:"))) {
7eada909 2884 r = get_alg_and_key(opt_string, &ic->internal_hash_alg, &ti->error,
56b67a4f 2885 "Invalid internal_hash argument");
7eada909
MP
2886 if (r)
2887 goto bad;
56b67a4f 2888 } else if (!memcmp(opt_string, "journal_crypt:", strlen("journal_crypt:"))) {
7eada909 2889 r = get_alg_and_key(opt_string, &ic->journal_crypt_alg, &ti->error,
56b67a4f 2890 "Invalid journal_crypt argument");
7eada909
MP
2891 if (r)
2892 goto bad;
56b67a4f 2893 } else if (!memcmp(opt_string, "journal_mac:", strlen("journal_mac:"))) {
7eada909 2894 r = get_alg_and_key(opt_string, &ic->journal_mac_alg, &ti->error,
56b67a4f 2895 "Invalid journal_mac argument");
7eada909
MP
2896 if (r)
2897 goto bad;
2898 } else {
2899 r = -EINVAL;
2900 ti->error = "Invalid argument";
2901 goto bad;
2902 }
2903 }
2904
2905 r = get_mac(&ic->internal_hash, &ic->internal_hash_alg, &ti->error,
2906 "Invalid internal hash", "Error setting internal hash key");
2907 if (r)
2908 goto bad;
2909
2910 r = get_mac(&ic->journal_mac, &ic->journal_mac_alg, &ti->error,
2911 "Invalid journal mac", "Error setting journal mac key");
2912 if (r)
2913 goto bad;
2914
2915 if (!ic->tag_size) {
2916 if (!ic->internal_hash) {
2917 ti->error = "Unknown tag size";
2918 r = -EINVAL;
2919 goto bad;
2920 }
2921 ic->tag_size = crypto_shash_digestsize(ic->internal_hash);
2922 }
2923 if (ic->tag_size > MAX_TAG_SIZE) {
2924 ti->error = "Too big tag size";
2925 r = -EINVAL;
2926 goto bad;
2927 }
2928 if (!(ic->tag_size & (ic->tag_size - 1)))
2929 ic->log2_tag_size = __ffs(ic->tag_size);
2930 else
2931 ic->log2_tag_size = -1;
2932
2933 ic->autocommit_jiffies = msecs_to_jiffies(sync_msec);
2934 ic->autocommit_msec = sync_msec;
2935 setup_timer(&ic->autocommit_timer, autocommit_fn, (unsigned long)ic);
2936
2937 ic->io = dm_io_client_create();
2938 if (IS_ERR(ic->io)) {
2939 r = PTR_ERR(ic->io);
2940 ic->io = NULL;
2941 ti->error = "Cannot allocate dm io";
2942 goto bad;
2943 }
2944
2945 ic->journal_io_mempool = mempool_create_slab_pool(JOURNAL_IO_MEMPOOL, journal_io_cache);
2946 if (!ic->journal_io_mempool) {
2947 r = -ENOMEM;
2948 ti->error = "Cannot allocate mempool";
2949 goto bad;
2950 }
2951
2952 ic->metadata_wq = alloc_workqueue("dm-integrity-metadata",
2953 WQ_MEM_RECLAIM, METADATA_WORKQUEUE_MAX_ACTIVE);
2954 if (!ic->metadata_wq) {
2955 ti->error = "Cannot allocate workqueue";
2956 r = -ENOMEM;
2957 goto bad;
2958 }
2959
2960 /*
2961 * If this workqueue were percpu, it would cause bio reordering
2962 * and reduced performance.
2963 */
2964 ic->wait_wq = alloc_workqueue("dm-integrity-wait", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
2965 if (!ic->wait_wq) {
2966 ti->error = "Cannot allocate workqueue";
2967 r = -ENOMEM;
2968 goto bad;
2969 }
2970
2971 ic->commit_wq = alloc_workqueue("dm-integrity-commit", WQ_MEM_RECLAIM, 1);
2972 if (!ic->commit_wq) {
2973 ti->error = "Cannot allocate workqueue";
2974 r = -ENOMEM;
2975 goto bad;
2976 }
2977 INIT_WORK(&ic->commit_work, integrity_commit);
2978
2979 if (ic->mode == 'J') {
2980 ic->writer_wq = alloc_workqueue("dm-integrity-writer", WQ_MEM_RECLAIM, 1);
2981 if (!ic->writer_wq) {
2982 ti->error = "Cannot allocate workqueue";
2983 r = -ENOMEM;
2984 goto bad;
2985 }
2986 INIT_WORK(&ic->writer_work, integrity_writer);
2987 }
2988
2989 ic->sb = alloc_pages_exact(SB_SECTORS << SECTOR_SHIFT, GFP_KERNEL);
2990 if (!ic->sb) {
2991 r = -ENOMEM;
2992 ti->error = "Cannot allocate superblock area";
2993 goto bad;
2994 }
2995
2996 r = sync_rw_sb(ic, REQ_OP_READ, 0);
2997 if (r) {
2998 ti->error = "Error reading superblock";
2999 goto bad;
3000 }
c2bcb2b7
MP
3001 should_write_sb = false;
3002 if (memcmp(ic->sb->magic, SB_MAGIC, 8)) {
3003 if (ic->mode != 'R') {
56b67a4f
MP
3004 if (memchr_inv(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT)) {
3005 r = -EINVAL;
3006 ti->error = "The device is not initialized";
3007 goto bad;
7eada909
MP
3008 }
3009 }
3010
3011 r = initialize_superblock(ic, journal_sectors, interleave_sectors);
3012 if (r) {
3013 ti->error = "Could not initialize superblock";
3014 goto bad;
3015 }
c2bcb2b7
MP
3016 if (ic->mode != 'R')
3017 should_write_sb = true;
7eada909
MP
3018 }
3019
3020 if (ic->sb->version != SB_VERSION) {
3021 r = -EINVAL;
3022 ti->error = "Unknown version";
3023 goto bad;
3024 }
3025 if (le16_to_cpu(ic->sb->integrity_tag_size) != ic->tag_size) {
3026 r = -EINVAL;
9d609f85
MP
3027 ti->error = "Tag size doesn't match the information in superblock";
3028 goto bad;
3029 }
3030 if (ic->sb->log2_sectors_per_block != __ffs(ic->sectors_per_block)) {
3031 r = -EINVAL;
3032 ti->error = "Block size doesn't match the information in superblock";
7eada909
MP
3033 goto bad;
3034 }
bc86a41e
MP
3035 if (!le32_to_cpu(ic->sb->journal_sections)) {
3036 r = -EINVAL;
3037 ti->error = "Corrupted superblock, journal_sections is 0";
3038 goto bad;
3039 }
7eada909 3040 /* make sure that ti->max_io_len doesn't overflow */
56b67a4f
MP
3041 if (ic->sb->log2_interleave_sectors < MIN_LOG2_INTERLEAVE_SECTORS ||
3042 ic->sb->log2_interleave_sectors > MAX_LOG2_INTERLEAVE_SECTORS) {
7eada909
MP
3043 r = -EINVAL;
3044 ti->error = "Invalid interleave_sectors in the superblock";
3045 goto bad;
3046 }
3047 ic->provided_data_sectors = le64_to_cpu(ic->sb->provided_data_sectors);
3048 if (ic->provided_data_sectors != le64_to_cpu(ic->sb->provided_data_sectors)) {
3049 /* test for overflow */
3050 r = -EINVAL;
3051 ti->error = "The superblock has 64-bit device size, but the kernel was compiled with 32-bit sectors";
3052 goto bad;
3053 }
3054 if (!!(ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC)) != !!ic->journal_mac_alg.alg_string) {
3055 r = -EINVAL;
3056 ti->error = "Journal mac mismatch";
3057 goto bad;
3058 }
3059 r = calculate_device_limits(ic);
3060 if (r) {
3061 ti->error = "The device is too small";
3062 goto bad;
3063 }
2ad50606
OM
3064 if (ti->len > ic->provided_data_sectors) {
3065 r = -EINVAL;
3066 ti->error = "Not enough provided sectors for requested mapping size";
3067 goto bad;
3068 }
7eada909
MP
3069
3070 if (!buffer_sectors)
3071 buffer_sectors = 1;
3072 ic->log2_buffer_sectors = min3((int)__fls(buffer_sectors), (int)__ffs(ic->metadata_run), 31 - SECTOR_SHIFT);
3073
3074 threshold = (__u64)ic->journal_entries * (100 - journal_watermark);
3075 threshold += 50;
3076 do_div(threshold, 100);
3077 ic->free_sectors_threshold = threshold;
3078
3079 DEBUG_print("initialized:\n");
3080 DEBUG_print(" integrity_tag_size %u\n", le16_to_cpu(ic->sb->integrity_tag_size));
3081 DEBUG_print(" journal_entry_size %u\n", ic->journal_entry_size);
3082 DEBUG_print(" journal_entries_per_sector %u\n", ic->journal_entries_per_sector);
3083 DEBUG_print(" journal_section_entries %u\n", ic->journal_section_entries);
3084 DEBUG_print(" journal_section_sectors %u\n", ic->journal_section_sectors);
3085 DEBUG_print(" journal_sections %u\n", (unsigned)le32_to_cpu(ic->sb->journal_sections));
3086 DEBUG_print(" journal_entries %u\n", ic->journal_entries);
3087 DEBUG_print(" log2_interleave_sectors %d\n", ic->sb->log2_interleave_sectors);
3088 DEBUG_print(" device_sectors 0x%llx\n", (unsigned long long)ic->device_sectors);
3089 DEBUG_print(" initial_sectors 0x%x\n", ic->initial_sectors);
3090 DEBUG_print(" metadata_run 0x%x\n", ic->metadata_run);
3091 DEBUG_print(" log2_metadata_run %d\n", ic->log2_metadata_run);
3092 DEBUG_print(" provided_data_sectors 0x%llx (%llu)\n", (unsigned long long)ic->provided_data_sectors,
3093 (unsigned long long)ic->provided_data_sectors);
3094 DEBUG_print(" log2_buffer_sectors %u\n", ic->log2_buffer_sectors);
3095
3096 ic->bufio = dm_bufio_client_create(ic->dev->bdev, 1U << (SECTOR_SHIFT + ic->log2_buffer_sectors),
3097 1, 0, NULL, NULL);
3098 if (IS_ERR(ic->bufio)) {
3099 r = PTR_ERR(ic->bufio);
3100 ti->error = "Cannot initialize dm-bufio";
3101 ic->bufio = NULL;
3102 goto bad;
3103 }
3104 dm_bufio_set_sector_offset(ic->bufio, ic->start + ic->initial_sectors);
3105
c2bcb2b7
MP
3106 if (ic->mode != 'R') {
3107 r = create_journal(ic, &ti->error);
3108 if (r)
3109 goto bad;
3110 }
7eada909
MP
3111
3112 if (should_write_sb) {
3113 int r;
3114
3115 init_journal(ic, 0, ic->journal_sections, 0);
3116 r = dm_integrity_failed(ic);
3117 if (unlikely(r)) {
3118 ti->error = "Error initializing journal";
3119 goto bad;
3120 }
3121 r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
3122 if (r) {
3123 ti->error = "Error initializing superblock";
3124 goto bad;
3125 }
3126 ic->just_formatted = true;
3127 }
3128
3129 r = dm_set_target_max_io_len(ti, 1U << ic->sb->log2_interleave_sectors);
3130 if (r)
3131 goto bad;
3132
3133 if (!ic->internal_hash)
3134 dm_integrity_set(ti, ic);
3135
3136 ti->num_flush_bios = 1;
3137 ti->flush_supported = true;
3138
3139 return 0;
3140bad:
3141 dm_integrity_dtr(ti);
3142 return r;
3143}
3144
3145static void dm_integrity_dtr(struct dm_target *ti)
3146{
3147 struct dm_integrity_c *ic = ti->private;
3148
3149 BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
3150
3151 if (ic->metadata_wq)
3152 destroy_workqueue(ic->metadata_wq);
3153 if (ic->wait_wq)
3154 destroy_workqueue(ic->wait_wq);
3155 if (ic->commit_wq)
3156 destroy_workqueue(ic->commit_wq);
3157 if (ic->writer_wq)
3158 destroy_workqueue(ic->writer_wq);
3159 if (ic->bufio)
3160 dm_bufio_client_destroy(ic->bufio);
3161 mempool_destroy(ic->journal_io_mempool);
3162 if (ic->io)
3163 dm_io_client_destroy(ic->io);
3164 if (ic->dev)
3165 dm_put_device(ti, ic->dev);
3166 dm_integrity_free_page_list(ic, ic->journal);
3167 dm_integrity_free_page_list(ic, ic->journal_io);
3168 dm_integrity_free_page_list(ic, ic->journal_xor);
3169 if (ic->journal_scatterlist)
3170 dm_integrity_free_journal_scatterlist(ic, ic->journal_scatterlist);
3171 if (ic->journal_io_scatterlist)
3172 dm_integrity_free_journal_scatterlist(ic, ic->journal_io_scatterlist);
3173 if (ic->sk_requests) {
3174 unsigned i;
3175
3176 for (i = 0; i < ic->journal_sections; i++) {
3177 struct skcipher_request *req = ic->sk_requests[i];
3178 if (req) {
3179 kzfree(req->iv);
3180 skcipher_request_free(req);
3181 }
3182 }
3183 kvfree(ic->sk_requests);
3184 }
3185 kvfree(ic->journal_tree);
3186 if (ic->sb)
3187 free_pages_exact(ic->sb, SB_SECTORS << SECTOR_SHIFT);
3188
3189 if (ic->internal_hash)
3190 crypto_free_shash(ic->internal_hash);
3191 free_alg(&ic->internal_hash_alg);
3192
3193 if (ic->journal_crypt)
3194 crypto_free_skcipher(ic->journal_crypt);
3195 free_alg(&ic->journal_crypt_alg);
3196
3197 if (ic->journal_mac)
3198 crypto_free_shash(ic->journal_mac);
3199 free_alg(&ic->journal_mac_alg);
3200
3201 kfree(ic);
3202}
3203
3204static struct target_type integrity_target = {
3205 .name = "integrity",
3206 .version = {1, 0, 0},
3207 .module = THIS_MODULE,
3208 .features = DM_TARGET_SINGLETON | DM_TARGET_INTEGRITY,
3209 .ctr = dm_integrity_ctr,
3210 .dtr = dm_integrity_dtr,
3211 .map = dm_integrity_map,
3212 .postsuspend = dm_integrity_postsuspend,
3213 .resume = dm_integrity_resume,
3214 .status = dm_integrity_status,
3215 .iterate_devices = dm_integrity_iterate_devices,
9d609f85 3216 .io_hints = dm_integrity_io_hints,
7eada909
MP
3217};
3218
3219int __init dm_integrity_init(void)
3220{
3221 int r;
3222
3223 journal_io_cache = kmem_cache_create("integrity_journal_io",
3224 sizeof(struct journal_io), 0, 0, NULL);
3225 if (!journal_io_cache) {
3226 DMERR("can't allocate journal io cache");
3227 return -ENOMEM;
3228 }
3229
3230 r = dm_register_target(&integrity_target);
3231
3232 if (r < 0)
3233 DMERR("register failed %d", r);
3234
3235 return r;
3236}
3237
3238void dm_integrity_exit(void)
3239{
3240 dm_unregister_target(&integrity_target);
3241 kmem_cache_destroy(journal_io_cache);
3242}
3243
3244module_init(dm_integrity_init);
3245module_exit(dm_integrity_exit);
3246
3247MODULE_AUTHOR("Milan Broz");
3248MODULE_AUTHOR("Mikulas Patocka");
3249MODULE_DESCRIPTION(DM_NAME " target for integrity tags extension");
3250MODULE_LICENSE("GPL");