1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Copyright (C) 2016-2017 Red Hat, Inc. All rights reserved.
4 * Copyright (C) 2016-2017 Milan Broz
5 * Copyright (C) 2016-2017 Mikulas Patocka
6 *
7 * This file is released under the GPL.
8 */
9
10 #include "dm-bio-record.h"
11
12 #include <linux/compiler.h>
13 #include <linux/module.h>
14 #include <linux/device-mapper.h>
15 #include <linux/dm-io.h>
16 #include <linux/vmalloc.h>
17 #include <linux/sort.h>
18 #include <linux/rbtree.h>
19 #include <linux/delay.h>
20 #include <linux/hex.h>
21 #include <linux/random.h>
22 #include <linux/reboot.h>
23 #include <crypto/hash.h>
24 #include <crypto/skcipher.h>
25 #include <crypto/utils.h>
26 #include <linux/async_tx.h>
27 #include <linux/dm-bufio.h>
28
29 #include "dm-audit.h"
30
31 #define DM_MSG_PREFIX "integrity"
32
33 #define DEFAULT_INTERLEAVE_SECTORS 32768
34 #define DEFAULT_JOURNAL_SIZE_FACTOR 7
35 #define DEFAULT_SECTORS_PER_BITMAP_BIT 32768
36 #define DEFAULT_BUFFER_SECTORS 128
37 #define DEFAULT_JOURNAL_WATERMARK 50
38 #define DEFAULT_SYNC_MSEC 10000
39 #define DEFAULT_MAX_JOURNAL_SECTORS (IS_ENABLED(CONFIG_64BIT) ? 131072 : 8192)
40 #define MIN_LOG2_INTERLEAVE_SECTORS 3
41 #define MAX_LOG2_INTERLEAVE_SECTORS 31
42 #define METADATA_WORKQUEUE_MAX_ACTIVE 16
43 #define RECALC_SECTORS (IS_ENABLED(CONFIG_64BIT) ? 32768 : 2048)
44 #define RECALC_WRITE_SUPER 16
45 #define BITMAP_BLOCK_SIZE 4096 /* don't change it */
46 #define BITMAP_FLUSH_INTERVAL (10 * HZ)
47 #define DISCARD_FILLER 0xf6
48 #define SALT_SIZE 16
49 #define RECHECK_POOL_SIZE 256
50
51 /*
52 * Warning - DEBUG_PRINT prints security-sensitive data to the log,
53 * so it should not be enabled in the official kernel
54 */
55 //#define DEBUG_PRINT
56 //#define INTERNAL_VERIFY
57
58 /*
59 * On disk structures
60 */
61
62 #define SB_MAGIC "integrt"
63 #define SB_VERSION_1 1
64 #define SB_VERSION_2 2
65 #define SB_VERSION_3 3
66 #define SB_VERSION_4 4
67 #define SB_VERSION_5 5
68 #define SB_VERSION_6 6
69 #define SB_VERSION_7 7
70 #define SB_SECTORS 8
71 #define MAX_SECTORS_PER_BLOCK 8
72
73 struct superblock {
74 __u8 magic[8];
75 __u8 version;
76 __u8 log2_interleave_sectors;
77 __le16 integrity_tag_size;
78 __le32 journal_sections;
79 __le64 provided_data_sectors; /* userspace uses this value */
80 __le32 flags;
81 __u8 log2_sectors_per_block;
82 __u8 log2_blocks_per_bitmap_bit;
83 __u8 pad[2];
84 __le64 recalc_sector;
85 __u8 pad2[8];
86 __u8 salt[SALT_SIZE];
87 };
88
89 #define SB_FLAG_HAVE_JOURNAL_MAC 0x1
90 #define SB_FLAG_RECALCULATING 0x2
91 #define SB_FLAG_DIRTY_BITMAP 0x4
92 #define SB_FLAG_FIXED_PADDING 0x8
93 #define SB_FLAG_FIXED_HMAC 0x10
94 #define SB_FLAG_INLINE 0x20
95 #define SB_FLAG_DISCARD_KEYED 0x40
96
97 #define JOURNAL_ENTRY_ROUNDUP 8
98
99 typedef __le64 commit_id_t;
100 #define JOURNAL_MAC_PER_SECTOR 8
101
102 struct journal_entry {
103 union {
104 struct {
105 __le32 sector_lo;
106 __le32 sector_hi;
107 } s;
108 __le64 sector;
109 } u;
110 commit_id_t last_bytes[];
111 /* __u8 tag[0]; */
112 };
113
114 #define journal_entry_tag(ic, je) ((__u8 *)&(je)->last_bytes[(ic)->sectors_per_block])
115
116 #if BITS_PER_LONG == 64
117 #define journal_entry_set_sector(je, x) do { smp_wmb(); WRITE_ONCE((je)->u.sector, cpu_to_le64(x)); } while (0)
118 #else
119 #define journal_entry_set_sector(je, x) do { (je)->u.s.sector_lo = cpu_to_le32(x); smp_wmb(); WRITE_ONCE((je)->u.s.sector_hi, cpu_to_le32((x) >> 32)); } while (0)
120 #endif
121 #define journal_entry_get_sector(je) le64_to_cpu((je)->u.sector)
122 #define journal_entry_is_unused(je) ((je)->u.s.sector_hi == cpu_to_le32(-1))
123 #define journal_entry_set_unused(je) ((je)->u.s.sector_hi = cpu_to_le32(-1))
124 #define journal_entry_is_inprogress(je) ((je)->u.s.sector_hi == cpu_to_le32(-2))
125 #define journal_entry_set_inprogress(je) ((je)->u.s.sector_hi = cpu_to_le32(-2))
126
127 #define JOURNAL_BLOCK_SECTORS 8
128 #define JOURNAL_SECTOR_DATA ((1 << SECTOR_SHIFT) - sizeof(commit_id_t))
129 #define JOURNAL_MAC_SIZE (JOURNAL_MAC_PER_SECTOR * JOURNAL_BLOCK_SECTORS)
130
131 struct journal_sector {
132 struct_group(sectors,
133 __u8 entries[JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR];
134 __u8 mac[JOURNAL_MAC_PER_SECTOR];
135 );
136 commit_id_t commit_id;
137 };
138
139 #define MAX_TAG_SIZE 255
140
141 #define METADATA_PADDING_SECTORS 8
142
143 #define N_COMMIT_IDS 4
144
prev_commit_seq(unsigned char seq)145 static unsigned char prev_commit_seq(unsigned char seq)
146 {
147 return (seq + N_COMMIT_IDS - 1) % N_COMMIT_IDS;
148 }
149
next_commit_seq(unsigned char seq)150 static unsigned char next_commit_seq(unsigned char seq)
151 {
152 return (seq + 1) % N_COMMIT_IDS;
153 }
154
155 /*
156 * In-memory structures
157 */
158
159 struct journal_node {
160 struct rb_node node;
161 sector_t sector;
162 };
163
164 struct alg_spec {
165 char *alg_string;
166 char *key_string;
167 __u8 *key;
168 unsigned int key_size;
169 };
170
171 struct dm_integrity_c {
172 struct dm_dev *dev;
173 struct dm_dev *meta_dev;
174 unsigned int tag_size;
175 __s8 log2_tag_size;
176 unsigned int tuple_size;
177 sector_t start;
178 mempool_t journal_io_mempool;
179 struct dm_io_client *io;
180 struct dm_bufio_client *bufio;
181 struct workqueue_struct *metadata_wq;
182 struct superblock *sb;
183 struct superblock *sb_copy;
184 unsigned int journal_pages;
185 unsigned int n_bitmap_blocks;
186
187 struct page_list *journal;
188 struct page_list *journal_io;
189 struct page_list *journal_xor;
190 struct page_list *recalc_bitmap;
191 struct page_list *may_write_bitmap;
192 struct bitmap_block_status *bbs;
193 unsigned int bitmap_flush_interval;
194 int synchronous_mode;
195 struct bio_list synchronous_bios;
196 struct delayed_work bitmap_flush_work;
197
198 struct crypto_skcipher *journal_crypt;
199 struct scatterlist **journal_scatterlist;
200 struct scatterlist **journal_io_scatterlist;
201 struct skcipher_request **sk_requests;
202
203 struct crypto_shash *journal_mac;
204
205 struct journal_node *journal_tree;
206 struct rb_root journal_tree_root;
207
208 sector_t provided_data_sectors;
209
210 unsigned short journal_entry_size;
211 unsigned char journal_entries_per_sector;
212 unsigned char journal_section_entries;
213 unsigned short journal_section_sectors;
214 unsigned int journal_sections;
215 unsigned int journal_entries;
216 sector_t data_device_sectors;
217 sector_t meta_device_sectors;
218 unsigned int initial_sectors;
219 unsigned int metadata_run;
220 __s8 log2_metadata_run;
221 __u8 log2_buffer_sectors;
222 __u8 sectors_per_block;
223 __u8 log2_blocks_per_bitmap_bit;
224
225 unsigned char mode;
226 bool internal_hash;
227
228 int failed;
229
230 struct crypto_shash *internal_shash;
231 struct crypto_ahash *internal_ahash;
232 unsigned int internal_hash_digestsize;
233
234 struct dm_target *ti;
235
236 /* these variables are locked with endio_wait.lock */
237 struct rb_root in_progress;
238 struct list_head wait_list;
239 wait_queue_head_t endio_wait;
240 struct workqueue_struct *wait_wq;
241 struct workqueue_struct *offload_wq;
242
243 unsigned char commit_seq;
244 commit_id_t commit_ids[N_COMMIT_IDS];
245
246 unsigned int committed_section;
247 unsigned int n_committed_sections;
248
249 unsigned int uncommitted_section;
250 unsigned int n_uncommitted_sections;
251
252 unsigned int free_section;
253 unsigned char free_section_entry;
254 unsigned int free_sectors;
255
256 unsigned int free_sectors_threshold;
257
258 struct workqueue_struct *commit_wq;
259 struct work_struct commit_work;
260
261 struct workqueue_struct *writer_wq;
262 struct work_struct writer_work;
263
264 struct workqueue_struct *recalc_wq;
265 struct work_struct recalc_work;
266
267 struct bio_list flush_bio_list;
268
269 unsigned long autocommit_jiffies;
270 struct timer_list autocommit_timer;
271 unsigned int autocommit_msec;
272
273 wait_queue_head_t copy_to_journal_wait;
274
275 struct completion crypto_backoff;
276
277 bool wrote_to_journal;
278 bool journal_uptodate;
279 bool just_formatted;
280 bool recalculate_flag;
281 bool reset_recalculate_flag;
282 bool discard;
283 bool discard_keyed;
284 bool fix_padding;
285 bool fix_hmac;
286 bool legacy_recalculate;
287
288 mempool_t ahash_req_pool;
289 struct ahash_request *journal_ahash_req;
290
291 struct alg_spec internal_hash_alg;
292 struct alg_spec journal_crypt_alg;
293 struct alg_spec journal_mac_alg;
294
295 atomic64_t number_of_mismatches;
296
297 mempool_t recheck_pool;
298 struct bio_set recheck_bios;
299 struct bio_set recalc_bios;
300
301 struct notifier_block reboot_notifier;
302 };
303
304 struct dm_integrity_range {
305 sector_t logical_sector;
306 sector_t n_sectors;
307 bool waiting;
308 union {
309 struct rb_node node;
310 struct {
311 struct task_struct *task;
312 struct list_head wait_entry;
313 };
314 };
315 };
316
317 struct dm_integrity_io {
318 struct work_struct work;
319
320 struct dm_integrity_c *ic;
321 enum req_op op;
322 bool fua;
323
324 struct dm_integrity_range range;
325
326 sector_t metadata_block;
327 unsigned int metadata_offset;
328
329 atomic_t in_flight;
330 blk_status_t bi_status;
331
332 struct completion *completion;
333
334 struct dm_bio_details bio_details;
335
336 char *integrity_payload;
337 unsigned payload_len;
338 bool integrity_payload_from_mempool;
339 bool integrity_range_locked;
340
341 struct ahash_request *ahash_req;
342 };
343
344 struct journal_completion {
345 struct dm_integrity_c *ic;
346 atomic_t in_flight;
347 struct completion comp;
348 };
349
350 struct journal_io {
351 struct dm_integrity_range range;
352 struct journal_completion *comp;
353 };
354
355 struct bitmap_block_status {
356 struct work_struct work;
357 struct dm_integrity_c *ic;
358 unsigned int idx;
359 unsigned long *bitmap;
360 struct bio_list bio_queue;
361 spinlock_t bio_queue_lock;
362
363 };
364
365 static struct kmem_cache *journal_io_cache;
366
367 #define JOURNAL_IO_MEMPOOL 32
368 #define AHASH_MEMPOOL 32
369
370 #ifdef DEBUG_PRINT
371 #define DEBUG_print(x, ...) printk(KERN_DEBUG x, ##__VA_ARGS__)
372 #define DEBUG_bytes(bytes, len, msg, ...) printk(KERN_DEBUG msg "%s%*ph\n", ##__VA_ARGS__, \
373 len ? ": " : "", len, bytes)
374 #else
375 #define DEBUG_print(x, ...) do { } while (0)
376 #define DEBUG_bytes(bytes, len, msg, ...) do { } while (0)
377 #endif
378
379 static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map);
380 static int dm_integrity_map_inline(struct dm_integrity_io *dio, bool from_map);
381 static void integrity_bio_wait(struct work_struct *w);
382 static void dm_integrity_dtr(struct dm_target *ti);
383
dm_integrity_io_error(struct dm_integrity_c * ic,const char * msg,int err)384 static void dm_integrity_io_error(struct dm_integrity_c *ic, const char *msg, int err)
385 {
386 if (err == -EILSEQ)
387 atomic64_inc(&ic->number_of_mismatches);
388 if (!cmpxchg(&ic->failed, 0, err))
389 DMERR("Error on %s: %d", msg, err);
390 }
391
dm_integrity_failed(struct dm_integrity_c * ic)392 static int dm_integrity_failed(struct dm_integrity_c *ic)
393 {
394 return READ_ONCE(ic->failed);
395 }
396
dm_integrity_disable_recalculate(struct dm_integrity_c * ic)397 static bool dm_integrity_disable_recalculate(struct dm_integrity_c *ic)
398 {
399 if (ic->legacy_recalculate)
400 return false;
401 if (!(ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) ?
402 ic->internal_hash_alg.key || ic->journal_mac_alg.key :
403 ic->internal_hash_alg.key && !ic->journal_mac_alg.key)
404 return true;
405 return false;
406 }
407
dm_integrity_commit_id(struct dm_integrity_c * ic,unsigned int i,unsigned int j,unsigned char seq)408 static commit_id_t dm_integrity_commit_id(struct dm_integrity_c *ic, unsigned int i,
409 unsigned int j, unsigned char seq)
410 {
411 /*
412 * Xor the number with section and sector, so that if a piece of
413 * journal is written at wrong place, it is detected.
414 */
415 return ic->commit_ids[seq] ^ cpu_to_le64(((__u64)i << 32) ^ j);
416 }
417
get_area_and_offset(struct dm_integrity_c * ic,sector_t data_sector,sector_t * area,sector_t * offset)418 static void get_area_and_offset(struct dm_integrity_c *ic, sector_t data_sector,
419 sector_t *area, sector_t *offset)
420 {
421 if (!ic->meta_dev) {
422 __u8 log2_interleave_sectors = ic->sb->log2_interleave_sectors;
423 *area = data_sector >> log2_interleave_sectors;
424 *offset = (unsigned int)data_sector & ((1U << log2_interleave_sectors) - 1);
425 } else {
426 *area = 0;
427 *offset = data_sector;
428 }
429 }
430
431 #define sector_to_block(ic, n) \
432 do { \
433 BUG_ON((n) & (unsigned int)((ic)->sectors_per_block - 1)); \
434 (n) >>= (ic)->sb->log2_sectors_per_block; \
435 } while (0)
436
get_metadata_sector_and_offset(struct dm_integrity_c * ic,sector_t area,sector_t offset,unsigned int * metadata_offset)437 static __u64 get_metadata_sector_and_offset(struct dm_integrity_c *ic, sector_t area,
438 sector_t offset, unsigned int *metadata_offset)
439 {
440 __u64 ms;
441 unsigned int mo;
442
443 ms = area << ic->sb->log2_interleave_sectors;
444 if (likely(ic->log2_metadata_run >= 0))
445 ms += area << ic->log2_metadata_run;
446 else
447 ms += area * ic->metadata_run;
448 ms >>= ic->log2_buffer_sectors;
449
450 sector_to_block(ic, offset);
451
452 if (likely(ic->log2_tag_size >= 0)) {
453 ms += offset >> (SECTOR_SHIFT + ic->log2_buffer_sectors - ic->log2_tag_size);
454 mo = (offset << ic->log2_tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
455 } else {
456 ms += (__u64)offset * ic->tag_size >> (SECTOR_SHIFT + ic->log2_buffer_sectors);
457 mo = (offset * ic->tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
458 }
459 *metadata_offset = mo;
460 return ms;
461 }
462
get_data_sector(struct dm_integrity_c * ic,sector_t area,sector_t offset)463 static sector_t get_data_sector(struct dm_integrity_c *ic, sector_t area, sector_t offset)
464 {
465 sector_t result;
466
467 if (ic->meta_dev)
468 return offset;
469
470 result = area << ic->sb->log2_interleave_sectors;
471 if (likely(ic->log2_metadata_run >= 0))
472 result += (area + 1) << ic->log2_metadata_run;
473 else
474 result += (area + 1) * ic->metadata_run;
475
476 result += (sector_t)ic->initial_sectors + offset;
477 result += ic->start;
478
479 return result;
480 }
481
wraparound_section(struct dm_integrity_c * ic,unsigned int * sec_ptr)482 static void wraparound_section(struct dm_integrity_c *ic, unsigned int *sec_ptr)
483 {
484 if (unlikely(*sec_ptr >= ic->journal_sections))
485 *sec_ptr -= ic->journal_sections;
486 }
487
sb_set_version(struct dm_integrity_c * ic)488 static void sb_set_version(struct dm_integrity_c *ic)
489 {
490 if (ic->sb->flags & cpu_to_le32(SB_FLAG_DISCARD_KEYED))
491 ic->sb->version = SB_VERSION_7;
492 else if (ic->sb->flags & cpu_to_le32(SB_FLAG_INLINE))
493 ic->sb->version = SB_VERSION_6;
494 else if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC))
495 ic->sb->version = SB_VERSION_5;
496 else if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING))
497 ic->sb->version = SB_VERSION_4;
498 else if (ic->mode == 'B' || ic->sb->flags & cpu_to_le32(SB_FLAG_DIRTY_BITMAP))
499 ic->sb->version = SB_VERSION_3;
500 else if (ic->meta_dev || ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
501 ic->sb->version = SB_VERSION_2;
502 else
503 ic->sb->version = SB_VERSION_1;
504 }
505
sb_mac(struct dm_integrity_c * ic,bool wr)506 static int sb_mac(struct dm_integrity_c *ic, bool wr)
507 {
508 SHASH_DESC_ON_STACK(desc, ic->journal_mac);
509 int r;
510 unsigned int mac_size = crypto_shash_digestsize(ic->journal_mac);
511 __u8 *sb = (__u8 *)ic->sb;
512 __u8 *mac = sb + (1 << SECTOR_SHIFT) - mac_size;
513
514 if (sizeof(struct superblock) + mac_size > 1 << SECTOR_SHIFT ||
515 mac_size > HASH_MAX_DIGESTSIZE) {
516 dm_integrity_io_error(ic, "digest is too long", -EINVAL);
517 return -EINVAL;
518 }
519
520 desc->tfm = ic->journal_mac;
521
522 if (likely(wr)) {
523 r = crypto_shash_digest(desc, sb, mac - sb, mac);
524 if (unlikely(r < 0)) {
525 dm_integrity_io_error(ic, "crypto_shash_digest", r);
526 return r;
527 }
528 } else {
529 __u8 actual_mac[HASH_MAX_DIGESTSIZE];
530
531 r = crypto_shash_digest(desc, sb, mac - sb, actual_mac);
532 if (unlikely(r < 0)) {
533 dm_integrity_io_error(ic, "crypto_shash_digest", r);
534 return r;
535 }
536 if (crypto_memneq(mac, actual_mac, mac_size)) {
537 dm_integrity_io_error(ic, "superblock mac", -EILSEQ);
538 dm_audit_log_target(DM_MSG_PREFIX, "mac-superblock", ic->ti, 0);
539 return -EILSEQ;
540 }
541 }
542
543 return 0;
544 }
545
sync_rw_sb(struct dm_integrity_c * ic,blk_opf_t opf)546 static int sync_rw_sb(struct dm_integrity_c *ic, blk_opf_t opf)
547 {
548 struct dm_io_request io_req;
549 struct dm_io_region io_loc;
550 const enum req_op op = opf & REQ_OP_MASK;
551 int r;
552
553 io_req.bi_opf = opf;
554 io_req.mem.type = DM_IO_KMEM;
555 io_req.mem.ptr.addr = ic->sb;
556 io_req.notify.fn = NULL;
557 io_req.client = ic->io;
558 io_loc.bdev = ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev;
559 io_loc.sector = ic->start;
560 io_loc.count = SB_SECTORS;
561
562 if (op == REQ_OP_WRITE) {
563 sb_set_version(ic);
564 if (ic->journal_mac && ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
565 r = sb_mac(ic, true);
566 if (unlikely(r))
567 return r;
568 }
569 }
570
571 r = dm_io(&io_req, 1, &io_loc, NULL, NULL, IOPRIO_DEFAULT);
572 if (unlikely(r))
573 return r;
574
575 if (op == REQ_OP_READ) {
576 if (ic->mode != 'R' && ic->journal_mac && ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
577 r = sb_mac(ic, false);
578 if (unlikely(r))
579 return r;
580 }
581 }
582
583 return 0;
584 }
585
586 #define BITMAP_OP_TEST_ALL_SET 0
587 #define BITMAP_OP_TEST_ALL_CLEAR 1
588 #define BITMAP_OP_SET 2
589 #define BITMAP_OP_CLEAR 3
590
block_bitmap_op(struct dm_integrity_c * ic,struct page_list * bitmap,sector_t sector,sector_t n_sectors,int mode)591 static bool block_bitmap_op(struct dm_integrity_c *ic, struct page_list *bitmap,
592 sector_t sector, sector_t n_sectors, int mode)
593 {
594 unsigned long bit, end_bit, this_end_bit, page, end_page;
595 unsigned long *data;
596
597 if (unlikely(((sector | n_sectors) & ((1 << ic->sb->log2_sectors_per_block) - 1)) != 0)) {
598 DMCRIT("invalid bitmap access (%llx,%llx,%d,%d,%d)",
599 sector,
600 n_sectors,
601 ic->sb->log2_sectors_per_block,
602 ic->log2_blocks_per_bitmap_bit,
603 mode);
604 BUG();
605 }
606
607 if (unlikely(!n_sectors))
608 return true;
609
610 bit = sector >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
611 end_bit = (sector + n_sectors - 1) >>
612 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
613
614 page = bit / (PAGE_SIZE * 8);
615 bit %= PAGE_SIZE * 8;
616
617 end_page = end_bit / (PAGE_SIZE * 8);
618 end_bit %= PAGE_SIZE * 8;
619
620 repeat:
621 if (page < end_page)
622 this_end_bit = PAGE_SIZE * 8 - 1;
623 else
624 this_end_bit = end_bit;
625
626 data = lowmem_page_address(bitmap[page].page);
627
628 if (mode == BITMAP_OP_TEST_ALL_SET) {
629 while (bit <= this_end_bit) {
630 if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
631 do {
632 if (data[bit / BITS_PER_LONG] != -1)
633 return false;
634 bit += BITS_PER_LONG;
635 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
636 continue;
637 }
638 if (!test_bit(bit, data))
639 return false;
640 bit++;
641 }
642 } else if (mode == BITMAP_OP_TEST_ALL_CLEAR) {
643 while (bit <= this_end_bit) {
644 if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
645 do {
646 if (data[bit / BITS_PER_LONG] != 0)
647 return false;
648 bit += BITS_PER_LONG;
649 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
650 continue;
651 }
652 if (test_bit(bit, data))
653 return false;
654 bit++;
655 }
656 } else if (mode == BITMAP_OP_SET) {
657 while (bit <= this_end_bit) {
658 if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
659 do {
660 data[bit / BITS_PER_LONG] = -1;
661 bit += BITS_PER_LONG;
662 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
663 continue;
664 }
665 __set_bit(bit, data);
666 bit++;
667 }
668 } else if (mode == BITMAP_OP_CLEAR) {
669 if (!bit && this_end_bit == PAGE_SIZE * 8 - 1)
670 clear_page(data);
671 else {
672 while (bit <= this_end_bit) {
673 if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
674 do {
675 data[bit / BITS_PER_LONG] = 0;
676 bit += BITS_PER_LONG;
677 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
678 continue;
679 }
680 __clear_bit(bit, data);
681 bit++;
682 }
683 }
684 } else {
685 BUG();
686 }
687
688 if (unlikely(page < end_page)) {
689 bit = 0;
690 page++;
691 goto repeat;
692 }
693
694 return true;
695 }
696
block_bitmap_copy(struct dm_integrity_c * ic,struct page_list * dst,struct page_list * src)697 static void block_bitmap_copy(struct dm_integrity_c *ic, struct page_list *dst, struct page_list *src)
698 {
699 unsigned int n_bitmap_pages = DIV_ROUND_UP(ic->n_bitmap_blocks, PAGE_SIZE / BITMAP_BLOCK_SIZE);
700 unsigned int i;
701
702 for (i = 0; i < n_bitmap_pages; i++) {
703 unsigned long *dst_data = lowmem_page_address(dst[i].page);
704 unsigned long *src_data = lowmem_page_address(src[i].page);
705
706 copy_page(dst_data, src_data);
707 }
708 }
709
sector_to_bitmap_block(struct dm_integrity_c * ic,sector_t sector)710 static struct bitmap_block_status *sector_to_bitmap_block(struct dm_integrity_c *ic, sector_t sector)
711 {
712 unsigned int bit = sector >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
713 unsigned int bitmap_block = bit / (BITMAP_BLOCK_SIZE * 8);
714
715 BUG_ON(bitmap_block >= ic->n_bitmap_blocks);
716 return &ic->bbs[bitmap_block];
717 }
718
access_journal_check(struct dm_integrity_c * ic,unsigned int section,unsigned int offset,bool e,const char * function)719 static void access_journal_check(struct dm_integrity_c *ic, unsigned int section, unsigned int offset,
720 bool e, const char *function)
721 {
722 #if defined(CONFIG_DM_DEBUG) || defined(INTERNAL_VERIFY)
723 unsigned int limit = e ? ic->journal_section_entries : ic->journal_section_sectors;
724
725 if (unlikely(section >= ic->journal_sections) ||
726 unlikely(offset >= limit)) {
727 DMCRIT("%s: invalid access at (%u,%u), limit (%u,%u)",
728 function, section, offset, ic->journal_sections, limit);
729 BUG();
730 }
731 #endif
732 }
733
page_list_location(struct dm_integrity_c * ic,unsigned int section,unsigned int offset,unsigned int * pl_index,unsigned int * pl_offset)734 static void page_list_location(struct dm_integrity_c *ic, unsigned int section, unsigned int offset,
735 unsigned int *pl_index, unsigned int *pl_offset)
736 {
737 unsigned int sector;
738
739 access_journal_check(ic, section, offset, false, "page_list_location");
740
741 sector = section * ic->journal_section_sectors + offset;
742
743 *pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
744 *pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
745 }
746
access_page_list(struct dm_integrity_c * ic,struct page_list * pl,unsigned int section,unsigned int offset,unsigned int * n_sectors)747 static struct journal_sector *access_page_list(struct dm_integrity_c *ic, struct page_list *pl,
748 unsigned int section, unsigned int offset, unsigned int *n_sectors)
749 {
750 unsigned int pl_index, pl_offset;
751 char *va;
752
753 page_list_location(ic, section, offset, &pl_index, &pl_offset);
754
755 if (n_sectors)
756 *n_sectors = (PAGE_SIZE - pl_offset) >> SECTOR_SHIFT;
757
758 va = lowmem_page_address(pl[pl_index].page);
759
760 return (struct journal_sector *)(va + pl_offset);
761 }
762
access_journal(struct dm_integrity_c * ic,unsigned int section,unsigned int offset)763 static struct journal_sector *access_journal(struct dm_integrity_c *ic, unsigned int section, unsigned int offset)
764 {
765 return access_page_list(ic, ic->journal, section, offset, NULL);
766 }
767
access_journal_entry(struct dm_integrity_c * ic,unsigned int section,unsigned int n)768 static struct journal_entry *access_journal_entry(struct dm_integrity_c *ic, unsigned int section, unsigned int n)
769 {
770 unsigned int rel_sector, offset;
771 struct journal_sector *js;
772
773 access_journal_check(ic, section, n, true, "access_journal_entry");
774
775 rel_sector = n % JOURNAL_BLOCK_SECTORS;
776 offset = n / JOURNAL_BLOCK_SECTORS;
777
778 js = access_journal(ic, section, rel_sector);
779 return (struct journal_entry *)((char *)js + offset * ic->journal_entry_size);
780 }
781
access_journal_data(struct dm_integrity_c * ic,unsigned int section,unsigned int n)782 static struct journal_sector *access_journal_data(struct dm_integrity_c *ic, unsigned int section, unsigned int n)
783 {
784 n <<= ic->sb->log2_sectors_per_block;
785
786 n += JOURNAL_BLOCK_SECTORS;
787
788 access_journal_check(ic, section, n, false, "access_journal_data");
789
790 return access_journal(ic, section, n);
791 }
792
section_mac(struct dm_integrity_c * ic,unsigned int section,__u8 result[JOURNAL_MAC_SIZE])793 static void section_mac(struct dm_integrity_c *ic, unsigned int section, __u8 result[JOURNAL_MAC_SIZE])
794 {
795 SHASH_DESC_ON_STACK(desc, ic->journal_mac);
796 int r;
797 unsigned int j, size;
798
799 desc->tfm = ic->journal_mac;
800
801 r = crypto_shash_init(desc);
802 if (unlikely(r < 0)) {
803 dm_integrity_io_error(ic, "crypto_shash_init", r);
804 goto err;
805 }
806
807 if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
808 __le64 section_le;
809
810 r = crypto_shash_update(desc, (__u8 *)&ic->sb->salt, SALT_SIZE);
811 if (unlikely(r < 0)) {
812 dm_integrity_io_error(ic, "crypto_shash_update", r);
813 goto err;
814 }
815
816 section_le = cpu_to_le64(section);
817 r = crypto_shash_update(desc, (__u8 *)§ion_le, sizeof(section_le));
818 if (unlikely(r < 0)) {
819 dm_integrity_io_error(ic, "crypto_shash_update", r);
820 goto err;
821 }
822 }
823
824 for (j = 0; j < ic->journal_section_entries; j++) {
825 struct journal_entry *je = access_journal_entry(ic, section, j);
826
827 r = crypto_shash_update(desc, (__u8 *)&je->u.sector, sizeof(je->u.sector));
828 if (unlikely(r < 0)) {
829 dm_integrity_io_error(ic, "crypto_shash_update", r);
830 goto err;
831 }
832 }
833
834 size = crypto_shash_digestsize(ic->journal_mac);
835
836 if (likely(size <= JOURNAL_MAC_SIZE)) {
837 r = crypto_shash_final(desc, result);
838 if (unlikely(r < 0)) {
839 dm_integrity_io_error(ic, "crypto_shash_final", r);
840 goto err;
841 }
842 memset(result + size, 0, JOURNAL_MAC_SIZE - size);
843 } else {
844 __u8 digest[HASH_MAX_DIGESTSIZE];
845
846 if (WARN_ON(size > sizeof(digest))) {
847 dm_integrity_io_error(ic, "digest_size", -EINVAL);
848 goto err;
849 }
850 r = crypto_shash_final(desc, digest);
851 if (unlikely(r < 0)) {
852 dm_integrity_io_error(ic, "crypto_shash_final", r);
853 goto err;
854 }
855 memcpy(result, digest, JOURNAL_MAC_SIZE);
856 }
857
858 return;
859 err:
860 memset(result, 0, JOURNAL_MAC_SIZE);
861 }
862
rw_section_mac(struct dm_integrity_c * ic,unsigned int section,bool wr)863 static void rw_section_mac(struct dm_integrity_c *ic, unsigned int section, bool wr)
864 {
865 __u8 result[JOURNAL_MAC_SIZE];
866 unsigned int j;
867
868 if (!ic->journal_mac)
869 return;
870
871 section_mac(ic, section, result);
872
873 for (j = 0; j < JOURNAL_BLOCK_SECTORS; j++) {
874 struct journal_sector *js = access_journal(ic, section, j);
875
876 if (likely(wr))
877 memcpy(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR);
878 else {
879 if (crypto_memneq(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR)) {
880 dm_integrity_io_error(ic, "journal mac", -EILSEQ);
881 dm_audit_log_target(DM_MSG_PREFIX, "mac-journal", ic->ti, 0);
882 }
883 }
884 }
885 }
886
complete_journal_op(void * context)887 static void complete_journal_op(void *context)
888 {
889 struct journal_completion *comp = context;
890
891 BUG_ON(!atomic_read(&comp->in_flight));
892 if (likely(atomic_dec_and_test(&comp->in_flight)))
893 complete(&comp->comp);
894 }
895
xor_journal(struct dm_integrity_c * ic,bool encrypt,unsigned int section,unsigned int n_sections,struct journal_completion * comp)896 static void xor_journal(struct dm_integrity_c *ic, bool encrypt, unsigned int section,
897 unsigned int n_sections, struct journal_completion *comp)
898 {
899 struct async_submit_ctl submit;
900 size_t n_bytes = (size_t)(n_sections * ic->journal_section_sectors) << SECTOR_SHIFT;
901 unsigned int pl_index, pl_offset, section_index;
902 struct page_list *source_pl, *target_pl;
903
904 if (likely(encrypt)) {
905 source_pl = ic->journal;
906 target_pl = ic->journal_io;
907 } else {
908 source_pl = ic->journal_io;
909 target_pl = ic->journal;
910 }
911
912 page_list_location(ic, section, 0, &pl_index, &pl_offset);
913
914 atomic_add(roundup(pl_offset + n_bytes, PAGE_SIZE) >> PAGE_SHIFT, &comp->in_flight);
915
916 init_async_submit(&submit, ASYNC_TX_XOR_ZERO_DST, NULL, complete_journal_op, comp, NULL);
917
918 section_index = pl_index;
919
920 do {
921 size_t this_step;
922 struct page *src_pages[2];
923 struct page *dst_page;
924
925 while (unlikely(pl_index == section_index)) {
926 unsigned int dummy;
927
928 if (likely(encrypt))
929 rw_section_mac(ic, section, true);
930 section++;
931 n_sections--;
932 if (!n_sections)
933 break;
934 page_list_location(ic, section, 0, §ion_index, &dummy);
935 }
936
937 this_step = min(n_bytes, (size_t)PAGE_SIZE - pl_offset);
938 dst_page = target_pl[pl_index].page;
939 src_pages[0] = source_pl[pl_index].page;
940 src_pages[1] = ic->journal_xor[pl_index].page;
941
942 async_xor(dst_page, src_pages, pl_offset, 2, this_step, &submit);
943
944 pl_index++;
945 pl_offset = 0;
946 n_bytes -= this_step;
947 } while (n_bytes);
948
949 BUG_ON(n_sections);
950
951 async_tx_issue_pending_all();
952 }
953
complete_journal_encrypt(void * data,int err)954 static void complete_journal_encrypt(void *data, int err)
955 {
956 struct journal_completion *comp = data;
957
958 if (unlikely(err)) {
959 if (likely(err == -EINPROGRESS)) {
960 complete(&comp->ic->crypto_backoff);
961 return;
962 }
963 dm_integrity_io_error(comp->ic, "asynchronous encrypt", err);
964 }
965 complete_journal_op(comp);
966 }
967
do_crypt(bool encrypt,struct skcipher_request * req,struct journal_completion * comp)968 static bool do_crypt(bool encrypt, struct skcipher_request *req, struct journal_completion *comp)
969 {
970 int r;
971
972 skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
973 complete_journal_encrypt, comp);
974 if (likely(encrypt))
975 r = crypto_skcipher_encrypt(req);
976 else
977 r = crypto_skcipher_decrypt(req);
978 if (likely(!r))
979 return false;
980 if (likely(r == -EINPROGRESS))
981 return true;
982 if (likely(r == -EBUSY)) {
983 wait_for_completion(&comp->ic->crypto_backoff);
984 reinit_completion(&comp->ic->crypto_backoff);
985 return true;
986 }
987 dm_integrity_io_error(comp->ic, "encrypt", r);
988 return false;
989 }
990
crypt_journal(struct dm_integrity_c * ic,bool encrypt,unsigned int section,unsigned int n_sections,struct journal_completion * comp)991 static void crypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned int section,
992 unsigned int n_sections, struct journal_completion *comp)
993 {
994 struct scatterlist **source_sg;
995 struct scatterlist **target_sg;
996
997 atomic_add(2, &comp->in_flight);
998
999 if (likely(encrypt)) {
1000 source_sg = ic->journal_scatterlist;
1001 target_sg = ic->journal_io_scatterlist;
1002 } else {
1003 source_sg = ic->journal_io_scatterlist;
1004 target_sg = ic->journal_scatterlist;
1005 }
1006
1007 do {
1008 struct skcipher_request *req;
1009 unsigned int ivsize;
1010 char *iv;
1011
1012 if (likely(encrypt))
1013 rw_section_mac(ic, section, true);
1014
1015 req = ic->sk_requests[section];
1016 ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
1017 iv = req->iv;
1018
1019 memcpy(iv, iv + ivsize, ivsize);
1020
1021 req->src = source_sg[section];
1022 req->dst = target_sg[section];
1023
1024 if (unlikely(do_crypt(encrypt, req, comp)))
1025 atomic_inc(&comp->in_flight);
1026
1027 section++;
1028 n_sections--;
1029 } while (n_sections);
1030
1031 atomic_dec(&comp->in_flight);
1032 complete_journal_op(comp);
1033 }
1034
encrypt_journal(struct dm_integrity_c * ic,bool encrypt,unsigned int section,unsigned int n_sections,struct journal_completion * comp)1035 static void encrypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned int section,
1036 unsigned int n_sections, struct journal_completion *comp)
1037 {
1038 if (ic->journal_xor)
1039 return xor_journal(ic, encrypt, section, n_sections, comp);
1040 else
1041 return crypt_journal(ic, encrypt, section, n_sections, comp);
1042 }
1043
complete_journal_io(unsigned long error,unsigned long unsup,void * context)1044 static void complete_journal_io(unsigned long error, unsigned long unsup, void *context)
1045 {
1046 struct journal_completion *comp = context;
1047
1048 if (unlikely(error != 0))
1049 dm_integrity_io_error(comp->ic, "writing journal", -EIO);
1050 else if (unlikely(unsup != 0))
1051 dm_integrity_io_error(comp->ic, "writing journal", -EOPNOTSUPP);
1052 complete_journal_op(comp);
1053 }
1054
rw_journal_sectors(struct dm_integrity_c * ic,blk_opf_t opf,unsigned int sector,unsigned int n_sectors,struct journal_completion * comp)1055 static void rw_journal_sectors(struct dm_integrity_c *ic, blk_opf_t opf,
1056 unsigned int sector, unsigned int n_sectors,
1057 struct journal_completion *comp)
1058 {
1059 struct dm_io_request io_req;
1060 struct dm_io_region io_loc;
1061 unsigned int pl_index, pl_offset;
1062 int r;
1063
1064 if (unlikely(dm_integrity_failed(ic))) {
1065 if (comp)
1066 complete_journal_io(-1UL, -1UL, comp);
1067 return;
1068 }
1069
1070 pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
1071 pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
1072
1073 io_req.bi_opf = opf;
1074 io_req.mem.type = DM_IO_PAGE_LIST;
1075 if (ic->journal_io)
1076 io_req.mem.ptr.pl = &ic->journal_io[pl_index];
1077 else
1078 io_req.mem.ptr.pl = &ic->journal[pl_index];
1079 io_req.mem.offset = pl_offset;
1080 if (likely(comp != NULL)) {
1081 io_req.notify.fn = complete_journal_io;
1082 io_req.notify.context = comp;
1083 } else {
1084 io_req.notify.fn = NULL;
1085 }
1086 io_req.client = ic->io;
1087 io_loc.bdev = ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev;
1088 io_loc.sector = ic->start + SB_SECTORS + sector;
1089 io_loc.count = n_sectors;
1090
1091 r = dm_io(&io_req, 1, &io_loc, NULL, NULL, IOPRIO_DEFAULT);
1092 if (unlikely(r)) {
1093 dm_integrity_io_error(ic, (opf & REQ_OP_MASK) == REQ_OP_READ ?
1094 "reading journal" : "writing journal", r);
1095 if (comp) {
1096 WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
1097 complete_journal_io(-1UL, -1UL, comp);
1098 }
1099 }
1100 }
1101
rw_journal(struct dm_integrity_c * ic,blk_opf_t opf,unsigned int section,unsigned int n_sections,struct journal_completion * comp)1102 static void rw_journal(struct dm_integrity_c *ic, blk_opf_t opf,
1103 unsigned int section, unsigned int n_sections,
1104 struct journal_completion *comp)
1105 {
1106 unsigned int sector, n_sectors;
1107
1108 sector = section * ic->journal_section_sectors;
1109 n_sectors = n_sections * ic->journal_section_sectors;
1110
1111 rw_journal_sectors(ic, opf, sector, n_sectors, comp);
1112 }
1113
write_journal(struct dm_integrity_c * ic,unsigned int commit_start,unsigned int commit_sections)1114 static void write_journal(struct dm_integrity_c *ic, unsigned int commit_start, unsigned int commit_sections)
1115 {
1116 struct journal_completion io_comp;
1117 struct journal_completion crypt_comp_1;
1118 struct journal_completion crypt_comp_2;
1119 unsigned int i;
1120
1121 io_comp.ic = ic;
1122 init_completion(&io_comp.comp);
1123
1124 if (commit_start + commit_sections <= ic->journal_sections) {
1125 io_comp.in_flight = (atomic_t)ATOMIC_INIT(1);
1126 if (ic->journal_io) {
1127 crypt_comp_1.ic = ic;
1128 init_completion(&crypt_comp_1.comp);
1129 crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
1130 encrypt_journal(ic, true, commit_start, commit_sections, &crypt_comp_1);
1131 wait_for_completion_io(&crypt_comp_1.comp);
1132 } else {
1133 for (i = 0; i < commit_sections; i++)
1134 rw_section_mac(ic, commit_start + i, true);
1135 }
1136 rw_journal(ic, REQ_OP_WRITE | REQ_FUA | REQ_SYNC, commit_start,
1137 commit_sections, &io_comp);
1138 } else {
1139 unsigned int to_end;
1140
1141 io_comp.in_flight = (atomic_t)ATOMIC_INIT(2);
1142 to_end = ic->journal_sections - commit_start;
1143 if (ic->journal_io) {
1144 crypt_comp_1.ic = ic;
1145 init_completion(&crypt_comp_1.comp);
1146 crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
1147 encrypt_journal(ic, true, commit_start, to_end, &crypt_comp_1);
1148 if (try_wait_for_completion(&crypt_comp_1.comp)) {
1149 rw_journal(ic, REQ_OP_WRITE | REQ_FUA,
1150 commit_start, to_end, &io_comp);
1151 reinit_completion(&crypt_comp_1.comp);
1152 crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
1153 encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_1);
1154 wait_for_completion_io(&crypt_comp_1.comp);
1155 } else {
1156 crypt_comp_2.ic = ic;
1157 init_completion(&crypt_comp_2.comp);
1158 crypt_comp_2.in_flight = (atomic_t)ATOMIC_INIT(0);
1159 encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_2);
1160 wait_for_completion_io(&crypt_comp_1.comp);
1161 rw_journal(ic, REQ_OP_WRITE | REQ_FUA, commit_start, to_end, &io_comp);
1162 wait_for_completion_io(&crypt_comp_2.comp);
1163 }
1164 } else {
1165 for (i = 0; i < to_end; i++)
1166 rw_section_mac(ic, commit_start + i, true);
1167 rw_journal(ic, REQ_OP_WRITE | REQ_FUA, commit_start, to_end, &io_comp);
1168 for (i = 0; i < commit_sections - to_end; i++)
1169 rw_section_mac(ic, i, true);
1170 }
1171 rw_journal(ic, REQ_OP_WRITE | REQ_FUA, 0, commit_sections - to_end, &io_comp);
1172 }
1173
1174 wait_for_completion_io(&io_comp.comp);
1175 }
1176
copy_from_journal(struct dm_integrity_c * ic,unsigned int section,unsigned int offset,unsigned int n_sectors,sector_t target,io_notify_fn fn,void * data)1177 static void copy_from_journal(struct dm_integrity_c *ic, unsigned int section, unsigned int offset,
1178 unsigned int n_sectors, sector_t target, io_notify_fn fn, void *data)
1179 {
1180 struct dm_io_request io_req;
1181 struct dm_io_region io_loc;
1182 int r;
1183 unsigned int sector, pl_index, pl_offset;
1184
1185 BUG_ON((target | n_sectors | offset) & (unsigned int)(ic->sectors_per_block - 1));
1186
1187 if (unlikely(dm_integrity_failed(ic))) {
1188 fn(-1UL, -1UL, data);
1189 return;
1190 }
1191
1192 sector = section * ic->journal_section_sectors + JOURNAL_BLOCK_SECTORS + offset;
1193
1194 pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
1195 pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
1196
1197 io_req.bi_opf = REQ_OP_WRITE;
1198 io_req.mem.type = DM_IO_PAGE_LIST;
1199 io_req.mem.ptr.pl = &ic->journal[pl_index];
1200 io_req.mem.offset = pl_offset;
1201 io_req.notify.fn = fn;
1202 io_req.notify.context = data;
1203 io_req.client = ic->io;
1204 io_loc.bdev = ic->dev->bdev;
1205 io_loc.sector = target;
1206 io_loc.count = n_sectors;
1207
1208 r = dm_io(&io_req, 1, &io_loc, NULL, NULL, IOPRIO_DEFAULT);
1209 if (unlikely(r)) {
1210 WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
1211 fn(-1UL, -1UL, data);
1212 }
1213 }
1214
ranges_overlap(struct dm_integrity_range * range1,struct dm_integrity_range * range2)1215 static bool ranges_overlap(struct dm_integrity_range *range1, struct dm_integrity_range *range2)
1216 {
1217 return range1->logical_sector < range2->logical_sector + range2->n_sectors &&
1218 range1->logical_sector + range1->n_sectors > range2->logical_sector;
1219 }
1220
add_new_range(struct dm_integrity_c * ic,struct dm_integrity_range * new_range,bool check_waiting)1221 static bool add_new_range(struct dm_integrity_c *ic, struct dm_integrity_range *new_range, bool check_waiting)
1222 {
1223 struct rb_node **n = &ic->in_progress.rb_node;
1224 struct rb_node *parent;
1225
1226 BUG_ON((new_range->logical_sector | new_range->n_sectors) & (unsigned int)(ic->sectors_per_block - 1));
1227
1228 if (likely(check_waiting)) {
1229 struct dm_integrity_range *range;
1230
1231 list_for_each_entry(range, &ic->wait_list, wait_entry) {
1232 if (unlikely(ranges_overlap(range, new_range)))
1233 return false;
1234 }
1235 }
1236
1237 parent = NULL;
1238
1239 while (*n) {
1240 struct dm_integrity_range *range = container_of(*n, struct dm_integrity_range, node);
1241
1242 parent = *n;
1243 if (new_range->logical_sector + new_range->n_sectors <= range->logical_sector)
1244 n = &range->node.rb_left;
1245 else if (new_range->logical_sector >= range->logical_sector + range->n_sectors)
1246 n = &range->node.rb_right;
1247 else
1248 return false;
1249 }
1250
1251 rb_link_node(&new_range->node, parent, n);
1252 rb_insert_color(&new_range->node, &ic->in_progress);
1253
1254 return true;
1255 }
1256
remove_range_unlocked(struct dm_integrity_c * ic,struct dm_integrity_range * range)1257 static void remove_range_unlocked(struct dm_integrity_c *ic, struct dm_integrity_range *range)
1258 {
1259 rb_erase(&range->node, &ic->in_progress);
1260 while (unlikely(!list_empty(&ic->wait_list))) {
1261 struct dm_integrity_range *last_range =
1262 list_first_entry(&ic->wait_list, struct dm_integrity_range, wait_entry);
1263 struct task_struct *last_range_task;
1264
1265 last_range_task = last_range->task;
1266 list_del(&last_range->wait_entry);
1267 if (!add_new_range(ic, last_range, false)) {
1268 last_range->task = last_range_task;
1269 list_add(&last_range->wait_entry, &ic->wait_list);
1270 break;
1271 }
1272 last_range->waiting = false;
1273 wake_up_process(last_range_task);
1274 }
1275 }
1276
remove_range(struct dm_integrity_c * ic,struct dm_integrity_range * range)1277 static void remove_range(struct dm_integrity_c *ic, struct dm_integrity_range *range)
1278 {
1279 unsigned long flags;
1280
1281 spin_lock_irqsave(&ic->endio_wait.lock, flags);
1282 remove_range_unlocked(ic, range);
1283 spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1284 }
1285
wait_and_add_new_range(struct dm_integrity_c * ic,struct dm_integrity_range * new_range)1286 static void wait_and_add_new_range(struct dm_integrity_c *ic, struct dm_integrity_range *new_range)
1287 {
1288 new_range->waiting = true;
1289 list_add_tail(&new_range->wait_entry, &ic->wait_list);
1290 new_range->task = current;
1291 do {
1292 __set_current_state(TASK_UNINTERRUPTIBLE);
1293 spin_unlock_irq(&ic->endio_wait.lock);
1294 io_schedule();
1295 spin_lock_irq(&ic->endio_wait.lock);
1296 } while (unlikely(new_range->waiting));
1297 }
1298
add_new_range_and_wait(struct dm_integrity_c * ic,struct dm_integrity_range * new_range)1299 static void add_new_range_and_wait(struct dm_integrity_c *ic, struct dm_integrity_range *new_range)
1300 {
1301 if (unlikely(!add_new_range(ic, new_range, true)))
1302 wait_and_add_new_range(ic, new_range);
1303 }
1304
init_journal_node(struct journal_node * node)1305 static void init_journal_node(struct journal_node *node)
1306 {
1307 RB_CLEAR_NODE(&node->node);
1308 node->sector = (sector_t)-1;
1309 }
1310
add_journal_node(struct dm_integrity_c * ic,struct journal_node * node,sector_t sector)1311 static void add_journal_node(struct dm_integrity_c *ic, struct journal_node *node, sector_t sector)
1312 {
1313 struct rb_node **link;
1314 struct rb_node *parent;
1315
1316 node->sector = sector;
1317 BUG_ON(!RB_EMPTY_NODE(&node->node));
1318
1319 link = &ic->journal_tree_root.rb_node;
1320 parent = NULL;
1321
1322 while (*link) {
1323 struct journal_node *j;
1324
1325 parent = *link;
1326 j = container_of(parent, struct journal_node, node);
1327 if (sector < j->sector)
1328 link = &j->node.rb_left;
1329 else
1330 link = &j->node.rb_right;
1331 }
1332
1333 rb_link_node(&node->node, parent, link);
1334 rb_insert_color(&node->node, &ic->journal_tree_root);
1335 }
1336
remove_journal_node(struct dm_integrity_c * ic,struct journal_node * node)1337 static void remove_journal_node(struct dm_integrity_c *ic, struct journal_node *node)
1338 {
1339 BUG_ON(RB_EMPTY_NODE(&node->node));
1340 rb_erase(&node->node, &ic->journal_tree_root);
1341 init_journal_node(node);
1342 }
1343
1344 #define NOT_FOUND (-1U)
1345
find_journal_node(struct dm_integrity_c * ic,sector_t sector,sector_t * next_sector)1346 static unsigned int find_journal_node(struct dm_integrity_c *ic, sector_t sector, sector_t *next_sector)
1347 {
1348 struct rb_node *n = ic->journal_tree_root.rb_node;
1349 unsigned int found = NOT_FOUND;
1350
1351 *next_sector = (sector_t)-1;
1352 while (n) {
1353 struct journal_node *j = container_of(n, struct journal_node, node);
1354
1355 if (sector == j->sector)
1356 found = j - ic->journal_tree;
1357
1358 if (sector < j->sector) {
1359 *next_sector = j->sector;
1360 n = j->node.rb_left;
1361 } else
1362 n = j->node.rb_right;
1363 }
1364
1365 return found;
1366 }
1367
test_journal_node(struct dm_integrity_c * ic,unsigned int pos,sector_t sector)1368 static bool test_journal_node(struct dm_integrity_c *ic, unsigned int pos, sector_t sector)
1369 {
1370 struct journal_node *node, *next_node;
1371 struct rb_node *next;
1372
1373 if (unlikely(pos >= ic->journal_entries))
1374 return false;
1375 node = &ic->journal_tree[pos];
1376 if (unlikely(RB_EMPTY_NODE(&node->node)))
1377 return false;
1378 if (unlikely(node->sector != sector))
1379 return false;
1380
1381 next = rb_next(&node->node);
1382 if (unlikely(!next))
1383 return true;
1384
1385 next_node = container_of(next, struct journal_node, node);
1386 return next_node->sector != sector;
1387 }
1388
find_newer_committed_node(struct dm_integrity_c * ic,struct journal_node * node)1389 static bool find_newer_committed_node(struct dm_integrity_c *ic, struct journal_node *node)
1390 {
1391 struct rb_node *next;
1392 struct journal_node *next_node;
1393 unsigned int next_section;
1394
1395 BUG_ON(RB_EMPTY_NODE(&node->node));
1396
1397 next = rb_next(&node->node);
1398 if (unlikely(!next))
1399 return false;
1400
1401 next_node = container_of(next, struct journal_node, node);
1402
1403 if (next_node->sector != node->sector)
1404 return false;
1405
1406 next_section = (unsigned int)(next_node - ic->journal_tree) / ic->journal_section_entries;
1407 if (next_section >= ic->committed_section &&
1408 next_section < ic->committed_section + ic->n_committed_sections)
1409 return true;
1410 if (next_section + ic->journal_sections < ic->committed_section + ic->n_committed_sections)
1411 return true;
1412
1413 return false;
1414 }
1415
1416 #define TAG_READ 0
1417 #define TAG_WRITE 1
1418 #define TAG_CMP 2
1419
dm_integrity_rw_tag(struct dm_integrity_c * ic,unsigned char * tag,sector_t * metadata_block,unsigned int * metadata_offset,unsigned int total_size,int op)1420 static int dm_integrity_rw_tag(struct dm_integrity_c *ic, unsigned char *tag, sector_t *metadata_block,
1421 unsigned int *metadata_offset, unsigned int total_size, int op)
1422 {
1423 unsigned int hash_offset = 0;
1424 unsigned char mismatch_hash = 0;
1425 unsigned char mismatch_filler = !ic->discard || ic->discard_keyed;
1426
1427 do {
1428 unsigned char *data, *dp;
1429 struct dm_buffer *b;
1430 unsigned int to_copy;
1431 int r;
1432
1433 r = dm_integrity_failed(ic);
1434 if (unlikely(r))
1435 return r;
1436
1437 data = dm_bufio_read(ic->bufio, *metadata_block, &b);
1438 if (IS_ERR(data))
1439 return PTR_ERR(data);
1440
1441 to_copy = min((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - *metadata_offset, total_size);
1442 dp = data + *metadata_offset;
1443 if (op == TAG_READ) {
1444 memcpy(tag, dp, to_copy);
1445 } else if (op == TAG_WRITE) {
1446 if (crypto_memneq(dp, tag, to_copy)) {
1447 memcpy(dp, tag, to_copy);
1448 dm_bufio_mark_partial_buffer_dirty(b, *metadata_offset, *metadata_offset + to_copy);
1449 }
1450 } else {
1451 /* e.g.: op == TAG_CMP */
1452
1453 if (likely(is_power_of_2(ic->tag_size))) {
1454 if (unlikely(crypto_memneq(dp, tag, to_copy)))
1455 goto thorough_test;
1456 } else {
1457 unsigned int i, ts;
1458 thorough_test:
1459 ts = total_size;
1460
1461 for (i = 0; i < to_copy; i++, ts--) {
1462 /*
1463 * Warning: the control flow must not be
1464 * dependent on match/mismatch of
1465 * individual bytes.
1466 */
1467 mismatch_hash |= dp[i] ^ tag[i];
1468 mismatch_filler |= dp[i] ^ DISCARD_FILLER;
1469 hash_offset++;
1470 if (unlikely(hash_offset == ic->tag_size)) {
1471 if (unlikely(mismatch_hash) && unlikely(mismatch_filler)) {
1472 dm_bufio_release(b);
1473 return ts;
1474 }
1475 hash_offset = 0;
1476 mismatch_hash = 0;
1477 mismatch_filler = !ic->discard || ic->discard_keyed;
1478 }
1479 }
1480 }
1481 }
1482 dm_bufio_release(b);
1483
1484 tag += to_copy;
1485 *metadata_offset += to_copy;
1486 if (unlikely(*metadata_offset == 1U << SECTOR_SHIFT << ic->log2_buffer_sectors)) {
1487 (*metadata_block)++;
1488 *metadata_offset = 0;
1489 }
1490
1491 total_size -= to_copy;
1492 } while (unlikely(total_size));
1493
1494 return 0;
1495 }
1496
1497 struct flush_request {
1498 struct dm_io_request io_req;
1499 struct dm_io_region io_reg;
1500 struct dm_integrity_c *ic;
1501 struct completion comp;
1502 };
1503
flush_notify(unsigned long error,unsigned long unsup,void * fr_)1504 static void flush_notify(unsigned long error, unsigned long unsup, void *fr_)
1505 {
1506 struct flush_request *fr = fr_;
1507
1508 if (unlikely(error != 0))
1509 dm_integrity_io_error(fr->ic, "flushing disk cache", -EIO);
1510 else if (unlikely(unsup != 0))
1511 dm_integrity_io_error(fr->ic, "flushing disk cache", -EOPNOTSUPP);
1512 complete(&fr->comp);
1513 }
1514
dm_integrity_flush_buffers(struct dm_integrity_c * ic,bool flush_data)1515 static void dm_integrity_flush_buffers(struct dm_integrity_c *ic, bool flush_data)
1516 {
1517 int r;
1518 struct flush_request fr;
1519
1520 if (!ic->meta_dev)
1521 flush_data = false;
1522 if (flush_data) {
1523 fr.io_req.bi_opf = REQ_OP_WRITE | REQ_PREFLUSH | REQ_SYNC;
1524 fr.io_req.mem.type = DM_IO_KMEM;
1525 fr.io_req.mem.ptr.addr = NULL;
1526 fr.io_req.notify.fn = flush_notify;
1527 fr.io_req.notify.context = &fr;
1528 fr.io_req.client = dm_bufio_get_dm_io_client(ic->bufio);
1529 fr.io_reg.bdev = ic->dev->bdev;
1530 fr.io_reg.sector = 0;
1531 fr.io_reg.count = 0;
1532 fr.ic = ic;
1533 init_completion(&fr.comp);
1534 r = dm_io(&fr.io_req, 1, &fr.io_reg, NULL, NULL, IOPRIO_DEFAULT);
1535 BUG_ON(r);
1536 }
1537
1538 r = dm_bufio_write_dirty_buffers(ic->bufio);
1539 if (unlikely(r))
1540 dm_integrity_io_error(ic, "writing tags", r);
1541
1542 if (flush_data)
1543 wait_for_completion(&fr.comp);
1544 }
1545
sleep_on_endio_wait(struct dm_integrity_c * ic)1546 static void sleep_on_endio_wait(struct dm_integrity_c *ic)
1547 {
1548 DECLARE_WAITQUEUE(wait, current);
1549
1550 __add_wait_queue(&ic->endio_wait, &wait);
1551 __set_current_state(TASK_UNINTERRUPTIBLE);
1552 spin_unlock_irq(&ic->endio_wait.lock);
1553 io_schedule();
1554 spin_lock_irq(&ic->endio_wait.lock);
1555 __remove_wait_queue(&ic->endio_wait, &wait);
1556 }
1557
autocommit_fn(struct timer_list * t)1558 static void autocommit_fn(struct timer_list *t)
1559 {
1560 struct dm_integrity_c *ic = timer_container_of(ic, t,
1561 autocommit_timer);
1562
1563 if (likely(!dm_integrity_failed(ic)))
1564 queue_work(ic->commit_wq, &ic->commit_work);
1565 }
1566
schedule_autocommit(struct dm_integrity_c * ic)1567 static void schedule_autocommit(struct dm_integrity_c *ic)
1568 {
1569 if (!timer_pending(&ic->autocommit_timer))
1570 mod_timer(&ic->autocommit_timer, jiffies + ic->autocommit_jiffies);
1571 }
1572
submit_flush_bio(struct dm_integrity_c * ic,struct dm_integrity_io * dio)1573 static void submit_flush_bio(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
1574 {
1575 struct bio *bio;
1576 unsigned long flags;
1577
1578 spin_lock_irqsave(&ic->endio_wait.lock, flags);
1579 bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1580 bio_list_add(&ic->flush_bio_list, bio);
1581 spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1582
1583 queue_work(ic->commit_wq, &ic->commit_work);
1584 }
1585
do_endio(struct dm_integrity_c * ic,struct bio * bio)1586 static void do_endio(struct dm_integrity_c *ic, struct bio *bio)
1587 {
1588 int r;
1589
1590 r = dm_integrity_failed(ic);
1591 if (unlikely(r) && !bio->bi_status)
1592 bio->bi_status = errno_to_blk_status(r);
1593 if (unlikely(ic->synchronous_mode) && bio_op(bio) == REQ_OP_WRITE) {
1594 unsigned long flags;
1595
1596 spin_lock_irqsave(&ic->endio_wait.lock, flags);
1597 bio_list_add(&ic->synchronous_bios, bio);
1598 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
1599 spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1600 return;
1601 }
1602 bio_endio(bio);
1603 }
1604
do_endio_flush(struct dm_integrity_c * ic,struct dm_integrity_io * dio)1605 static void do_endio_flush(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
1606 {
1607 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1608
1609 if (unlikely(dio->fua) && likely(!bio->bi_status) && likely(!dm_integrity_failed(ic)))
1610 submit_flush_bio(ic, dio);
1611 else
1612 do_endio(ic, bio);
1613 }
1614
dec_in_flight(struct dm_integrity_io * dio)1615 static void dec_in_flight(struct dm_integrity_io *dio)
1616 {
1617 if (atomic_dec_and_test(&dio->in_flight)) {
1618 struct dm_integrity_c *ic = dio->ic;
1619 struct bio *bio;
1620
1621 remove_range(ic, &dio->range);
1622
1623 if (dio->op == REQ_OP_WRITE || unlikely(dio->op == REQ_OP_DISCARD))
1624 schedule_autocommit(ic);
1625
1626 bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1627 if (unlikely(dio->bi_status) && !bio->bi_status)
1628 bio->bi_status = dio->bi_status;
1629 if (likely(!bio->bi_status) && unlikely(bio_sectors(bio) != dio->range.n_sectors)) {
1630 dio->range.logical_sector += dio->range.n_sectors;
1631 bio_advance(bio, dio->range.n_sectors << SECTOR_SHIFT);
1632 INIT_WORK(&dio->work, integrity_bio_wait);
1633 queue_work(ic->offload_wq, &dio->work);
1634 return;
1635 }
1636 do_endio_flush(ic, dio);
1637 }
1638 }
1639
integrity_end_io(struct bio * bio)1640 static void integrity_end_io(struct bio *bio)
1641 {
1642 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
1643
1644 dm_bio_restore(&dio->bio_details, bio);
1645 if (bio->bi_integrity)
1646 bio->bi_opf |= REQ_INTEGRITY;
1647
1648 if (dio->completion)
1649 complete(dio->completion);
1650
1651 dec_in_flight(dio);
1652 }
1653
integrity_sector_checksum_shash(struct dm_integrity_c * ic,sector_t sector,const char * data,unsigned offset,unsigned int len,char * result)1654 static void integrity_sector_checksum_shash(struct dm_integrity_c *ic, sector_t sector,
1655 const char *data, unsigned offset,
1656 unsigned int len, char *result)
1657 {
1658 __le64 sector_le = cpu_to_le64(sector);
1659 SHASH_DESC_ON_STACK(req, ic->internal_shash);
1660 int r;
1661 unsigned int digest_size;
1662
1663 req->tfm = ic->internal_shash;
1664
1665 r = crypto_shash_init(req);
1666 if (unlikely(r < 0)) {
1667 dm_integrity_io_error(ic, "crypto_shash_init", r);
1668 goto failed;
1669 }
1670
1671 if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
1672 r = crypto_shash_update(req, (__u8 *)&ic->sb->salt, SALT_SIZE);
1673 if (unlikely(r < 0)) {
1674 dm_integrity_io_error(ic, "crypto_shash_update", r);
1675 goto failed;
1676 }
1677 }
1678
1679 r = crypto_shash_update(req, (const __u8 *)§or_le, sizeof(sector_le));
1680 if (unlikely(r < 0)) {
1681 dm_integrity_io_error(ic, "crypto_shash_update", r);
1682 goto failed;
1683 }
1684
1685 if (likely(len)) {
1686 r = crypto_shash_update(req, data + offset, len);
1687 if (unlikely(r < 0)) {
1688 dm_integrity_io_error(ic, "crypto_shash_update", r);
1689 goto failed;
1690 }
1691 }
1692
1693 r = crypto_shash_final(req, result);
1694 if (unlikely(r < 0)) {
1695 dm_integrity_io_error(ic, "crypto_shash_final", r);
1696 goto failed;
1697 }
1698
1699 digest_size = ic->internal_hash_digestsize;
1700 if (unlikely(digest_size < ic->tag_size))
1701 memset(result + digest_size, 0, ic->tag_size - digest_size);
1702
1703 return;
1704
1705 failed:
1706 /* this shouldn't happen anyway, the hash functions have no reason to fail */
1707 get_random_bytes(result, ic->tag_size);
1708 }
1709
integrity_sector_checksum_ahash(struct dm_integrity_c * ic,struct ahash_request ** ahash_req,sector_t sector,struct page * page,unsigned offset,unsigned int len,char * result)1710 static void integrity_sector_checksum_ahash(struct dm_integrity_c *ic, struct ahash_request **ahash_req,
1711 sector_t sector, struct page *page, unsigned offset,
1712 unsigned int len, char *result)
1713 {
1714 __le64 sector_le = cpu_to_le64(sector);
1715 struct ahash_request *req;
1716 DECLARE_CRYPTO_WAIT(wait);
1717 struct scatterlist sg[3], *s = sg;
1718 int r;
1719 unsigned int digest_size;
1720 unsigned int nbytes = 0;
1721 unsigned int nents = 1 + (len ? 1 : 0);
1722
1723 might_sleep();
1724
1725 req = *ahash_req;
1726 if (unlikely(!req)) {
1727 req = mempool_alloc(&ic->ahash_req_pool, GFP_NOIO);
1728 *ahash_req = req;
1729 }
1730
1731 ahash_request_set_tfm(req, ic->internal_ahash);
1732 ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP, crypto_req_done, &wait);
1733
1734 if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
1735 sg_init_table(sg, nents + 1);
1736 sg_set_buf(s, (const __u8 *)&ic->sb->salt, SALT_SIZE);
1737 nbytes += SALT_SIZE;
1738 s++;
1739 } else {
1740 sg_init_table(sg, nents);
1741 }
1742
1743 if (likely(!is_vmalloc_addr(§or_le))) {
1744 sg_set_buf(s, §or_le, sizeof(sector_le));
1745 } else {
1746 struct page *sec_page = vmalloc_to_page(§or_le);
1747 unsigned int sec_off = offset_in_page(§or_le);
1748 sg_set_page(s, sec_page, sizeof(sector_le), sec_off);
1749 }
1750 nbytes += sizeof(sector_le);
1751 s++;
1752
1753 if (likely(len)) {
1754 sg_set_page(s, page, len, offset);
1755 nbytes += len;
1756 }
1757
1758 ahash_request_set_crypt(req, sg, result, nbytes);
1759
1760 r = crypto_wait_req(crypto_ahash_digest(req), &wait);
1761 if (unlikely(r)) {
1762 dm_integrity_io_error(ic, "crypto_ahash_digest", r);
1763 goto failed;
1764 }
1765
1766 digest_size = ic->internal_hash_digestsize;
1767 if (unlikely(digest_size < ic->tag_size))
1768 memset(result + digest_size, 0, ic->tag_size - digest_size);
1769
1770 return;
1771
1772 failed:
1773 /* this shouldn't happen anyway, the hash functions have no reason to fail */
1774 get_random_bytes(result, ic->tag_size);
1775 }
1776
integrity_sector_checksum(struct dm_integrity_c * ic,struct ahash_request ** ahash_req,sector_t sector,const char * data,unsigned offset,char * result)1777 static void integrity_sector_checksum(struct dm_integrity_c *ic, struct ahash_request **ahash_req,
1778 sector_t sector, const char *data, unsigned offset, char *result)
1779 {
1780 unsigned int len = ic->sectors_per_block << SECTOR_SHIFT;
1781
1782 if (likely(ic->internal_shash != NULL))
1783 integrity_sector_checksum_shash(ic, sector, data, offset, len, result);
1784 else
1785 integrity_sector_checksum_ahash(ic, ahash_req, sector, (struct page *)data,
1786 offset, len, result);
1787 }
1788
1789 /*
1790 * Authenticated marker for a discarded block: HMAC_key(salt || sector), with
1791 * no data payload. Because a real data tag's input always covers a full
1792 * block, its length differs from this marker's, so the two can never
1793 * collide structurally, regardless of block content.
1794 */
integrity_discard_checksum(struct dm_integrity_c * ic,struct ahash_request ** ahash_req,sector_t sector,char * result)1795 static void integrity_discard_checksum(struct dm_integrity_c *ic, struct ahash_request **ahash_req,
1796 sector_t sector, char *result)
1797 {
1798 if (likely(ic->internal_shash != NULL))
1799 integrity_sector_checksum_shash(ic, sector, NULL, 0, 0, result);
1800 else
1801 integrity_sector_checksum_ahash(ic, ahash_req, sector, NULL, 0, 0, result);
1802 }
1803
integrity_discard_fill_tags(struct dm_integrity_c * ic,struct ahash_request ** ahash_req,unsigned char * checksums,sector_t * sector,unsigned int blocks)1804 static void integrity_discard_fill_tags(struct dm_integrity_c *ic, struct ahash_request **ahash_req,
1805 unsigned char *checksums, sector_t *sector,
1806 unsigned int blocks)
1807 {
1808 unsigned int i;
1809
1810 for (i = 0; i < blocks; i++) {
1811 integrity_discard_checksum(ic, ahash_req, *sector, checksums + i * ic->tag_size);
1812 *sector += ic->sectors_per_block;
1813 }
1814 }
1815
integrity_kmap(struct dm_integrity_c * ic,struct page * p)1816 static void *integrity_kmap(struct dm_integrity_c *ic, struct page *p)
1817 {
1818 if (likely(ic->internal_shash != NULL))
1819 return kmap_local_page(p);
1820 else
1821 return p;
1822 }
1823
integrity_kunmap(struct dm_integrity_c * ic,const void * ptr)1824 static void integrity_kunmap(struct dm_integrity_c *ic, const void *ptr)
1825 {
1826 if (likely(ic->internal_shash != NULL))
1827 kunmap_local(ptr);
1828 }
1829
integrity_identity(struct dm_integrity_c * ic,void * data)1830 static void *integrity_identity(struct dm_integrity_c *ic, void *data)
1831 {
1832 #ifdef CONFIG_DEBUG_SG
1833 BUG_ON(offset_in_page(data));
1834 BUG_ON(!virt_addr_valid(data));
1835 #endif
1836 if (likely(ic->internal_shash != NULL))
1837 return data;
1838 else
1839 return virt_to_page(data);
1840 }
1841
integrity_recheck_verify_tag(struct dm_integrity_io * dio,char * checksum,char * on_disk_tag,sector_t logical_sector)1842 static int integrity_recheck_verify_tag(struct dm_integrity_io *dio, char *checksum,
1843 char *on_disk_tag, sector_t logical_sector)
1844 {
1845 struct dm_integrity_c *ic = dio->ic;
1846 int r;
1847
1848 if (!ic->discard_keyed)
1849 return dm_integrity_rw_tag(ic, checksum, &dio->metadata_block,
1850 &dio->metadata_offset, ic->tag_size, TAG_CMP);
1851
1852 r = dm_integrity_rw_tag(ic, on_disk_tag, &dio->metadata_block,
1853 &dio->metadata_offset, ic->tag_size, TAG_READ);
1854 if (unlikely(r))
1855 return r;
1856
1857 r = crypto_memneq(on_disk_tag, checksum, ic->tag_size);
1858 if (unlikely(r)) {
1859 integrity_discard_checksum(ic, &dio->ahash_req, logical_sector, checksum);
1860 r = crypto_memneq(on_disk_tag, checksum, ic->tag_size);
1861 }
1862 return r;
1863 }
1864
integrity_recheck(struct dm_integrity_io * dio,char * checksum)1865 static noinline void integrity_recheck(struct dm_integrity_io *dio, char *checksum)
1866 {
1867 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1868 struct dm_integrity_c *ic = dio->ic;
1869 struct bvec_iter iter;
1870 struct bio_vec bv;
1871 sector_t sector, logical_sector, area, offset;
1872 struct page *page;
1873
1874 get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
1875 dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset,
1876 &dio->metadata_offset);
1877 sector = get_data_sector(ic, area, offset);
1878 logical_sector = dio->range.logical_sector;
1879
1880 page = mempool_alloc(&ic->recheck_pool, GFP_NOIO);
1881
1882 __bio_for_each_segment(bv, bio, iter, dio->bio_details.bi_iter) {
1883 unsigned pos = 0;
1884
1885 do {
1886 sector_t alignment;
1887 char *mem;
1888 char *buffer = page_to_virt(page);
1889 unsigned int buffer_offset;
1890 char on_disk_tag[MAX_T(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
1891 int r;
1892 struct dm_io_request io_req;
1893 struct dm_io_region io_loc;
1894 io_req.bi_opf = REQ_OP_READ;
1895 io_req.mem.type = DM_IO_KMEM;
1896 io_req.mem.ptr.addr = buffer;
1897 io_req.notify.fn = NULL;
1898 io_req.client = ic->io;
1899 io_loc.bdev = ic->dev->bdev;
1900 io_loc.sector = sector;
1901 io_loc.count = ic->sectors_per_block;
1902
1903 /* Align the bio to logical block size */
1904 alignment = dio->range.logical_sector | bio_sectors(bio) | (PAGE_SIZE >> SECTOR_SHIFT);
1905 alignment &= -alignment;
1906 io_loc.sector = round_down(io_loc.sector, alignment);
1907 io_loc.count += sector - io_loc.sector;
1908 buffer_offset = (sector - io_loc.sector) << SECTOR_SHIFT;
1909 io_loc.count = round_up(io_loc.count, alignment);
1910
1911 r = dm_io(&io_req, 1, &io_loc, NULL, NULL, IOPRIO_DEFAULT);
1912 if (unlikely(r)) {
1913 dio->bi_status = errno_to_blk_status(r);
1914 goto free_ret;
1915 }
1916
1917 integrity_sector_checksum(ic, &dio->ahash_req, logical_sector, integrity_identity(ic, buffer), buffer_offset, checksum);
1918 r = integrity_recheck_verify_tag(dio, checksum, on_disk_tag,
1919 logical_sector);
1920 if (r) {
1921 if (r > 0) {
1922 DMERR_LIMIT("%pg: Checksum failed at sector 0x%llx",
1923 bio->bi_bdev, logical_sector);
1924 atomic64_inc(&ic->number_of_mismatches);
1925 dm_audit_log_bio(DM_MSG_PREFIX, "integrity-checksum",
1926 bio, logical_sector, 0);
1927 r = -EILSEQ;
1928 }
1929 dio->bi_status = errno_to_blk_status(r);
1930 goto free_ret;
1931 }
1932
1933 mem = bvec_kmap_local(&bv);
1934 memcpy(mem + pos, buffer + buffer_offset, ic->sectors_per_block << SECTOR_SHIFT);
1935 kunmap_local(mem);
1936
1937 pos += ic->sectors_per_block << SECTOR_SHIFT;
1938 sector += ic->sectors_per_block;
1939 logical_sector += ic->sectors_per_block;
1940 } while (pos < bv.bv_len);
1941 }
1942 free_ret:
1943 mempool_free(page, &ic->recheck_pool);
1944 }
1945
integrity_metadata(struct work_struct * w)1946 static void integrity_metadata(struct work_struct *w)
1947 {
1948 struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
1949 struct dm_integrity_c *ic = dio->ic;
1950
1951 int r;
1952
1953 if (ic->internal_hash) {
1954 struct bvec_iter iter;
1955 struct bio_vec bv;
1956 unsigned int digest_size = ic->internal_hash_digestsize;
1957 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1958 char *checksums;
1959 unsigned int extra_space = unlikely(digest_size > ic->tag_size) ? digest_size - ic->tag_size : 0;
1960 char checksums_onstack[MAX_T(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
1961 sector_t sector;
1962 unsigned int sectors_to_process;
1963
1964 if (unlikely(ic->mode == 'R'))
1965 goto skip_io;
1966
1967 if (likely(dio->op != REQ_OP_DISCARD))
1968 checksums = kmalloc((PAGE_SIZE >> SECTOR_SHIFT >> ic->sb->log2_sectors_per_block) * ic->tag_size + extra_space,
1969 GFP_NOIO | __GFP_NORETRY | __GFP_NOWARN);
1970 else
1971 checksums = kmalloc(PAGE_SIZE, GFP_NOIO | __GFP_NORETRY | __GFP_NOWARN);
1972 if (!checksums) {
1973 checksums = checksums_onstack;
1974 if (WARN_ON(extra_space &&
1975 digest_size > sizeof(checksums_onstack))) {
1976 r = -EINVAL;
1977 goto error;
1978 }
1979 }
1980
1981 if (unlikely(dio->op == REQ_OP_DISCARD)) {
1982 unsigned int bi_size = dio->bio_details.bi_iter.bi_size;
1983 unsigned int max_size = likely(checksums != checksums_onstack) ? PAGE_SIZE : sizeof(checksums_onstack);
1984 unsigned int max_blocks = (max_size - extra_space) / ic->tag_size;
1985 sector_t sector = dio->range.logical_sector;
1986
1987 if (!ic->discard_keyed)
1988 memset(checksums, DISCARD_FILLER, max_size);
1989
1990 while (bi_size) {
1991 unsigned int this_step_blocks = bi_size >> (SECTOR_SHIFT + ic->sb->log2_sectors_per_block);
1992
1993 this_step_blocks = min(this_step_blocks, max_blocks);
1994 if (ic->discard_keyed)
1995 integrity_discard_fill_tags(ic, &dio->ahash_req, checksums,
1996 §or, this_step_blocks);
1997 r = dm_integrity_rw_tag(ic, checksums, &dio->metadata_block, &dio->metadata_offset,
1998 this_step_blocks * ic->tag_size, TAG_WRITE);
1999 if (unlikely(r)) {
2000 if (likely(checksums != checksums_onstack))
2001 kfree(checksums);
2002 goto error;
2003 }
2004
2005 bi_size -= this_step_blocks << (SECTOR_SHIFT + ic->sb->log2_sectors_per_block);
2006 }
2007
2008 if (likely(checksums != checksums_onstack))
2009 kfree(checksums);
2010 goto skip_io;
2011 }
2012
2013 sector = dio->range.logical_sector;
2014 sectors_to_process = dio->range.n_sectors;
2015
2016 __bio_for_each_segment(bv, bio, iter, dio->bio_details.bi_iter) {
2017 struct bio_vec bv_copy = bv;
2018 unsigned int pos;
2019 char *mem, *checksums_ptr;
2020
2021 again:
2022 mem = integrity_kmap(ic, bv_copy.bv_page);
2023 pos = 0;
2024 checksums_ptr = checksums;
2025 do {
2026 integrity_sector_checksum(ic, &dio->ahash_req, sector, mem, bv_copy.bv_offset + pos, checksums_ptr);
2027 checksums_ptr += ic->tag_size;
2028 sectors_to_process -= ic->sectors_per_block;
2029 pos += ic->sectors_per_block << SECTOR_SHIFT;
2030 sector += ic->sectors_per_block;
2031 } while (pos < bv_copy.bv_len && sectors_to_process && checksums != checksums_onstack);
2032 integrity_kunmap(ic, mem);
2033
2034 r = dm_integrity_rw_tag(ic, checksums, &dio->metadata_block, &dio->metadata_offset,
2035 checksums_ptr - checksums, dio->op == REQ_OP_READ ? TAG_CMP : TAG_WRITE);
2036 if (unlikely(r)) {
2037 if (likely(checksums != checksums_onstack))
2038 kfree(checksums);
2039 if (r > 0) {
2040 integrity_recheck(dio, checksums_onstack);
2041 goto skip_io;
2042 }
2043 goto error;
2044 }
2045
2046 if (!sectors_to_process)
2047 break;
2048
2049 if (unlikely(pos < bv_copy.bv_len)) {
2050 bv_copy.bv_offset += pos;
2051 bv_copy.bv_len -= pos;
2052 goto again;
2053 }
2054 }
2055
2056 if (likely(checksums != checksums_onstack))
2057 kfree(checksums);
2058 } else {
2059 struct bio_integrity_payload *bip = dio->bio_details.bi_integrity;
2060
2061 if (bip) {
2062 struct bio_vec biv;
2063 struct bvec_iter iter;
2064 unsigned int data_to_process = dio->range.n_sectors;
2065
2066 sector_to_block(ic, data_to_process);
2067 data_to_process *= ic->tag_size;
2068
2069 bip_for_each_vec(biv, bip, iter) {
2070 unsigned char *tag;
2071 unsigned int this_len;
2072
2073 BUG_ON(PageHighMem(biv.bv_page));
2074 tag = bvec_virt(&biv);
2075 this_len = min(biv.bv_len, data_to_process);
2076 r = dm_integrity_rw_tag(ic, tag, &dio->metadata_block, &dio->metadata_offset,
2077 this_len, dio->op == REQ_OP_READ ? TAG_READ : TAG_WRITE);
2078 if (unlikely(r))
2079 goto error;
2080 data_to_process -= this_len;
2081 if (!data_to_process)
2082 break;
2083 }
2084 }
2085 }
2086 skip_io:
2087 dec_in_flight(dio);
2088 return;
2089 error:
2090 dio->bi_status = errno_to_blk_status(r);
2091 dec_in_flight(dio);
2092 }
2093
dm_integrity_check_limits(struct dm_integrity_c * ic,sector_t logical_sector,struct bio * bio)2094 static inline bool dm_integrity_check_limits(struct dm_integrity_c *ic, sector_t logical_sector, struct bio *bio)
2095 {
2096 if (unlikely(logical_sector + bio_sectors(bio) > ic->provided_data_sectors)) {
2097 DMERR("Too big sector number: 0x%llx + 0x%x > 0x%llx",
2098 logical_sector, bio_sectors(bio),
2099 ic->provided_data_sectors);
2100 return false;
2101 }
2102 if (unlikely((logical_sector | bio_sectors(bio)) & (unsigned int)(ic->sectors_per_block - 1))) {
2103 DMERR("Bio not aligned on %u sectors: 0x%llx, 0x%x",
2104 ic->sectors_per_block,
2105 logical_sector, bio_sectors(bio));
2106 return false;
2107 }
2108 if (ic->sectors_per_block > 1 && likely(bio_op(bio) != REQ_OP_DISCARD)) {
2109 struct bvec_iter iter;
2110 struct bio_vec bv;
2111
2112 bio_for_each_segment(bv, bio, iter) {
2113 if (unlikely(bv.bv_len & ((ic->sectors_per_block << SECTOR_SHIFT) - 1))) {
2114 DMERR("Bio vector (%u,%u) is not aligned on %u-sector boundary",
2115 bv.bv_offset, bv.bv_len, ic->sectors_per_block);
2116 return false;
2117 }
2118 }
2119 }
2120 return true;
2121 }
2122
dm_integrity_map(struct dm_target * ti,struct bio * bio)2123 static int dm_integrity_map(struct dm_target *ti, struct bio *bio)
2124 {
2125 struct dm_integrity_c *ic = ti->private;
2126 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
2127 struct bio_integrity_payload *bip;
2128
2129 sector_t area, offset;
2130
2131 dio->ic = ic;
2132 dio->bi_status = 0;
2133 dio->op = bio_op(bio);
2134 dio->ahash_req = NULL;
2135
2136 if (ic->mode == 'I') {
2137 bio->bi_iter.bi_sector = dm_target_offset(ic->ti, bio->bi_iter.bi_sector);
2138 dio->integrity_payload = NULL;
2139 dio->integrity_payload_from_mempool = false;
2140 dio->integrity_range_locked = false;
2141 return dm_integrity_map_inline(dio, true);
2142 }
2143
2144 if (unlikely(dio->op == REQ_OP_DISCARD)) {
2145 if (ti->max_io_len) {
2146 sector_t sec = dm_target_offset(ti, bio->bi_iter.bi_sector);
2147 unsigned int log2_max_io_len = __fls(ti->max_io_len);
2148 sector_t start_boundary = sec >> log2_max_io_len;
2149 sector_t end_boundary = (sec + bio_sectors(bio) - 1) >> log2_max_io_len;
2150
2151 if (start_boundary < end_boundary) {
2152 sector_t len = ti->max_io_len - (sec & (ti->max_io_len - 1));
2153
2154 dm_accept_partial_bio(bio, len);
2155 }
2156 }
2157 }
2158
2159 if (unlikely(bio->bi_opf & REQ_PREFLUSH)) {
2160 submit_flush_bio(ic, dio);
2161 return DM_MAPIO_SUBMITTED;
2162 }
2163
2164 dio->range.logical_sector = dm_target_offset(ti, bio->bi_iter.bi_sector);
2165 dio->fua = dio->op == REQ_OP_WRITE && bio->bi_opf & REQ_FUA;
2166 if (unlikely(dio->fua)) {
2167 /*
2168 * Don't pass down the FUA flag because we have to flush
2169 * disk cache anyway.
2170 */
2171 bio->bi_opf &= ~REQ_FUA;
2172 }
2173 if (unlikely(!dm_integrity_check_limits(ic, dio->range.logical_sector, bio)))
2174 return DM_MAPIO_KILL;
2175
2176 bip = bio_integrity(bio);
2177 if (!ic->internal_hash) {
2178 if (bip) {
2179 unsigned int wanted_tag_size = bio_sectors(bio) >> ic->sb->log2_sectors_per_block;
2180
2181 if (ic->log2_tag_size >= 0)
2182 wanted_tag_size <<= ic->log2_tag_size;
2183 else
2184 wanted_tag_size *= ic->tag_size;
2185 if (unlikely(wanted_tag_size != bip->bip_iter.bi_size)) {
2186 DMERR("Invalid integrity data size %u, expected %u",
2187 bip->bip_iter.bi_size, wanted_tag_size);
2188 return DM_MAPIO_KILL;
2189 }
2190 }
2191 } else {
2192 if (unlikely(bip != NULL)) {
2193 DMERR("Unexpected integrity data when using internal hash");
2194 return DM_MAPIO_KILL;
2195 }
2196 }
2197
2198 if (unlikely(ic->mode == 'R') && unlikely(dio->op != REQ_OP_READ))
2199 return DM_MAPIO_KILL;
2200
2201 get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
2202 dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
2203 bio->bi_iter.bi_sector = get_data_sector(ic, area, offset);
2204
2205 dm_integrity_map_continue(dio, true);
2206 return DM_MAPIO_SUBMITTED;
2207 }
2208
__journal_read_write(struct dm_integrity_io * dio,struct bio * bio,unsigned int journal_section,unsigned int journal_entry)2209 static bool __journal_read_write(struct dm_integrity_io *dio, struct bio *bio,
2210 unsigned int journal_section, unsigned int journal_entry)
2211 {
2212 struct dm_integrity_c *ic = dio->ic;
2213 sector_t logical_sector;
2214 unsigned int n_sectors;
2215
2216 logical_sector = dio->range.logical_sector;
2217 n_sectors = dio->range.n_sectors;
2218 do {
2219 struct bio_vec bv = bio_iovec(bio);
2220 char *mem;
2221
2222 if (unlikely(bv.bv_len >> SECTOR_SHIFT > n_sectors))
2223 bv.bv_len = n_sectors << SECTOR_SHIFT;
2224 n_sectors -= bv.bv_len >> SECTOR_SHIFT;
2225 bio_advance_iter(bio, &bio->bi_iter, bv.bv_len);
2226 retry_kmap:
2227 mem = kmap_local_page(bv.bv_page);
2228 if (likely(dio->op == REQ_OP_WRITE))
2229 flush_dcache_page(bv.bv_page);
2230
2231 do {
2232 struct journal_entry *je = access_journal_entry(ic, journal_section, journal_entry);
2233
2234 if (unlikely(dio->op == REQ_OP_READ)) {
2235 struct journal_sector *js;
2236 char *mem_ptr;
2237 unsigned int s;
2238
2239 if (unlikely(journal_entry_is_inprogress(je))) {
2240 flush_dcache_page(bv.bv_page);
2241 kunmap_local(mem);
2242
2243 __io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
2244 goto retry_kmap;
2245 }
2246 smp_rmb();
2247 BUG_ON(journal_entry_get_sector(je) != logical_sector);
2248 js = access_journal_data(ic, journal_section, journal_entry);
2249 mem_ptr = mem + bv.bv_offset;
2250 s = 0;
2251 do {
2252 memcpy(mem_ptr, js, JOURNAL_SECTOR_DATA);
2253 *(commit_id_t *)(mem_ptr + JOURNAL_SECTOR_DATA) = je->last_bytes[s];
2254 js++;
2255 mem_ptr += 1 << SECTOR_SHIFT;
2256 } while (++s < ic->sectors_per_block);
2257 }
2258
2259 if (!ic->internal_hash) {
2260 struct bio_integrity_payload *bip = bio_integrity(bio);
2261 unsigned int tag_todo = ic->tag_size;
2262 char *tag_ptr = journal_entry_tag(ic, je);
2263
2264 if (bip) {
2265 do {
2266 struct bio_vec biv = bvec_iter_bvec(bip->bip_vec, bip->bip_iter);
2267 unsigned int tag_now = min(biv.bv_len, tag_todo);
2268 char *tag_addr;
2269
2270 BUG_ON(PageHighMem(biv.bv_page));
2271 tag_addr = bvec_virt(&biv);
2272 if (likely(dio->op == REQ_OP_WRITE))
2273 memcpy(tag_ptr, tag_addr, tag_now);
2274 else
2275 memcpy(tag_addr, tag_ptr, tag_now);
2276 bvec_iter_advance(bip->bip_vec, &bip->bip_iter, tag_now);
2277 tag_ptr += tag_now;
2278 tag_todo -= tag_now;
2279 } while (unlikely(tag_todo));
2280 } else if (likely(dio->op == REQ_OP_WRITE))
2281 memset(tag_ptr, 0, tag_todo);
2282 }
2283
2284 if (likely(dio->op == REQ_OP_WRITE)) {
2285 struct journal_sector *js;
2286 unsigned int s;
2287
2288 js = access_journal_data(ic, journal_section, journal_entry);
2289 memcpy(js, mem + bv.bv_offset, ic->sectors_per_block << SECTOR_SHIFT);
2290
2291 s = 0;
2292 do {
2293 je->last_bytes[s] = js[s].commit_id;
2294 } while (++s < ic->sectors_per_block);
2295
2296 if (ic->internal_hash) {
2297 unsigned int digest_size = ic->internal_hash_digestsize;
2298 void *js_page = integrity_identity(ic, (char *)js - offset_in_page(js));
2299 unsigned js_offset = offset_in_page(js);
2300
2301 if (unlikely(digest_size > ic->tag_size)) {
2302 char checksums_onstack[HASH_MAX_DIGESTSIZE];
2303
2304 integrity_sector_checksum(ic, &dio->ahash_req, logical_sector, js_page, js_offset, checksums_onstack);
2305 memcpy(journal_entry_tag(ic, je), checksums_onstack, ic->tag_size);
2306 } else
2307 integrity_sector_checksum(ic, &dio->ahash_req, logical_sector, js_page, js_offset, journal_entry_tag(ic, je));
2308 }
2309
2310 journal_entry_set_sector(je, logical_sector);
2311 }
2312 logical_sector += ic->sectors_per_block;
2313
2314 journal_entry++;
2315 if (unlikely(journal_entry == ic->journal_section_entries)) {
2316 journal_entry = 0;
2317 journal_section++;
2318 wraparound_section(ic, &journal_section);
2319 }
2320
2321 bv.bv_offset += ic->sectors_per_block << SECTOR_SHIFT;
2322 } while (bv.bv_len -= ic->sectors_per_block << SECTOR_SHIFT);
2323
2324 if (unlikely(dio->op == REQ_OP_READ))
2325 flush_dcache_page(bv.bv_page);
2326 kunmap_local(mem);
2327 } while (n_sectors);
2328
2329 if (likely(dio->op == REQ_OP_WRITE)) {
2330 smp_mb();
2331 if (unlikely(waitqueue_active(&ic->copy_to_journal_wait)))
2332 wake_up(&ic->copy_to_journal_wait);
2333 if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold)
2334 queue_work(ic->commit_wq, &ic->commit_work);
2335 else
2336 schedule_autocommit(ic);
2337 } else
2338 remove_range(ic, &dio->range);
2339
2340 if (unlikely(bio->bi_iter.bi_size)) {
2341 sector_t area, offset;
2342
2343 dio->range.logical_sector = logical_sector;
2344 get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
2345 dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
2346 return true;
2347 }
2348
2349 return false;
2350 }
2351
dm_integrity_map_continue(struct dm_integrity_io * dio,bool from_map)2352 static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map)
2353 {
2354 struct dm_integrity_c *ic = dio->ic;
2355 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
2356 unsigned int journal_section, journal_entry;
2357 unsigned int journal_read_pos;
2358 sector_t recalc_sector;
2359 struct completion read_comp;
2360 bool discard_retried = false;
2361 bool need_sync_io = ic->internal_hash && dio->op == REQ_OP_READ;
2362
2363 if (unlikely(dio->op == REQ_OP_DISCARD) && ic->mode != 'D')
2364 need_sync_io = true;
2365
2366 if (need_sync_io && from_map) {
2367 INIT_WORK(&dio->work, integrity_bio_wait);
2368 queue_work(ic->offload_wq, &dio->work);
2369 return;
2370 }
2371
2372 lock_retry:
2373 spin_lock_irq(&ic->endio_wait.lock);
2374 retry:
2375 if (unlikely(dm_integrity_failed(ic))) {
2376 spin_unlock_irq(&ic->endio_wait.lock);
2377 do_endio(ic, bio);
2378 return;
2379 }
2380 dio->range.n_sectors = bio_sectors(bio);
2381 journal_read_pos = NOT_FOUND;
2382 if (ic->mode == 'J' && likely(dio->op != REQ_OP_DISCARD)) {
2383 if (dio->op == REQ_OP_WRITE) {
2384 unsigned int next_entry, i, pos;
2385 unsigned int ws, we, range_sectors;
2386
2387 dio->range.n_sectors = min(dio->range.n_sectors,
2388 (sector_t)ic->free_sectors << ic->sb->log2_sectors_per_block);
2389 if (unlikely(!dio->range.n_sectors)) {
2390 if (from_map)
2391 goto offload_to_thread;
2392 sleep_on_endio_wait(ic);
2393 goto retry;
2394 }
2395 range_sectors = dio->range.n_sectors >> ic->sb->log2_sectors_per_block;
2396 ic->free_sectors -= range_sectors;
2397 journal_section = ic->free_section;
2398 journal_entry = ic->free_section_entry;
2399
2400 next_entry = ic->free_section_entry + range_sectors;
2401 ic->free_section_entry = next_entry % ic->journal_section_entries;
2402 ic->free_section += next_entry / ic->journal_section_entries;
2403 ic->n_uncommitted_sections += next_entry / ic->journal_section_entries;
2404 wraparound_section(ic, &ic->free_section);
2405
2406 pos = journal_section * ic->journal_section_entries + journal_entry;
2407 ws = journal_section;
2408 we = journal_entry;
2409 i = 0;
2410 do {
2411 struct journal_entry *je;
2412
2413 add_journal_node(ic, &ic->journal_tree[pos], dio->range.logical_sector + i);
2414 pos++;
2415 if (unlikely(pos >= ic->journal_entries))
2416 pos = 0;
2417
2418 je = access_journal_entry(ic, ws, we);
2419 BUG_ON(!journal_entry_is_unused(je));
2420 journal_entry_set_inprogress(je);
2421 we++;
2422 if (unlikely(we == ic->journal_section_entries)) {
2423 we = 0;
2424 ws++;
2425 wraparound_section(ic, &ws);
2426 }
2427 } while ((i += ic->sectors_per_block) < dio->range.n_sectors);
2428
2429 spin_unlock_irq(&ic->endio_wait.lock);
2430 goto journal_read_write;
2431 } else {
2432 sector_t next_sector;
2433
2434 journal_read_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
2435 if (likely(journal_read_pos == NOT_FOUND)) {
2436 if (unlikely(dio->range.n_sectors > next_sector - dio->range.logical_sector))
2437 dio->range.n_sectors = next_sector - dio->range.logical_sector;
2438 } else {
2439 unsigned int i;
2440 unsigned int jp = journal_read_pos + 1;
2441
2442 for (i = ic->sectors_per_block; i < dio->range.n_sectors; i += ic->sectors_per_block, jp++) {
2443 if (!test_journal_node(ic, jp, dio->range.logical_sector + i))
2444 break;
2445 }
2446 dio->range.n_sectors = i;
2447 }
2448 }
2449 }
2450 if (unlikely(!add_new_range(ic, &dio->range, true))) {
2451 /*
2452 * We must not sleep in the request routine because it could
2453 * stall bios on current->bio_list.
2454 * So, we offload the bio to a workqueue if we have to sleep.
2455 */
2456 if (from_map) {
2457 offload_to_thread:
2458 spin_unlock_irq(&ic->endio_wait.lock);
2459 INIT_WORK(&dio->work, integrity_bio_wait);
2460 queue_work(ic->wait_wq, &dio->work);
2461 return;
2462 }
2463 if (journal_read_pos != NOT_FOUND)
2464 dio->range.n_sectors = ic->sectors_per_block;
2465 wait_and_add_new_range(ic, &dio->range);
2466 /*
2467 * wait_and_add_new_range drops the spinlock, so the journal
2468 * may have been changed arbitrarily. We need to recheck.
2469 * To simplify the code, we restrict I/O size to just one block.
2470 */
2471 if (journal_read_pos != NOT_FOUND) {
2472 sector_t next_sector;
2473 unsigned int new_pos;
2474
2475 new_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
2476 if (unlikely(new_pos != journal_read_pos)) {
2477 remove_range_unlocked(ic, &dio->range);
2478 goto retry;
2479 }
2480 }
2481 }
2482 if (ic->mode == 'J' && likely(dio->op == REQ_OP_DISCARD) && !discard_retried) {
2483 sector_t next_sector;
2484 unsigned int new_pos;
2485
2486 new_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
2487 if (unlikely(new_pos != NOT_FOUND) ||
2488 unlikely(next_sector < dio->range.logical_sector + dio->range.n_sectors)) {
2489 remove_range_unlocked(ic, &dio->range);
2490 spin_unlock_irq(&ic->endio_wait.lock);
2491 queue_work(ic->commit_wq, &ic->commit_work);
2492 flush_workqueue(ic->commit_wq);
2493 queue_work(ic->writer_wq, &ic->writer_work);
2494 flush_workqueue(ic->writer_wq);
2495 discard_retried = true;
2496 goto lock_retry;
2497 }
2498 }
2499 recalc_sector = le64_to_cpu(ic->sb->recalc_sector);
2500 spin_unlock_irq(&ic->endio_wait.lock);
2501
2502 if (unlikely(journal_read_pos != NOT_FOUND)) {
2503 journal_section = journal_read_pos / ic->journal_section_entries;
2504 journal_entry = journal_read_pos % ic->journal_section_entries;
2505 goto journal_read_write;
2506 }
2507
2508 if (ic->mode == 'B' && (dio->op == REQ_OP_WRITE || unlikely(dio->op == REQ_OP_DISCARD))) {
2509 if (!block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
2510 dio->range.n_sectors, BITMAP_OP_TEST_ALL_SET)) {
2511 struct bitmap_block_status *bbs;
2512
2513 bbs = sector_to_bitmap_block(ic, dio->range.logical_sector);
2514 spin_lock(&bbs->bio_queue_lock);
2515 bio_list_add(&bbs->bio_queue, bio);
2516 spin_unlock(&bbs->bio_queue_lock);
2517 queue_work(ic->writer_wq, &bbs->work);
2518 return;
2519 }
2520 }
2521
2522 dio->in_flight = (atomic_t)ATOMIC_INIT(2);
2523
2524 if (need_sync_io) {
2525 init_completion(&read_comp);
2526 dio->completion = &read_comp;
2527 } else
2528 dio->completion = NULL;
2529
2530 dm_bio_record(&dio->bio_details, bio);
2531 bio_set_dev(bio, ic->dev->bdev);
2532 bio->bi_integrity = NULL;
2533 bio->bi_opf &= ~REQ_INTEGRITY;
2534 bio->bi_end_io = integrity_end_io;
2535 bio->bi_iter.bi_size = dio->range.n_sectors << SECTOR_SHIFT;
2536
2537 if (unlikely(dio->op == REQ_OP_DISCARD) && likely(ic->mode != 'D')) {
2538 integrity_metadata(&dio->work);
2539 dm_integrity_flush_buffers(ic, false);
2540
2541 dio->in_flight = (atomic_t)ATOMIC_INIT(1);
2542 dio->completion = NULL;
2543
2544 submit_bio_noacct(bio);
2545
2546 return;
2547 }
2548
2549 submit_bio_noacct(bio);
2550
2551 if (need_sync_io) {
2552 wait_for_completion_io(&read_comp);
2553 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
2554 dio->range.logical_sector + dio->range.n_sectors > recalc_sector)
2555 goto skip_check;
2556 if (ic->mode == 'B') {
2557 if (!block_bitmap_op(ic, ic->recalc_bitmap, dio->range.logical_sector,
2558 dio->range.n_sectors, BITMAP_OP_TEST_ALL_CLEAR))
2559 goto skip_check;
2560 }
2561
2562 if (likely(!bio->bi_status))
2563 integrity_metadata(&dio->work);
2564 else
2565 skip_check:
2566 dec_in_flight(dio);
2567 } else {
2568 INIT_WORK(&dio->work, integrity_metadata);
2569 queue_work(ic->metadata_wq, &dio->work);
2570 }
2571
2572 return;
2573
2574 journal_read_write:
2575 if (unlikely(__journal_read_write(dio, bio, journal_section, journal_entry)))
2576 goto lock_retry;
2577
2578 do_endio_flush(ic, dio);
2579 }
2580
dm_integrity_map_inline(struct dm_integrity_io * dio,bool from_map)2581 static int dm_integrity_map_inline(struct dm_integrity_io *dio, bool from_map)
2582 {
2583 struct dm_integrity_c *ic = dio->ic;
2584 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
2585 struct bio_integrity_payload *bip;
2586 unsigned ret;
2587 sector_t recalc_sector;
2588
2589 if (unlikely(bio_integrity(bio))) {
2590 bio->bi_status = BLK_STS_NOTSUPP;
2591 bio_endio(bio);
2592 return DM_MAPIO_SUBMITTED;
2593 }
2594
2595 bio_set_dev(bio, ic->dev->bdev);
2596 if (unlikely((bio->bi_opf & REQ_PREFLUSH) != 0))
2597 return DM_MAPIO_REMAPPED;
2598
2599 if (unlikely(!dm_integrity_check_limits(ic, bio->bi_iter.bi_sector, bio)))
2600 return DM_MAPIO_KILL;
2601
2602 retry:
2603 if (!dio->integrity_payload) {
2604 unsigned digest_size, extra_size;
2605 dio->payload_len = ic->tuple_size * (bio_sectors(bio) >> ic->sb->log2_sectors_per_block);
2606 digest_size = ic->internal_hash_digestsize;
2607 extra_size = unlikely(digest_size > ic->tag_size) ? digest_size - ic->tag_size : 0;
2608 dio->payload_len += extra_size;
2609 dio->integrity_payload = kmalloc(dio->payload_len, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
2610 if (unlikely(!dio->integrity_payload)) {
2611 const unsigned x_size = PAGE_SIZE << 1;
2612 if (dio->payload_len > x_size) {
2613 unsigned sectors = ((x_size - extra_size) / ic->tuple_size) << ic->sb->log2_sectors_per_block;
2614 if (WARN_ON(!sectors || sectors >= bio_sectors(bio))) {
2615 bio->bi_status = BLK_STS_NOTSUPP;
2616 bio_endio(bio);
2617 return DM_MAPIO_SUBMITTED;
2618 }
2619 dm_accept_partial_bio(bio, sectors);
2620 goto retry;
2621 }
2622 }
2623 }
2624
2625 dio->range.logical_sector = bio->bi_iter.bi_sector;
2626 dio->range.n_sectors = bio_sectors(bio);
2627
2628 if (!(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)))
2629 goto skip_spinlock;
2630 #ifdef CONFIG_64BIT
2631 /*
2632 * On 64-bit CPUs we can optimize the lock away (so that it won't cause
2633 * cache line bouncing) and use acquire/release barriers instead.
2634 *
2635 * Paired with smp_store_release in integrity_recalc_inline.
2636 */
2637 recalc_sector = le64_to_cpu(smp_load_acquire(&ic->sb->recalc_sector));
2638 if (likely(dio->range.logical_sector + dio->range.n_sectors <= recalc_sector))
2639 goto skip_spinlock;
2640 #endif
2641 spin_lock_irq(&ic->endio_wait.lock);
2642 recalc_sector = le64_to_cpu(ic->sb->recalc_sector);
2643 if (dio->range.logical_sector + dio->range.n_sectors <= recalc_sector)
2644 goto skip_unlock;
2645 if (unlikely(!add_new_range(ic, &dio->range, true))) {
2646 if (from_map) {
2647 spin_unlock_irq(&ic->endio_wait.lock);
2648 INIT_WORK(&dio->work, integrity_bio_wait);
2649 queue_work(ic->wait_wq, &dio->work);
2650 return DM_MAPIO_SUBMITTED;
2651 }
2652 wait_and_add_new_range(ic, &dio->range);
2653 }
2654 dio->integrity_range_locked = true;
2655 skip_unlock:
2656 spin_unlock_irq(&ic->endio_wait.lock);
2657 skip_spinlock:
2658
2659 if (unlikely(!dio->integrity_payload)) {
2660 dio->integrity_payload = page_to_virt((struct page *)mempool_alloc(&ic->recheck_pool, GFP_NOIO));
2661 dio->integrity_payload_from_mempool = true;
2662 }
2663
2664 dio->bio_details.bi_iter = bio->bi_iter;
2665
2666 bio->bi_iter.bi_sector += ic->start + SB_SECTORS;
2667
2668 bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
2669 if (IS_ERR(bip)) {
2670 bio->bi_status = errno_to_blk_status(PTR_ERR(bip));
2671 bio_endio(bio);
2672 return DM_MAPIO_SUBMITTED;
2673 }
2674
2675 if (dio->op == REQ_OP_WRITE) {
2676 unsigned pos = 0;
2677 while (dio->bio_details.bi_iter.bi_size) {
2678 struct bio_vec bv = bio_iter_iovec(bio, dio->bio_details.bi_iter);
2679 const char *mem = integrity_kmap(ic, bv.bv_page);
2680 if (ic->tag_size < ic->tuple_size)
2681 memset(dio->integrity_payload + pos + ic->tag_size, 0, ic->tuple_size - ic->tag_size);
2682 integrity_sector_checksum(ic, &dio->ahash_req, dio->bio_details.bi_iter.bi_sector, mem, bv.bv_offset, dio->integrity_payload + pos);
2683 integrity_kunmap(ic, mem);
2684 pos += ic->tuple_size;
2685 bio_advance_iter_single(bio, &dio->bio_details.bi_iter, ic->sectors_per_block << SECTOR_SHIFT);
2686 }
2687 }
2688
2689 ret = bio_integrity_add_page(bio, virt_to_page(dio->integrity_payload),
2690 dio->payload_len, offset_in_page(dio->integrity_payload));
2691 if (unlikely(ret != dio->payload_len)) {
2692 bio->bi_status = BLK_STS_RESOURCE;
2693 bio_endio(bio);
2694 return DM_MAPIO_SUBMITTED;
2695 }
2696
2697 return DM_MAPIO_REMAPPED;
2698 }
2699
dm_integrity_free_payload(struct dm_integrity_io * dio)2700 static inline void dm_integrity_free_payload(struct dm_integrity_io *dio)
2701 {
2702 struct dm_integrity_c *ic = dio->ic;
2703 if (unlikely(dio->integrity_payload_from_mempool))
2704 mempool_free(virt_to_page(dio->integrity_payload), &ic->recheck_pool);
2705 else
2706 kfree(dio->integrity_payload);
2707 dio->integrity_payload = NULL;
2708 dio->integrity_payload_from_mempool = false;
2709 }
2710
dm_integrity_inline_recheck(struct work_struct * w)2711 static void dm_integrity_inline_recheck(struct work_struct *w)
2712 {
2713 struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
2714 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
2715 struct dm_integrity_c *ic = dio->ic;
2716 struct bio *outgoing_bio;
2717 void *outgoing_data;
2718
2719 dio->integrity_payload = page_to_virt((struct page *)mempool_alloc(&ic->recheck_pool, GFP_NOIO));
2720 dio->integrity_payload_from_mempool = true;
2721
2722 outgoing_data = dio->integrity_payload + PAGE_SIZE;
2723
2724 while (dio->bio_details.bi_iter.bi_size) {
2725 char digest[MAX_T(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
2726 int r;
2727 struct bio_integrity_payload *bip;
2728 struct bio_vec bv;
2729 char *mem;
2730
2731 outgoing_bio = bio_alloc_bioset(ic->dev->bdev, 1, REQ_OP_READ, GFP_NOIO, &ic->recheck_bios);
2732 bio_add_virt_nofail(outgoing_bio, outgoing_data,
2733 ic->sectors_per_block << SECTOR_SHIFT);
2734
2735 bip = bio_integrity_alloc(outgoing_bio, GFP_NOIO, 1);
2736 if (IS_ERR(bip)) {
2737 bio_put(outgoing_bio);
2738 bio->bi_status = errno_to_blk_status(PTR_ERR(bip));
2739 bio_endio(bio);
2740 return;
2741 }
2742
2743 r = bio_integrity_add_page(outgoing_bio, virt_to_page(dio->integrity_payload), ic->tuple_size, 0);
2744 if (unlikely(r != ic->tuple_size)) {
2745 bio_put(outgoing_bio);
2746 bio->bi_status = BLK_STS_RESOURCE;
2747 bio_endio(bio);
2748 return;
2749 }
2750
2751 outgoing_bio->bi_iter.bi_sector = dio->bio_details.bi_iter.bi_sector + ic->start + SB_SECTORS;
2752
2753 r = submit_bio_wait(outgoing_bio);
2754 if (unlikely(r != 0)) {
2755 bio_put(outgoing_bio);
2756 bio->bi_status = errno_to_blk_status(r);
2757 bio_endio(bio);
2758 return;
2759 }
2760 bio_put(outgoing_bio);
2761
2762 integrity_sector_checksum(ic, &dio->ahash_req, dio->bio_details.bi_iter.bi_sector, integrity_identity(ic, outgoing_data), 0, digest);
2763 if (unlikely(crypto_memneq(digest, dio->integrity_payload, min(ic->internal_hash_digestsize, ic->tag_size)))) {
2764 DMERR_LIMIT("%pg: Checksum failed at sector 0x%llx",
2765 ic->dev->bdev, dio->bio_details.bi_iter.bi_sector);
2766 atomic64_inc(&ic->number_of_mismatches);
2767 dm_audit_log_bio(DM_MSG_PREFIX, "integrity-checksum",
2768 bio, dio->bio_details.bi_iter.bi_sector, 0);
2769
2770 bio->bi_status = BLK_STS_PROTECTION;
2771 bio_endio(bio);
2772 return;
2773 }
2774
2775 bv = bio_iter_iovec(bio, dio->bio_details.bi_iter);
2776 mem = bvec_kmap_local(&bv);
2777 memcpy(mem, outgoing_data, ic->sectors_per_block << SECTOR_SHIFT);
2778 kunmap_local(mem);
2779
2780 bio_advance_iter_single(bio, &dio->bio_details.bi_iter, ic->sectors_per_block << SECTOR_SHIFT);
2781 }
2782
2783 bio_endio(bio);
2784 }
2785
dm_integrity_check(struct dm_integrity_c * ic,struct dm_integrity_io * dio)2786 static inline bool dm_integrity_check(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
2787 {
2788 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
2789 unsigned pos = 0;
2790
2791 while (dio->bio_details.bi_iter.bi_size) {
2792 char digest[MAX_T(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
2793 struct bio_vec bv = bio_iter_iovec(bio, dio->bio_details.bi_iter);
2794 char *mem = integrity_kmap(ic, bv.bv_page);
2795 integrity_sector_checksum(ic, &dio->ahash_req, dio->bio_details.bi_iter.bi_sector, mem, bv.bv_offset, digest);
2796 if (unlikely(crypto_memneq(digest, dio->integrity_payload + pos,
2797 min(ic->internal_hash_digestsize, ic->tag_size)))) {
2798 integrity_kunmap(ic, mem);
2799 dm_integrity_free_payload(dio);
2800 INIT_WORK(&dio->work, dm_integrity_inline_recheck);
2801 queue_work(ic->offload_wq, &dio->work);
2802 return false;
2803 }
2804 integrity_kunmap(ic, mem);
2805 pos += ic->tuple_size;
2806 bio_advance_iter_single(bio, &dio->bio_details.bi_iter, ic->sectors_per_block << SECTOR_SHIFT);
2807 }
2808
2809 return true;
2810 }
2811
dm_integrity_inline_async_check(struct work_struct * w)2812 static void dm_integrity_inline_async_check(struct work_struct *w)
2813 {
2814 struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
2815 struct dm_integrity_c *ic = dio->ic;
2816 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
2817
2818 if (likely(dm_integrity_check(ic, dio)))
2819 bio_endio(bio);
2820 }
2821
dm_integrity_end_io(struct dm_target * ti,struct bio * bio,blk_status_t * status)2822 static int dm_integrity_end_io(struct dm_target *ti, struct bio *bio, blk_status_t *status)
2823 {
2824 struct dm_integrity_c *ic = ti->private;
2825 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
2826 if (ic->mode == 'I') {
2827 if (dio->op == REQ_OP_READ && likely(*status == BLK_STS_OK) && likely(dio->bio_details.bi_iter.bi_size != 0)) {
2828 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
2829 unlikely(dio->integrity_range_locked))
2830 goto skip_check;
2831 if (likely(ic->internal_shash != NULL)) {
2832 if (unlikely(!dm_integrity_check(ic, dio)))
2833 return DM_ENDIO_INCOMPLETE;
2834 } else {
2835 INIT_WORK(&dio->work, dm_integrity_inline_async_check);
2836 queue_work(ic->offload_wq, &dio->work);
2837 return DM_ENDIO_INCOMPLETE;
2838 }
2839 }
2840 skip_check:
2841 dm_integrity_free_payload(dio);
2842 if (unlikely(dio->integrity_range_locked))
2843 remove_range(ic, &dio->range);
2844 }
2845 if (unlikely(dio->ahash_req))
2846 mempool_free(dio->ahash_req, &ic->ahash_req_pool);
2847 return DM_ENDIO_DONE;
2848 }
2849
integrity_bio_wait(struct work_struct * w)2850 static void integrity_bio_wait(struct work_struct *w)
2851 {
2852 struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
2853 struct dm_integrity_c *ic = dio->ic;
2854
2855 if (ic->mode == 'I') {
2856 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
2857 int r = dm_integrity_map_inline(dio, false);
2858 switch (r) {
2859 case DM_MAPIO_KILL:
2860 bio->bi_status = BLK_STS_IOERR;
2861 bio_endio(bio);
2862 return;
2863 case DM_MAPIO_REMAPPED:
2864 submit_bio_noacct(bio);
2865 fallthrough;
2866 case DM_MAPIO_SUBMITTED:
2867 return;
2868 default:
2869 BUG();
2870 }
2871 } else {
2872 dm_integrity_map_continue(dio, false);
2873 }
2874 }
2875
pad_uncommitted(struct dm_integrity_c * ic)2876 static void pad_uncommitted(struct dm_integrity_c *ic)
2877 {
2878 if (ic->free_section_entry) {
2879 ic->free_sectors -= ic->journal_section_entries - ic->free_section_entry;
2880 ic->free_section_entry = 0;
2881 ic->free_section++;
2882 wraparound_section(ic, &ic->free_section);
2883 ic->n_uncommitted_sections++;
2884 }
2885 if (WARN_ON(ic->journal_sections * ic->journal_section_entries !=
2886 (ic->n_uncommitted_sections + ic->n_committed_sections) *
2887 ic->journal_section_entries + ic->free_sectors)) {
2888 DMCRIT("journal_sections %u, journal_section_entries %u, "
2889 "n_uncommitted_sections %u, n_committed_sections %u, "
2890 "journal_section_entries %u, free_sectors %u",
2891 ic->journal_sections, ic->journal_section_entries,
2892 ic->n_uncommitted_sections, ic->n_committed_sections,
2893 ic->journal_section_entries, ic->free_sectors);
2894 }
2895 }
2896
integrity_commit(struct work_struct * w)2897 static void integrity_commit(struct work_struct *w)
2898 {
2899 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, commit_work);
2900 unsigned int commit_start, commit_sections;
2901 unsigned int i, j, n;
2902 struct bio *flushes;
2903
2904 timer_delete(&ic->autocommit_timer);
2905
2906 if (ic->mode == 'I')
2907 return;
2908
2909 spin_lock_irq(&ic->endio_wait.lock);
2910 flushes = bio_list_get(&ic->flush_bio_list);
2911 if (unlikely(ic->mode != 'J')) {
2912 spin_unlock_irq(&ic->endio_wait.lock);
2913 dm_integrity_flush_buffers(ic, true);
2914 goto release_flush_bios;
2915 }
2916
2917 pad_uncommitted(ic);
2918 commit_start = ic->uncommitted_section;
2919 commit_sections = ic->n_uncommitted_sections;
2920 spin_unlock_irq(&ic->endio_wait.lock);
2921
2922 if (!commit_sections)
2923 goto release_flush_bios;
2924
2925 ic->wrote_to_journal = true;
2926
2927 i = commit_start;
2928 for (n = 0; n < commit_sections; n++) {
2929 for (j = 0; j < ic->journal_section_entries; j++) {
2930 struct journal_entry *je;
2931
2932 je = access_journal_entry(ic, i, j);
2933 io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
2934 }
2935 for (j = 0; j < ic->journal_section_sectors; j++) {
2936 struct journal_sector *js;
2937
2938 js = access_journal(ic, i, j);
2939 js->commit_id = dm_integrity_commit_id(ic, i, j, ic->commit_seq);
2940 }
2941 i++;
2942 if (unlikely(i >= ic->journal_sections))
2943 ic->commit_seq = next_commit_seq(ic->commit_seq);
2944 wraparound_section(ic, &i);
2945 }
2946 smp_rmb();
2947
2948 write_journal(ic, commit_start, commit_sections);
2949
2950 spin_lock_irq(&ic->endio_wait.lock);
2951 ic->uncommitted_section += commit_sections;
2952 wraparound_section(ic, &ic->uncommitted_section);
2953 ic->n_uncommitted_sections -= commit_sections;
2954 ic->n_committed_sections += commit_sections;
2955 spin_unlock_irq(&ic->endio_wait.lock);
2956
2957 if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold)
2958 queue_work(ic->writer_wq, &ic->writer_work);
2959
2960 release_flush_bios:
2961 while (flushes) {
2962 struct bio *next = flushes->bi_next;
2963
2964 flushes->bi_next = NULL;
2965 do_endio(ic, flushes);
2966 flushes = next;
2967 }
2968 }
2969
complete_copy_from_journal(unsigned long error,unsigned long unsup,void * context)2970 static void complete_copy_from_journal(unsigned long error, unsigned long unsup, void *context)
2971 {
2972 struct journal_io *io = context;
2973 struct journal_completion *comp = io->comp;
2974 struct dm_integrity_c *ic = comp->ic;
2975
2976 remove_range(ic, &io->range);
2977 mempool_free(io, &ic->journal_io_mempool);
2978 if (unlikely(error != 0))
2979 dm_integrity_io_error(ic, "copying from journal", -EIO);
2980 else if (unlikely(unsup != 0))
2981 dm_integrity_io_error(ic, "copying from journal", -EOPNOTSUPP);
2982 complete_journal_op(comp);
2983 }
2984
restore_last_bytes(struct dm_integrity_c * ic,struct journal_sector * js,struct journal_entry * je)2985 static void restore_last_bytes(struct dm_integrity_c *ic, struct journal_sector *js,
2986 struct journal_entry *je)
2987 {
2988 unsigned int s = 0;
2989
2990 do {
2991 js->commit_id = je->last_bytes[s];
2992 js++;
2993 } while (++s < ic->sectors_per_block);
2994 }
2995
do_journal_write(struct dm_integrity_c * ic,unsigned int write_start,unsigned int write_sections,bool from_replay)2996 static void do_journal_write(struct dm_integrity_c *ic, unsigned int write_start,
2997 unsigned int write_sections, bool from_replay)
2998 {
2999 unsigned int i, j, n;
3000 struct journal_completion comp;
3001 struct blk_plug plug;
3002
3003 blk_start_plug(&plug);
3004
3005 comp.ic = ic;
3006 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
3007 init_completion(&comp.comp);
3008
3009 i = write_start;
3010 for (n = 0; n < write_sections; n++, i++, wraparound_section(ic, &i)) {
3011 #ifndef INTERNAL_VERIFY
3012 if (unlikely(from_replay))
3013 #endif
3014 rw_section_mac(ic, i, false);
3015 for (j = 0; j < ic->journal_section_entries; j++) {
3016 struct journal_entry *je = access_journal_entry(ic, i, j);
3017 sector_t sec, area, offset;
3018 unsigned int k, l, next_loop;
3019 sector_t metadata_block;
3020 unsigned int metadata_offset;
3021 struct journal_io *io;
3022
3023 if (journal_entry_is_unused(je))
3024 continue;
3025 BUG_ON(unlikely(journal_entry_is_inprogress(je)) && !from_replay);
3026 sec = journal_entry_get_sector(je);
3027 if (unlikely(from_replay)) {
3028 if (unlikely(sec & (unsigned int)(ic->sectors_per_block - 1))) {
3029 dm_integrity_io_error(ic, "invalid sector in journal", -EIO);
3030 sec &= ~(sector_t)(ic->sectors_per_block - 1);
3031 }
3032 if (unlikely(sec >= ic->provided_data_sectors)) {
3033 journal_entry_set_unused(je);
3034 continue;
3035 }
3036 }
3037 get_area_and_offset(ic, sec, &area, &offset);
3038 restore_last_bytes(ic, access_journal_data(ic, i, j), je);
3039 for (k = j + 1; k < ic->journal_section_entries; k++) {
3040 struct journal_entry *je2 = access_journal_entry(ic, i, k);
3041 sector_t sec2, area2, offset2;
3042
3043 if (journal_entry_is_unused(je2))
3044 break;
3045 BUG_ON(unlikely(journal_entry_is_inprogress(je2)) && !from_replay);
3046 sec2 = journal_entry_get_sector(je2);
3047 if (unlikely(sec2 >= ic->provided_data_sectors))
3048 break;
3049 get_area_and_offset(ic, sec2, &area2, &offset2);
3050 if (area2 != area || offset2 != offset + ((k - j) << ic->sb->log2_sectors_per_block))
3051 break;
3052 restore_last_bytes(ic, access_journal_data(ic, i, k), je2);
3053 }
3054 next_loop = k - 1;
3055
3056 io = mempool_alloc(&ic->journal_io_mempool, GFP_NOIO);
3057 io->comp = ∁
3058 io->range.logical_sector = sec;
3059 io->range.n_sectors = (k - j) << ic->sb->log2_sectors_per_block;
3060
3061 spin_lock_irq(&ic->endio_wait.lock);
3062 add_new_range_and_wait(ic, &io->range);
3063
3064 if (likely(!from_replay)) {
3065 struct journal_node *section_node = &ic->journal_tree[i * ic->journal_section_entries];
3066
3067 /* don't write if there is newer committed sector */
3068 while (j < k && find_newer_committed_node(ic, §ion_node[j])) {
3069 struct journal_entry *je2 = access_journal_entry(ic, i, j);
3070
3071 journal_entry_set_unused(je2);
3072 remove_journal_node(ic, §ion_node[j]);
3073 j++;
3074 sec += ic->sectors_per_block;
3075 offset += ic->sectors_per_block;
3076 }
3077 while (j < k && find_newer_committed_node(ic, §ion_node[k - 1])) {
3078 struct journal_entry *je2 = access_journal_entry(ic, i, k - 1);
3079
3080 journal_entry_set_unused(je2);
3081 remove_journal_node(ic, §ion_node[k - 1]);
3082 k--;
3083 }
3084 if (j == k) {
3085 remove_range_unlocked(ic, &io->range);
3086 spin_unlock_irq(&ic->endio_wait.lock);
3087 mempool_free(io, &ic->journal_io_mempool);
3088 goto skip_io;
3089 }
3090 for (l = j; l < k; l++)
3091 remove_journal_node(ic, §ion_node[l]);
3092 }
3093 spin_unlock_irq(&ic->endio_wait.lock);
3094
3095 metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
3096 for (l = j; l < k; l++) {
3097 int r;
3098 struct journal_entry *je2 = access_journal_entry(ic, i, l);
3099
3100 if (
3101 #ifndef INTERNAL_VERIFY
3102 unlikely(from_replay) &&
3103 #endif
3104 ic->internal_hash) {
3105 char test_tag[MAX_T(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
3106 struct journal_sector *js = access_journal_data(ic, i, l);
3107 void *js_page = integrity_identity(ic, (char *)js - offset_in_page(js));
3108 unsigned js_offset = offset_in_page(js);
3109
3110 integrity_sector_checksum(ic, &ic->journal_ahash_req, sec + ((l - j) << ic->sb->log2_sectors_per_block),
3111 js_page, js_offset, test_tag);
3112 if (unlikely(crypto_memneq(test_tag, journal_entry_tag(ic, je2), ic->tag_size))) {
3113 dm_integrity_io_error(ic, "tag mismatch when replaying journal", -EILSEQ);
3114 dm_audit_log_target(DM_MSG_PREFIX, "integrity-replay-journal", ic->ti, 0);
3115 }
3116 }
3117
3118 journal_entry_set_unused(je2);
3119 r = dm_integrity_rw_tag(ic, journal_entry_tag(ic, je2), &metadata_block, &metadata_offset,
3120 ic->tag_size, TAG_WRITE);
3121 if (unlikely(r))
3122 dm_integrity_io_error(ic, "writing tags", r);
3123 }
3124
3125 atomic_inc(&comp.in_flight);
3126 copy_from_journal(ic, i, j << ic->sb->log2_sectors_per_block,
3127 (k - j) << ic->sb->log2_sectors_per_block,
3128 get_data_sector(ic, area, offset),
3129 complete_copy_from_journal, io);
3130 skip_io:
3131 j = next_loop;
3132 }
3133 }
3134
3135 dm_bufio_write_dirty_buffers_async(ic->bufio);
3136
3137 blk_finish_plug(&plug);
3138
3139 complete_journal_op(&comp);
3140 wait_for_completion_io(&comp.comp);
3141
3142 dm_integrity_flush_buffers(ic, true);
3143 }
3144
integrity_writer(struct work_struct * w)3145 static void integrity_writer(struct work_struct *w)
3146 {
3147 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, writer_work);
3148 unsigned int write_start, write_sections;
3149 unsigned int prev_free_sectors;
3150
3151 spin_lock_irq(&ic->endio_wait.lock);
3152 write_start = ic->committed_section;
3153 write_sections = ic->n_committed_sections;
3154 spin_unlock_irq(&ic->endio_wait.lock);
3155
3156 if (!write_sections)
3157 return;
3158
3159 do_journal_write(ic, write_start, write_sections, false);
3160
3161 spin_lock_irq(&ic->endio_wait.lock);
3162
3163 ic->committed_section += write_sections;
3164 wraparound_section(ic, &ic->committed_section);
3165 ic->n_committed_sections -= write_sections;
3166
3167 prev_free_sectors = ic->free_sectors;
3168 ic->free_sectors += write_sections * ic->journal_section_entries;
3169 if (unlikely(!prev_free_sectors))
3170 wake_up_locked(&ic->endio_wait);
3171
3172 spin_unlock_irq(&ic->endio_wait.lock);
3173 }
3174
recalc_write_super(struct dm_integrity_c * ic)3175 static void recalc_write_super(struct dm_integrity_c *ic)
3176 {
3177 int r;
3178
3179 dm_integrity_flush_buffers(ic, false);
3180 if (dm_integrity_failed(ic))
3181 return;
3182
3183 r = sync_rw_sb(ic, REQ_OP_WRITE);
3184 if (unlikely(r))
3185 dm_integrity_io_error(ic, "writing superblock", r);
3186 }
3187
integrity_recalc(struct work_struct * w)3188 static void integrity_recalc(struct work_struct *w)
3189 {
3190 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, recalc_work);
3191 size_t recalc_tags_size;
3192 u8 *recalc_buffer = NULL;
3193 u8 *recalc_tags = NULL;
3194 struct ahash_request *ahash_req = NULL;
3195 struct dm_integrity_range range;
3196 struct dm_io_request io_req;
3197 struct dm_io_region io_loc;
3198 sector_t area, offset;
3199 sector_t metadata_block;
3200 unsigned int metadata_offset;
3201 sector_t logical_sector, n_sectors;
3202 __u8 *t;
3203 unsigned int i;
3204 int r;
3205 unsigned int super_counter = 0;
3206 unsigned recalc_sectors = RECALC_SECTORS;
3207
3208 retry:
3209 recalc_buffer = kmalloc(recalc_sectors << SECTOR_SHIFT, GFP_NOIO | __GFP_NOWARN);
3210 if (!recalc_buffer) {
3211 oom:
3212 recalc_sectors >>= 1;
3213 if (recalc_sectors >= 1U << ic->sb->log2_sectors_per_block)
3214 goto retry;
3215 DMCRIT("out of memory for recalculate buffer - recalculation disabled");
3216 goto free_ret;
3217 }
3218 recalc_tags_size = (recalc_sectors >> ic->sb->log2_sectors_per_block) * ic->tag_size;
3219 if (ic->internal_hash_digestsize > ic->tag_size)
3220 recalc_tags_size += ic->internal_hash_digestsize - ic->tag_size;
3221 recalc_tags = kvmalloc(recalc_tags_size, GFP_NOIO);
3222 if (!recalc_tags) {
3223 kfree(recalc_buffer);
3224 recalc_buffer = NULL;
3225 goto oom;
3226 }
3227
3228 DEBUG_print("start recalculation... (position %llx)\n", le64_to_cpu(ic->sb->recalc_sector));
3229
3230 spin_lock_irq(&ic->endio_wait.lock);
3231
3232 next_chunk:
3233
3234 if (unlikely(dm_post_suspending(ic->ti)))
3235 goto unlock_ret;
3236
3237 range.logical_sector = le64_to_cpu(ic->sb->recalc_sector);
3238 if (unlikely(range.logical_sector >= ic->provided_data_sectors)) {
3239 if (ic->mode == 'B') {
3240 block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
3241 DEBUG_print("queue_delayed_work: bitmap_flush_work\n");
3242 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
3243 }
3244 goto unlock_ret;
3245 }
3246
3247 get_area_and_offset(ic, range.logical_sector, &area, &offset);
3248 range.n_sectors = min((sector_t)recalc_sectors, ic->provided_data_sectors - range.logical_sector);
3249 if (!ic->meta_dev)
3250 range.n_sectors = min(range.n_sectors, ((sector_t)1U << ic->sb->log2_interleave_sectors) - (unsigned int)offset);
3251
3252 add_new_range_and_wait(ic, &range);
3253 spin_unlock_irq(&ic->endio_wait.lock);
3254 logical_sector = range.logical_sector;
3255 n_sectors = range.n_sectors;
3256
3257 if (ic->mode == 'B') {
3258 if (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector, n_sectors, BITMAP_OP_TEST_ALL_CLEAR))
3259 goto advance_and_next;
3260
3261 while (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector,
3262 ic->sectors_per_block, BITMAP_OP_TEST_ALL_CLEAR)) {
3263 logical_sector += ic->sectors_per_block;
3264 n_sectors -= ic->sectors_per_block;
3265 cond_resched();
3266 }
3267 while (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector + n_sectors - ic->sectors_per_block,
3268 ic->sectors_per_block, BITMAP_OP_TEST_ALL_CLEAR)) {
3269 n_sectors -= ic->sectors_per_block;
3270 cond_resched();
3271 }
3272 get_area_and_offset(ic, logical_sector, &area, &offset);
3273 }
3274
3275 DEBUG_print("recalculating: %llx, %llx\n", logical_sector, n_sectors);
3276
3277 if (unlikely(++super_counter == RECALC_WRITE_SUPER)) {
3278 recalc_write_super(ic);
3279 if (ic->mode == 'B')
3280 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, ic->bitmap_flush_interval);
3281
3282 super_counter = 0;
3283 }
3284
3285 if (unlikely(dm_integrity_failed(ic)))
3286 goto err;
3287
3288 io_req.bi_opf = REQ_OP_READ;
3289 io_req.mem.type = DM_IO_KMEM;
3290 io_req.mem.ptr.addr = recalc_buffer;
3291 io_req.notify.fn = NULL;
3292 io_req.client = ic->io;
3293 io_loc.bdev = ic->dev->bdev;
3294 io_loc.sector = get_data_sector(ic, area, offset);
3295 io_loc.count = n_sectors;
3296
3297 r = dm_io(&io_req, 1, &io_loc, NULL, NULL, IOPRIO_DEFAULT);
3298 if (unlikely(r)) {
3299 dm_integrity_io_error(ic, "reading data", r);
3300 goto err;
3301 }
3302
3303 t = recalc_tags;
3304 for (i = 0; i < n_sectors; i += ic->sectors_per_block) {
3305 void *ptr = recalc_buffer + (i << SECTOR_SHIFT);
3306 void *ptr_page = integrity_identity(ic, (char *)ptr - offset_in_page(ptr));
3307 unsigned ptr_offset = offset_in_page(ptr);
3308 integrity_sector_checksum(ic, &ahash_req, logical_sector + i, ptr_page, ptr_offset, t);
3309 t += ic->tag_size;
3310 }
3311
3312 metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
3313
3314 r = dm_integrity_rw_tag(ic, recalc_tags, &metadata_block, &metadata_offset, t - recalc_tags, TAG_WRITE);
3315 if (unlikely(r)) {
3316 dm_integrity_io_error(ic, "writing tags", r);
3317 goto err;
3318 }
3319
3320 if (ic->mode == 'B') {
3321 sector_t start, end;
3322
3323 start = (range.logical_sector >>
3324 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit)) <<
3325 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
3326 end = ((range.logical_sector + range.n_sectors) >>
3327 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit)) <<
3328 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
3329 block_bitmap_op(ic, ic->recalc_bitmap, start, end - start, BITMAP_OP_CLEAR);
3330 }
3331
3332 advance_and_next:
3333 cond_resched();
3334
3335 spin_lock_irq(&ic->endio_wait.lock);
3336 remove_range_unlocked(ic, &range);
3337 ic->sb->recalc_sector = cpu_to_le64(range.logical_sector + range.n_sectors);
3338 goto next_chunk;
3339
3340 err:
3341 remove_range(ic, &range);
3342 goto free_ret;
3343
3344 unlock_ret:
3345 spin_unlock_irq(&ic->endio_wait.lock);
3346
3347 recalc_write_super(ic);
3348
3349 free_ret:
3350 kfree(recalc_buffer);
3351 kvfree(recalc_tags);
3352 mempool_free(ahash_req, &ic->ahash_req_pool);
3353 }
3354
integrity_recalc_inline(struct work_struct * w)3355 static void integrity_recalc_inline(struct work_struct *w)
3356 {
3357 struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, recalc_work);
3358 size_t recalc_tags_size;
3359 u8 *recalc_buffer = NULL;
3360 u8 *recalc_tags = NULL;
3361 struct ahash_request *ahash_req = NULL;
3362 struct dm_integrity_range range;
3363 struct bio *bio;
3364 struct bio_integrity_payload *bip;
3365 __u8 *t;
3366 unsigned int i;
3367 int r;
3368 unsigned ret;
3369 unsigned int super_counter = 0;
3370 unsigned recalc_sectors = RECALC_SECTORS;
3371
3372 retry:
3373 recalc_buffer = kmalloc(recalc_sectors << SECTOR_SHIFT, GFP_NOIO | __GFP_NOWARN);
3374 if (!recalc_buffer) {
3375 oom:
3376 recalc_sectors >>= 1;
3377 if (recalc_sectors >= 1U << ic->sb->log2_sectors_per_block)
3378 goto retry;
3379 DMCRIT("out of memory for recalculate buffer - recalculation disabled");
3380 goto free_ret;
3381 }
3382
3383 recalc_tags_size = (recalc_sectors >> ic->sb->log2_sectors_per_block) * ic->tuple_size;
3384 if (ic->internal_hash_digestsize > ic->tuple_size)
3385 recalc_tags_size += ic->internal_hash_digestsize - ic->tuple_size;
3386 recalc_tags = kmalloc(recalc_tags_size, GFP_NOIO | __GFP_NOWARN);
3387 if (!recalc_tags) {
3388 kfree(recalc_buffer);
3389 recalc_buffer = NULL;
3390 goto oom;
3391 }
3392
3393 spin_lock_irq(&ic->endio_wait.lock);
3394
3395 next_chunk:
3396 if (unlikely(dm_post_suspending(ic->ti)))
3397 goto unlock_ret;
3398
3399 range.logical_sector = le64_to_cpu(ic->sb->recalc_sector);
3400 if (unlikely(range.logical_sector >= ic->provided_data_sectors))
3401 goto unlock_ret;
3402 range.n_sectors = min((sector_t)recalc_sectors, ic->provided_data_sectors - range.logical_sector);
3403
3404 add_new_range_and_wait(ic, &range);
3405 spin_unlock_irq(&ic->endio_wait.lock);
3406
3407 if (unlikely(++super_counter == RECALC_WRITE_SUPER)) {
3408 recalc_write_super(ic);
3409 super_counter = 0;
3410 }
3411
3412 if (unlikely(dm_integrity_failed(ic)))
3413 goto err;
3414
3415 DEBUG_print("recalculating: %llx - %llx\n", range.logical_sector, range.n_sectors);
3416
3417 bio = bio_alloc_bioset(ic->dev->bdev, 1, REQ_OP_READ, GFP_NOIO, &ic->recalc_bios);
3418 bio->bi_iter.bi_sector = ic->start + SB_SECTORS + range.logical_sector;
3419 bio_add_virt_nofail(bio, recalc_buffer,
3420 range.n_sectors << SECTOR_SHIFT);
3421 r = submit_bio_wait(bio);
3422 bio_put(bio);
3423 if (unlikely(r)) {
3424 dm_integrity_io_error(ic, "reading data", r);
3425 goto err;
3426 }
3427
3428 t = recalc_tags;
3429 for (i = 0; i < range.n_sectors; i += ic->sectors_per_block) {
3430 void *ptr = recalc_buffer + (i << SECTOR_SHIFT);
3431 void *ptr_page = integrity_identity(ic, (char *)ptr - offset_in_page(ptr));
3432 unsigned ptr_offset = offset_in_page(ptr);
3433 memset(t, 0, ic->tuple_size);
3434 integrity_sector_checksum(ic, &ahash_req, range.logical_sector + i, ptr_page, ptr_offset, t);
3435 t += ic->tuple_size;
3436 }
3437
3438 bio = bio_alloc_bioset(ic->dev->bdev, 1, REQ_OP_WRITE, GFP_NOIO, &ic->recalc_bios);
3439 bio->bi_iter.bi_sector = ic->start + SB_SECTORS + range.logical_sector;
3440 bio_add_virt_nofail(bio, recalc_buffer,
3441 range.n_sectors << SECTOR_SHIFT);
3442
3443 bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
3444 if (unlikely(IS_ERR(bip))) {
3445 bio_put(bio);
3446 DMCRIT("out of memory for bio integrity payload - recalculation disabled");
3447 goto err;
3448 }
3449 ret = bio_integrity_add_page(bio, virt_to_page(recalc_tags), t - recalc_tags, offset_in_page(recalc_tags));
3450 if (unlikely(ret != t - recalc_tags)) {
3451 bio_put(bio);
3452 dm_integrity_io_error(ic, "attaching integrity tags", -ENOMEM);
3453 goto err;
3454 }
3455
3456 r = submit_bio_wait(bio);
3457 bio_put(bio);
3458 if (unlikely(r)) {
3459 dm_integrity_io_error(ic, "writing data", r);
3460 goto err;
3461 }
3462
3463 cond_resched();
3464 spin_lock_irq(&ic->endio_wait.lock);
3465 remove_range_unlocked(ic, &range);
3466 #ifdef CONFIG_64BIT
3467 /* Paired with smp_load_acquire in dm_integrity_map_inline. */
3468 smp_store_release(&ic->sb->recalc_sector, cpu_to_le64(range.logical_sector + range.n_sectors));
3469 #else
3470 ic->sb->recalc_sector = cpu_to_le64(range.logical_sector + range.n_sectors);
3471 #endif
3472 goto next_chunk;
3473
3474 err:
3475 remove_range(ic, &range);
3476 goto free_ret;
3477
3478 unlock_ret:
3479 spin_unlock_irq(&ic->endio_wait.lock);
3480
3481 recalc_write_super(ic);
3482
3483 free_ret:
3484 kfree(recalc_buffer);
3485 kfree(recalc_tags);
3486 mempool_free(ahash_req, &ic->ahash_req_pool);
3487 }
3488
bitmap_block_work(struct work_struct * w)3489 static void bitmap_block_work(struct work_struct *w)
3490 {
3491 struct bitmap_block_status *bbs = container_of(w, struct bitmap_block_status, work);
3492 struct dm_integrity_c *ic = bbs->ic;
3493 struct bio *bio;
3494 struct bio_list bio_queue;
3495 struct bio_list waiting;
3496
3497 bio_list_init(&waiting);
3498
3499 spin_lock(&bbs->bio_queue_lock);
3500 bio_queue = bbs->bio_queue;
3501 bio_list_init(&bbs->bio_queue);
3502 spin_unlock(&bbs->bio_queue_lock);
3503
3504 while ((bio = bio_list_pop(&bio_queue))) {
3505 struct dm_integrity_io *dio;
3506
3507 dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
3508
3509 if (block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
3510 dio->range.n_sectors, BITMAP_OP_TEST_ALL_SET)) {
3511 remove_range(ic, &dio->range);
3512 INIT_WORK(&dio->work, integrity_bio_wait);
3513 queue_work(ic->offload_wq, &dio->work);
3514 } else {
3515 block_bitmap_op(ic, ic->journal, dio->range.logical_sector,
3516 dio->range.n_sectors, BITMAP_OP_SET);
3517 bio_list_add(&waiting, bio);
3518 }
3519 }
3520
3521 if (bio_list_empty(&waiting))
3522 return;
3523
3524 rw_journal_sectors(ic, REQ_OP_WRITE | REQ_FUA | REQ_SYNC,
3525 bbs->idx * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT),
3526 BITMAP_BLOCK_SIZE >> SECTOR_SHIFT, NULL);
3527
3528 while ((bio = bio_list_pop(&waiting))) {
3529 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
3530
3531 block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
3532 dio->range.n_sectors, BITMAP_OP_SET);
3533
3534 remove_range(ic, &dio->range);
3535 INIT_WORK(&dio->work, integrity_bio_wait);
3536 queue_work(ic->offload_wq, &dio->work);
3537 }
3538
3539 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, ic->bitmap_flush_interval);
3540 }
3541
bitmap_flush_work(struct work_struct * work)3542 static void bitmap_flush_work(struct work_struct *work)
3543 {
3544 struct dm_integrity_c *ic = container_of(work, struct dm_integrity_c, bitmap_flush_work.work);
3545 struct dm_integrity_range range;
3546 unsigned long limit;
3547 struct bio *bio;
3548
3549 dm_integrity_flush_buffers(ic, false);
3550
3551 range.logical_sector = 0;
3552 range.n_sectors = ic->provided_data_sectors;
3553
3554 spin_lock_irq(&ic->endio_wait.lock);
3555 add_new_range_and_wait(ic, &range);
3556 spin_unlock_irq(&ic->endio_wait.lock);
3557
3558 dm_integrity_flush_buffers(ic, true);
3559
3560 limit = ic->provided_data_sectors;
3561 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
3562 limit = le64_to_cpu(ic->sb->recalc_sector)
3563 >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit)
3564 << (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
3565 }
3566 /*DEBUG_print("zeroing journal\n");*/
3567 block_bitmap_op(ic, ic->journal, 0, limit, BITMAP_OP_CLEAR);
3568 block_bitmap_op(ic, ic->may_write_bitmap, 0, limit, BITMAP_OP_CLEAR);
3569
3570 rw_journal_sectors(ic, REQ_OP_WRITE | REQ_FUA | REQ_SYNC, 0,
3571 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3572
3573 spin_lock_irq(&ic->endio_wait.lock);
3574 remove_range_unlocked(ic, &range);
3575 while (unlikely((bio = bio_list_pop(&ic->synchronous_bios)) != NULL)) {
3576 bio_endio(bio);
3577 spin_unlock_irq(&ic->endio_wait.lock);
3578 spin_lock_irq(&ic->endio_wait.lock);
3579 }
3580 spin_unlock_irq(&ic->endio_wait.lock);
3581 }
3582
3583
init_journal(struct dm_integrity_c * ic,unsigned int start_section,unsigned int n_sections,unsigned char commit_seq)3584 static void init_journal(struct dm_integrity_c *ic, unsigned int start_section,
3585 unsigned int n_sections, unsigned char commit_seq)
3586 {
3587 unsigned int i, j, n;
3588
3589 if (!n_sections)
3590 return;
3591
3592 for (n = 0; n < n_sections; n++) {
3593 i = start_section + n;
3594 wraparound_section(ic, &i);
3595 for (j = 0; j < ic->journal_section_sectors; j++) {
3596 struct journal_sector *js = access_journal(ic, i, j);
3597
3598 BUILD_BUG_ON(sizeof(js->sectors) != JOURNAL_SECTOR_DATA);
3599 memset(&js->sectors, 0, sizeof(js->sectors));
3600 js->commit_id = dm_integrity_commit_id(ic, i, j, commit_seq);
3601 }
3602 for (j = 0; j < ic->journal_section_entries; j++) {
3603 struct journal_entry *je = access_journal_entry(ic, i, j);
3604
3605 journal_entry_set_unused(je);
3606 }
3607 }
3608
3609 write_journal(ic, start_section, n_sections);
3610 }
3611
find_commit_seq(struct dm_integrity_c * ic,unsigned int i,unsigned int j,commit_id_t id)3612 static int find_commit_seq(struct dm_integrity_c *ic, unsigned int i, unsigned int j, commit_id_t id)
3613 {
3614 unsigned char k;
3615
3616 for (k = 0; k < N_COMMIT_IDS; k++) {
3617 if (dm_integrity_commit_id(ic, i, j, k) == id)
3618 return k;
3619 }
3620 dm_integrity_io_error(ic, "journal commit id", -EIO);
3621 return -EIO;
3622 }
3623
replay_journal(struct dm_integrity_c * ic)3624 static void replay_journal(struct dm_integrity_c *ic)
3625 {
3626 unsigned int i, j;
3627 bool used_commit_ids[N_COMMIT_IDS];
3628 unsigned int max_commit_id_sections[N_COMMIT_IDS];
3629 unsigned int write_start, write_sections;
3630 unsigned int continue_section;
3631 bool journal_empty;
3632 unsigned char unused, last_used, want_commit_seq;
3633
3634 if (ic->mode == 'R')
3635 return;
3636
3637 if (ic->journal_uptodate)
3638 return;
3639
3640 last_used = 0;
3641 write_start = 0;
3642
3643 if (!ic->just_formatted) {
3644 DEBUG_print("reading journal\n");
3645 rw_journal(ic, REQ_OP_READ, 0, ic->journal_sections, NULL);
3646 if (ic->journal_io)
3647 DEBUG_bytes(lowmem_page_address(ic->journal_io[0].page), 64, "read journal");
3648 if (ic->journal_io) {
3649 struct journal_completion crypt_comp;
3650
3651 crypt_comp.ic = ic;
3652 init_completion(&crypt_comp.comp);
3653 crypt_comp.in_flight = (atomic_t)ATOMIC_INIT(0);
3654 encrypt_journal(ic, false, 0, ic->journal_sections, &crypt_comp);
3655 wait_for_completion(&crypt_comp.comp);
3656 }
3657 DEBUG_bytes(lowmem_page_address(ic->journal[0].page), 64, "decrypted journal");
3658 }
3659
3660 if (dm_integrity_failed(ic))
3661 goto clear_journal;
3662
3663 journal_empty = true;
3664 memset(used_commit_ids, 0, sizeof(used_commit_ids));
3665 memset(max_commit_id_sections, 0, sizeof(max_commit_id_sections));
3666 for (i = 0; i < ic->journal_sections; i++) {
3667 for (j = 0; j < ic->journal_section_sectors; j++) {
3668 int k;
3669 struct journal_sector *js = access_journal(ic, i, j);
3670
3671 k = find_commit_seq(ic, i, j, js->commit_id);
3672 if (k < 0)
3673 goto clear_journal;
3674 used_commit_ids[k] = true;
3675 max_commit_id_sections[k] = i;
3676 }
3677 if (journal_empty) {
3678 for (j = 0; j < ic->journal_section_entries; j++) {
3679 struct journal_entry *je = access_journal_entry(ic, i, j);
3680
3681 if (!journal_entry_is_unused(je)) {
3682 journal_empty = false;
3683 break;
3684 }
3685 }
3686 }
3687 }
3688
3689 if (!used_commit_ids[N_COMMIT_IDS - 1]) {
3690 unused = N_COMMIT_IDS - 1;
3691 while (unused && !used_commit_ids[unused - 1])
3692 unused--;
3693 } else {
3694 for (unused = 0; unused < N_COMMIT_IDS; unused++)
3695 if (!used_commit_ids[unused])
3696 break;
3697 if (unused == N_COMMIT_IDS) {
3698 dm_integrity_io_error(ic, "journal commit ids", -EIO);
3699 goto clear_journal;
3700 }
3701 }
3702 DEBUG_print("first unused commit seq %d [%d,%d,%d,%d]\n",
3703 unused, used_commit_ids[0], used_commit_ids[1],
3704 used_commit_ids[2], used_commit_ids[3]);
3705
3706 last_used = prev_commit_seq(unused);
3707 want_commit_seq = prev_commit_seq(last_used);
3708
3709 if (!used_commit_ids[want_commit_seq] && used_commit_ids[prev_commit_seq(want_commit_seq)])
3710 journal_empty = true;
3711
3712 write_start = max_commit_id_sections[last_used] + 1;
3713 if (unlikely(write_start >= ic->journal_sections))
3714 want_commit_seq = next_commit_seq(want_commit_seq);
3715 wraparound_section(ic, &write_start);
3716
3717 i = write_start;
3718 for (write_sections = 0; write_sections < ic->journal_sections; write_sections++) {
3719 for (j = 0; j < ic->journal_section_sectors; j++) {
3720 struct journal_sector *js = access_journal(ic, i, j);
3721
3722 if (js->commit_id != dm_integrity_commit_id(ic, i, j, want_commit_seq)) {
3723 /*
3724 * This could be caused by crash during writing.
3725 * We won't replay the inconsistent part of the
3726 * journal.
3727 */
3728 DEBUG_print("commit id mismatch at position (%u, %u): %d != %d\n",
3729 i, j, find_commit_seq(ic, i, j, js->commit_id), want_commit_seq);
3730 goto brk;
3731 }
3732 }
3733 i++;
3734 if (unlikely(i >= ic->journal_sections))
3735 want_commit_seq = next_commit_seq(want_commit_seq);
3736 wraparound_section(ic, &i);
3737 }
3738 brk:
3739
3740 if (!journal_empty) {
3741 DEBUG_print("replaying %u sections, starting at %u, commit seq %d\n",
3742 write_sections, write_start, want_commit_seq);
3743 do_journal_write(ic, write_start, write_sections, true);
3744 }
3745
3746 if (write_sections == ic->journal_sections && (ic->mode == 'J' || journal_empty)) {
3747 continue_section = write_start;
3748 ic->commit_seq = want_commit_seq;
3749 DEBUG_print("continuing from section %u, commit seq %d\n", write_start, ic->commit_seq);
3750 } else {
3751 unsigned int s;
3752 unsigned char erase_seq;
3753
3754 clear_journal:
3755 DEBUG_print("clearing journal\n");
3756
3757 erase_seq = prev_commit_seq(prev_commit_seq(last_used));
3758 s = write_start;
3759 init_journal(ic, s, 1, erase_seq);
3760 s++;
3761 wraparound_section(ic, &s);
3762 if (ic->journal_sections >= 2) {
3763 init_journal(ic, s, ic->journal_sections - 2, erase_seq);
3764 s += ic->journal_sections - 2;
3765 wraparound_section(ic, &s);
3766 init_journal(ic, s, 1, erase_seq);
3767 }
3768
3769 continue_section = 0;
3770 ic->commit_seq = next_commit_seq(erase_seq);
3771 }
3772
3773 ic->committed_section = continue_section;
3774 ic->n_committed_sections = 0;
3775
3776 ic->uncommitted_section = continue_section;
3777 ic->n_uncommitted_sections = 0;
3778
3779 ic->free_section = continue_section;
3780 ic->free_section_entry = 0;
3781 ic->free_sectors = ic->journal_entries;
3782
3783 ic->journal_tree_root = RB_ROOT;
3784 for (i = 0; i < ic->journal_entries; i++)
3785 init_journal_node(&ic->journal_tree[i]);
3786 }
3787
dm_integrity_enter_synchronous_mode(struct dm_integrity_c * ic)3788 static void dm_integrity_enter_synchronous_mode(struct dm_integrity_c *ic)
3789 {
3790 DEBUG_print("%s\n", __func__);
3791
3792 if (ic->mode == 'B') {
3793 ic->bitmap_flush_interval = msecs_to_jiffies(10) + 1;
3794 ic->synchronous_mode = 1;
3795
3796 cancel_delayed_work_sync(&ic->bitmap_flush_work);
3797 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
3798 flush_workqueue(ic->commit_wq);
3799 }
3800 }
3801
dm_integrity_reboot(struct notifier_block * n,unsigned long code,void * x)3802 static int dm_integrity_reboot(struct notifier_block *n, unsigned long code, void *x)
3803 {
3804 struct dm_integrity_c *ic = container_of(n, struct dm_integrity_c, reboot_notifier);
3805
3806 DEBUG_print("%s\n", __func__);
3807
3808 dm_integrity_enter_synchronous_mode(ic);
3809
3810 return NOTIFY_DONE;
3811 }
3812
dm_integrity_postsuspend(struct dm_target * ti)3813 static void dm_integrity_postsuspend(struct dm_target *ti)
3814 {
3815 struct dm_integrity_c *ic = ti->private;
3816 int r;
3817
3818 WARN_ON(unregister_reboot_notifier(&ic->reboot_notifier));
3819
3820 timer_delete_sync(&ic->autocommit_timer);
3821
3822 if (ic->recalc_wq)
3823 drain_workqueue(ic->recalc_wq);
3824
3825 if (ic->mode == 'B')
3826 cancel_delayed_work_sync(&ic->bitmap_flush_work);
3827
3828 queue_work(ic->commit_wq, &ic->commit_work);
3829 drain_workqueue(ic->commit_wq);
3830
3831 if (ic->mode == 'J') {
3832 queue_work(ic->writer_wq, &ic->writer_work);
3833 drain_workqueue(ic->writer_wq);
3834 dm_integrity_flush_buffers(ic, true);
3835 if (ic->wrote_to_journal) {
3836 init_journal(ic, ic->free_section,
3837 ic->journal_sections - ic->free_section, ic->commit_seq);
3838 if (ic->free_section) {
3839 init_journal(ic, 0, ic->free_section,
3840 next_commit_seq(ic->commit_seq));
3841 }
3842 }
3843 }
3844
3845 if (ic->mode == 'B') {
3846 dm_integrity_flush_buffers(ic, true);
3847 #if 1
3848 /* set to 0 to test bitmap replay code */
3849 init_journal(ic, 0, ic->journal_sections, 0);
3850 ic->sb->flags &= ~cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
3851 r = sync_rw_sb(ic, REQ_OP_WRITE | REQ_FUA);
3852 if (unlikely(r))
3853 dm_integrity_io_error(ic, "writing superblock", r);
3854 #endif
3855 }
3856
3857 BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
3858
3859 ic->journal_uptodate = true;
3860 }
3861
3862 /*
3863 * The superblock is re-read from the device on every resume, so that we pick
3864 * up the flags and the recalculate position. The geometry described by the
3865 * superblock must not change though - the in-memory structures (and the
3866 * journal in particular) were sized according to the superblock that was
3867 * validated in the constructor. Reject a superblock that was modified behind
3868 * our back.
3869 *
3870 * Only the fields that the driver never rewrites may be tested here. In
3871 * particular, "version" is recalculated by sb_set_version on every superblock
3872 * write and it depends on SB_FLAG_RECALCULATING and SB_FLAG_DIRTY_BITMAP, and
3873 * SB_FLAG_DISCARD_KEYED may be set by dm_integrity_resume itself.
3874 */
superblock_changed(struct dm_integrity_c * ic)3875 static bool superblock_changed(struct dm_integrity_c *ic)
3876 {
3877 const __le32 immutable_flags = cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC |
3878 SB_FLAG_FIXED_PADDING |
3879 SB_FLAG_FIXED_HMAC |
3880 SB_FLAG_INLINE);
3881
3882 return memcmp(ic->sb->magic, ic->sb_copy->magic, sizeof(ic->sb->magic)) != 0 ||
3883 ic->sb->log2_interleave_sectors != ic->sb_copy->log2_interleave_sectors ||
3884 ic->sb->integrity_tag_size != ic->sb_copy->integrity_tag_size ||
3885 ic->sb->journal_sections != ic->sb_copy->journal_sections ||
3886 ic->sb->log2_sectors_per_block != ic->sb_copy->log2_sectors_per_block ||
3887 ((ic->sb->flags ^ ic->sb_copy->flags) & immutable_flags) != 0 ||
3888 memcmp(ic->sb->salt, ic->sb_copy->salt, SALT_SIZE) != 0;
3889 }
3890
dm_integrity_resume(struct dm_target * ti)3891 static void dm_integrity_resume(struct dm_target *ti)
3892 {
3893 struct dm_integrity_c *ic = ti->private;
3894 __u64 old_provided_data_sectors = le64_to_cpu(ic->sb->provided_data_sectors);
3895 int r;
3896 __le32 flags;
3897
3898 DEBUG_print("resume\n");
3899
3900 ic->wrote_to_journal = false;
3901
3902 flags = ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING);
3903 if (ic->discard_keyed)
3904 flags |= cpu_to_le32(SB_FLAG_DISCARD_KEYED);
3905 r = sync_rw_sb(ic, REQ_OP_READ);
3906 if (r)
3907 dm_integrity_io_error(ic, "reading superblock", r);
3908
3909 if (unlikely(superblock_changed(ic))) {
3910 /*
3911 * Restore the superblock that we validated in the constructor,
3912 * so that the rest of the driver doesn't operate on values
3913 * that don't match the in-memory structures.
3914 */
3915 memcpy(ic->sb, ic->sb_copy, sizeof(struct superblock));
3916 DMERR("The superblock was changed while the device was suspended");
3917 dm_integrity_io_error(ic, "superblock check", -EINVAL);
3918 goto skip_writes;
3919 }
3920
3921 if (ic->mode == 'R')
3922 goto skip_writes;
3923
3924 if ((ic->sb->flags & flags) != flags) {
3925 ic->sb->flags |= flags;
3926 r = sync_rw_sb(ic, REQ_OP_WRITE | REQ_FUA);
3927 if (unlikely(r))
3928 dm_integrity_io_error(ic, "writing superblock", r);
3929 }
3930
3931 if (ic->provided_data_sectors != old_provided_data_sectors) {
3932 if (ic->provided_data_sectors > old_provided_data_sectors &&
3933 ic->mode == 'B' &&
3934 ic->sb->flags & cpu_to_le32(SB_FLAG_DIRTY_BITMAP) &&
3935 ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit) {
3936 rw_journal_sectors(ic, REQ_OP_READ, 0,
3937 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3938 block_bitmap_op(ic, ic->journal, old_provided_data_sectors,
3939 ic->provided_data_sectors - old_provided_data_sectors, BITMAP_OP_SET);
3940 rw_journal_sectors(ic, REQ_OP_WRITE | REQ_FUA | REQ_SYNC, 0,
3941 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3942 }
3943
3944 ic->sb->provided_data_sectors = cpu_to_le64(ic->provided_data_sectors);
3945 r = sync_rw_sb(ic, REQ_OP_WRITE | REQ_FUA);
3946 if (unlikely(r))
3947 dm_integrity_io_error(ic, "writing superblock", r);
3948 }
3949
3950 if (ic->sb->flags & cpu_to_le32(SB_FLAG_DIRTY_BITMAP)) {
3951 DEBUG_print("resume dirty_bitmap\n");
3952 rw_journal_sectors(ic, REQ_OP_READ, 0,
3953 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3954 if (ic->mode == 'B') {
3955 if (ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit &&
3956 !ic->reset_recalculate_flag) {
3957 block_bitmap_copy(ic, ic->recalc_bitmap, ic->journal);
3958 block_bitmap_copy(ic, ic->may_write_bitmap, ic->journal);
3959 if (!block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors,
3960 BITMAP_OP_TEST_ALL_CLEAR)) {
3961 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
3962 ic->sb->recalc_sector = cpu_to_le64(0);
3963 }
3964 } else {
3965 DEBUG_print("non-matching blocks_per_bitmap_bit: %u, %u\n",
3966 ic->sb->log2_blocks_per_bitmap_bit, ic->log2_blocks_per_bitmap_bit);
3967 ic->sb->log2_blocks_per_bitmap_bit = ic->log2_blocks_per_bitmap_bit;
3968 block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_SET);
3969 block_bitmap_op(ic, ic->may_write_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_SET);
3970 block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_SET);
3971 rw_journal_sectors(ic, REQ_OP_WRITE | REQ_FUA | REQ_SYNC, 0,
3972 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3973 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
3974 ic->sb->recalc_sector = cpu_to_le64(0);
3975 }
3976 } else {
3977 if (!(ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit &&
3978 block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_TEST_ALL_CLEAR)) ||
3979 ic->reset_recalculate_flag) {
3980 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
3981 ic->sb->recalc_sector = cpu_to_le64(0);
3982 }
3983 init_journal(ic, 0, ic->journal_sections, 0);
3984 replay_journal(ic);
3985 ic->sb->flags &= ~cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
3986 }
3987 r = sync_rw_sb(ic, REQ_OP_WRITE | REQ_FUA);
3988 if (unlikely(r))
3989 dm_integrity_io_error(ic, "writing superblock", r);
3990 } else {
3991 replay_journal(ic);
3992 if (ic->reset_recalculate_flag) {
3993 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
3994 ic->sb->recalc_sector = cpu_to_le64(0);
3995 }
3996 if (ic->mode == 'B') {
3997 ic->sb->flags |= cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
3998 ic->sb->log2_blocks_per_bitmap_bit = ic->log2_blocks_per_bitmap_bit;
3999 r = sync_rw_sb(ic, REQ_OP_WRITE | REQ_FUA);
4000 if (unlikely(r))
4001 dm_integrity_io_error(ic, "writing superblock", r);
4002
4003 block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
4004 block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
4005 block_bitmap_op(ic, ic->may_write_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
4006 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
4007 le64_to_cpu(ic->sb->recalc_sector) < ic->provided_data_sectors) {
4008 block_bitmap_op(ic, ic->journal, le64_to_cpu(ic->sb->recalc_sector),
4009 ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
4010 block_bitmap_op(ic, ic->recalc_bitmap, le64_to_cpu(ic->sb->recalc_sector),
4011 ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
4012 block_bitmap_op(ic, ic->may_write_bitmap, le64_to_cpu(ic->sb->recalc_sector),
4013 ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
4014 }
4015 rw_journal_sectors(ic, REQ_OP_WRITE | REQ_FUA | REQ_SYNC, 0,
4016 ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
4017 }
4018 }
4019
4020 DEBUG_print("testing recalc: %x\n", ic->sb->flags);
4021 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
4022 __u64 recalc_pos = le64_to_cpu(ic->sb->recalc_sector);
4023
4024 DEBUG_print("recalc pos: %llx / %llx\n", recalc_pos, ic->provided_data_sectors);
4025 if (recalc_pos < ic->provided_data_sectors) {
4026 queue_work(ic->recalc_wq, &ic->recalc_work);
4027 } else if (recalc_pos > ic->provided_data_sectors) {
4028 ic->sb->recalc_sector = cpu_to_le64(ic->provided_data_sectors);
4029 recalc_write_super(ic);
4030 }
4031 }
4032
4033 skip_writes:
4034 ic->reboot_notifier.notifier_call = dm_integrity_reboot;
4035 ic->reboot_notifier.next = NULL;
4036 ic->reboot_notifier.priority = INT_MAX - 1; /* be notified after md and before hardware drivers */
4037 WARN_ON(register_reboot_notifier(&ic->reboot_notifier));
4038
4039 #if 0
4040 /* set to 1 to stress test synchronous mode */
4041 dm_integrity_enter_synchronous_mode(ic);
4042 #endif
4043 }
4044
dm_integrity_status(struct dm_target * ti,status_type_t type,unsigned int status_flags,char * result,unsigned int maxlen)4045 static void dm_integrity_status(struct dm_target *ti, status_type_t type,
4046 unsigned int status_flags, char *result, unsigned int maxlen)
4047 {
4048 struct dm_integrity_c *ic = ti->private;
4049 unsigned int arg_count;
4050 size_t sz = 0;
4051
4052 switch (type) {
4053 case STATUSTYPE_INFO:
4054 DMEMIT("%llu %llu",
4055 (unsigned long long)atomic64_read(&ic->number_of_mismatches),
4056 ic->provided_data_sectors);
4057 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
4058 DMEMIT(" %llu", le64_to_cpu(ic->sb->recalc_sector));
4059 else
4060 DMEMIT(" -");
4061 break;
4062
4063 case STATUSTYPE_TABLE: {
4064 arg_count = 1; /* buffer_sectors */
4065 arg_count += !!ic->meta_dev;
4066 arg_count += ic->sectors_per_block != 1;
4067 arg_count += !!(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING));
4068 arg_count += ic->reset_recalculate_flag;
4069 arg_count += ic->discard && !ic->discard_keyed;
4070 arg_count += ic->discard_keyed;
4071 arg_count += ic->mode != 'I'; /* interleave_sectors */
4072 arg_count += ic->mode == 'J'; /* journal_sectors */
4073 arg_count += ic->mode == 'J'; /* journal_watermark */
4074 arg_count += ic->mode == 'J'; /* commit_time */
4075 arg_count += ic->mode == 'B'; /* sectors_per_bit */
4076 arg_count += ic->mode == 'B'; /* bitmap_flush_interval */
4077 arg_count += !!ic->internal_hash_alg.alg_string;
4078 arg_count += !!ic->journal_crypt_alg.alg_string;
4079 arg_count += !!ic->journal_mac_alg.alg_string;
4080 arg_count += (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING)) != 0;
4081 arg_count += (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) != 0;
4082 arg_count += ic->legacy_recalculate;
4083 DMEMIT("%s %llu %u %c %u", ic->dev->name, ic->start,
4084 ic->tag_size, ic->mode, arg_count);
4085 if (ic->meta_dev)
4086 DMEMIT(" meta_device:%s", ic->meta_dev->name);
4087 if (ic->sectors_per_block != 1)
4088 DMEMIT(" block_size:%u", ic->sectors_per_block << SECTOR_SHIFT);
4089 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
4090 DMEMIT(" recalculate");
4091 if (ic->reset_recalculate_flag)
4092 DMEMIT(" reset_recalculate");
4093 if (ic->discard && !ic->discard_keyed)
4094 DMEMIT(" allow_discards");
4095 if (ic->discard_keyed)
4096 DMEMIT(" allow_discards_keyed");
4097 if (ic->mode != 'I')
4098 DMEMIT(" interleave_sectors:%u", 1U << ic->sb->log2_interleave_sectors);
4099 DMEMIT(" buffer_sectors:%u", 1U << ic->log2_buffer_sectors);
4100 if (ic->mode == 'J') {
4101 __u64 watermark_percentage = (__u64)(ic->journal_entries - ic->free_sectors_threshold) * 100;
4102
4103 watermark_percentage += ic->journal_entries / 2;
4104 do_div(watermark_percentage, ic->journal_entries);
4105 DMEMIT(" journal_sectors:%u", ic->initial_sectors - SB_SECTORS);
4106 DMEMIT(" journal_watermark:%u", (unsigned int)watermark_percentage);
4107 DMEMIT(" commit_time:%u", ic->autocommit_msec);
4108 }
4109 if (ic->mode == 'B') {
4110 DMEMIT(" sectors_per_bit:%llu", (sector_t)ic->sectors_per_block << ic->log2_blocks_per_bitmap_bit);
4111 DMEMIT(" bitmap_flush_interval:%u", jiffies_to_msecs(ic->bitmap_flush_interval));
4112 }
4113 if ((ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING)) != 0)
4114 DMEMIT(" fix_padding");
4115 if ((ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) != 0)
4116 DMEMIT(" fix_hmac");
4117 if (ic->legacy_recalculate)
4118 DMEMIT(" legacy_recalculate");
4119
4120 #define EMIT_ALG(a, n) \
4121 do { \
4122 if (ic->a.alg_string) { \
4123 DMEMIT(" %s:%s", n, ic->a.alg_string); \
4124 if (ic->a.key_string) \
4125 DMEMIT(":%s", ic->a.key_string);\
4126 } \
4127 } while (0)
4128 EMIT_ALG(internal_hash_alg, "internal_hash");
4129 EMIT_ALG(journal_crypt_alg, "journal_crypt");
4130 EMIT_ALG(journal_mac_alg, "journal_mac");
4131 break;
4132 }
4133 case STATUSTYPE_IMA:
4134 DMEMIT_TARGET_NAME_VERSION(ti->type);
4135 DMEMIT(",dev_name=%s,start=%llu,tag_size=%u,mode=%c",
4136 ic->dev->name, ic->start, ic->tag_size, ic->mode);
4137
4138 if (ic->meta_dev)
4139 DMEMIT(",meta_device=%s", ic->meta_dev->name);
4140 if (ic->sectors_per_block != 1)
4141 DMEMIT(",block_size=%u", ic->sectors_per_block << SECTOR_SHIFT);
4142
4143 DMEMIT(",recalculate=%c", (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) ?
4144 'y' : 'n');
4145 DMEMIT(",allow_discards=%c", ic->discard ? 'y' : 'n');
4146 DMEMIT(",allow_discards_keyed=%c", ic->discard_keyed ? 'y' : 'n');
4147 DMEMIT(",fix_padding=%c",
4148 ((ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING)) != 0) ? 'y' : 'n');
4149 DMEMIT(",fix_hmac=%c",
4150 ((ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) != 0) ? 'y' : 'n');
4151 DMEMIT(",legacy_recalculate=%c", ic->legacy_recalculate ? 'y' : 'n');
4152
4153 DMEMIT(",journal_sectors=%u", ic->initial_sectors - SB_SECTORS);
4154 DMEMIT(",interleave_sectors=%u", 1U << ic->sb->log2_interleave_sectors);
4155 DMEMIT(",buffer_sectors=%u", 1U << ic->log2_buffer_sectors);
4156 DMEMIT(";");
4157 break;
4158 }
4159 }
4160
dm_integrity_iterate_devices(struct dm_target * ti,iterate_devices_callout_fn fn,void * data)4161 static int dm_integrity_iterate_devices(struct dm_target *ti,
4162 iterate_devices_callout_fn fn, void *data)
4163 {
4164 struct dm_integrity_c *ic = ti->private;
4165
4166 if (!ic->meta_dev)
4167 return fn(ti, ic->dev, ic->start + ic->initial_sectors + ic->metadata_run, ti->len, data);
4168 else
4169 return fn(ti, ic->dev, 0, ti->len, data);
4170 }
4171
dm_integrity_io_hints(struct dm_target * ti,struct queue_limits * limits)4172 static void dm_integrity_io_hints(struct dm_target *ti, struct queue_limits *limits)
4173 {
4174 struct dm_integrity_c *ic = ti->private;
4175
4176 dm_stack_bs_limits(limits, ic->sectors_per_block << SECTOR_SHIFT);
4177 limits->dma_alignment = limits->logical_block_size - 1;
4178 limits->discard_granularity = ic->sectors_per_block << SECTOR_SHIFT;
4179
4180 if (ic->internal_hash &&
4181 (ic->mode == 'D' || ic->mode == 'B' || ic->mode == 'I'))
4182 limits->features |= BLK_FEAT_STABLE_WRITES;
4183
4184 if (!ic->internal_hash) {
4185 struct blk_integrity *bi = &limits->integrity;
4186
4187 memset(bi, 0, sizeof(*bi));
4188 bi->metadata_size = ic->tag_size;
4189 bi->tag_size = bi->metadata_size;
4190 bi->interval_exp =
4191 ic->sb->log2_sectors_per_block + SECTOR_SHIFT;
4192 }
4193
4194 limits->max_integrity_segments = USHRT_MAX;
4195 }
4196
calculate_journal_section_size(struct dm_integrity_c * ic)4197 static void calculate_journal_section_size(struct dm_integrity_c *ic)
4198 {
4199 unsigned int sector_space = JOURNAL_SECTOR_DATA;
4200
4201 ic->journal_sections = le32_to_cpu(ic->sb->journal_sections);
4202 ic->journal_entry_size = roundup(offsetof(struct journal_entry, last_bytes[ic->sectors_per_block]) + ic->tag_size,
4203 JOURNAL_ENTRY_ROUNDUP);
4204
4205 if (ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC))
4206 sector_space -= JOURNAL_MAC_PER_SECTOR;
4207 ic->journal_entries_per_sector = sector_space / ic->journal_entry_size;
4208 ic->journal_section_entries = ic->journal_entries_per_sector * JOURNAL_BLOCK_SECTORS;
4209 ic->journal_section_sectors = (ic->journal_section_entries << ic->sb->log2_sectors_per_block) + JOURNAL_BLOCK_SECTORS;
4210 ic->journal_entries = ic->journal_section_entries * ic->journal_sections;
4211 }
4212
calculate_device_limits(struct dm_integrity_c * ic)4213 static int calculate_device_limits(struct dm_integrity_c *ic)
4214 {
4215 __u64 initial_sectors;
4216
4217 calculate_journal_section_size(ic);
4218 initial_sectors = SB_SECTORS + (__u64)ic->journal_section_sectors * ic->journal_sections;
4219 if (initial_sectors + METADATA_PADDING_SECTORS >= ic->meta_device_sectors || initial_sectors > UINT_MAX)
4220 return -EINVAL;
4221 ic->initial_sectors = initial_sectors;
4222
4223 if (ic->mode == 'I') {
4224 if (ic->initial_sectors + ic->provided_data_sectors > ic->meta_device_sectors)
4225 return -EINVAL;
4226 } else if (!ic->meta_dev) {
4227 sector_t last_sector, last_area, last_offset;
4228
4229 /* we have to maintain excessive padding for compatibility with existing volumes */
4230 __u64 metadata_run_padding =
4231 ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING) ?
4232 (__u64)(METADATA_PADDING_SECTORS << SECTOR_SHIFT) :
4233 (__u64)(1 << SECTOR_SHIFT << METADATA_PADDING_SECTORS);
4234
4235 ic->metadata_run = round_up((__u64)ic->tag_size << (ic->sb->log2_interleave_sectors - ic->sb->log2_sectors_per_block),
4236 metadata_run_padding) >> SECTOR_SHIFT;
4237 if (!(ic->metadata_run & (ic->metadata_run - 1)))
4238 ic->log2_metadata_run = __ffs(ic->metadata_run);
4239 else
4240 ic->log2_metadata_run = -1;
4241
4242 get_area_and_offset(ic, ic->provided_data_sectors - 1, &last_area, &last_offset);
4243 last_sector = get_data_sector(ic, last_area, last_offset);
4244 if (last_sector < ic->start || last_sector >= ic->meta_device_sectors)
4245 return -EINVAL;
4246 } else {
4247 __u64 meta_size = (ic->provided_data_sectors >> ic->sb->log2_sectors_per_block) * ic->tag_size;
4248
4249 meta_size = (meta_size + ((1U << (ic->log2_buffer_sectors + SECTOR_SHIFT)) - 1))
4250 >> (ic->log2_buffer_sectors + SECTOR_SHIFT);
4251 meta_size <<= ic->log2_buffer_sectors;
4252 if (ic->initial_sectors + meta_size < ic->initial_sectors ||
4253 ic->initial_sectors + meta_size > ic->meta_device_sectors)
4254 return -EINVAL;
4255 ic->metadata_run = 1;
4256 ic->log2_metadata_run = 0;
4257 }
4258
4259 return 0;
4260 }
4261
get_provided_data_sectors(struct dm_integrity_c * ic)4262 static void get_provided_data_sectors(struct dm_integrity_c *ic)
4263 {
4264 if (!ic->meta_dev) {
4265 int test_bit;
4266
4267 ic->provided_data_sectors = 0;
4268 for (test_bit = fls64(ic->meta_device_sectors) - 1; test_bit >= 3; test_bit--) {
4269 __u64 prev_data_sectors = ic->provided_data_sectors;
4270
4271 ic->provided_data_sectors |= (sector_t)1 << test_bit;
4272 if (calculate_device_limits(ic))
4273 ic->provided_data_sectors = prev_data_sectors;
4274 }
4275 } else {
4276 ic->provided_data_sectors = ic->data_device_sectors;
4277 ic->provided_data_sectors &= ~(sector_t)(ic->sectors_per_block - 1);
4278 }
4279 }
4280
initialize_superblock(struct dm_integrity_c * ic,unsigned int journal_sectors,unsigned int interleave_sectors)4281 static int initialize_superblock(struct dm_integrity_c *ic,
4282 unsigned int journal_sectors, unsigned int interleave_sectors)
4283 {
4284 unsigned int journal_sections;
4285 int test_bit;
4286
4287 memset(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT);
4288 memcpy(ic->sb->magic, SB_MAGIC, 8);
4289 if (ic->mode == 'I')
4290 ic->sb->flags |= cpu_to_le32(SB_FLAG_INLINE);
4291 ic->sb->integrity_tag_size = cpu_to_le16(ic->tag_size);
4292 ic->sb->log2_sectors_per_block = __ffs(ic->sectors_per_block);
4293 if (ic->journal_mac_alg.alg_string)
4294 ic->sb->flags |= cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC);
4295
4296 calculate_journal_section_size(ic);
4297 journal_sections = journal_sectors / ic->journal_section_sectors;
4298 if (!journal_sections)
4299 journal_sections = 1;
4300 if (ic->mode == 'I')
4301 journal_sections = 0;
4302
4303 if (ic->fix_hmac && (ic->internal_hash_alg.alg_string || ic->journal_mac_alg.alg_string)) {
4304 ic->sb->flags |= cpu_to_le32(SB_FLAG_FIXED_HMAC);
4305 get_random_bytes(ic->sb->salt, SALT_SIZE);
4306 }
4307
4308 if (ic->discard_keyed)
4309 ic->sb->flags |= cpu_to_le32(SB_FLAG_DISCARD_KEYED);
4310
4311 if (!ic->meta_dev) {
4312 if (ic->fix_padding)
4313 ic->sb->flags |= cpu_to_le32(SB_FLAG_FIXED_PADDING);
4314 ic->sb->journal_sections = cpu_to_le32(journal_sections);
4315 if (!interleave_sectors)
4316 interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
4317 ic->sb->log2_interleave_sectors = __fls(interleave_sectors);
4318 ic->sb->log2_interleave_sectors = max_t(__u8, MIN_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
4319 ic->sb->log2_interleave_sectors = min_t(__u8, MAX_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
4320
4321 get_provided_data_sectors(ic);
4322 if (!ic->provided_data_sectors)
4323 return -EINVAL;
4324 } else {
4325 ic->sb->log2_interleave_sectors = 0;
4326
4327 get_provided_data_sectors(ic);
4328 if (!ic->provided_data_sectors)
4329 return -EINVAL;
4330
4331 try_smaller_buffer:
4332 ic->sb->journal_sections = cpu_to_le32(0);
4333 for (test_bit = fls(journal_sections) - 1; test_bit >= 0; test_bit--) {
4334 __u32 prev_journal_sections = le32_to_cpu(ic->sb->journal_sections);
4335 __u32 test_journal_sections = prev_journal_sections | (1U << test_bit);
4336
4337 if (test_journal_sections > journal_sections)
4338 continue;
4339 ic->sb->journal_sections = cpu_to_le32(test_journal_sections);
4340 if (calculate_device_limits(ic))
4341 ic->sb->journal_sections = cpu_to_le32(prev_journal_sections);
4342
4343 }
4344 if (!le32_to_cpu(ic->sb->journal_sections)) {
4345 if (ic->log2_buffer_sectors > 3) {
4346 ic->log2_buffer_sectors--;
4347 goto try_smaller_buffer;
4348 }
4349 return -EINVAL;
4350 }
4351 }
4352
4353 ic->sb->provided_data_sectors = cpu_to_le64(ic->provided_data_sectors);
4354
4355 sb_set_version(ic);
4356
4357 return 0;
4358 }
4359
dm_integrity_free_page_list(struct page_list * pl)4360 static void dm_integrity_free_page_list(struct page_list *pl)
4361 {
4362 unsigned int i;
4363
4364 if (!pl)
4365 return;
4366 for (i = 0; pl[i].page; i++)
4367 __free_page(pl[i].page);
4368 kvfree(pl);
4369 }
4370
dm_integrity_alloc_page_list(unsigned int n_pages)4371 static struct page_list *dm_integrity_alloc_page_list(unsigned int n_pages)
4372 {
4373 struct page_list *pl;
4374 unsigned int i;
4375
4376 pl = kvmalloc_objs(struct page_list, n_pages + 1,
4377 GFP_KERNEL | __GFP_ZERO);
4378 if (!pl)
4379 return NULL;
4380
4381 for (i = 0; i < n_pages; i++) {
4382 pl[i].page = alloc_page(GFP_KERNEL);
4383 if (!pl[i].page) {
4384 dm_integrity_free_page_list(pl);
4385 return NULL;
4386 }
4387 if (i)
4388 pl[i - 1].next = &pl[i];
4389 }
4390 pl[i].page = NULL;
4391 pl[i].next = NULL;
4392
4393 return pl;
4394 }
4395
dm_integrity_free_journal_scatterlist(struct dm_integrity_c * ic,struct scatterlist ** sl)4396 static void dm_integrity_free_journal_scatterlist(struct dm_integrity_c *ic, struct scatterlist **sl)
4397 {
4398 unsigned int i;
4399
4400 for (i = 0; i < ic->journal_sections; i++)
4401 kvfree(sl[i]);
4402 kvfree(sl);
4403 }
4404
dm_integrity_alloc_journal_scatterlist(struct dm_integrity_c * ic,struct page_list * pl)4405 static struct scatterlist **dm_integrity_alloc_journal_scatterlist(struct dm_integrity_c *ic,
4406 struct page_list *pl)
4407 {
4408 struct scatterlist **sl;
4409 unsigned int i;
4410
4411 sl = kvmalloc_objs(struct scatterlist *, ic->journal_sections,
4412 GFP_KERNEL | __GFP_ZERO);
4413 if (!sl)
4414 return NULL;
4415
4416 for (i = 0; i < ic->journal_sections; i++) {
4417 struct scatterlist *s;
4418 unsigned int start_index, start_offset;
4419 unsigned int end_index, end_offset;
4420 unsigned int n_pages;
4421 unsigned int idx;
4422
4423 page_list_location(ic, i, 0, &start_index, &start_offset);
4424 page_list_location(ic, i, ic->journal_section_sectors - 1,
4425 &end_index, &end_offset);
4426
4427 n_pages = (end_index - start_index + 1);
4428
4429 s = kvmalloc_objs(struct scatterlist, n_pages);
4430 if (!s) {
4431 dm_integrity_free_journal_scatterlist(ic, sl);
4432 return NULL;
4433 }
4434
4435 sg_init_table(s, n_pages);
4436 for (idx = start_index; idx <= end_index; idx++) {
4437 char *va = lowmem_page_address(pl[idx].page);
4438 unsigned int start = 0, end = PAGE_SIZE;
4439
4440 if (idx == start_index)
4441 start = start_offset;
4442 if (idx == end_index)
4443 end = end_offset + (1 << SECTOR_SHIFT);
4444 sg_set_buf(&s[idx - start_index], va + start, end - start);
4445 }
4446
4447 sl[i] = s;
4448 }
4449
4450 return sl;
4451 }
4452
free_alg(struct alg_spec * a)4453 static void free_alg(struct alg_spec *a)
4454 {
4455 kfree_sensitive(a->alg_string);
4456 kfree_sensitive(a->key);
4457 memset(a, 0, sizeof(*a));
4458 }
4459
get_alg_and_key(const char * arg,struct alg_spec * a,char ** error,char * error_inval)4460 static int get_alg_and_key(const char *arg, struct alg_spec *a, char **error, char *error_inval)
4461 {
4462 char *k;
4463
4464 free_alg(a);
4465
4466 a->alg_string = kstrdup(strchr(arg, ':') + 1, GFP_KERNEL);
4467 if (!a->alg_string)
4468 goto nomem;
4469
4470 k = strchr(a->alg_string, ':');
4471 if (k) {
4472 *k = 0;
4473 a->key_string = k + 1;
4474 if (strlen(a->key_string) & 1)
4475 goto inval;
4476
4477 a->key_size = strlen(a->key_string) / 2;
4478 a->key = kmalloc(a->key_size, GFP_KERNEL);
4479 if (!a->key)
4480 goto nomem;
4481 if (hex2bin(a->key, a->key_string, a->key_size))
4482 goto inval;
4483 }
4484
4485 return 0;
4486 inval:
4487 *error = error_inval;
4488 return -EINVAL;
4489 nomem:
4490 *error = "Out of memory for an argument";
4491 return -ENOMEM;
4492 }
4493
get_mac(struct crypto_shash ** shash,struct crypto_ahash ** ahash,struct alg_spec * a,char ** error,char * error_alg,char * error_key)4494 static int get_mac(struct crypto_shash **shash, struct crypto_ahash **ahash,
4495 struct alg_spec *a, char **error, char *error_alg, char *error_key)
4496 {
4497 int r;
4498
4499 if (a->alg_string) {
4500 if (shash) {
4501 *shash = crypto_alloc_shash(a->alg_string, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
4502 if (IS_ERR(*shash)) {
4503 *shash = NULL;
4504 goto try_ahash;
4505 }
4506 if (a->key) {
4507 r = crypto_shash_setkey(*shash, a->key, a->key_size);
4508 if (r) {
4509 *error = error_key;
4510 return r;
4511 }
4512 } else if (crypto_shash_get_flags(*shash) & CRYPTO_TFM_NEED_KEY) {
4513 *error = error_key;
4514 return -ENOKEY;
4515 }
4516 return 0;
4517 }
4518 try_ahash:
4519 if (ahash) {
4520 *ahash = crypto_alloc_ahash(a->alg_string, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
4521 if (IS_ERR(*ahash)) {
4522 *error = error_alg;
4523 r = PTR_ERR(*ahash);
4524 *ahash = NULL;
4525 return r;
4526 }
4527 if (a->key) {
4528 r = crypto_ahash_setkey(*ahash, a->key, a->key_size);
4529 if (r) {
4530 *error = error_key;
4531 return r;
4532 }
4533 } else if (crypto_ahash_get_flags(*ahash) & CRYPTO_TFM_NEED_KEY) {
4534 *error = error_key;
4535 return -ENOKEY;
4536 }
4537 return 0;
4538 }
4539 *error = error_alg;
4540 return -ENOENT;
4541 }
4542
4543 return 0;
4544 }
4545
create_journal(struct dm_integrity_c * ic,char ** error)4546 static int create_journal(struct dm_integrity_c *ic, char **error)
4547 {
4548 int r = 0;
4549 unsigned int i;
4550 __u64 journal_pages, journal_desc_size, journal_tree_size;
4551 unsigned char *crypt_data = NULL, *crypt_iv = NULL;
4552 struct skcipher_request *req = NULL;
4553
4554 ic->commit_ids[0] = cpu_to_le64(0x1111111111111111ULL);
4555 ic->commit_ids[1] = cpu_to_le64(0x2222222222222222ULL);
4556 ic->commit_ids[2] = cpu_to_le64(0x3333333333333333ULL);
4557 ic->commit_ids[3] = cpu_to_le64(0x4444444444444444ULL);
4558
4559 journal_pages = roundup((__u64)ic->journal_sections * ic->journal_section_sectors,
4560 PAGE_SIZE >> SECTOR_SHIFT) >> (PAGE_SHIFT - SECTOR_SHIFT);
4561 journal_desc_size = journal_pages * sizeof(struct page_list);
4562 if (journal_pages >= totalram_pages() - totalhigh_pages() || journal_desc_size > ULONG_MAX) {
4563 *error = "Journal doesn't fit into memory";
4564 r = -ENOMEM;
4565 goto bad;
4566 }
4567 ic->journal_pages = journal_pages;
4568
4569 ic->journal = dm_integrity_alloc_page_list(ic->journal_pages);
4570 if (!ic->journal) {
4571 *error = "Could not allocate memory for journal";
4572 r = -ENOMEM;
4573 goto bad;
4574 }
4575 if (ic->journal_crypt_alg.alg_string) {
4576 unsigned int ivsize, blocksize;
4577 struct journal_completion comp;
4578
4579 comp.ic = ic;
4580 ic->journal_crypt = crypto_alloc_skcipher(ic->journal_crypt_alg.alg_string, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
4581 if (IS_ERR(ic->journal_crypt)) {
4582 *error = "Invalid journal cipher";
4583 r = PTR_ERR(ic->journal_crypt);
4584 ic->journal_crypt = NULL;
4585 goto bad;
4586 }
4587 ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
4588 blocksize = crypto_skcipher_blocksize(ic->journal_crypt);
4589
4590 if (ic->journal_crypt_alg.key) {
4591 r = crypto_skcipher_setkey(ic->journal_crypt, ic->journal_crypt_alg.key,
4592 ic->journal_crypt_alg.key_size);
4593 if (r) {
4594 *error = "Error setting encryption key";
4595 goto bad;
4596 }
4597 }
4598 DEBUG_print("cipher %s, block size %u iv size %u\n",
4599 ic->journal_crypt_alg.alg_string, blocksize, ivsize);
4600
4601 ic->journal_io = dm_integrity_alloc_page_list(ic->journal_pages);
4602 if (!ic->journal_io) {
4603 *error = "Could not allocate memory for journal io";
4604 r = -ENOMEM;
4605 goto bad;
4606 }
4607
4608 if (blocksize == 1) {
4609 struct scatterlist *sg;
4610
4611 req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
4612 if (!req) {
4613 *error = "Could not allocate crypt request";
4614 r = -ENOMEM;
4615 goto bad;
4616 }
4617
4618 crypt_iv = kzalloc(ivsize, GFP_KERNEL);
4619 if (!crypt_iv) {
4620 *error = "Could not allocate iv";
4621 r = -ENOMEM;
4622 goto bad;
4623 }
4624
4625 ic->journal_xor = dm_integrity_alloc_page_list(ic->journal_pages);
4626 if (!ic->journal_xor) {
4627 *error = "Could not allocate memory for journal xor";
4628 r = -ENOMEM;
4629 goto bad;
4630 }
4631
4632 sg = kvmalloc_objs(struct scatterlist,
4633 ic->journal_pages + 1);
4634 if (!sg) {
4635 *error = "Unable to allocate sg list";
4636 r = -ENOMEM;
4637 goto bad;
4638 }
4639 sg_init_table(sg, ic->journal_pages + 1);
4640 for (i = 0; i < ic->journal_pages; i++) {
4641 char *va = lowmem_page_address(ic->journal_xor[i].page);
4642
4643 clear_page(va);
4644 sg_set_buf(&sg[i], va, PAGE_SIZE);
4645 }
4646 sg_set_buf(&sg[i], &ic->commit_ids, sizeof(ic->commit_ids));
4647
4648 skcipher_request_set_crypt(req, sg, sg,
4649 PAGE_SIZE * ic->journal_pages + sizeof(ic->commit_ids), crypt_iv);
4650 init_completion(&comp.comp);
4651 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
4652 if (do_crypt(true, req, &comp))
4653 wait_for_completion(&comp.comp);
4654 kvfree(sg);
4655 r = dm_integrity_failed(ic);
4656 if (r) {
4657 *error = "Unable to encrypt journal";
4658 goto bad;
4659 }
4660 DEBUG_bytes(lowmem_page_address(ic->journal_xor[0].page), 64, "xor data");
4661
4662 crypto_free_skcipher(ic->journal_crypt);
4663 ic->journal_crypt = NULL;
4664 } else {
4665 unsigned int crypt_len = roundup(ivsize, blocksize);
4666
4667 req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
4668 if (!req) {
4669 *error = "Could not allocate crypt request";
4670 r = -ENOMEM;
4671 goto bad;
4672 }
4673
4674 crypt_iv = kmalloc(ivsize, GFP_KERNEL);
4675 if (!crypt_iv) {
4676 *error = "Could not allocate iv";
4677 r = -ENOMEM;
4678 goto bad;
4679 }
4680
4681 crypt_data = kmalloc(crypt_len, GFP_KERNEL);
4682 if (!crypt_data) {
4683 *error = "Unable to allocate crypt data";
4684 r = -ENOMEM;
4685 goto bad;
4686 }
4687
4688 ic->journal_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal);
4689 if (!ic->journal_scatterlist) {
4690 *error = "Unable to allocate sg list";
4691 r = -ENOMEM;
4692 goto bad;
4693 }
4694 ic->journal_io_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal_io);
4695 if (!ic->journal_io_scatterlist) {
4696 *error = "Unable to allocate sg list";
4697 r = -ENOMEM;
4698 goto bad;
4699 }
4700 ic->sk_requests = kvmalloc_objs(struct skcipher_request *,
4701 ic->journal_sections,
4702 GFP_KERNEL | __GFP_ZERO);
4703 if (!ic->sk_requests) {
4704 *error = "Unable to allocate sk requests";
4705 r = -ENOMEM;
4706 goto bad;
4707 }
4708 for (i = 0; i < ic->journal_sections; i++) {
4709 struct scatterlist sg;
4710 struct skcipher_request *section_req;
4711 __le32 section_le = cpu_to_le32(i);
4712
4713 memset(crypt_iv, 0x00, ivsize);
4714 memset(crypt_data, 0x00, crypt_len);
4715 memcpy(crypt_data, §ion_le, min_t(size_t, crypt_len, sizeof(section_le)));
4716
4717 sg_init_one(&sg, crypt_data, crypt_len);
4718 skcipher_request_set_crypt(req, &sg, &sg, crypt_len, crypt_iv);
4719 init_completion(&comp.comp);
4720 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
4721 if (do_crypt(true, req, &comp))
4722 wait_for_completion(&comp.comp);
4723
4724 r = dm_integrity_failed(ic);
4725 if (r) {
4726 *error = "Unable to generate iv";
4727 goto bad;
4728 }
4729
4730 section_req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
4731 if (!section_req) {
4732 *error = "Unable to allocate crypt request";
4733 r = -ENOMEM;
4734 goto bad;
4735 }
4736 section_req->iv = kmalloc_array(ivsize, 2,
4737 GFP_KERNEL);
4738 if (!section_req->iv) {
4739 skcipher_request_free(section_req);
4740 *error = "Unable to allocate iv";
4741 r = -ENOMEM;
4742 goto bad;
4743 }
4744 memcpy(section_req->iv + ivsize, crypt_data, ivsize);
4745 section_req->cryptlen = (size_t)ic->journal_section_sectors << SECTOR_SHIFT;
4746 ic->sk_requests[i] = section_req;
4747 DEBUG_bytes(crypt_data, ivsize, "iv(%u)", i);
4748 }
4749 }
4750 }
4751
4752 for (i = 0; i < N_COMMIT_IDS; i++) {
4753 unsigned int j;
4754
4755 retest_commit_id:
4756 for (j = 0; j < i; j++) {
4757 if (ic->commit_ids[j] == ic->commit_ids[i]) {
4758 ic->commit_ids[i] = cpu_to_le64(le64_to_cpu(ic->commit_ids[i]) + 1);
4759 goto retest_commit_id;
4760 }
4761 }
4762 DEBUG_print("commit id %u: %016llx\n", i, ic->commit_ids[i]);
4763 }
4764
4765 journal_tree_size = (__u64)ic->journal_entries * sizeof(struct journal_node);
4766 if (journal_tree_size > ULONG_MAX) {
4767 *error = "Journal doesn't fit into memory";
4768 r = -ENOMEM;
4769 goto bad;
4770 }
4771 ic->journal_tree = kvmalloc(journal_tree_size, GFP_KERNEL);
4772 if (!ic->journal_tree) {
4773 *error = "Could not allocate memory for journal tree";
4774 r = -ENOMEM;
4775 goto bad;
4776 }
4777 bad:
4778 kfree(crypt_data);
4779 kfree(crypt_iv);
4780 skcipher_request_free(req);
4781
4782 return r;
4783 }
4784
4785 /*
4786 * Construct a integrity mapping
4787 *
4788 * Arguments:
4789 * device
4790 * offset from the start of the device
4791 * tag size
4792 * D - direct writes, J - journal writes, B - bitmap mode, R - recovery mode
4793 * number of optional arguments
4794 * optional arguments:
4795 * journal_sectors
4796 * interleave_sectors
4797 * buffer_sectors
4798 * journal_watermark
4799 * commit_time
4800 * meta_device
4801 * block_size
4802 * sectors_per_bit
4803 * bitmap_flush_interval
4804 * internal_hash
4805 * journal_crypt
4806 * journal_mac
4807 * recalculate
4808 */
dm_integrity_ctr(struct dm_target * ti,unsigned int argc,char ** argv)4809 static int dm_integrity_ctr(struct dm_target *ti, unsigned int argc, char **argv)
4810 {
4811 struct dm_integrity_c *ic;
4812 char dummy;
4813 int r;
4814 unsigned int extra_args;
4815 struct dm_arg_set as;
4816 static const struct dm_arg _args[] = {
4817 {0, 18, "Invalid number of feature args"},
4818 };
4819 unsigned int journal_sectors, interleave_sectors, buffer_sectors, journal_watermark, sync_msec;
4820 bool should_write_sb;
4821 __u64 threshold;
4822 unsigned long long start;
4823 __s8 log2_sectors_per_bitmap_bit = -1;
4824 __s8 log2_blocks_per_bitmap_bit;
4825 __u64 bits_in_journal;
4826 __u64 n_bitmap_bits;
4827
4828 #define DIRECT_ARGUMENTS 4
4829
4830 if (argc <= DIRECT_ARGUMENTS) {
4831 ti->error = "Invalid argument count";
4832 return -EINVAL;
4833 }
4834
4835 ic = kzalloc_obj(struct dm_integrity_c);
4836 if (!ic) {
4837 ti->error = "Cannot allocate integrity context";
4838 return -ENOMEM;
4839 }
4840 ti->private = ic;
4841 ti->per_io_data_size = sizeof(struct dm_integrity_io);
4842 ic->ti = ti;
4843
4844 ic->in_progress = RB_ROOT;
4845 INIT_LIST_HEAD(&ic->wait_list);
4846 init_waitqueue_head(&ic->endio_wait);
4847 bio_list_init(&ic->flush_bio_list);
4848 init_waitqueue_head(&ic->copy_to_journal_wait);
4849 init_completion(&ic->crypto_backoff);
4850 atomic64_set(&ic->number_of_mismatches, 0);
4851 ic->bitmap_flush_interval = BITMAP_FLUSH_INTERVAL;
4852
4853 r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &ic->dev);
4854 if (r) {
4855 ti->error = "Device lookup failed";
4856 goto bad;
4857 }
4858
4859 if (sscanf(argv[1], "%llu%c", &start, &dummy) != 1 || start != (sector_t)start) {
4860 ti->error = "Invalid starting offset";
4861 r = -EINVAL;
4862 goto bad;
4863 }
4864 ic->start = start;
4865
4866 if (strcmp(argv[2], "-")) {
4867 if (sscanf(argv[2], "%u%c", &ic->tag_size, &dummy) != 1 || !ic->tag_size) {
4868 ti->error = "Invalid tag size";
4869 r = -EINVAL;
4870 goto bad;
4871 }
4872 }
4873
4874 if (!strcmp(argv[3], "J") || !strcmp(argv[3], "B") ||
4875 !strcmp(argv[3], "D") || !strcmp(argv[3], "R") ||
4876 !strcmp(argv[3], "I")) {
4877 ic->mode = argv[3][0];
4878 } else {
4879 ti->error = "Invalid mode (expecting J, B, D, R, I)";
4880 r = -EINVAL;
4881 goto bad;
4882 }
4883
4884 journal_sectors = 0;
4885 interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
4886 buffer_sectors = DEFAULT_BUFFER_SECTORS;
4887 journal_watermark = DEFAULT_JOURNAL_WATERMARK;
4888 sync_msec = DEFAULT_SYNC_MSEC;
4889 ic->sectors_per_block = 1;
4890
4891 as.argc = argc - DIRECT_ARGUMENTS;
4892 as.argv = argv + DIRECT_ARGUMENTS;
4893 r = dm_read_arg_group(_args, &as, &extra_args, &ti->error);
4894 if (r)
4895 goto bad;
4896
4897 while (extra_args--) {
4898 const char *opt_string;
4899 unsigned int val;
4900 unsigned long long llval;
4901
4902 opt_string = dm_shift_arg(&as);
4903 if (!opt_string) {
4904 r = -EINVAL;
4905 ti->error = "Not enough feature arguments";
4906 goto bad;
4907 }
4908 if (sscanf(opt_string, "journal_sectors:%u%c", &val, &dummy) == 1)
4909 journal_sectors = val ? val : 1;
4910 else if (sscanf(opt_string, "interleave_sectors:%u%c", &val, &dummy) == 1)
4911 interleave_sectors = val;
4912 else if (sscanf(opt_string, "buffer_sectors:%u%c", &val, &dummy) == 1)
4913 buffer_sectors = val;
4914 else if (sscanf(opt_string, "journal_watermark:%u%c", &val, &dummy) == 1 && val <= 100)
4915 journal_watermark = val;
4916 else if (sscanf(opt_string, "commit_time:%u%c", &val, &dummy) == 1)
4917 sync_msec = val;
4918 else if (!strncmp(opt_string, "meta_device:", strlen("meta_device:"))) {
4919 if (ic->meta_dev) {
4920 dm_put_device(ti, ic->meta_dev);
4921 ic->meta_dev = NULL;
4922 }
4923 r = dm_get_device(ti, strchr(opt_string, ':') + 1,
4924 dm_table_get_mode(ti->table), &ic->meta_dev);
4925 if (r) {
4926 ti->error = "Device lookup failed";
4927 goto bad;
4928 }
4929 } else if (sscanf(opt_string, "block_size:%u%c", &val, &dummy) == 1) {
4930 if (val < 1 << SECTOR_SHIFT ||
4931 val > MAX_SECTORS_PER_BLOCK << SECTOR_SHIFT ||
4932 (val & (val - 1))) {
4933 r = -EINVAL;
4934 ti->error = "Invalid block_size argument";
4935 goto bad;
4936 }
4937 ic->sectors_per_block = val >> SECTOR_SHIFT;
4938 } else if (sscanf(opt_string, "sectors_per_bit:%llu%c", &llval, &dummy) == 1) {
4939 log2_sectors_per_bitmap_bit = !llval ? 0 : __ilog2_u64(llval);
4940 } else if (sscanf(opt_string, "bitmap_flush_interval:%u%c", &val, &dummy) == 1) {
4941 if ((uint64_t)val >= (uint64_t)UINT_MAX * 1000 / HZ) {
4942 r = -EINVAL;
4943 ti->error = "Invalid bitmap_flush_interval argument";
4944 goto bad;
4945 }
4946 ic->bitmap_flush_interval = msecs_to_jiffies(val);
4947 } else if (!strncmp(opt_string, "internal_hash:", strlen("internal_hash:"))) {
4948 r = get_alg_and_key(opt_string, &ic->internal_hash_alg, &ti->error,
4949 "Invalid internal_hash argument");
4950 if (r)
4951 goto bad;
4952 } else if (!strncmp(opt_string, "journal_crypt:", strlen("journal_crypt:"))) {
4953 r = get_alg_and_key(opt_string, &ic->journal_crypt_alg, &ti->error,
4954 "Invalid journal_crypt argument");
4955 if (r)
4956 goto bad;
4957 } else if (!strncmp(opt_string, "journal_mac:", strlen("journal_mac:"))) {
4958 r = get_alg_and_key(opt_string, &ic->journal_mac_alg, &ti->error,
4959 "Invalid journal_mac argument");
4960 if (r)
4961 goto bad;
4962 } else if (!strcmp(opt_string, "recalculate")) {
4963 ic->recalculate_flag = true;
4964 } else if (!strcmp(opt_string, "reset_recalculate")) {
4965 ic->recalculate_flag = true;
4966 ic->reset_recalculate_flag = true;
4967 } else if (!strcmp(opt_string, "allow_discards")) {
4968 ic->discard = true;
4969 } else if (!strcmp(opt_string, "allow_discards_keyed")) {
4970 ic->discard = true;
4971 ic->discard_keyed = true;
4972 } else if (!strcmp(opt_string, "fix_padding")) {
4973 ic->fix_padding = true;
4974 } else if (!strcmp(opt_string, "fix_hmac")) {
4975 ic->fix_hmac = true;
4976 } else if (!strcmp(opt_string, "legacy_recalculate")) {
4977 ic->legacy_recalculate = true;
4978 } else {
4979 r = -EINVAL;
4980 ti->error = "Invalid argument";
4981 goto bad;
4982 }
4983 }
4984
4985 ic->data_device_sectors = bdev_nr_sectors(ic->dev->bdev);
4986 if (!ic->meta_dev)
4987 ic->meta_device_sectors = ic->data_device_sectors;
4988 else
4989 ic->meta_device_sectors = bdev_nr_sectors(ic->meta_dev->bdev);
4990
4991 if (!journal_sectors) {
4992 journal_sectors = min((sector_t)DEFAULT_MAX_JOURNAL_SECTORS,
4993 ic->data_device_sectors >> DEFAULT_JOURNAL_SIZE_FACTOR);
4994 }
4995
4996 if (!buffer_sectors)
4997 buffer_sectors = 1;
4998 ic->log2_buffer_sectors = min((int)__fls(buffer_sectors), 31 - SECTOR_SHIFT);
4999
5000 r = get_mac(&ic->internal_shash, &ic->internal_ahash, &ic->internal_hash_alg, &ti->error,
5001 "Invalid internal hash", "Error setting internal hash key");
5002 if (r)
5003 goto bad;
5004 if (ic->internal_shash) {
5005 ic->internal_hash = true;
5006 ic->internal_hash_digestsize = crypto_shash_digestsize(ic->internal_shash);
5007 }
5008 if (ic->internal_ahash) {
5009 ic->internal_hash = true;
5010 ic->internal_hash_digestsize = crypto_ahash_digestsize(ic->internal_ahash);
5011 r = mempool_init_kmalloc_pool(&ic->ahash_req_pool, AHASH_MEMPOOL,
5012 sizeof(struct ahash_request) + crypto_ahash_reqsize(ic->internal_ahash));
5013 if (r) {
5014 ti->error = "Cannot allocate mempool";
5015 goto bad;
5016 }
5017 }
5018
5019 r = get_mac(&ic->journal_mac, NULL, &ic->journal_mac_alg, &ti->error,
5020 "Invalid journal mac", "Error setting journal mac key");
5021 if (r)
5022 goto bad;
5023
5024 if (!ic->tag_size) {
5025 if (!ic->internal_hash) {
5026 ti->error = "Unknown tag size";
5027 r = -EINVAL;
5028 goto bad;
5029 }
5030 ic->tag_size = ic->internal_hash_digestsize;
5031 }
5032 if (ic->tag_size > MAX_TAG_SIZE) {
5033 ti->error = "Too big tag size";
5034 r = -EINVAL;
5035 goto bad;
5036 }
5037 if (!(ic->tag_size & (ic->tag_size - 1)))
5038 ic->log2_tag_size = __ffs(ic->tag_size);
5039 else
5040 ic->log2_tag_size = -1;
5041
5042 if (ic->mode == 'I') {
5043 struct blk_integrity *bi;
5044 if (ic->meta_dev) {
5045 r = -EINVAL;
5046 ti->error = "Metadata device not supported in inline mode";
5047 goto bad;
5048 }
5049 if (!ic->internal_hash_alg.alg_string) {
5050 r = -EINVAL;
5051 ti->error = "Internal hash not set in inline mode";
5052 goto bad;
5053 }
5054 if (ic->journal_crypt_alg.alg_string || ic->journal_mac_alg.alg_string) {
5055 r = -EINVAL;
5056 ti->error = "Journal crypt not supported in inline mode";
5057 goto bad;
5058 }
5059 if (ic->discard) {
5060 r = -EINVAL;
5061 ti->error = "Discards not supported in inline mode";
5062 goto bad;
5063 }
5064 bi = blk_get_integrity(ic->dev->bdev->bd_disk);
5065 if (!bi || bi->csum_type != BLK_INTEGRITY_CSUM_NONE) {
5066 r = -EINVAL;
5067 ti->error = "Integrity profile not supported";
5068 goto bad;
5069 }
5070 /*printk("tag_size: %u, metadata_size: %u\n", bi->tag_size, bi->metadata_size);*/
5071 if (bi->metadata_size < ic->tag_size) {
5072 r = -EINVAL;
5073 ti->error = "The integrity profile is smaller than tag size";
5074 goto bad;
5075 }
5076 if ((unsigned long)bi->metadata_size > PAGE_SIZE / 2) {
5077 r = -EINVAL;
5078 ti->error = "Too big tuple size";
5079 goto bad;
5080 }
5081 ic->tuple_size = bi->metadata_size;
5082 if (1 << bi->interval_exp != ic->sectors_per_block << SECTOR_SHIFT) {
5083 r = -EINVAL;
5084 ti->error = "Integrity profile sector size mismatch";
5085 goto bad;
5086 }
5087 }
5088
5089 if (ic->mode == 'B' && !ic->internal_hash) {
5090 r = -EINVAL;
5091 ti->error = "Bitmap mode can be only used with internal hash";
5092 goto bad;
5093 }
5094
5095 if (ic->discard && !ic->internal_hash) {
5096 r = -EINVAL;
5097 ti->error = "Discard can be only used with internal hash";
5098 goto bad;
5099 }
5100 if (ic->discard_keyed && !ic->internal_hash_alg.key) {
5101 r = -EINVAL;
5102 ti->error = "Keyed discard can only be used with keyed internal hash";
5103 goto bad;
5104 }
5105
5106 ic->autocommit_jiffies = msecs_to_jiffies(sync_msec);
5107 ic->autocommit_msec = sync_msec;
5108 timer_setup(&ic->autocommit_timer, autocommit_fn, 0);
5109
5110 ic->io = dm_io_client_create();
5111 if (IS_ERR(ic->io)) {
5112 r = PTR_ERR(ic->io);
5113 ic->io = NULL;
5114 ti->error = "Cannot allocate dm io";
5115 goto bad;
5116 }
5117
5118 r = mempool_init_slab_pool(&ic->journal_io_mempool, JOURNAL_IO_MEMPOOL, journal_io_cache);
5119 if (r) {
5120 ti->error = "Cannot allocate mempool";
5121 goto bad;
5122 }
5123
5124 r = mempool_init_page_pool(&ic->recheck_pool, 1, ic->mode == 'I' ? 1 : 0);
5125 if (r) {
5126 ti->error = "Cannot allocate mempool";
5127 goto bad;
5128 }
5129
5130 if (ic->mode == 'I') {
5131 r = bioset_init(&ic->recheck_bios, RECHECK_POOL_SIZE, 0, BIOSET_NEED_BVECS);
5132 if (r) {
5133 ti->error = "Cannot allocate bio set";
5134 goto bad;
5135 }
5136 r = bioset_init(&ic->recalc_bios, 1, 0, BIOSET_NEED_BVECS);
5137 if (r) {
5138 ti->error = "Cannot allocate bio set";
5139 goto bad;
5140 }
5141 }
5142
5143 ic->metadata_wq = alloc_workqueue("dm-integrity-metadata",
5144 WQ_MEM_RECLAIM | WQ_PERCPU,
5145 METADATA_WORKQUEUE_MAX_ACTIVE);
5146 if (!ic->metadata_wq) {
5147 ti->error = "Cannot allocate workqueue";
5148 r = -ENOMEM;
5149 goto bad;
5150 }
5151
5152 /*
5153 * If this workqueue weren't ordered, it would cause bio reordering
5154 * and reduced performance.
5155 */
5156 ic->wait_wq = alloc_ordered_workqueue("dm-integrity-wait", WQ_MEM_RECLAIM);
5157 if (!ic->wait_wq) {
5158 ti->error = "Cannot allocate workqueue";
5159 r = -ENOMEM;
5160 goto bad;
5161 }
5162
5163 ic->offload_wq = alloc_workqueue("dm-integrity-offload",
5164 WQ_MEM_RECLAIM | WQ_PERCPU,
5165 METADATA_WORKQUEUE_MAX_ACTIVE);
5166 if (!ic->offload_wq) {
5167 ti->error = "Cannot allocate workqueue";
5168 r = -ENOMEM;
5169 goto bad;
5170 }
5171
5172 ic->commit_wq = alloc_workqueue("dm-integrity-commit",
5173 WQ_MEM_RECLAIM | WQ_PERCPU, 1);
5174 if (!ic->commit_wq) {
5175 ti->error = "Cannot allocate workqueue";
5176 r = -ENOMEM;
5177 goto bad;
5178 }
5179 INIT_WORK(&ic->commit_work, integrity_commit);
5180
5181 if (ic->mode == 'J' || ic->mode == 'B') {
5182 ic->writer_wq = alloc_workqueue("dm-integrity-writer",
5183 WQ_MEM_RECLAIM | WQ_PERCPU, 1);
5184 if (!ic->writer_wq) {
5185 ti->error = "Cannot allocate workqueue";
5186 r = -ENOMEM;
5187 goto bad;
5188 }
5189 INIT_WORK(&ic->writer_work, integrity_writer);
5190 }
5191
5192 ic->sb = alloc_pages_exact(SB_SECTORS << SECTOR_SHIFT, GFP_KERNEL);
5193 if (!ic->sb) {
5194 r = -ENOMEM;
5195 ti->error = "Cannot allocate superblock area";
5196 goto bad;
5197 }
5198
5199 r = sync_rw_sb(ic, REQ_OP_READ);
5200 if (r) {
5201 ti->error = "Error reading superblock";
5202 goto bad;
5203 }
5204 should_write_sb = false;
5205 if (memcmp(ic->sb->magic, SB_MAGIC, 8)) {
5206 if (ic->mode != 'R') {
5207 if (memchr_inv(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT)) {
5208 r = -EINVAL;
5209 ti->error = "The device is not initialized";
5210 goto bad;
5211 }
5212 }
5213
5214 r = initialize_superblock(ic, journal_sectors, interleave_sectors);
5215 if (r) {
5216 ti->error = "Could not initialize superblock";
5217 goto bad;
5218 }
5219 if (ic->mode != 'R')
5220 should_write_sb = true;
5221 }
5222
5223 if (!ic->sb->version || ic->sb->version > SB_VERSION_7) {
5224 r = -EINVAL;
5225 ti->error = "Unknown version";
5226 goto bad;
5227 }
5228 if (!!(ic->sb->flags & cpu_to_le32(SB_FLAG_INLINE)) != (ic->mode == 'I')) {
5229 r = -EINVAL;
5230 ti->error = "Inline flag mismatch";
5231 goto bad;
5232 }
5233 if (le16_to_cpu(ic->sb->integrity_tag_size) != ic->tag_size) {
5234 r = -EINVAL;
5235 ti->error = "Tag size doesn't match the information in superblock";
5236 goto bad;
5237 }
5238 if (ic->sb->log2_sectors_per_block != __ffs(ic->sectors_per_block)) {
5239 r = -EINVAL;
5240 ti->error = "Block size doesn't match the information in superblock";
5241 goto bad;
5242 }
5243 if (ic->mode != 'I') {
5244 if (!le32_to_cpu(ic->sb->journal_sections)) {
5245 r = -EINVAL;
5246 ti->error = "Corrupted superblock, journal_sections is 0";
5247 goto bad;
5248 }
5249 } else {
5250 if (le32_to_cpu(ic->sb->journal_sections)) {
5251 r = -EINVAL;
5252 ti->error = "Corrupted superblock, journal_sections is not 0";
5253 goto bad;
5254 }
5255 }
5256 /* make sure that ti->max_io_len doesn't overflow */
5257 if (!ic->meta_dev) {
5258 if (ic->sb->log2_interleave_sectors < MIN_LOG2_INTERLEAVE_SECTORS ||
5259 ic->sb->log2_interleave_sectors > MAX_LOG2_INTERLEAVE_SECTORS) {
5260 r = -EINVAL;
5261 ti->error = "Invalid interleave_sectors in the superblock";
5262 goto bad;
5263 }
5264 } else {
5265 if (ic->sb->log2_interleave_sectors) {
5266 r = -EINVAL;
5267 ti->error = "Invalid interleave_sectors in the superblock";
5268 goto bad;
5269 }
5270 }
5271 if (!ic->discard_keyed && (ic->sb->flags & cpu_to_le32(SB_FLAG_DISCARD_KEYED))) {
5272 r = -EINVAL;
5273 ti->error = "Keyed discard cannot be disabled once enabled";
5274 goto bad;
5275 }
5276 if (!!(ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC)) != !!ic->journal_mac_alg.alg_string) {
5277 r = -EINVAL;
5278 ti->error = "Journal mac mismatch";
5279 goto bad;
5280 }
5281 if (ic->fix_hmac && !(ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) && ic->journal_mac_alg.key_string) {
5282 /*
5283 * If this happens, it may be either because someone tampered
5284 * with the device or it may be due to a bug in the
5285 * integritysetup tool.
5286 *
5287 * In the latter case, upgrade to integritysetup 2.8.7 and use
5288 * the argument --integrity-legacy-hmac when using the open
5289 * command.
5290 */
5291 r = -EINVAL;
5292 ti->error = "fix_hmac is on the command line but not in the superblock";
5293 goto bad;
5294 }
5295
5296 get_provided_data_sectors(ic);
5297 if (!ic->provided_data_sectors) {
5298 r = -EINVAL;
5299 ti->error = "The device is too small";
5300 goto bad;
5301 }
5302
5303 try_smaller_buffer:
5304 r = calculate_device_limits(ic);
5305 if (r) {
5306 if (ic->meta_dev) {
5307 if (ic->log2_buffer_sectors > 3) {
5308 ic->log2_buffer_sectors--;
5309 goto try_smaller_buffer;
5310 }
5311 }
5312 ti->error = "The device is too small";
5313 goto bad;
5314 }
5315
5316 if (log2_sectors_per_bitmap_bit < 0)
5317 log2_sectors_per_bitmap_bit = __fls(DEFAULT_SECTORS_PER_BITMAP_BIT);
5318 if (log2_sectors_per_bitmap_bit < ic->sb->log2_sectors_per_block)
5319 log2_sectors_per_bitmap_bit = ic->sb->log2_sectors_per_block;
5320
5321 bits_in_journal = ((__u64)ic->journal_section_sectors * ic->journal_sections) << (SECTOR_SHIFT + 3);
5322 if (bits_in_journal > UINT_MAX)
5323 bits_in_journal = UINT_MAX;
5324 if (bits_in_journal)
5325 while (bits_in_journal < (ic->provided_data_sectors + ((sector_t)1 << log2_sectors_per_bitmap_bit) - 1) >> log2_sectors_per_bitmap_bit)
5326 log2_sectors_per_bitmap_bit++;
5327
5328 log2_blocks_per_bitmap_bit = log2_sectors_per_bitmap_bit - ic->sb->log2_sectors_per_block;
5329 ic->log2_blocks_per_bitmap_bit = log2_blocks_per_bitmap_bit;
5330 if (should_write_sb)
5331 ic->sb->log2_blocks_per_bitmap_bit = log2_blocks_per_bitmap_bit;
5332
5333 n_bitmap_bits = ((ic->provided_data_sectors >> ic->sb->log2_sectors_per_block)
5334 + (((sector_t)1 << log2_blocks_per_bitmap_bit) - 1)) >> log2_blocks_per_bitmap_bit;
5335 ic->n_bitmap_blocks = DIV_ROUND_UP(n_bitmap_bits, BITMAP_BLOCK_SIZE * 8);
5336
5337 if (!ic->meta_dev)
5338 ic->log2_buffer_sectors = min(ic->log2_buffer_sectors, (__u8)__ffs(ic->metadata_run));
5339
5340 if (ti->len > ic->provided_data_sectors) {
5341 r = -EINVAL;
5342 ti->error = "Not enough provided sectors for requested mapping size";
5343 goto bad;
5344 }
5345
5346 threshold = (__u64)ic->journal_entries * (100 - journal_watermark);
5347 threshold += 50;
5348 do_div(threshold, 100);
5349 ic->free_sectors_threshold = threshold;
5350
5351 DEBUG_print("initialized:\n");
5352 DEBUG_print(" integrity_tag_size %u\n", le16_to_cpu(ic->sb->integrity_tag_size));
5353 DEBUG_print(" journal_entry_size %u\n", ic->journal_entry_size);
5354 DEBUG_print(" journal_entries_per_sector %u\n", ic->journal_entries_per_sector);
5355 DEBUG_print(" journal_section_entries %u\n", ic->journal_section_entries);
5356 DEBUG_print(" journal_section_sectors %u\n", ic->journal_section_sectors);
5357 DEBUG_print(" journal_sections %u\n", (unsigned int)le32_to_cpu(ic->sb->journal_sections));
5358 DEBUG_print(" journal_entries %u\n", ic->journal_entries);
5359 DEBUG_print(" log2_interleave_sectors %d\n", ic->sb->log2_interleave_sectors);
5360 DEBUG_print(" data_device_sectors 0x%llx\n", bdev_nr_sectors(ic->dev->bdev));
5361 DEBUG_print(" initial_sectors 0x%x\n", ic->initial_sectors);
5362 DEBUG_print(" metadata_run 0x%x\n", ic->metadata_run);
5363 DEBUG_print(" log2_metadata_run %d\n", ic->log2_metadata_run);
5364 DEBUG_print(" provided_data_sectors 0x%llx (%llu)\n", ic->provided_data_sectors, ic->provided_data_sectors);
5365 DEBUG_print(" log2_buffer_sectors %u\n", ic->log2_buffer_sectors);
5366 DEBUG_print(" bits_in_journal %llu\n", bits_in_journal);
5367
5368 if (ic->recalculate_flag && !(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))) {
5369 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
5370 ic->sb->recalc_sector = cpu_to_le64(0);
5371 }
5372
5373 if (ic->internal_hash) {
5374 ic->recalc_wq = alloc_workqueue("dm-integrity-recalc",
5375 WQ_MEM_RECLAIM | WQ_PERCPU, 1);
5376 if (!ic->recalc_wq) {
5377 ti->error = "Cannot allocate workqueue";
5378 r = -ENOMEM;
5379 goto bad;
5380 }
5381 INIT_WORK(&ic->recalc_work, ic->mode == 'I' ? integrity_recalc_inline : integrity_recalc);
5382 } else {
5383 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
5384 ti->error = "Recalculate can only be specified with internal_hash";
5385 r = -EINVAL;
5386 goto bad;
5387 }
5388 }
5389
5390 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
5391 le64_to_cpu(ic->sb->recalc_sector) < ic->provided_data_sectors &&
5392 dm_integrity_disable_recalculate(ic)) {
5393 ti->error = "Recalculating with HMAC is disabled for security reasons - if you really need it, use the argument \"legacy_recalculate\"";
5394 r = -EOPNOTSUPP;
5395 goto bad;
5396 }
5397
5398 ic->bufio = dm_bufio_client_create(ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev,
5399 1U << (SECTOR_SHIFT + ic->log2_buffer_sectors), 1, 0, NULL, NULL, 0);
5400 if (IS_ERR(ic->bufio)) {
5401 r = PTR_ERR(ic->bufio);
5402 ti->error = "Cannot initialize dm-bufio";
5403 ic->bufio = NULL;
5404 goto bad;
5405 }
5406 dm_bufio_set_sector_offset(ic->bufio, ic->start + ic->initial_sectors);
5407
5408 if (ic->mode != 'R' && ic->mode != 'I') {
5409 r = create_journal(ic, &ti->error);
5410 if (r)
5411 goto bad;
5412
5413 }
5414
5415 if (ic->mode == 'B') {
5416 unsigned int i;
5417 unsigned int n_bitmap_pages = DIV_ROUND_UP(ic->n_bitmap_blocks, PAGE_SIZE / BITMAP_BLOCK_SIZE);
5418
5419 ic->recalc_bitmap = dm_integrity_alloc_page_list(n_bitmap_pages);
5420 if (!ic->recalc_bitmap) {
5421 ti->error = "Could not allocate memory for bitmap";
5422 r = -ENOMEM;
5423 goto bad;
5424 }
5425 ic->may_write_bitmap = dm_integrity_alloc_page_list(n_bitmap_pages);
5426 if (!ic->may_write_bitmap) {
5427 ti->error = "Could not allocate memory for bitmap";
5428 r = -ENOMEM;
5429 goto bad;
5430 }
5431 ic->bbs = kvmalloc_objs(struct bitmap_block_status,
5432 ic->n_bitmap_blocks);
5433 if (!ic->bbs) {
5434 ti->error = "Could not allocate memory for bitmap";
5435 r = -ENOMEM;
5436 goto bad;
5437 }
5438 INIT_DELAYED_WORK(&ic->bitmap_flush_work, bitmap_flush_work);
5439 for (i = 0; i < ic->n_bitmap_blocks; i++) {
5440 struct bitmap_block_status *bbs = &ic->bbs[i];
5441 unsigned int sector, pl_index, pl_offset;
5442
5443 INIT_WORK(&bbs->work, bitmap_block_work);
5444 bbs->ic = ic;
5445 bbs->idx = i;
5446 bio_list_init(&bbs->bio_queue);
5447 spin_lock_init(&bbs->bio_queue_lock);
5448
5449 sector = i * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT);
5450 pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
5451 pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
5452
5453 bbs->bitmap = lowmem_page_address(ic->journal[pl_index].page) + pl_offset;
5454 }
5455 }
5456
5457 if (should_write_sb) {
5458 init_journal(ic, 0, ic->journal_sections, 0);
5459 r = dm_integrity_failed(ic);
5460 if (unlikely(r)) {
5461 ti->error = "Error initializing journal";
5462 goto bad;
5463 }
5464 r = sync_rw_sb(ic, REQ_OP_WRITE | REQ_FUA);
5465 if (r) {
5466 ti->error = "Error initializing superblock";
5467 goto bad;
5468 }
5469 ic->just_formatted = true;
5470 }
5471
5472 ic->sb_copy = kmemdup(ic->sb, sizeof(struct superblock), GFP_KERNEL);
5473 if (!ic->sb_copy) {
5474 ti->error = "Cannot allocate superblock copy";
5475 r = -ENOMEM;
5476 goto bad;
5477 }
5478
5479 if (!ic->meta_dev && ic->mode != 'I') {
5480 r = dm_set_target_max_io_len(ti, 1U << ic->sb->log2_interleave_sectors);
5481 if (r)
5482 goto bad;
5483 }
5484 if (ic->mode == 'B') {
5485 unsigned int max_io_len;
5486
5487 max_io_len = ((sector_t)ic->sectors_per_block << ic->log2_blocks_per_bitmap_bit) * (BITMAP_BLOCK_SIZE * 8);
5488 if (!max_io_len)
5489 max_io_len = 1U << 31;
5490 DEBUG_print("max_io_len: old %u, new %u\n", ti->max_io_len, max_io_len);
5491 if (!ti->max_io_len || ti->max_io_len > max_io_len) {
5492 r = dm_set_target_max_io_len(ti, max_io_len);
5493 if (r)
5494 goto bad;
5495 }
5496 }
5497
5498 ti->num_flush_bios = 1;
5499 ti->flush_supported = true;
5500 if (ic->discard)
5501 ti->num_discard_bios = 1;
5502
5503 if (ic->mode == 'I')
5504 ti->mempool_needs_integrity = true;
5505
5506 dm_audit_log_ctr(DM_MSG_PREFIX, ti, 1);
5507 return 0;
5508
5509 bad:
5510 dm_audit_log_ctr(DM_MSG_PREFIX, ti, 0);
5511 dm_integrity_dtr(ti);
5512 return r;
5513 }
5514
dm_integrity_dtr(struct dm_target * ti)5515 static void dm_integrity_dtr(struct dm_target *ti)
5516 {
5517 struct dm_integrity_c *ic = ti->private;
5518
5519 BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
5520 BUG_ON(!list_empty(&ic->wait_list));
5521
5522 if (ic->mode == 'B' && ic->bitmap_flush_work.work.func)
5523 cancel_delayed_work_sync(&ic->bitmap_flush_work);
5524 if (ic->metadata_wq)
5525 destroy_workqueue(ic->metadata_wq);
5526 if (ic->wait_wq)
5527 destroy_workqueue(ic->wait_wq);
5528 if (ic->offload_wq)
5529 destroy_workqueue(ic->offload_wq);
5530 if (ic->commit_wq)
5531 destroy_workqueue(ic->commit_wq);
5532 if (ic->writer_wq)
5533 destroy_workqueue(ic->writer_wq);
5534 if (ic->recalc_wq)
5535 destroy_workqueue(ic->recalc_wq);
5536 kvfree(ic->bbs);
5537 if (ic->bufio)
5538 dm_bufio_client_destroy(ic->bufio);
5539 mempool_free(ic->journal_ahash_req, &ic->ahash_req_pool);
5540 mempool_exit(&ic->ahash_req_pool);
5541 bioset_exit(&ic->recalc_bios);
5542 bioset_exit(&ic->recheck_bios);
5543 mempool_exit(&ic->recheck_pool);
5544 mempool_exit(&ic->journal_io_mempool);
5545 if (ic->io)
5546 dm_io_client_destroy(ic->io);
5547 if (ic->dev)
5548 dm_put_device(ti, ic->dev);
5549 if (ic->meta_dev)
5550 dm_put_device(ti, ic->meta_dev);
5551 dm_integrity_free_page_list(ic->journal);
5552 dm_integrity_free_page_list(ic->journal_io);
5553 dm_integrity_free_page_list(ic->journal_xor);
5554 dm_integrity_free_page_list(ic->recalc_bitmap);
5555 dm_integrity_free_page_list(ic->may_write_bitmap);
5556 if (ic->journal_scatterlist)
5557 dm_integrity_free_journal_scatterlist(ic, ic->journal_scatterlist);
5558 if (ic->journal_io_scatterlist)
5559 dm_integrity_free_journal_scatterlist(ic, ic->journal_io_scatterlist);
5560 if (ic->sk_requests) {
5561 unsigned int i;
5562
5563 for (i = 0; i < ic->journal_sections; i++) {
5564 struct skcipher_request *req;
5565
5566 req = ic->sk_requests[i];
5567 if (req) {
5568 kfree_sensitive(req->iv);
5569 skcipher_request_free(req);
5570 }
5571 }
5572 kvfree(ic->sk_requests);
5573 }
5574 kvfree(ic->journal_tree);
5575 if (ic->sb)
5576 free_pages_exact(ic->sb, SB_SECTORS << SECTOR_SHIFT);
5577 kfree(ic->sb_copy);
5578
5579 if (ic->internal_shash)
5580 crypto_free_shash(ic->internal_shash);
5581 if (ic->internal_ahash)
5582 crypto_free_ahash(ic->internal_ahash);
5583 free_alg(&ic->internal_hash_alg);
5584
5585 if (ic->journal_crypt)
5586 crypto_free_skcipher(ic->journal_crypt);
5587 free_alg(&ic->journal_crypt_alg);
5588
5589 if (ic->journal_mac)
5590 crypto_free_shash(ic->journal_mac);
5591 free_alg(&ic->journal_mac_alg);
5592
5593 kfree(ic);
5594 dm_audit_log_dtr(DM_MSG_PREFIX, ti, 1);
5595 }
5596
5597 static struct target_type integrity_target = {
5598 .name = "integrity",
5599 .version = {1, 15, 0},
5600 .module = THIS_MODULE,
5601 .features = DM_TARGET_SINGLETON | DM_TARGET_INTEGRITY,
5602 .ctr = dm_integrity_ctr,
5603 .dtr = dm_integrity_dtr,
5604 .map = dm_integrity_map,
5605 .end_io = dm_integrity_end_io,
5606 .postsuspend = dm_integrity_postsuspend,
5607 .resume = dm_integrity_resume,
5608 .status = dm_integrity_status,
5609 .iterate_devices = dm_integrity_iterate_devices,
5610 .io_hints = dm_integrity_io_hints,
5611 };
5612
dm_integrity_init(void)5613 static int __init dm_integrity_init(void)
5614 {
5615 int r;
5616
5617 journal_io_cache = kmem_cache_create("integrity_journal_io",
5618 sizeof(struct journal_io), 0, 0, NULL);
5619 if (!journal_io_cache) {
5620 DMERR("can't allocate journal io cache");
5621 return -ENOMEM;
5622 }
5623
5624 r = dm_register_target(&integrity_target);
5625 if (r < 0) {
5626 kmem_cache_destroy(journal_io_cache);
5627 return r;
5628 }
5629
5630 return 0;
5631 }
5632
dm_integrity_exit(void)5633 static void __exit dm_integrity_exit(void)
5634 {
5635 dm_unregister_target(&integrity_target);
5636 kmem_cache_destroy(journal_io_cache);
5637 }
5638
5639 module_init(dm_integrity_init);
5640 module_exit(dm_integrity_exit);
5641
5642 MODULE_AUTHOR("Milan Broz");
5643 MODULE_AUTHOR("Mikulas Patocka");
5644 MODULE_DESCRIPTION(DM_NAME " target for integrity tags extension");
5645 MODULE_LICENSE("GPL");
5646