blob: be3b6f42095c6d0a047d49ad97239d851a1f6566 [file] [log] [blame]
Mikulas Patocka7eada902017-01-04 20:23:53 +01001/*
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
Mikulas Patocka56b67a42017-04-18 16:51:50 -040030#define MIN_LOG2_INTERLEAVE_SECTORS 3
31#define MAX_LOG2_INTERLEAVE_SECTORS 31
Mikulas Patocka7eada902017-01-04 20:23:53 +010032#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
Mikulas Patocka9d609f82017-04-18 16:51:52 -040048#define MAX_SECTORS_PER_BLOCK 8
Mikulas Patocka7eada902017-01-04 20:23:53 +010049
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;
Mikulas Patocka9d609f82017-04-18 16:51:52 -040058 __u8 log2_sectors_per_block;
Mikulas Patocka7eada902017-01-04 20:23:53 +010059};
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;
Mikulas Patocka9d609f82017-04-18 16:51:52 -040076 commit_id_t last_bytes[0];
77 /* __u8 tag[0]; */
Mikulas Patocka7eada902017-01-04 20:23:53 +010078};
79
Mikulas Patocka9d609f82017-04-18 16:51:52 -040080#define journal_entry_tag(ic, je) ((__u8 *)&(je)->last_bytes[(ic)->sectors_per_block])
81
Mikulas Patocka7eada902017-01-04 20:23:53 +010082#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
Mikulas Patocka9d609f82017-04-18 16:51:52 -0400107#define MAX_TAG_SIZE (JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR - offsetof(struct journal_entry, last_bytes[MAX_SECTORS_PER_BLOCK]))
Mikulas Patocka7eada902017-01-04 20:23:53 +0100108
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;
Mikulas Patocka9d609f82017-04-18 16:51:52 -0400169 unsigned short journal_section_sectors;
Mikulas Patocka7eada902017-01-04 20:23:53 +0100170 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;
Mikulas Patocka9d609f82017-04-18 16:51:52 -0400177 __u8 sectors_per_block;
Mikulas Patocka7eada902017-01-04 20:23:53 +0100178
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;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200249 blk_status_t bi_status;
Mikulas Patocka7eada902017-01-04 20:23:53 +0100250
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
Mikulas Patocka9d609f82017-04-18 16:51:52 -0400340#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
Mikulas Patocka7eada902017-01-04 20:23:53 +0100346static __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
Mikulas Patocka9d609f82017-04-18 16:51:52 -0400359 sector_to_block(ic, offset);
360
Mikulas Patocka7eada902017-01-04 20:23:53 +0100361 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
Mikulas Patocka56b67a42017-04-18 16:51:50 -0400430 access_journal_check(ic, section, offset, false, "page_list_location");
Mikulas Patocka7eada902017-01-04 20:23:53 +0100431
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{
Mikulas Patocka9d609f82017-04-18 16:51:52 -0400475 n <<= ic->sb->log2_sectors_per_block;
Mikulas Patocka7eada902017-01-04 20:23:53 +0100476
Mikulas Patocka9d609f82017-04-18 16:51:52 -0400477 n += JOURNAL_BLOCK_SECTORS;
478
479 access_journal_check(ic, section, n, false, "access_journal_data");
480
481 return access_journal(ic, section, n);
Mikulas Patocka7eada902017-01-04 20:23:53 +0100482}
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 }
Jan Karaff0361b2017-05-31 09:44:32 +0200786 rw_journal(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, commit_start,
787 commit_sections, &io_comp);
Mikulas Patocka7eada902017-01-04 20:23:53 +0100788 } 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
Mikulas Patocka9d609f82017-04-18 16:51:52 -0400833 BUG_ON((target | n_sectors | offset) & (unsigned)(ic->sectors_per_block - 1));
834
Mikulas Patocka7eada902017-01-04 20:23:53 +0100835 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
Mikulas Patocka9d609f82017-04-18 16:51:52 -0400869 BUG_ON((new_range->logical_sector | new_range->n_sectors) & (unsigned)(ic->sectors_per_block - 1));
870
Mikulas Patocka7eada902017-01-04 20:23:53 +0100871 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;
Mike Snitzer7def52b2017-06-19 10:55:47 -04001108 unsigned long flags;
1109
1110 spin_lock_irqsave(&ic->endio_wait.lock, flags);
Mikulas Patocka7eada902017-01-04 20:23:53 +01001111 bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1112 bio_list_add(&ic->flush_bio_list, bio);
Mike Snitzer7def52b2017-06-19 10:55:47 -04001113 spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1114
Mikulas Patocka7eada902017-01-04 20:23:53 +01001115 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);
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +02001121 if (unlikely(r) && !bio->bi_status)
1122 bio->bi_status = errno_to_blk_status(r);
Mikulas Patocka7eada902017-01-04 20:23:53 +01001123 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
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +02001130 if (unlikely(dio->fua) && likely(!bio->bi_status) && likely(!dm_integrity_failed(ic)))
Mikulas Patocka7eada902017-01-04 20:23:53 +01001131 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
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +02001149 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)) {
Mikulas Patocka7eada902017-01-04 20:23:53 +01001152 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
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001203 r = crypto_shash_update(req, data, ic->sectors_per_block << SECTOR_SHIFT);
Mikulas Patocka7eada902017-01-04 20:23:53 +01001204 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;
Mikulas Patocka56b67a42017-04-18 16:51:50 -04001239 unsigned extra_space = unlikely(digest_size > ic->tag_size) ? digest_size - ic->tag_size : 0;
Mikulas Patocka7eada902017-01-04 20:23:53 +01001240 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
Mikulas Patockac2bcb2b2017-03-17 12:40:51 -04001244 if (unlikely(ic->mode == 'R'))
1245 goto skip_io;
1246
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001247 checksums = kmalloc((PAGE_SIZE >> SECTOR_SHIFT >> ic->sb->log2_sectors_per_block) * ic->tag_size + extra_space,
Mikulas Patocka7eada902017-01-04 20:23:53 +01001248 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;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001263 sectors_to_process -= ic->sectors_per_block;
1264 pos += ic->sectors_per_block << SECTOR_SHIFT;
1265 sector += ic->sectors_per_block;
Mikulas Patocka7eada902017-01-04 20:23:53 +01001266 } 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;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001300 unsigned data_to_process = dio->range.n_sectors;
1301 sector_to_block(ic, data_to_process);
1302 data_to_process *= ic->tag_size;
Mikulas Patocka7eada902017-01-04 20:23:53 +01001303
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 }
Mikulas Patockac2bcb2b2017-03-17 12:40:51 -04001321skip_io:
Mikulas Patocka7eada902017-01-04 20:23:53 +01001322 dec_in_flight(dio);
1323 return;
1324error:
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +02001325 dio->bi_status = errno_to_blk_status(r);
Mikulas Patocka7eada902017-01-04 20:23:53 +01001326 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));
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001333 struct bio_integrity_payload *bip;
Mikulas Patocka7eada902017-01-04 20:23:53 +01001334
1335 sector_t area, offset;
1336
1337 dio->ic = ic;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +02001338 dio->bi_status = 0;
Mikulas Patocka7eada902017-01-04 20:23:53 +01001339
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);
Christoph Hellwig846785e2017-06-03 09:38:02 +02001359 return DM_MAPIO_KILL;
Mikulas Patocka7eada902017-01-04 20:23:53 +01001360 }
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001361 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));
Christoph Hellwig846785e2017-06-03 09:38:02 +02001365 return DM_MAPIO_KILL;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001366 }
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);
Christoph Hellwig846785e2017-06-03 09:38:02 +02001375 return DM_MAPIO_KILL;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001376 }
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);
Christoph Hellwig846785e2017-06-03 09:38:02 +02001390 return DM_MAPIO_KILL;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001391 }
1392 }
1393 } else {
1394 if (unlikely(bip != NULL)) {
1395 DMERR("Unexpected integrity data when using internal hash");
Christoph Hellwig846785e2017-06-03 09:38:02 +02001396 return DM_MAPIO_KILL;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001397 }
1398 }
Mikulas Patocka7eada902017-01-04 20:23:53 +01001399
Mikulas Patockac2bcb2b2017-03-17 12:40:51 -04001400 if (unlikely(ic->mode == 'R') && unlikely(dio->write))
Christoph Hellwig846785e2017-06-03 09:38:02 +02001401 return DM_MAPIO_KILL;
Mikulas Patockac2bcb2b2017-03-17 12:40:51 -04001402
Mikulas Patocka7eada902017-01-04 20:23:53 +01001403 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;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001438 char *mem_ptr;
1439 unsigned s;
Mikulas Patocka7eada902017-01-04 20:23:53 +01001440
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);
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001451 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);
Mikulas Patocka7eada902017-01-04 20:23:53 +01001459#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);
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001464 if (unlikely(memcmp(checksums_onstack, journal_entry_tag(ic, je), ic->tag_size))) {
Mikulas Patocka7eada902017-01-04 20:23:53 +01001465 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;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001475 char *tag_ptr = journal_entry_tag(ic, je);
Mikulas Patocka7eada902017-01-04 20:23:53 +01001476
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;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001498 unsigned s;
Mikulas Patocka7eada902017-01-04 20:23:53 +01001499
1500 js = access_journal_data(ic, journal_section, journal_entry);
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001501 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);
Mikulas Patocka7eada902017-01-04 20:23:53 +01001507
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);
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001513 memcpy(journal_entry_tag(ic, je), checksums_onstack, ic->tag_size);
Mikulas Patocka7eada902017-01-04 20:23:53 +01001514 } else
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001515 integrity_sector_checksum(ic, logical_sector, (char *)js, journal_entry_tag(ic, je));
Mikulas Patocka7eada902017-01-04 20:23:53 +01001516 }
1517
1518 journal_entry_set_sector(je, logical_sector);
1519 }
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001520 logical_sector += ic->sectors_per_block;
Mikulas Patocka7eada902017-01-04 20:23:53 +01001521
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
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001529 bv.bv_offset += ic->sectors_per_block << SECTOR_SHIFT;
1530 } while (bv.bv_len -= ic->sectors_per_block << SECTOR_SHIFT);
Mikulas Patocka7eada902017-01-04 20:23:53 +01001531
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;
Mikulas Patocka9dd59722017-07-19 11:23:40 -04001590 unsigned ws, we, range_sectors;
Mikulas Patocka7eada902017-01-04 20:23:53 +01001591
Mikulas Patocka9dd59722017-07-19 11:23:40 -04001592 dio->range.n_sectors = min(dio->range.n_sectors,
1593 ic->free_sectors << ic->sb->log2_sectors_per_block);
Mikulas Patocka7eada902017-01-04 20:23:53 +01001594 if (unlikely(!dio->range.n_sectors))
1595 goto sleep;
Mikulas Patocka9dd59722017-07-19 11:23:40 -04001596 range_sectors = dio->range.n_sectors >> ic->sb->log2_sectors_per_block;
1597 ic->free_sectors -= range_sectors;
Mikulas Patocka7eada902017-01-04 20:23:53 +01001598 journal_section = ic->free_section;
1599 journal_entry = ic->free_section_entry;
1600
Mikulas Patocka9dd59722017-07-19 11:23:40 -04001601 next_entry = ic->free_section_entry + range_sectors;
Mikulas Patocka7eada902017-01-04 20:23:53 +01001602 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;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001610 i = 0;
1611 do {
Mikulas Patocka7eada902017-01-04 20:23:53 +01001612 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 }
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001628 } while ((i += ic->sectors_per_block) < dio->range.n_sectors);
Mikulas Patocka7eada902017-01-04 20:23:53 +01001629
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;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001640 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))
Mikulas Patocka7eada902017-01-04 20:23:53 +01001643 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);
1700 integrity_metadata(&dio->work);
1701 } else {
1702 INIT_WORK(&dio->work, integrity_metadata);
1703 queue_work(ic->metadata_wq, &dio->work);
1704 }
1705
1706 return;
1707
1708journal_read_write:
1709 if (unlikely(__journal_read_write(dio, bio, journal_section, journal_entry)))
1710 goto lock_retry;
1711
1712 do_endio_flush(ic, dio);
1713}
1714
1715
1716static void integrity_bio_wait(struct work_struct *w)
1717{
1718 struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
1719
1720 dm_integrity_map_continue(dio, false);
1721}
1722
1723static void pad_uncommitted(struct dm_integrity_c *ic)
1724{
1725 if (ic->free_section_entry) {
1726 ic->free_sectors -= ic->journal_section_entries - ic->free_section_entry;
1727 ic->free_section_entry = 0;
1728 ic->free_section++;
1729 wraparound_section(ic, &ic->free_section);
1730 ic->n_uncommitted_sections++;
1731 }
1732}
1733
1734static void integrity_commit(struct work_struct *w)
1735{
1736 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, commit_work);
1737 unsigned commit_start, commit_sections;
1738 unsigned i, j, n;
1739 struct bio *flushes;
1740
1741 del_timer(&ic->autocommit_timer);
1742
1743 spin_lock_irq(&ic->endio_wait.lock);
1744 flushes = bio_list_get(&ic->flush_bio_list);
1745 if (unlikely(ic->mode != 'J')) {
1746 spin_unlock_irq(&ic->endio_wait.lock);
1747 dm_integrity_flush_buffers(ic);
1748 goto release_flush_bios;
1749 }
1750
1751 pad_uncommitted(ic);
1752 commit_start = ic->uncommitted_section;
1753 commit_sections = ic->n_uncommitted_sections;
1754 spin_unlock_irq(&ic->endio_wait.lock);
1755
1756 if (!commit_sections)
1757 goto release_flush_bios;
1758
1759 i = commit_start;
1760 for (n = 0; n < commit_sections; n++) {
1761 for (j = 0; j < ic->journal_section_entries; j++) {
1762 struct journal_entry *je;
1763 je = access_journal_entry(ic, i, j);
1764 io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
1765 }
1766 for (j = 0; j < ic->journal_section_sectors; j++) {
1767 struct journal_sector *js;
1768 js = access_journal(ic, i, j);
1769 js->commit_id = dm_integrity_commit_id(ic, i, j, ic->commit_seq);
1770 }
1771 i++;
1772 if (unlikely(i >= ic->journal_sections))
1773 ic->commit_seq = next_commit_seq(ic->commit_seq);
1774 wraparound_section(ic, &i);
1775 }
1776 smp_rmb();
1777
1778 write_journal(ic, commit_start, commit_sections);
1779
1780 spin_lock_irq(&ic->endio_wait.lock);
1781 ic->uncommitted_section += commit_sections;
1782 wraparound_section(ic, &ic->uncommitted_section);
1783 ic->n_uncommitted_sections -= commit_sections;
1784 ic->n_committed_sections += commit_sections;
1785 spin_unlock_irq(&ic->endio_wait.lock);
1786
1787 if (ACCESS_ONCE(ic->free_sectors) <= ic->free_sectors_threshold)
1788 queue_work(ic->writer_wq, &ic->writer_work);
1789
1790release_flush_bios:
1791 while (flushes) {
1792 struct bio *next = flushes->bi_next;
1793 flushes->bi_next = NULL;
1794 do_endio(ic, flushes);
1795 flushes = next;
1796 }
1797}
1798
1799static void complete_copy_from_journal(unsigned long error, void *context)
1800{
1801 struct journal_io *io = context;
1802 struct journal_completion *comp = io->comp;
1803 struct dm_integrity_c *ic = comp->ic;
1804 remove_range(ic, &io->range);
1805 mempool_free(io, ic->journal_io_mempool);
1806 if (unlikely(error != 0))
1807 dm_integrity_io_error(ic, "copying from journal", -EIO);
1808 complete_journal_op(comp);
1809}
1810
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001811static void restore_last_bytes(struct dm_integrity_c *ic, struct journal_sector *js,
1812 struct journal_entry *je)
1813{
1814 unsigned s = 0;
1815 do {
1816 js->commit_id = je->last_bytes[s];
1817 js++;
1818 } while (++s < ic->sectors_per_block);
1819}
1820
Mikulas Patocka7eada902017-01-04 20:23:53 +01001821static void do_journal_write(struct dm_integrity_c *ic, unsigned write_start,
1822 unsigned write_sections, bool from_replay)
1823{
1824 unsigned i, j, n;
1825 struct journal_completion comp;
Mikulas Patockaa7c3e62b2017-07-19 11:24:08 -04001826 struct blk_plug plug;
1827
1828 blk_start_plug(&plug);
Mikulas Patocka7eada902017-01-04 20:23:53 +01001829
1830 comp.ic = ic;
1831 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
1832 comp.comp = COMPLETION_INITIALIZER_ONSTACK(comp.comp);
1833
1834 i = write_start;
1835 for (n = 0; n < write_sections; n++, i++, wraparound_section(ic, &i)) {
1836#ifndef INTERNAL_VERIFY
1837 if (unlikely(from_replay))
1838#endif
1839 rw_section_mac(ic, i, false);
1840 for (j = 0; j < ic->journal_section_entries; j++) {
1841 struct journal_entry *je = access_journal_entry(ic, i, j);
1842 sector_t sec, area, offset;
1843 unsigned k, l, next_loop;
1844 sector_t metadata_block;
1845 unsigned metadata_offset;
1846 struct journal_io *io;
1847
1848 if (journal_entry_is_unused(je))
1849 continue;
1850 BUG_ON(unlikely(journal_entry_is_inprogress(je)) && !from_replay);
1851 sec = journal_entry_get_sector(je);
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001852 if (unlikely(from_replay)) {
1853 if (unlikely(sec & (unsigned)(ic->sectors_per_block - 1))) {
1854 dm_integrity_io_error(ic, "invalid sector in journal", -EIO);
1855 sec &= ~(sector_t)(ic->sectors_per_block - 1);
1856 }
1857 }
Mikulas Patocka7eada902017-01-04 20:23:53 +01001858 get_area_and_offset(ic, sec, &area, &offset);
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001859 restore_last_bytes(ic, access_journal_data(ic, i, j), je);
Mikulas Patocka7eada902017-01-04 20:23:53 +01001860 for (k = j + 1; k < ic->journal_section_entries; k++) {
1861 struct journal_entry *je2 = access_journal_entry(ic, i, k);
1862 sector_t sec2, area2, offset2;
1863 if (journal_entry_is_unused(je2))
1864 break;
1865 BUG_ON(unlikely(journal_entry_is_inprogress(je2)) && !from_replay);
1866 sec2 = journal_entry_get_sector(je2);
1867 get_area_and_offset(ic, sec2, &area2, &offset2);
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001868 if (area2 != area || offset2 != offset + ((k - j) << ic->sb->log2_sectors_per_block))
Mikulas Patocka7eada902017-01-04 20:23:53 +01001869 break;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001870 restore_last_bytes(ic, access_journal_data(ic, i, k), je2);
Mikulas Patocka7eada902017-01-04 20:23:53 +01001871 }
1872 next_loop = k - 1;
1873
1874 io = mempool_alloc(ic->journal_io_mempool, GFP_NOIO);
1875 io->comp = &comp;
1876 io->range.logical_sector = sec;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001877 io->range.n_sectors = (k - j) << ic->sb->log2_sectors_per_block;
Mikulas Patocka7eada902017-01-04 20:23:53 +01001878
1879 spin_lock_irq(&ic->endio_wait.lock);
1880 while (unlikely(!add_new_range(ic, &io->range)))
1881 sleep_on_endio_wait(ic);
1882
1883 if (likely(!from_replay)) {
1884 struct journal_node *section_node = &ic->journal_tree[i * ic->journal_section_entries];
1885
1886 /* don't write if there is newer committed sector */
1887 while (j < k && find_newer_committed_node(ic, &section_node[j])) {
1888 struct journal_entry *je2 = access_journal_entry(ic, i, j);
1889
1890 journal_entry_set_unused(je2);
1891 remove_journal_node(ic, &section_node[j]);
1892 j++;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001893 sec += ic->sectors_per_block;
1894 offset += ic->sectors_per_block;
Mikulas Patocka7eada902017-01-04 20:23:53 +01001895 }
1896 while (j < k && find_newer_committed_node(ic, &section_node[k - 1])) {
1897 struct journal_entry *je2 = access_journal_entry(ic, i, k - 1);
1898
1899 journal_entry_set_unused(je2);
1900 remove_journal_node(ic, &section_node[k - 1]);
1901 k--;
1902 }
1903 if (j == k) {
1904 remove_range_unlocked(ic, &io->range);
1905 spin_unlock_irq(&ic->endio_wait.lock);
1906 mempool_free(io, ic->journal_io_mempool);
1907 goto skip_io;
1908 }
1909 for (l = j; l < k; l++) {
1910 remove_journal_node(ic, &section_node[l]);
1911 }
1912 }
1913 spin_unlock_irq(&ic->endio_wait.lock);
1914
1915 metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
1916 for (l = j; l < k; l++) {
1917 int r;
1918 struct journal_entry *je2 = access_journal_entry(ic, i, l);
1919
1920 if (
1921#ifndef INTERNAL_VERIFY
1922 unlikely(from_replay) &&
1923#endif
1924 ic->internal_hash) {
Mikulas Patocka56b67a42017-04-18 16:51:50 -04001925 char test_tag[max(crypto_shash_digestsize(ic->internal_hash), ic->tag_size)];
Mikulas Patocka7eada902017-01-04 20:23:53 +01001926
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001927 integrity_sector_checksum(ic, sec + ((l - j) << ic->sb->log2_sectors_per_block),
Mikulas Patocka7eada902017-01-04 20:23:53 +01001928 (char *)access_journal_data(ic, i, l), test_tag);
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001929 if (unlikely(memcmp(test_tag, journal_entry_tag(ic, je2), ic->tag_size)))
Mikulas Patocka7eada902017-01-04 20:23:53 +01001930 dm_integrity_io_error(ic, "tag mismatch when replaying journal", -EILSEQ);
1931 }
1932
1933 journal_entry_set_unused(je2);
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001934 r = dm_integrity_rw_tag(ic, journal_entry_tag(ic, je2), &metadata_block, &metadata_offset,
Mikulas Patocka7eada902017-01-04 20:23:53 +01001935 ic->tag_size, TAG_WRITE);
1936 if (unlikely(r)) {
1937 dm_integrity_io_error(ic, "reading tags", r);
1938 }
1939 }
1940
1941 atomic_inc(&comp.in_flight);
Mikulas Patocka9d609f82017-04-18 16:51:52 -04001942 copy_from_journal(ic, i, j << ic->sb->log2_sectors_per_block,
1943 (k - j) << ic->sb->log2_sectors_per_block,
1944 get_data_sector(ic, area, offset),
Mikulas Patocka7eada902017-01-04 20:23:53 +01001945 complete_copy_from_journal, io);
1946skip_io:
1947 j = next_loop;
1948 }
1949 }
1950
1951 dm_bufio_write_dirty_buffers_async(ic->bufio);
1952
Mikulas Patockaa7c3e62b2017-07-19 11:24:08 -04001953 blk_finish_plug(&plug);
1954
Mikulas Patocka7eada902017-01-04 20:23:53 +01001955 complete_journal_op(&comp);
1956 wait_for_completion_io(&comp.comp);
1957
1958 dm_integrity_flush_buffers(ic);
1959}
1960
1961static void integrity_writer(struct work_struct *w)
1962{
1963 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, writer_work);
1964 unsigned write_start, write_sections;
1965
1966 unsigned prev_free_sectors;
1967
1968 /* the following test is not needed, but it tests the replay code */
1969 if (ACCESS_ONCE(ic->suspending))
1970 return;
1971
1972 spin_lock_irq(&ic->endio_wait.lock);
1973 write_start = ic->committed_section;
1974 write_sections = ic->n_committed_sections;
1975 spin_unlock_irq(&ic->endio_wait.lock);
1976
1977 if (!write_sections)
1978 return;
1979
1980 do_journal_write(ic, write_start, write_sections, false);
1981
1982 spin_lock_irq(&ic->endio_wait.lock);
1983
1984 ic->committed_section += write_sections;
1985 wraparound_section(ic, &ic->committed_section);
1986 ic->n_committed_sections -= write_sections;
1987
1988 prev_free_sectors = ic->free_sectors;
1989 ic->free_sectors += write_sections * ic->journal_section_entries;
1990 if (unlikely(!prev_free_sectors))
1991 wake_up_locked(&ic->endio_wait);
1992
1993 spin_unlock_irq(&ic->endio_wait.lock);
1994}
1995
1996static void init_journal(struct dm_integrity_c *ic, unsigned start_section,
1997 unsigned n_sections, unsigned char commit_seq)
1998{
1999 unsigned i, j, n;
2000
2001 if (!n_sections)
2002 return;
2003
2004 for (n = 0; n < n_sections; n++) {
2005 i = start_section + n;
2006 wraparound_section(ic, &i);
2007 for (j = 0; j < ic->journal_section_sectors; j++) {
2008 struct journal_sector *js = access_journal(ic, i, j);
2009 memset(&js->entries, 0, JOURNAL_SECTOR_DATA);
2010 js->commit_id = dm_integrity_commit_id(ic, i, j, commit_seq);
2011 }
2012 for (j = 0; j < ic->journal_section_entries; j++) {
2013 struct journal_entry *je = access_journal_entry(ic, i, j);
2014 journal_entry_set_unused(je);
2015 }
2016 }
2017
2018 write_journal(ic, start_section, n_sections);
2019}
2020
2021static int find_commit_seq(struct dm_integrity_c *ic, unsigned i, unsigned j, commit_id_t id)
2022{
2023 unsigned char k;
2024 for (k = 0; k < N_COMMIT_IDS; k++) {
2025 if (dm_integrity_commit_id(ic, i, j, k) == id)
2026 return k;
2027 }
2028 dm_integrity_io_error(ic, "journal commit id", -EIO);
2029 return -EIO;
2030}
2031
2032static void replay_journal(struct dm_integrity_c *ic)
2033{
2034 unsigned i, j;
2035 bool used_commit_ids[N_COMMIT_IDS];
2036 unsigned max_commit_id_sections[N_COMMIT_IDS];
2037 unsigned write_start, write_sections;
2038 unsigned continue_section;
2039 bool journal_empty;
2040 unsigned char unused, last_used, want_commit_seq;
2041
Mikulas Patockac2bcb2b2017-03-17 12:40:51 -04002042 if (ic->mode == 'R')
2043 return;
2044
Mikulas Patocka7eada902017-01-04 20:23:53 +01002045 if (ic->journal_uptodate)
2046 return;
2047
2048 last_used = 0;
2049 write_start = 0;
2050
2051 if (!ic->just_formatted) {
2052 DEBUG_print("reading journal\n");
2053 rw_journal(ic, REQ_OP_READ, 0, 0, ic->journal_sections, NULL);
2054 if (ic->journal_io)
2055 DEBUG_bytes(lowmem_page_address(ic->journal_io[0].page), 64, "read journal");
2056 if (ic->journal_io) {
2057 struct journal_completion crypt_comp;
2058 crypt_comp.ic = ic;
2059 crypt_comp.comp = COMPLETION_INITIALIZER_ONSTACK(crypt_comp.comp);
2060 crypt_comp.in_flight = (atomic_t)ATOMIC_INIT(0);
2061 encrypt_journal(ic, false, 0, ic->journal_sections, &crypt_comp);
2062 wait_for_completion(&crypt_comp.comp);
2063 }
2064 DEBUG_bytes(lowmem_page_address(ic->journal[0].page), 64, "decrypted journal");
2065 }
2066
2067 if (dm_integrity_failed(ic))
2068 goto clear_journal;
2069
2070 journal_empty = true;
2071 memset(used_commit_ids, 0, sizeof used_commit_ids);
2072 memset(max_commit_id_sections, 0, sizeof max_commit_id_sections);
2073 for (i = 0; i < ic->journal_sections; i++) {
2074 for (j = 0; j < ic->journal_section_sectors; j++) {
2075 int k;
2076 struct journal_sector *js = access_journal(ic, i, j);
2077 k = find_commit_seq(ic, i, j, js->commit_id);
2078 if (k < 0)
2079 goto clear_journal;
2080 used_commit_ids[k] = true;
2081 max_commit_id_sections[k] = i;
2082 }
2083 if (journal_empty) {
2084 for (j = 0; j < ic->journal_section_entries; j++) {
2085 struct journal_entry *je = access_journal_entry(ic, i, j);
2086 if (!journal_entry_is_unused(je)) {
2087 journal_empty = false;
2088 break;
2089 }
2090 }
2091 }
2092 }
2093
2094 if (!used_commit_ids[N_COMMIT_IDS - 1]) {
2095 unused = N_COMMIT_IDS - 1;
2096 while (unused && !used_commit_ids[unused - 1])
2097 unused--;
2098 } else {
2099 for (unused = 0; unused < N_COMMIT_IDS; unused++)
2100 if (!used_commit_ids[unused])
2101 break;
2102 if (unused == N_COMMIT_IDS) {
2103 dm_integrity_io_error(ic, "journal commit ids", -EIO);
2104 goto clear_journal;
2105 }
2106 }
2107 DEBUG_print("first unused commit seq %d [%d,%d,%d,%d]\n",
2108 unused, used_commit_ids[0], used_commit_ids[1],
2109 used_commit_ids[2], used_commit_ids[3]);
2110
2111 last_used = prev_commit_seq(unused);
2112 want_commit_seq = prev_commit_seq(last_used);
2113
2114 if (!used_commit_ids[want_commit_seq] && used_commit_ids[prev_commit_seq(want_commit_seq)])
2115 journal_empty = true;
2116
2117 write_start = max_commit_id_sections[last_used] + 1;
2118 if (unlikely(write_start >= ic->journal_sections))
2119 want_commit_seq = next_commit_seq(want_commit_seq);
2120 wraparound_section(ic, &write_start);
2121
2122 i = write_start;
2123 for (write_sections = 0; write_sections < ic->journal_sections; write_sections++) {
2124 for (j = 0; j < ic->journal_section_sectors; j++) {
2125 struct journal_sector *js = access_journal(ic, i, j);
2126
2127 if (js->commit_id != dm_integrity_commit_id(ic, i, j, want_commit_seq)) {
2128 /*
2129 * This could be caused by crash during writing.
2130 * We won't replay the inconsistent part of the
2131 * journal.
2132 */
2133 DEBUG_print("commit id mismatch at position (%u, %u): %d != %d\n",
2134 i, j, find_commit_seq(ic, i, j, js->commit_id), want_commit_seq);
2135 goto brk;
2136 }
2137 }
2138 i++;
2139 if (unlikely(i >= ic->journal_sections))
2140 want_commit_seq = next_commit_seq(want_commit_seq);
2141 wraparound_section(ic, &i);
2142 }
2143brk:
2144
2145 if (!journal_empty) {
2146 DEBUG_print("replaying %u sections, starting at %u, commit seq %d\n",
2147 write_sections, write_start, want_commit_seq);
2148 do_journal_write(ic, write_start, write_sections, true);
2149 }
2150
2151 if (write_sections == ic->journal_sections && (ic->mode == 'J' || journal_empty)) {
2152 continue_section = write_start;
2153 ic->commit_seq = want_commit_seq;
2154 DEBUG_print("continuing from section %u, commit seq %d\n", write_start, ic->commit_seq);
2155 } else {
2156 unsigned s;
2157 unsigned char erase_seq;
2158clear_journal:
2159 DEBUG_print("clearing journal\n");
2160
2161 erase_seq = prev_commit_seq(prev_commit_seq(last_used));
2162 s = write_start;
2163 init_journal(ic, s, 1, erase_seq);
2164 s++;
2165 wraparound_section(ic, &s);
2166 if (ic->journal_sections >= 2) {
2167 init_journal(ic, s, ic->journal_sections - 2, erase_seq);
2168 s += ic->journal_sections - 2;
2169 wraparound_section(ic, &s);
2170 init_journal(ic, s, 1, erase_seq);
2171 }
2172
2173 continue_section = 0;
2174 ic->commit_seq = next_commit_seq(erase_seq);
2175 }
2176
2177 ic->committed_section = continue_section;
2178 ic->n_committed_sections = 0;
2179
2180 ic->uncommitted_section = continue_section;
2181 ic->n_uncommitted_sections = 0;
2182
2183 ic->free_section = continue_section;
2184 ic->free_section_entry = 0;
2185 ic->free_sectors = ic->journal_entries;
2186
2187 ic->journal_tree_root = RB_ROOT;
2188 for (i = 0; i < ic->journal_entries; i++)
2189 init_journal_node(&ic->journal_tree[i]);
2190}
2191
2192static void dm_integrity_postsuspend(struct dm_target *ti)
2193{
2194 struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2195
2196 del_timer_sync(&ic->autocommit_timer);
2197
2198 ic->suspending = true;
2199
2200 queue_work(ic->commit_wq, &ic->commit_work);
2201 drain_workqueue(ic->commit_wq);
2202
2203 if (ic->mode == 'J') {
2204 drain_workqueue(ic->writer_wq);
2205 dm_integrity_flush_buffers(ic);
2206 }
2207
2208 ic->suspending = false;
2209
2210 BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
2211
2212 ic->journal_uptodate = true;
2213}
2214
2215static void dm_integrity_resume(struct dm_target *ti)
2216{
2217 struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2218
2219 replay_journal(ic);
2220}
2221
2222static void dm_integrity_status(struct dm_target *ti, status_type_t type,
2223 unsigned status_flags, char *result, unsigned maxlen)
2224{
2225 struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2226 unsigned arg_count;
2227 size_t sz = 0;
2228
2229 switch (type) {
2230 case STATUSTYPE_INFO:
2231 result[0] = '\0';
2232 break;
2233
2234 case STATUSTYPE_TABLE: {
2235 __u64 watermark_percentage = (__u64)(ic->journal_entries - ic->free_sectors_threshold) * 100;
2236 watermark_percentage += ic->journal_entries / 2;
2237 do_div(watermark_percentage, ic->journal_entries);
2238 arg_count = 5;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04002239 arg_count += ic->sectors_per_block != 1;
Mikulas Patocka7eada902017-01-04 20:23:53 +01002240 arg_count += !!ic->internal_hash_alg.alg_string;
2241 arg_count += !!ic->journal_crypt_alg.alg_string;
2242 arg_count += !!ic->journal_mac_alg.alg_string;
2243 DMEMIT("%s %llu %u %c %u", ic->dev->name, (unsigned long long)ic->start,
2244 ic->tag_size, ic->mode, arg_count);
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002245 DMEMIT(" journal_sectors:%u", ic->initial_sectors - SB_SECTORS);
2246 DMEMIT(" interleave_sectors:%u", 1U << ic->sb->log2_interleave_sectors);
2247 DMEMIT(" buffer_sectors:%u", 1U << ic->log2_buffer_sectors);
2248 DMEMIT(" journal_watermark:%u", (unsigned)watermark_percentage);
2249 DMEMIT(" commit_time:%u", ic->autocommit_msec);
Mikulas Patocka9d609f82017-04-18 16:51:52 -04002250 if (ic->sectors_per_block != 1)
2251 DMEMIT(" block_size:%u", ic->sectors_per_block << SECTOR_SHIFT);
Mikulas Patocka7eada902017-01-04 20:23:53 +01002252
2253#define EMIT_ALG(a, n) \
2254 do { \
2255 if (ic->a.alg_string) { \
2256 DMEMIT(" %s:%s", n, ic->a.alg_string); \
2257 if (ic->a.key_string) \
2258 DMEMIT(":%s", ic->a.key_string);\
2259 } \
2260 } while (0)
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002261 EMIT_ALG(internal_hash_alg, "internal_hash");
2262 EMIT_ALG(journal_crypt_alg, "journal_crypt");
2263 EMIT_ALG(journal_mac_alg, "journal_mac");
Mikulas Patocka7eada902017-01-04 20:23:53 +01002264 break;
2265 }
2266 }
2267}
2268
2269static int dm_integrity_iterate_devices(struct dm_target *ti,
2270 iterate_devices_callout_fn fn, void *data)
2271{
2272 struct dm_integrity_c *ic = ti->private;
2273
2274 return fn(ti, ic->dev, ic->start + ic->initial_sectors + ic->metadata_run, ti->len, data);
2275}
2276
Mikulas Patocka9d609f82017-04-18 16:51:52 -04002277static void dm_integrity_io_hints(struct dm_target *ti, struct queue_limits *limits)
2278{
2279 struct dm_integrity_c *ic = ti->private;
2280
2281 if (ic->sectors_per_block > 1) {
2282 limits->logical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
2283 limits->physical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
2284 blk_limits_io_min(limits, ic->sectors_per_block << SECTOR_SHIFT);
2285 }
2286}
2287
Mikulas Patocka7eada902017-01-04 20:23:53 +01002288static void calculate_journal_section_size(struct dm_integrity_c *ic)
2289{
2290 unsigned sector_space = JOURNAL_SECTOR_DATA;
2291
2292 ic->journal_sections = le32_to_cpu(ic->sb->journal_sections);
Mikulas Patocka9d609f82017-04-18 16:51:52 -04002293 ic->journal_entry_size = roundup(offsetof(struct journal_entry, last_bytes[ic->sectors_per_block]) + ic->tag_size,
Mikulas Patocka7eada902017-01-04 20:23:53 +01002294 JOURNAL_ENTRY_ROUNDUP);
2295
2296 if (ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC))
2297 sector_space -= JOURNAL_MAC_PER_SECTOR;
2298 ic->journal_entries_per_sector = sector_space / ic->journal_entry_size;
2299 ic->journal_section_entries = ic->journal_entries_per_sector * JOURNAL_BLOCK_SECTORS;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04002300 ic->journal_section_sectors = (ic->journal_section_entries << ic->sb->log2_sectors_per_block) + JOURNAL_BLOCK_SECTORS;
Mikulas Patocka7eada902017-01-04 20:23:53 +01002301 ic->journal_entries = ic->journal_section_entries * ic->journal_sections;
2302}
2303
2304static int calculate_device_limits(struct dm_integrity_c *ic)
2305{
2306 __u64 initial_sectors;
2307 sector_t last_sector, last_area, last_offset;
2308
2309 calculate_journal_section_size(ic);
2310 initial_sectors = SB_SECTORS + (__u64)ic->journal_section_sectors * ic->journal_sections;
2311 if (initial_sectors + METADATA_PADDING_SECTORS >= ic->device_sectors || initial_sectors > UINT_MAX)
2312 return -EINVAL;
2313 ic->initial_sectors = initial_sectors;
2314
Mikulas Patocka9d609f82017-04-18 16:51:52 -04002315 ic->metadata_run = roundup((__u64)ic->tag_size << (ic->sb->log2_interleave_sectors - ic->sb->log2_sectors_per_block),
Mikulas Patocka7eada902017-01-04 20:23:53 +01002316 (__u64)(1 << SECTOR_SHIFT << METADATA_PADDING_SECTORS)) >> SECTOR_SHIFT;
2317 if (!(ic->metadata_run & (ic->metadata_run - 1)))
2318 ic->log2_metadata_run = __ffs(ic->metadata_run);
2319 else
2320 ic->log2_metadata_run = -1;
2321
2322 get_area_and_offset(ic, ic->provided_data_sectors - 1, &last_area, &last_offset);
2323 last_sector = get_data_sector(ic, last_area, last_offset);
2324
2325 if (ic->start + last_sector < last_sector || ic->start + last_sector >= ic->device_sectors)
2326 return -EINVAL;
2327
2328 return 0;
2329}
2330
2331static int initialize_superblock(struct dm_integrity_c *ic, unsigned journal_sectors, unsigned interleave_sectors)
2332{
2333 unsigned journal_sections;
2334 int test_bit;
2335
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002336 memset(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT);
Mikulas Patocka7eada902017-01-04 20:23:53 +01002337 memcpy(ic->sb->magic, SB_MAGIC, 8);
2338 ic->sb->version = SB_VERSION;
2339 ic->sb->integrity_tag_size = cpu_to_le16(ic->tag_size);
Mikulas Patocka9d609f82017-04-18 16:51:52 -04002340 ic->sb->log2_sectors_per_block = __ffs(ic->sectors_per_block);
Mikulas Patocka7eada902017-01-04 20:23:53 +01002341 if (ic->journal_mac_alg.alg_string)
2342 ic->sb->flags |= cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC);
2343
2344 calculate_journal_section_size(ic);
2345 journal_sections = journal_sectors / ic->journal_section_sectors;
2346 if (!journal_sections)
2347 journal_sections = 1;
2348 ic->sb->journal_sections = cpu_to_le32(journal_sections);
2349
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002350 if (!interleave_sectors)
2351 interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
Mikulas Patocka7eada902017-01-04 20:23:53 +01002352 ic->sb->log2_interleave_sectors = __fls(interleave_sectors);
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002353 ic->sb->log2_interleave_sectors = max((__u8)MIN_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
2354 ic->sb->log2_interleave_sectors = min((__u8)MAX_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
Mikulas Patocka7eada902017-01-04 20:23:53 +01002355
2356 ic->provided_data_sectors = 0;
2357 for (test_bit = fls64(ic->device_sectors) - 1; test_bit >= 3; test_bit--) {
2358 __u64 prev_data_sectors = ic->provided_data_sectors;
2359
2360 ic->provided_data_sectors |= (sector_t)1 << test_bit;
2361 if (calculate_device_limits(ic))
2362 ic->provided_data_sectors = prev_data_sectors;
2363 }
2364
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002365 if (!ic->provided_data_sectors)
Mikulas Patocka7eada902017-01-04 20:23:53 +01002366 return -EINVAL;
2367
2368 ic->sb->provided_data_sectors = cpu_to_le64(ic->provided_data_sectors);
2369
2370 return 0;
2371}
2372
2373static void dm_integrity_set(struct dm_target *ti, struct dm_integrity_c *ic)
2374{
2375 struct gendisk *disk = dm_disk(dm_table_get_md(ti->table));
2376 struct blk_integrity bi;
2377
2378 memset(&bi, 0, sizeof(bi));
2379 bi.profile = &dm_integrity_profile;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04002380 bi.tuple_size = ic->tag_size;
2381 bi.tag_size = bi.tuple_size;
Mikulas Patocka84ff1bc2017-04-26 18:39:47 -04002382 bi.interval_exp = ic->sb->log2_sectors_per_block + SECTOR_SHIFT;
Mikulas Patocka7eada902017-01-04 20:23:53 +01002383
2384 blk_integrity_register(disk, &bi);
2385 blk_queue_max_integrity_segments(disk->queue, UINT_MAX);
2386}
2387
Mikulas Patocka7eada902017-01-04 20:23:53 +01002388static void dm_integrity_free_page_list(struct dm_integrity_c *ic, struct page_list *pl)
2389{
2390 unsigned i;
2391
2392 if (!pl)
2393 return;
2394 for (i = 0; i < ic->journal_pages; i++)
2395 if (pl[i].page)
2396 __free_page(pl[i].page);
2397 kvfree(pl);
2398}
2399
2400static struct page_list *dm_integrity_alloc_page_list(struct dm_integrity_c *ic)
2401{
2402 size_t page_list_desc_size = ic->journal_pages * sizeof(struct page_list);
2403 struct page_list *pl;
2404 unsigned i;
2405
Mikulas Patocka702a6202017-05-20 14:56:21 -04002406 pl = kvmalloc(page_list_desc_size, GFP_KERNEL | __GFP_ZERO);
Mikulas Patocka7eada902017-01-04 20:23:53 +01002407 if (!pl)
2408 return NULL;
2409
2410 for (i = 0; i < ic->journal_pages; i++) {
2411 pl[i].page = alloc_page(GFP_KERNEL);
2412 if (!pl[i].page) {
2413 dm_integrity_free_page_list(ic, pl);
2414 return NULL;
2415 }
2416 if (i)
2417 pl[i - 1].next = &pl[i];
2418 }
2419
2420 return pl;
2421}
2422
2423static void dm_integrity_free_journal_scatterlist(struct dm_integrity_c *ic, struct scatterlist **sl)
2424{
2425 unsigned i;
2426 for (i = 0; i < ic->journal_sections; i++)
2427 kvfree(sl[i]);
2428 kfree(sl);
2429}
2430
2431static struct scatterlist **dm_integrity_alloc_journal_scatterlist(struct dm_integrity_c *ic, struct page_list *pl)
2432{
2433 struct scatterlist **sl;
2434 unsigned i;
2435
Mikulas Patocka702a6202017-05-20 14:56:21 -04002436 sl = kvmalloc(ic->journal_sections * sizeof(struct scatterlist *), GFP_KERNEL | __GFP_ZERO);
Mikulas Patocka7eada902017-01-04 20:23:53 +01002437 if (!sl)
2438 return NULL;
2439
2440 for (i = 0; i < ic->journal_sections; i++) {
2441 struct scatterlist *s;
2442 unsigned start_index, start_offset;
2443 unsigned end_index, end_offset;
2444 unsigned n_pages;
2445 unsigned idx;
2446
2447 page_list_location(ic, i, 0, &start_index, &start_offset);
2448 page_list_location(ic, i, ic->journal_section_sectors - 1, &end_index, &end_offset);
2449
2450 n_pages = (end_index - start_index + 1);
2451
Mikulas Patocka702a6202017-05-20 14:56:21 -04002452 s = kvmalloc(n_pages * sizeof(struct scatterlist), GFP_KERNEL);
Mikulas Patocka7eada902017-01-04 20:23:53 +01002453 if (!s) {
2454 dm_integrity_free_journal_scatterlist(ic, sl);
2455 return NULL;
2456 }
2457
2458 sg_init_table(s, n_pages);
2459 for (idx = start_index; idx <= end_index; idx++) {
2460 char *va = lowmem_page_address(pl[idx].page);
2461 unsigned start = 0, end = PAGE_SIZE;
2462 if (idx == start_index)
2463 start = start_offset;
2464 if (idx == end_index)
2465 end = end_offset + (1 << SECTOR_SHIFT);
2466 sg_set_buf(&s[idx - start_index], va + start, end - start);
2467 }
2468
2469 sl[i] = s;
2470 }
2471
2472 return sl;
2473}
2474
2475static void free_alg(struct alg_spec *a)
2476{
2477 kzfree(a->alg_string);
2478 kzfree(a->key);
2479 memset(a, 0, sizeof *a);
2480}
2481
2482static int get_alg_and_key(const char *arg, struct alg_spec *a, char **error, char *error_inval)
2483{
2484 char *k;
2485
2486 free_alg(a);
2487
2488 a->alg_string = kstrdup(strchr(arg, ':') + 1, GFP_KERNEL);
2489 if (!a->alg_string)
2490 goto nomem;
2491
2492 k = strchr(a->alg_string, ':');
2493 if (k) {
Mikulas Patocka7eada902017-01-04 20:23:53 +01002494 *k = 0;
2495 a->key_string = k + 1;
2496 if (strlen(a->key_string) & 1)
2497 goto inval;
2498
2499 a->key_size = strlen(a->key_string) / 2;
2500 a->key = kmalloc(a->key_size, GFP_KERNEL);
2501 if (!a->key)
2502 goto nomem;
Mikulas Patocka6625d902017-04-27 11:49:33 -04002503 if (hex2bin(a->key, a->key_string, a->key_size))
2504 goto inval;
Mikulas Patocka7eada902017-01-04 20:23:53 +01002505 }
2506
2507 return 0;
2508inval:
2509 *error = error_inval;
2510 return -EINVAL;
2511nomem:
2512 *error = "Out of memory for an argument";
2513 return -ENOMEM;
2514}
2515
2516static int get_mac(struct crypto_shash **hash, struct alg_spec *a, char **error,
2517 char *error_alg, char *error_key)
2518{
2519 int r;
2520
2521 if (a->alg_string) {
2522 *hash = crypto_alloc_shash(a->alg_string, 0, CRYPTO_ALG_ASYNC);
2523 if (IS_ERR(*hash)) {
2524 *error = error_alg;
2525 r = PTR_ERR(*hash);
2526 *hash = NULL;
2527 return r;
2528 }
2529
2530 if (a->key) {
2531 r = crypto_shash_setkey(*hash, a->key, a->key_size);
2532 if (r) {
2533 *error = error_key;
2534 return r;
2535 }
2536 }
2537 }
2538
2539 return 0;
2540}
2541
Mike Snitzer1aa0efd2017-03-17 14:56:17 -04002542static int create_journal(struct dm_integrity_c *ic, char **error)
2543{
2544 int r = 0;
2545 unsigned i;
2546 __u64 journal_pages, journal_desc_size, journal_tree_size;
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002547 unsigned char *crypt_data = NULL;
2548
2549 ic->commit_ids[0] = cpu_to_le64(0x1111111111111111ULL);
2550 ic->commit_ids[1] = cpu_to_le64(0x2222222222222222ULL);
2551 ic->commit_ids[2] = cpu_to_le64(0x3333333333333333ULL);
2552 ic->commit_ids[3] = cpu_to_le64(0x4444444444444444ULL);
Mike Snitzer1aa0efd2017-03-17 14:56:17 -04002553
2554 journal_pages = roundup((__u64)ic->journal_sections * ic->journal_section_sectors,
2555 PAGE_SIZE >> SECTOR_SHIFT) >> (PAGE_SHIFT - SECTOR_SHIFT);
2556 journal_desc_size = journal_pages * sizeof(struct page_list);
2557 if (journal_pages >= totalram_pages - totalhigh_pages || journal_desc_size > ULONG_MAX) {
2558 *error = "Journal doesn't fit into memory";
2559 r = -ENOMEM;
2560 goto bad;
2561 }
2562 ic->journal_pages = journal_pages;
2563
2564 ic->journal = dm_integrity_alloc_page_list(ic);
2565 if (!ic->journal) {
2566 *error = "Could not allocate memory for journal";
2567 r = -ENOMEM;
2568 goto bad;
2569 }
2570 if (ic->journal_crypt_alg.alg_string) {
2571 unsigned ivsize, blocksize;
2572 struct journal_completion comp;
2573
2574 comp.ic = ic;
2575 ic->journal_crypt = crypto_alloc_skcipher(ic->journal_crypt_alg.alg_string, 0, 0);
2576 if (IS_ERR(ic->journal_crypt)) {
2577 *error = "Invalid journal cipher";
2578 r = PTR_ERR(ic->journal_crypt);
2579 ic->journal_crypt = NULL;
2580 goto bad;
2581 }
2582 ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
2583 blocksize = crypto_skcipher_blocksize(ic->journal_crypt);
2584
2585 if (ic->journal_crypt_alg.key) {
2586 r = crypto_skcipher_setkey(ic->journal_crypt, ic->journal_crypt_alg.key,
2587 ic->journal_crypt_alg.key_size);
2588 if (r) {
2589 *error = "Error setting encryption key";
2590 goto bad;
2591 }
2592 }
2593 DEBUG_print("cipher %s, block size %u iv size %u\n",
2594 ic->journal_crypt_alg.alg_string, blocksize, ivsize);
2595
2596 ic->journal_io = dm_integrity_alloc_page_list(ic);
2597 if (!ic->journal_io) {
2598 *error = "Could not allocate memory for journal io";
2599 r = -ENOMEM;
2600 goto bad;
2601 }
2602
2603 if (blocksize == 1) {
2604 struct scatterlist *sg;
2605 SKCIPHER_REQUEST_ON_STACK(req, ic->journal_crypt);
2606 unsigned char iv[ivsize];
2607 skcipher_request_set_tfm(req, ic->journal_crypt);
2608
2609 ic->journal_xor = dm_integrity_alloc_page_list(ic);
2610 if (!ic->journal_xor) {
2611 *error = "Could not allocate memory for journal xor";
2612 r = -ENOMEM;
2613 goto bad;
2614 }
2615
Mikulas Patocka702a6202017-05-20 14:56:21 -04002616 sg = kvmalloc((ic->journal_pages + 1) * sizeof(struct scatterlist), GFP_KERNEL);
Mike Snitzer1aa0efd2017-03-17 14:56:17 -04002617 if (!sg) {
2618 *error = "Unable to allocate sg list";
2619 r = -ENOMEM;
2620 goto bad;
2621 }
2622 sg_init_table(sg, ic->journal_pages + 1);
2623 for (i = 0; i < ic->journal_pages; i++) {
2624 char *va = lowmem_page_address(ic->journal_xor[i].page);
2625 clear_page(va);
2626 sg_set_buf(&sg[i], va, PAGE_SIZE);
2627 }
2628 sg_set_buf(&sg[i], &ic->commit_ids, sizeof ic->commit_ids);
2629 memset(iv, 0x00, ivsize);
2630
2631 skcipher_request_set_crypt(req, sg, sg, PAGE_SIZE * ic->journal_pages + sizeof ic->commit_ids, iv);
2632 comp.comp = COMPLETION_INITIALIZER_ONSTACK(comp.comp);
2633 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
2634 if (do_crypt(true, req, &comp))
2635 wait_for_completion(&comp.comp);
2636 kvfree(sg);
2637 r = dm_integrity_failed(ic);
2638 if (r) {
2639 *error = "Unable to encrypt journal";
2640 goto bad;
2641 }
2642 DEBUG_bytes(lowmem_page_address(ic->journal_xor[0].page), 64, "xor data");
2643
2644 crypto_free_skcipher(ic->journal_crypt);
2645 ic->journal_crypt = NULL;
2646 } else {
2647 SKCIPHER_REQUEST_ON_STACK(req, ic->journal_crypt);
2648 unsigned char iv[ivsize];
2649 unsigned crypt_len = roundup(ivsize, blocksize);
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002650
2651 crypt_data = kmalloc(crypt_len, GFP_KERNEL);
2652 if (!crypt_data) {
2653 *error = "Unable to allocate crypt data";
2654 r = -ENOMEM;
2655 goto bad;
2656 }
Mike Snitzer1aa0efd2017-03-17 14:56:17 -04002657
2658 skcipher_request_set_tfm(req, ic->journal_crypt);
2659
2660 ic->journal_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal);
2661 if (!ic->journal_scatterlist) {
2662 *error = "Unable to allocate sg list";
2663 r = -ENOMEM;
2664 goto bad;
2665 }
2666 ic->journal_io_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal_io);
2667 if (!ic->journal_io_scatterlist) {
2668 *error = "Unable to allocate sg list";
2669 r = -ENOMEM;
2670 goto bad;
2671 }
Mikulas Patocka702a6202017-05-20 14:56:21 -04002672 ic->sk_requests = kvmalloc(ic->journal_sections * sizeof(struct skcipher_request *), GFP_KERNEL | __GFP_ZERO);
Mike Snitzer1aa0efd2017-03-17 14:56:17 -04002673 if (!ic->sk_requests) {
2674 *error = "Unable to allocate sk requests";
2675 r = -ENOMEM;
2676 goto bad;
2677 }
2678 for (i = 0; i < ic->journal_sections; i++) {
2679 struct scatterlist sg;
2680 struct skcipher_request *section_req;
2681 __u32 section_le = cpu_to_le32(i);
2682
2683 memset(iv, 0x00, ivsize);
2684 memset(crypt_data, 0x00, crypt_len);
2685 memcpy(crypt_data, &section_le, min((size_t)crypt_len, sizeof(section_le)));
2686
2687 sg_init_one(&sg, crypt_data, crypt_len);
2688 skcipher_request_set_crypt(req, &sg, &sg, crypt_len, iv);
2689 comp.comp = COMPLETION_INITIALIZER_ONSTACK(comp.comp);
2690 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
2691 if (do_crypt(true, req, &comp))
2692 wait_for_completion(&comp.comp);
2693
2694 r = dm_integrity_failed(ic);
2695 if (r) {
2696 *error = "Unable to generate iv";
2697 goto bad;
2698 }
2699
2700 section_req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
2701 if (!section_req) {
2702 *error = "Unable to allocate crypt request";
2703 r = -ENOMEM;
2704 goto bad;
2705 }
2706 section_req->iv = kmalloc(ivsize * 2, GFP_KERNEL);
2707 if (!section_req->iv) {
2708 skcipher_request_free(section_req);
2709 *error = "Unable to allocate iv";
2710 r = -ENOMEM;
2711 goto bad;
2712 }
2713 memcpy(section_req->iv + ivsize, crypt_data, ivsize);
2714 section_req->cryptlen = (size_t)ic->journal_section_sectors << SECTOR_SHIFT;
2715 ic->sk_requests[i] = section_req;
2716 DEBUG_bytes(crypt_data, ivsize, "iv(%u)", i);
2717 }
2718 }
2719 }
2720
2721 for (i = 0; i < N_COMMIT_IDS; i++) {
2722 unsigned j;
2723retest_commit_id:
2724 for (j = 0; j < i; j++) {
2725 if (ic->commit_ids[j] == ic->commit_ids[i]) {
2726 ic->commit_ids[i] = cpu_to_le64(le64_to_cpu(ic->commit_ids[i]) + 1);
2727 goto retest_commit_id;
2728 }
2729 }
2730 DEBUG_print("commit id %u: %016llx\n", i, ic->commit_ids[i]);
2731 }
2732
2733 journal_tree_size = (__u64)ic->journal_entries * sizeof(struct journal_node);
2734 if (journal_tree_size > ULONG_MAX) {
2735 *error = "Journal doesn't fit into memory";
2736 r = -ENOMEM;
2737 goto bad;
2738 }
Mikulas Patocka702a6202017-05-20 14:56:21 -04002739 ic->journal_tree = kvmalloc(journal_tree_size, GFP_KERNEL);
Mike Snitzer1aa0efd2017-03-17 14:56:17 -04002740 if (!ic->journal_tree) {
2741 *error = "Could not allocate memory for journal tree";
2742 r = -ENOMEM;
2743 }
2744bad:
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002745 kfree(crypt_data);
Mike Snitzer1aa0efd2017-03-17 14:56:17 -04002746 return r;
2747}
2748
Mikulas Patocka7eada902017-01-04 20:23:53 +01002749/*
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002750 * Construct a integrity mapping
Mikulas Patocka7eada902017-01-04 20:23:53 +01002751 *
2752 * Arguments:
2753 * device
2754 * offset from the start of the device
2755 * tag size
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002756 * D - direct writes, J - journal writes, R - recovery mode
Mikulas Patocka7eada902017-01-04 20:23:53 +01002757 * number of optional arguments
2758 * optional arguments:
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002759 * journal_sectors
2760 * interleave_sectors
2761 * buffer_sectors
2762 * journal_watermark
2763 * commit_time
2764 * internal_hash
2765 * journal_crypt
2766 * journal_mac
Mikulas Patocka9d609f82017-04-18 16:51:52 -04002767 * block_size
Mikulas Patocka7eada902017-01-04 20:23:53 +01002768 */
2769static int dm_integrity_ctr(struct dm_target *ti, unsigned argc, char **argv)
2770{
2771 struct dm_integrity_c *ic;
2772 char dummy;
2773 int r;
Mikulas Patocka7eada902017-01-04 20:23:53 +01002774 unsigned extra_args;
2775 struct dm_arg_set as;
2776 static struct dm_arg _args[] = {
Mikulas Patocka9d609f82017-04-18 16:51:52 -04002777 {0, 9, "Invalid number of feature args"},
Mikulas Patocka7eada902017-01-04 20:23:53 +01002778 };
2779 unsigned journal_sectors, interleave_sectors, buffer_sectors, journal_watermark, sync_msec;
2780 bool should_write_sb;
Mikulas Patocka7eada902017-01-04 20:23:53 +01002781 __u64 threshold;
2782 unsigned long long start;
2783
2784#define DIRECT_ARGUMENTS 4
2785
2786 if (argc <= DIRECT_ARGUMENTS) {
2787 ti->error = "Invalid argument count";
2788 return -EINVAL;
2789 }
2790
2791 ic = kzalloc(sizeof(struct dm_integrity_c), GFP_KERNEL);
2792 if (!ic) {
2793 ti->error = "Cannot allocate integrity context";
2794 return -ENOMEM;
2795 }
2796 ti->private = ic;
2797 ti->per_io_data_size = sizeof(struct dm_integrity_io);
2798
Mikulas Patocka7eada902017-01-04 20:23:53 +01002799 ic->in_progress = RB_ROOT;
2800 init_waitqueue_head(&ic->endio_wait);
2801 bio_list_init(&ic->flush_bio_list);
2802 init_waitqueue_head(&ic->copy_to_journal_wait);
2803 init_completion(&ic->crypto_backoff);
2804
2805 r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &ic->dev);
2806 if (r) {
2807 ti->error = "Device lookup failed";
2808 goto bad;
2809 }
2810
2811 if (sscanf(argv[1], "%llu%c", &start, &dummy) != 1 || start != (sector_t)start) {
2812 ti->error = "Invalid starting offset";
2813 r = -EINVAL;
2814 goto bad;
2815 }
2816 ic->start = start;
2817
2818 if (strcmp(argv[2], "-")) {
2819 if (sscanf(argv[2], "%u%c", &ic->tag_size, &dummy) != 1 || !ic->tag_size) {
2820 ti->error = "Invalid tag size";
2821 r = -EINVAL;
2822 goto bad;
2823 }
2824 }
2825
Mikulas Patockac2bcb2b2017-03-17 12:40:51 -04002826 if (!strcmp(argv[3], "J") || !strcmp(argv[3], "D") || !strcmp(argv[3], "R"))
Mikulas Patocka7eada902017-01-04 20:23:53 +01002827 ic->mode = argv[3][0];
2828 else {
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002829 ti->error = "Invalid mode (expecting J, D, R)";
Mikulas Patocka7eada902017-01-04 20:23:53 +01002830 r = -EINVAL;
2831 goto bad;
2832 }
2833
2834 ic->device_sectors = i_size_read(ic->dev->bdev->bd_inode) >> SECTOR_SHIFT;
2835 journal_sectors = min((sector_t)DEFAULT_MAX_JOURNAL_SECTORS,
2836 ic->device_sectors >> DEFAULT_JOURNAL_SIZE_FACTOR);
2837 interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
2838 buffer_sectors = DEFAULT_BUFFER_SECTORS;
2839 journal_watermark = DEFAULT_JOURNAL_WATERMARK;
2840 sync_msec = DEFAULT_SYNC_MSEC;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04002841 ic->sectors_per_block = 1;
Mikulas Patocka7eada902017-01-04 20:23:53 +01002842
2843 as.argc = argc - DIRECT_ARGUMENTS;
2844 as.argv = argv + DIRECT_ARGUMENTS;
2845 r = dm_read_arg_group(_args, &as, &extra_args, &ti->error);
2846 if (r)
2847 goto bad;
2848
2849 while (extra_args--) {
2850 const char *opt_string;
2851 unsigned val;
2852 opt_string = dm_shift_arg(&as);
2853 if (!opt_string) {
2854 r = -EINVAL;
2855 ti->error = "Not enough feature arguments";
2856 goto bad;
2857 }
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002858 if (sscanf(opt_string, "journal_sectors:%u%c", &val, &dummy) == 1)
Mikulas Patocka7eada902017-01-04 20:23:53 +01002859 journal_sectors = val;
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002860 else if (sscanf(opt_string, "interleave_sectors:%u%c", &val, &dummy) == 1)
Mikulas Patocka7eada902017-01-04 20:23:53 +01002861 interleave_sectors = val;
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002862 else if (sscanf(opt_string, "buffer_sectors:%u%c", &val, &dummy) == 1)
Mikulas Patocka7eada902017-01-04 20:23:53 +01002863 buffer_sectors = val;
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002864 else if (sscanf(opt_string, "journal_watermark:%u%c", &val, &dummy) == 1 && val <= 100)
Mikulas Patocka7eada902017-01-04 20:23:53 +01002865 journal_watermark = val;
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002866 else if (sscanf(opt_string, "commit_time:%u%c", &val, &dummy) == 1)
Mikulas Patocka7eada902017-01-04 20:23:53 +01002867 sync_msec = val;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04002868 else if (sscanf(opt_string, "block_size:%u%c", &val, &dummy) == 1) {
2869 if (val < 1 << SECTOR_SHIFT ||
2870 val > MAX_SECTORS_PER_BLOCK << SECTOR_SHIFT ||
2871 (val & (val -1))) {
2872 r = -EINVAL;
2873 ti->error = "Invalid block_size argument";
2874 goto bad;
2875 }
2876 ic->sectors_per_block = val >> SECTOR_SHIFT;
2877 } else if (!memcmp(opt_string, "internal_hash:", strlen("internal_hash:"))) {
Mikulas Patocka7eada902017-01-04 20:23:53 +01002878 r = get_alg_and_key(opt_string, &ic->internal_hash_alg, &ti->error,
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002879 "Invalid internal_hash argument");
Mikulas Patocka7eada902017-01-04 20:23:53 +01002880 if (r)
2881 goto bad;
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002882 } else if (!memcmp(opt_string, "journal_crypt:", strlen("journal_crypt:"))) {
Mikulas Patocka7eada902017-01-04 20:23:53 +01002883 r = get_alg_and_key(opt_string, &ic->journal_crypt_alg, &ti->error,
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002884 "Invalid journal_crypt argument");
Mikulas Patocka7eada902017-01-04 20:23:53 +01002885 if (r)
2886 goto bad;
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002887 } else if (!memcmp(opt_string, "journal_mac:", strlen("journal_mac:"))) {
Mikulas Patocka7eada902017-01-04 20:23:53 +01002888 r = get_alg_and_key(opt_string, &ic->journal_mac_alg, &ti->error,
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002889 "Invalid journal_mac argument");
Mikulas Patocka7eada902017-01-04 20:23:53 +01002890 if (r)
2891 goto bad;
2892 } else {
2893 r = -EINVAL;
2894 ti->error = "Invalid argument";
2895 goto bad;
2896 }
2897 }
2898
2899 r = get_mac(&ic->internal_hash, &ic->internal_hash_alg, &ti->error,
2900 "Invalid internal hash", "Error setting internal hash key");
2901 if (r)
2902 goto bad;
2903
2904 r = get_mac(&ic->journal_mac, &ic->journal_mac_alg, &ti->error,
2905 "Invalid journal mac", "Error setting journal mac key");
2906 if (r)
2907 goto bad;
2908
2909 if (!ic->tag_size) {
2910 if (!ic->internal_hash) {
2911 ti->error = "Unknown tag size";
2912 r = -EINVAL;
2913 goto bad;
2914 }
2915 ic->tag_size = crypto_shash_digestsize(ic->internal_hash);
2916 }
2917 if (ic->tag_size > MAX_TAG_SIZE) {
2918 ti->error = "Too big tag size";
2919 r = -EINVAL;
2920 goto bad;
2921 }
2922 if (!(ic->tag_size & (ic->tag_size - 1)))
2923 ic->log2_tag_size = __ffs(ic->tag_size);
2924 else
2925 ic->log2_tag_size = -1;
2926
2927 ic->autocommit_jiffies = msecs_to_jiffies(sync_msec);
2928 ic->autocommit_msec = sync_msec;
2929 setup_timer(&ic->autocommit_timer, autocommit_fn, (unsigned long)ic);
2930
2931 ic->io = dm_io_client_create();
2932 if (IS_ERR(ic->io)) {
2933 r = PTR_ERR(ic->io);
2934 ic->io = NULL;
2935 ti->error = "Cannot allocate dm io";
2936 goto bad;
2937 }
2938
2939 ic->journal_io_mempool = mempool_create_slab_pool(JOURNAL_IO_MEMPOOL, journal_io_cache);
2940 if (!ic->journal_io_mempool) {
2941 r = -ENOMEM;
2942 ti->error = "Cannot allocate mempool";
2943 goto bad;
2944 }
2945
2946 ic->metadata_wq = alloc_workqueue("dm-integrity-metadata",
2947 WQ_MEM_RECLAIM, METADATA_WORKQUEUE_MAX_ACTIVE);
2948 if (!ic->metadata_wq) {
2949 ti->error = "Cannot allocate workqueue";
2950 r = -ENOMEM;
2951 goto bad;
2952 }
2953
2954 /*
2955 * If this workqueue were percpu, it would cause bio reordering
2956 * and reduced performance.
2957 */
2958 ic->wait_wq = alloc_workqueue("dm-integrity-wait", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
2959 if (!ic->wait_wq) {
2960 ti->error = "Cannot allocate workqueue";
2961 r = -ENOMEM;
2962 goto bad;
2963 }
2964
2965 ic->commit_wq = alloc_workqueue("dm-integrity-commit", WQ_MEM_RECLAIM, 1);
2966 if (!ic->commit_wq) {
2967 ti->error = "Cannot allocate workqueue";
2968 r = -ENOMEM;
2969 goto bad;
2970 }
2971 INIT_WORK(&ic->commit_work, integrity_commit);
2972
2973 if (ic->mode == 'J') {
2974 ic->writer_wq = alloc_workqueue("dm-integrity-writer", WQ_MEM_RECLAIM, 1);
2975 if (!ic->writer_wq) {
2976 ti->error = "Cannot allocate workqueue";
2977 r = -ENOMEM;
2978 goto bad;
2979 }
2980 INIT_WORK(&ic->writer_work, integrity_writer);
2981 }
2982
2983 ic->sb = alloc_pages_exact(SB_SECTORS << SECTOR_SHIFT, GFP_KERNEL);
2984 if (!ic->sb) {
2985 r = -ENOMEM;
2986 ti->error = "Cannot allocate superblock area";
2987 goto bad;
2988 }
2989
2990 r = sync_rw_sb(ic, REQ_OP_READ, 0);
2991 if (r) {
2992 ti->error = "Error reading superblock";
2993 goto bad;
2994 }
Mikulas Patockac2bcb2b2017-03-17 12:40:51 -04002995 should_write_sb = false;
2996 if (memcmp(ic->sb->magic, SB_MAGIC, 8)) {
2997 if (ic->mode != 'R') {
Mikulas Patocka56b67a42017-04-18 16:51:50 -04002998 if (memchr_inv(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT)) {
2999 r = -EINVAL;
3000 ti->error = "The device is not initialized";
3001 goto bad;
Mikulas Patocka7eada902017-01-04 20:23:53 +01003002 }
3003 }
3004
3005 r = initialize_superblock(ic, journal_sectors, interleave_sectors);
3006 if (r) {
3007 ti->error = "Could not initialize superblock";
3008 goto bad;
3009 }
Mikulas Patockac2bcb2b2017-03-17 12:40:51 -04003010 if (ic->mode != 'R')
3011 should_write_sb = true;
Mikulas Patocka7eada902017-01-04 20:23:53 +01003012 }
3013
3014 if (ic->sb->version != SB_VERSION) {
3015 r = -EINVAL;
3016 ti->error = "Unknown version";
3017 goto bad;
3018 }
3019 if (le16_to_cpu(ic->sb->integrity_tag_size) != ic->tag_size) {
3020 r = -EINVAL;
Mikulas Patocka9d609f82017-04-18 16:51:52 -04003021 ti->error = "Tag size doesn't match the information in superblock";
3022 goto bad;
3023 }
3024 if (ic->sb->log2_sectors_per_block != __ffs(ic->sectors_per_block)) {
3025 r = -EINVAL;
3026 ti->error = "Block size doesn't match the information in superblock";
Mikulas Patocka7eada902017-01-04 20:23:53 +01003027 goto bad;
3028 }
3029 /* make sure that ti->max_io_len doesn't overflow */
Mikulas Patocka56b67a42017-04-18 16:51:50 -04003030 if (ic->sb->log2_interleave_sectors < MIN_LOG2_INTERLEAVE_SECTORS ||
3031 ic->sb->log2_interleave_sectors > MAX_LOG2_INTERLEAVE_SECTORS) {
Mikulas Patocka7eada902017-01-04 20:23:53 +01003032 r = -EINVAL;
3033 ti->error = "Invalid interleave_sectors in the superblock";
3034 goto bad;
3035 }
3036 ic->provided_data_sectors = le64_to_cpu(ic->sb->provided_data_sectors);
3037 if (ic->provided_data_sectors != le64_to_cpu(ic->sb->provided_data_sectors)) {
3038 /* test for overflow */
3039 r = -EINVAL;
3040 ti->error = "The superblock has 64-bit device size, but the kernel was compiled with 32-bit sectors";
3041 goto bad;
3042 }
3043 if (!!(ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC)) != !!ic->journal_mac_alg.alg_string) {
3044 r = -EINVAL;
3045 ti->error = "Journal mac mismatch";
3046 goto bad;
3047 }
3048 r = calculate_device_limits(ic);
3049 if (r) {
3050 ti->error = "The device is too small";
3051 goto bad;
3052 }
Ondrej Mosnáček2ad50602017-06-05 17:52:39 +02003053 if (ti->len > ic->provided_data_sectors) {
3054 r = -EINVAL;
3055 ti->error = "Not enough provided sectors for requested mapping size";
3056 goto bad;
3057 }
Mikulas Patocka7eada902017-01-04 20:23:53 +01003058
3059 if (!buffer_sectors)
3060 buffer_sectors = 1;
3061 ic->log2_buffer_sectors = min3((int)__fls(buffer_sectors), (int)__ffs(ic->metadata_run), 31 - SECTOR_SHIFT);
3062
3063 threshold = (__u64)ic->journal_entries * (100 - journal_watermark);
3064 threshold += 50;
3065 do_div(threshold, 100);
3066 ic->free_sectors_threshold = threshold;
3067
3068 DEBUG_print("initialized:\n");
3069 DEBUG_print(" integrity_tag_size %u\n", le16_to_cpu(ic->sb->integrity_tag_size));
3070 DEBUG_print(" journal_entry_size %u\n", ic->journal_entry_size);
3071 DEBUG_print(" journal_entries_per_sector %u\n", ic->journal_entries_per_sector);
3072 DEBUG_print(" journal_section_entries %u\n", ic->journal_section_entries);
3073 DEBUG_print(" journal_section_sectors %u\n", ic->journal_section_sectors);
3074 DEBUG_print(" journal_sections %u\n", (unsigned)le32_to_cpu(ic->sb->journal_sections));
3075 DEBUG_print(" journal_entries %u\n", ic->journal_entries);
3076 DEBUG_print(" log2_interleave_sectors %d\n", ic->sb->log2_interleave_sectors);
3077 DEBUG_print(" device_sectors 0x%llx\n", (unsigned long long)ic->device_sectors);
3078 DEBUG_print(" initial_sectors 0x%x\n", ic->initial_sectors);
3079 DEBUG_print(" metadata_run 0x%x\n", ic->metadata_run);
3080 DEBUG_print(" log2_metadata_run %d\n", ic->log2_metadata_run);
3081 DEBUG_print(" provided_data_sectors 0x%llx (%llu)\n", (unsigned long long)ic->provided_data_sectors,
3082 (unsigned long long)ic->provided_data_sectors);
3083 DEBUG_print(" log2_buffer_sectors %u\n", ic->log2_buffer_sectors);
3084
3085 ic->bufio = dm_bufio_client_create(ic->dev->bdev, 1U << (SECTOR_SHIFT + ic->log2_buffer_sectors),
3086 1, 0, NULL, NULL);
3087 if (IS_ERR(ic->bufio)) {
3088 r = PTR_ERR(ic->bufio);
3089 ti->error = "Cannot initialize dm-bufio";
3090 ic->bufio = NULL;
3091 goto bad;
3092 }
3093 dm_bufio_set_sector_offset(ic->bufio, ic->start + ic->initial_sectors);
3094
Mikulas Patockac2bcb2b2017-03-17 12:40:51 -04003095 if (ic->mode != 'R') {
3096 r = create_journal(ic, &ti->error);
3097 if (r)
3098 goto bad;
3099 }
Mikulas Patocka7eada902017-01-04 20:23:53 +01003100
3101 if (should_write_sb) {
3102 int r;
3103
3104 init_journal(ic, 0, ic->journal_sections, 0);
3105 r = dm_integrity_failed(ic);
3106 if (unlikely(r)) {
3107 ti->error = "Error initializing journal";
3108 goto bad;
3109 }
3110 r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
3111 if (r) {
3112 ti->error = "Error initializing superblock";
3113 goto bad;
3114 }
3115 ic->just_formatted = true;
3116 }
3117
3118 r = dm_set_target_max_io_len(ti, 1U << ic->sb->log2_interleave_sectors);
3119 if (r)
3120 goto bad;
3121
3122 if (!ic->internal_hash)
3123 dm_integrity_set(ti, ic);
3124
3125 ti->num_flush_bios = 1;
3126 ti->flush_supported = true;
3127
3128 return 0;
3129bad:
3130 dm_integrity_dtr(ti);
3131 return r;
3132}
3133
3134static void dm_integrity_dtr(struct dm_target *ti)
3135{
3136 struct dm_integrity_c *ic = ti->private;
3137
3138 BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
3139
3140 if (ic->metadata_wq)
3141 destroy_workqueue(ic->metadata_wq);
3142 if (ic->wait_wq)
3143 destroy_workqueue(ic->wait_wq);
3144 if (ic->commit_wq)
3145 destroy_workqueue(ic->commit_wq);
3146 if (ic->writer_wq)
3147 destroy_workqueue(ic->writer_wq);
3148 if (ic->bufio)
3149 dm_bufio_client_destroy(ic->bufio);
3150 mempool_destroy(ic->journal_io_mempool);
3151 if (ic->io)
3152 dm_io_client_destroy(ic->io);
3153 if (ic->dev)
3154 dm_put_device(ti, ic->dev);
3155 dm_integrity_free_page_list(ic, ic->journal);
3156 dm_integrity_free_page_list(ic, ic->journal_io);
3157 dm_integrity_free_page_list(ic, ic->journal_xor);
3158 if (ic->journal_scatterlist)
3159 dm_integrity_free_journal_scatterlist(ic, ic->journal_scatterlist);
3160 if (ic->journal_io_scatterlist)
3161 dm_integrity_free_journal_scatterlist(ic, ic->journal_io_scatterlist);
3162 if (ic->sk_requests) {
3163 unsigned i;
3164
3165 for (i = 0; i < ic->journal_sections; i++) {
3166 struct skcipher_request *req = ic->sk_requests[i];
3167 if (req) {
3168 kzfree(req->iv);
3169 skcipher_request_free(req);
3170 }
3171 }
3172 kvfree(ic->sk_requests);
3173 }
3174 kvfree(ic->journal_tree);
3175 if (ic->sb)
3176 free_pages_exact(ic->sb, SB_SECTORS << SECTOR_SHIFT);
3177
3178 if (ic->internal_hash)
3179 crypto_free_shash(ic->internal_hash);
3180 free_alg(&ic->internal_hash_alg);
3181
3182 if (ic->journal_crypt)
3183 crypto_free_skcipher(ic->journal_crypt);
3184 free_alg(&ic->journal_crypt_alg);
3185
3186 if (ic->journal_mac)
3187 crypto_free_shash(ic->journal_mac);
3188 free_alg(&ic->journal_mac_alg);
3189
3190 kfree(ic);
3191}
3192
3193static struct target_type integrity_target = {
3194 .name = "integrity",
3195 .version = {1, 0, 0},
3196 .module = THIS_MODULE,
3197 .features = DM_TARGET_SINGLETON | DM_TARGET_INTEGRITY,
3198 .ctr = dm_integrity_ctr,
3199 .dtr = dm_integrity_dtr,
3200 .map = dm_integrity_map,
3201 .postsuspend = dm_integrity_postsuspend,
3202 .resume = dm_integrity_resume,
3203 .status = dm_integrity_status,
3204 .iterate_devices = dm_integrity_iterate_devices,
Mikulas Patocka9d609f82017-04-18 16:51:52 -04003205 .io_hints = dm_integrity_io_hints,
Mikulas Patocka7eada902017-01-04 20:23:53 +01003206};
3207
3208int __init dm_integrity_init(void)
3209{
3210 int r;
3211
3212 journal_io_cache = kmem_cache_create("integrity_journal_io",
3213 sizeof(struct journal_io), 0, 0, NULL);
3214 if (!journal_io_cache) {
3215 DMERR("can't allocate journal io cache");
3216 return -ENOMEM;
3217 }
3218
3219 r = dm_register_target(&integrity_target);
3220
3221 if (r < 0)
3222 DMERR("register failed %d", r);
3223
3224 return r;
3225}
3226
3227void dm_integrity_exit(void)
3228{
3229 dm_unregister_target(&integrity_target);
3230 kmem_cache_destroy(journal_io_cache);
3231}
3232
3233module_init(dm_integrity_init);
3234module_exit(dm_integrity_exit);
3235
3236MODULE_AUTHOR("Milan Broz");
3237MODULE_AUTHOR("Mikulas Patocka");
3238MODULE_DESCRIPTION(DM_NAME " target for integrity tags extension");
3239MODULE_LICENSE("GPL");