dm clone: replace spin_lock_irqsave with spin_lock_irq
[platform/kernel/linux-rpi.git] / drivers / md / dm-integrity.c
1 /*
2  * Copyright (C) 2016-2017 Red Hat, Inc. All rights reserved.
3  * Copyright (C) 2016-2017 Milan Broz
4  * Copyright (C) 2016-2017 Mikulas Patocka
5  *
6  * This file is released under the GPL.
7  */
8
9 #include "dm-bio-record.h"
10
11 #include <linux/compiler.h>
12 #include <linux/module.h>
13 #include <linux/device-mapper.h>
14 #include <linux/dm-io.h>
15 #include <linux/vmalloc.h>
16 #include <linux/sort.h>
17 #include <linux/rbtree.h>
18 #include <linux/delay.h>
19 #include <linux/random.h>
20 #include <linux/reboot.h>
21 #include <crypto/hash.h>
22 #include <crypto/skcipher.h>
23 #include <linux/async_tx.h>
24 #include <linux/dm-bufio.h>
25
26 #define DM_MSG_PREFIX "integrity"
27
28 #define DEFAULT_INTERLEAVE_SECTORS      32768
29 #define DEFAULT_JOURNAL_SIZE_FACTOR     7
30 #define DEFAULT_SECTORS_PER_BITMAP_BIT  32768
31 #define DEFAULT_BUFFER_SECTORS          128
32 #define DEFAULT_JOURNAL_WATERMARK       50
33 #define DEFAULT_SYNC_MSEC               10000
34 #define DEFAULT_MAX_JOURNAL_SECTORS     131072
35 #define MIN_LOG2_INTERLEAVE_SECTORS     3
36 #define MAX_LOG2_INTERLEAVE_SECTORS     31
37 #define METADATA_WORKQUEUE_MAX_ACTIVE   16
38 #define RECALC_SECTORS                  8192
39 #define RECALC_WRITE_SUPER              16
40 #define BITMAP_BLOCK_SIZE               4096    /* don't change it */
41 #define BITMAP_FLUSH_INTERVAL           (10 * HZ)
42
43 /*
44  * Warning - DEBUG_PRINT prints security-sensitive data to the log,
45  * so it should not be enabled in the official kernel
46  */
47 //#define DEBUG_PRINT
48 //#define INTERNAL_VERIFY
49
50 /*
51  * On disk structures
52  */
53
54 #define SB_MAGIC                        "integrt"
55 #define SB_VERSION_1                    1
56 #define SB_VERSION_2                    2
57 #define SB_VERSION_3                    3
58 #define SB_SECTORS                      8
59 #define MAX_SECTORS_PER_BLOCK           8
60
61 struct superblock {
62         __u8 magic[8];
63         __u8 version;
64         __u8 log2_interleave_sectors;
65         __u16 integrity_tag_size;
66         __u32 journal_sections;
67         __u64 provided_data_sectors;    /* userspace uses this value */
68         __u32 flags;
69         __u8 log2_sectors_per_block;
70         __u8 log2_blocks_per_bitmap_bit;
71         __u8 pad[2];
72         __u64 recalc_sector;
73 };
74
75 #define SB_FLAG_HAVE_JOURNAL_MAC        0x1
76 #define SB_FLAG_RECALCULATING           0x2
77 #define SB_FLAG_DIRTY_BITMAP            0x4
78
79 #define JOURNAL_ENTRY_ROUNDUP           8
80
81 typedef __u64 commit_id_t;
82 #define JOURNAL_MAC_PER_SECTOR          8
83
84 struct journal_entry {
85         union {
86                 struct {
87                         __u32 sector_lo;
88                         __u32 sector_hi;
89                 } s;
90                 __u64 sector;
91         } u;
92         commit_id_t last_bytes[0];
93         /* __u8 tag[0]; */
94 };
95
96 #define journal_entry_tag(ic, je)               ((__u8 *)&(je)->last_bytes[(ic)->sectors_per_block])
97
98 #if BITS_PER_LONG == 64
99 #define journal_entry_set_sector(je, x)         do { smp_wmb(); WRITE_ONCE((je)->u.sector, cpu_to_le64(x)); } while (0)
100 #else
101 #define journal_entry_set_sector(je, x)         do { (je)->u.s.sector_lo = cpu_to_le32(x); smp_wmb(); WRITE_ONCE((je)->u.s.sector_hi, cpu_to_le32((x) >> 32)); } while (0)
102 #endif
103 #define journal_entry_get_sector(je)            le64_to_cpu((je)->u.sector)
104 #define journal_entry_is_unused(je)             ((je)->u.s.sector_hi == cpu_to_le32(-1))
105 #define journal_entry_set_unused(je)            do { ((je)->u.s.sector_hi = cpu_to_le32(-1)); } while (0)
106 #define journal_entry_is_inprogress(je)         ((je)->u.s.sector_hi == cpu_to_le32(-2))
107 #define journal_entry_set_inprogress(je)        do { ((je)->u.s.sector_hi = cpu_to_le32(-2)); } while (0)
108
109 #define JOURNAL_BLOCK_SECTORS           8
110 #define JOURNAL_SECTOR_DATA             ((1 << SECTOR_SHIFT) - sizeof(commit_id_t))
111 #define JOURNAL_MAC_SIZE                (JOURNAL_MAC_PER_SECTOR * JOURNAL_BLOCK_SECTORS)
112
113 struct journal_sector {
114         __u8 entries[JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR];
115         __u8 mac[JOURNAL_MAC_PER_SECTOR];
116         commit_id_t commit_id;
117 };
118
119 #define MAX_TAG_SIZE                    (JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR - offsetof(struct journal_entry, last_bytes[MAX_SECTORS_PER_BLOCK]))
120
121 #define METADATA_PADDING_SECTORS        8
122
123 #define N_COMMIT_IDS                    4
124
125 static unsigned char prev_commit_seq(unsigned char seq)
126 {
127         return (seq + N_COMMIT_IDS - 1) % N_COMMIT_IDS;
128 }
129
130 static unsigned char next_commit_seq(unsigned char seq)
131 {
132         return (seq + 1) % N_COMMIT_IDS;
133 }
134
135 /*
136  * In-memory structures
137  */
138
139 struct journal_node {
140         struct rb_node node;
141         sector_t sector;
142 };
143
144 struct alg_spec {
145         char *alg_string;
146         char *key_string;
147         __u8 *key;
148         unsigned key_size;
149 };
150
151 struct dm_integrity_c {
152         struct dm_dev *dev;
153         struct dm_dev *meta_dev;
154         unsigned tag_size;
155         __s8 log2_tag_size;
156         sector_t start;
157         mempool_t journal_io_mempool;
158         struct dm_io_client *io;
159         struct dm_bufio_client *bufio;
160         struct workqueue_struct *metadata_wq;
161         struct superblock *sb;
162         unsigned journal_pages;
163         unsigned n_bitmap_blocks;
164
165         struct page_list *journal;
166         struct page_list *journal_io;
167         struct page_list *journal_xor;
168         struct page_list *recalc_bitmap;
169         struct page_list *may_write_bitmap;
170         struct bitmap_block_status *bbs;
171         unsigned bitmap_flush_interval;
172         int synchronous_mode;
173         struct bio_list synchronous_bios;
174         struct delayed_work bitmap_flush_work;
175
176         struct crypto_skcipher *journal_crypt;
177         struct scatterlist **journal_scatterlist;
178         struct scatterlist **journal_io_scatterlist;
179         struct skcipher_request **sk_requests;
180
181         struct crypto_shash *journal_mac;
182
183         struct journal_node *journal_tree;
184         struct rb_root journal_tree_root;
185
186         sector_t provided_data_sectors;
187
188         unsigned short journal_entry_size;
189         unsigned char journal_entries_per_sector;
190         unsigned char journal_section_entries;
191         unsigned short journal_section_sectors;
192         unsigned journal_sections;
193         unsigned journal_entries;
194         sector_t data_device_sectors;
195         sector_t meta_device_sectors;
196         unsigned initial_sectors;
197         unsigned metadata_run;
198         __s8 log2_metadata_run;
199         __u8 log2_buffer_sectors;
200         __u8 sectors_per_block;
201         __u8 log2_blocks_per_bitmap_bit;
202
203         unsigned char mode;
204
205         int failed;
206
207         struct crypto_shash *internal_hash;
208
209         struct dm_target *ti;
210
211         /* these variables are locked with endio_wait.lock */
212         struct rb_root in_progress;
213         struct list_head wait_list;
214         wait_queue_head_t endio_wait;
215         struct workqueue_struct *wait_wq;
216         struct workqueue_struct *offload_wq;
217
218         unsigned char commit_seq;
219         commit_id_t commit_ids[N_COMMIT_IDS];
220
221         unsigned committed_section;
222         unsigned n_committed_sections;
223
224         unsigned uncommitted_section;
225         unsigned n_uncommitted_sections;
226
227         unsigned free_section;
228         unsigned char free_section_entry;
229         unsigned free_sectors;
230
231         unsigned free_sectors_threshold;
232
233         struct workqueue_struct *commit_wq;
234         struct work_struct commit_work;
235
236         struct workqueue_struct *writer_wq;
237         struct work_struct writer_work;
238
239         struct workqueue_struct *recalc_wq;
240         struct work_struct recalc_work;
241         u8 *recalc_buffer;
242         u8 *recalc_tags;
243
244         struct bio_list flush_bio_list;
245
246         unsigned long autocommit_jiffies;
247         struct timer_list autocommit_timer;
248         unsigned autocommit_msec;
249
250         wait_queue_head_t copy_to_journal_wait;
251
252         struct completion crypto_backoff;
253
254         bool journal_uptodate;
255         bool just_formatted;
256         bool recalculate_flag;
257
258         struct alg_spec internal_hash_alg;
259         struct alg_spec journal_crypt_alg;
260         struct alg_spec journal_mac_alg;
261
262         atomic64_t number_of_mismatches;
263
264         struct notifier_block reboot_notifier;
265 };
266
267 struct dm_integrity_range {
268         sector_t logical_sector;
269         sector_t n_sectors;
270         bool waiting;
271         union {
272                 struct rb_node node;
273                 struct {
274                         struct task_struct *task;
275                         struct list_head wait_entry;
276                 };
277         };
278 };
279
280 struct dm_integrity_io {
281         struct work_struct work;
282
283         struct dm_integrity_c *ic;
284         bool write;
285         bool fua;
286
287         struct dm_integrity_range range;
288
289         sector_t metadata_block;
290         unsigned metadata_offset;
291
292         atomic_t in_flight;
293         blk_status_t bi_status;
294
295         struct completion *completion;
296
297         struct dm_bio_details bio_details;
298 };
299
300 struct journal_completion {
301         struct dm_integrity_c *ic;
302         atomic_t in_flight;
303         struct completion comp;
304 };
305
306 struct journal_io {
307         struct dm_integrity_range range;
308         struct journal_completion *comp;
309 };
310
311 struct bitmap_block_status {
312         struct work_struct work;
313         struct dm_integrity_c *ic;
314         unsigned idx;
315         unsigned long *bitmap;
316         struct bio_list bio_queue;
317         spinlock_t bio_queue_lock;
318
319 };
320
321 static struct kmem_cache *journal_io_cache;
322
323 #define JOURNAL_IO_MEMPOOL      32
324
325 #ifdef DEBUG_PRINT
326 #define DEBUG_print(x, ...)     printk(KERN_DEBUG x, ##__VA_ARGS__)
327 static void __DEBUG_bytes(__u8 *bytes, size_t len, const char *msg, ...)
328 {
329         va_list args;
330         va_start(args, msg);
331         vprintk(msg, args);
332         va_end(args);
333         if (len)
334                 pr_cont(":");
335         while (len) {
336                 pr_cont(" %02x", *bytes);
337                 bytes++;
338                 len--;
339         }
340         pr_cont("\n");
341 }
342 #define DEBUG_bytes(bytes, len, msg, ...)       __DEBUG_bytes(bytes, len, KERN_DEBUG msg, ##__VA_ARGS__)
343 #else
344 #define DEBUG_print(x, ...)                     do { } while (0)
345 #define DEBUG_bytes(bytes, len, msg, ...)       do { } while (0)
346 #endif
347
348 static void dm_integrity_prepare(struct request *rq)
349 {
350 }
351
352 static void dm_integrity_complete(struct request *rq, unsigned int nr_bytes)
353 {
354 }
355
356 /*
357  * DM Integrity profile, protection is performed layer above (dm-crypt)
358  */
359 static const struct blk_integrity_profile dm_integrity_profile = {
360         .name                   = "DM-DIF-EXT-TAG",
361         .generate_fn            = NULL,
362         .verify_fn              = NULL,
363         .prepare_fn             = dm_integrity_prepare,
364         .complete_fn            = dm_integrity_complete,
365 };
366
367 static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map);
368 static void integrity_bio_wait(struct work_struct *w);
369 static void dm_integrity_dtr(struct dm_target *ti);
370
371 static void dm_integrity_io_error(struct dm_integrity_c *ic, const char *msg, int err)
372 {
373         if (err == -EILSEQ)
374                 atomic64_inc(&ic->number_of_mismatches);
375         if (!cmpxchg(&ic->failed, 0, err))
376                 DMERR("Error on %s: %d", msg, err);
377 }
378
379 static int dm_integrity_failed(struct dm_integrity_c *ic)
380 {
381         return READ_ONCE(ic->failed);
382 }
383
384 static commit_id_t dm_integrity_commit_id(struct dm_integrity_c *ic, unsigned i,
385                                           unsigned j, unsigned char seq)
386 {
387         /*
388          * Xor the number with section and sector, so that if a piece of
389          * journal is written at wrong place, it is detected.
390          */
391         return ic->commit_ids[seq] ^ cpu_to_le64(((__u64)i << 32) ^ j);
392 }
393
394 static void get_area_and_offset(struct dm_integrity_c *ic, sector_t data_sector,
395                                 sector_t *area, sector_t *offset)
396 {
397         if (!ic->meta_dev) {
398                 __u8 log2_interleave_sectors = ic->sb->log2_interleave_sectors;
399                 *area = data_sector >> log2_interleave_sectors;
400                 *offset = (unsigned)data_sector & ((1U << log2_interleave_sectors) - 1);
401         } else {
402                 *area = 0;
403                 *offset = data_sector;
404         }
405 }
406
407 #define sector_to_block(ic, n)                                          \
408 do {                                                                    \
409         BUG_ON((n) & (unsigned)((ic)->sectors_per_block - 1));          \
410         (n) >>= (ic)->sb->log2_sectors_per_block;                       \
411 } while (0)
412
413 static __u64 get_metadata_sector_and_offset(struct dm_integrity_c *ic, sector_t area,
414                                             sector_t offset, unsigned *metadata_offset)
415 {
416         __u64 ms;
417         unsigned mo;
418
419         ms = area << ic->sb->log2_interleave_sectors;
420         if (likely(ic->log2_metadata_run >= 0))
421                 ms += area << ic->log2_metadata_run;
422         else
423                 ms += area * ic->metadata_run;
424         ms >>= ic->log2_buffer_sectors;
425
426         sector_to_block(ic, offset);
427
428         if (likely(ic->log2_tag_size >= 0)) {
429                 ms += offset >> (SECTOR_SHIFT + ic->log2_buffer_sectors - ic->log2_tag_size);
430                 mo = (offset << ic->log2_tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
431         } else {
432                 ms += (__u64)offset * ic->tag_size >> (SECTOR_SHIFT + ic->log2_buffer_sectors);
433                 mo = (offset * ic->tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
434         }
435         *metadata_offset = mo;
436         return ms;
437 }
438
439 static sector_t get_data_sector(struct dm_integrity_c *ic, sector_t area, sector_t offset)
440 {
441         sector_t result;
442
443         if (ic->meta_dev)
444                 return offset;
445
446         result = area << ic->sb->log2_interleave_sectors;
447         if (likely(ic->log2_metadata_run >= 0))
448                 result += (area + 1) << ic->log2_metadata_run;
449         else
450                 result += (area + 1) * ic->metadata_run;
451
452         result += (sector_t)ic->initial_sectors + offset;
453         result += ic->start;
454
455         return result;
456 }
457
458 static void wraparound_section(struct dm_integrity_c *ic, unsigned *sec_ptr)
459 {
460         if (unlikely(*sec_ptr >= ic->journal_sections))
461                 *sec_ptr -= ic->journal_sections;
462 }
463
464 static void sb_set_version(struct dm_integrity_c *ic)
465 {
466         if (ic->mode == 'B' || ic->sb->flags & cpu_to_le32(SB_FLAG_DIRTY_BITMAP))
467                 ic->sb->version = SB_VERSION_3;
468         else if (ic->meta_dev || ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
469                 ic->sb->version = SB_VERSION_2;
470         else
471                 ic->sb->version = SB_VERSION_1;
472 }
473
474 static int sync_rw_sb(struct dm_integrity_c *ic, int op, int op_flags)
475 {
476         struct dm_io_request io_req;
477         struct dm_io_region io_loc;
478
479         io_req.bi_op = op;
480         io_req.bi_op_flags = op_flags;
481         io_req.mem.type = DM_IO_KMEM;
482         io_req.mem.ptr.addr = ic->sb;
483         io_req.notify.fn = NULL;
484         io_req.client = ic->io;
485         io_loc.bdev = ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev;
486         io_loc.sector = ic->start;
487         io_loc.count = SB_SECTORS;
488
489         if (op == REQ_OP_WRITE)
490                 sb_set_version(ic);
491
492         return dm_io(&io_req, 1, &io_loc, NULL);
493 }
494
495 #define BITMAP_OP_TEST_ALL_SET          0
496 #define BITMAP_OP_TEST_ALL_CLEAR        1
497 #define BITMAP_OP_SET                   2
498 #define BITMAP_OP_CLEAR                 3
499
500 static bool block_bitmap_op(struct dm_integrity_c *ic, struct page_list *bitmap,
501                             sector_t sector, sector_t n_sectors, int mode)
502 {
503         unsigned long bit, end_bit, this_end_bit, page, end_page;
504         unsigned long *data;
505
506         if (unlikely(((sector | n_sectors) & ((1 << ic->sb->log2_sectors_per_block) - 1)) != 0)) {
507                 DMCRIT("invalid bitmap access (%llx,%llx,%d,%d,%d)",
508                         (unsigned long long)sector,
509                         (unsigned long long)n_sectors,
510                         ic->sb->log2_sectors_per_block,
511                         ic->log2_blocks_per_bitmap_bit,
512                         mode);
513                 BUG();
514         }
515
516         if (unlikely(!n_sectors))
517                 return true;
518
519         bit = sector >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
520         end_bit = (sector + n_sectors - 1) >>
521                 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
522
523         page = bit / (PAGE_SIZE * 8);
524         bit %= PAGE_SIZE * 8;
525
526         end_page = end_bit / (PAGE_SIZE * 8);
527         end_bit %= PAGE_SIZE * 8;
528
529 repeat:
530         if (page < end_page) {
531                 this_end_bit = PAGE_SIZE * 8 - 1;
532         } else {
533                 this_end_bit = end_bit;
534         }
535
536         data = lowmem_page_address(bitmap[page].page);
537
538         if (mode == BITMAP_OP_TEST_ALL_SET) {
539                 while (bit <= this_end_bit) {
540                         if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
541                                 do {
542                                         if (data[bit / BITS_PER_LONG] != -1)
543                                                 return false;
544                                         bit += BITS_PER_LONG;
545                                 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
546                                 continue;
547                         }
548                         if (!test_bit(bit, data))
549                                 return false;
550                         bit++;
551                 }
552         } else if (mode == BITMAP_OP_TEST_ALL_CLEAR) {
553                 while (bit <= this_end_bit) {
554                         if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
555                                 do {
556                                         if (data[bit / BITS_PER_LONG] != 0)
557                                                 return false;
558                                         bit += BITS_PER_LONG;
559                                 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
560                                 continue;
561                         }
562                         if (test_bit(bit, data))
563                                 return false;
564                         bit++;
565                 }
566         } else if (mode == BITMAP_OP_SET) {
567                 while (bit <= this_end_bit) {
568                         if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
569                                 do {
570                                         data[bit / BITS_PER_LONG] = -1;
571                                         bit += BITS_PER_LONG;
572                                 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
573                                 continue;
574                         }
575                         __set_bit(bit, data);
576                         bit++;
577                 }
578         } else if (mode == BITMAP_OP_CLEAR) {
579                 if (!bit && this_end_bit == PAGE_SIZE * 8 - 1)
580                         clear_page(data);
581                 else while (bit <= this_end_bit) {
582                         if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
583                                 do {
584                                         data[bit / BITS_PER_LONG] = 0;
585                                         bit += BITS_PER_LONG;
586                                 } while (this_end_bit >= bit + BITS_PER_LONG - 1);
587                                 continue;
588                         }
589                         __clear_bit(bit, data);
590                         bit++;
591                 }
592         } else {
593                 BUG();
594         }
595
596         if (unlikely(page < end_page)) {
597                 bit = 0;
598                 page++;
599                 goto repeat;
600         }
601
602         return true;
603 }
604
605 static void block_bitmap_copy(struct dm_integrity_c *ic, struct page_list *dst, struct page_list *src)
606 {
607         unsigned n_bitmap_pages = DIV_ROUND_UP(ic->n_bitmap_blocks, PAGE_SIZE / BITMAP_BLOCK_SIZE);
608         unsigned i;
609
610         for (i = 0; i < n_bitmap_pages; i++) {
611                 unsigned long *dst_data = lowmem_page_address(dst[i].page);
612                 unsigned long *src_data = lowmem_page_address(src[i].page);
613                 copy_page(dst_data, src_data);
614         }
615 }
616
617 static struct bitmap_block_status *sector_to_bitmap_block(struct dm_integrity_c *ic, sector_t sector)
618 {
619         unsigned bit = sector >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
620         unsigned bitmap_block = bit / (BITMAP_BLOCK_SIZE * 8);
621
622         BUG_ON(bitmap_block >= ic->n_bitmap_blocks);
623         return &ic->bbs[bitmap_block];
624 }
625
626 static void access_journal_check(struct dm_integrity_c *ic, unsigned section, unsigned offset,
627                                  bool e, const char *function)
628 {
629 #if defined(CONFIG_DM_DEBUG) || defined(INTERNAL_VERIFY)
630         unsigned limit = e ? ic->journal_section_entries : ic->journal_section_sectors;
631
632         if (unlikely(section >= ic->journal_sections) ||
633             unlikely(offset >= limit)) {
634                 DMCRIT("%s: invalid access at (%u,%u), limit (%u,%u)",
635                        function, section, offset, ic->journal_sections, limit);
636                 BUG();
637         }
638 #endif
639 }
640
641 static void page_list_location(struct dm_integrity_c *ic, unsigned section, unsigned offset,
642                                unsigned *pl_index, unsigned *pl_offset)
643 {
644         unsigned sector;
645
646         access_journal_check(ic, section, offset, false, "page_list_location");
647
648         sector = section * ic->journal_section_sectors + offset;
649
650         *pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
651         *pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
652 }
653
654 static struct journal_sector *access_page_list(struct dm_integrity_c *ic, struct page_list *pl,
655                                                unsigned section, unsigned offset, unsigned *n_sectors)
656 {
657         unsigned pl_index, pl_offset;
658         char *va;
659
660         page_list_location(ic, section, offset, &pl_index, &pl_offset);
661
662         if (n_sectors)
663                 *n_sectors = (PAGE_SIZE - pl_offset) >> SECTOR_SHIFT;
664
665         va = lowmem_page_address(pl[pl_index].page);
666
667         return (struct journal_sector *)(va + pl_offset);
668 }
669
670 static struct journal_sector *access_journal(struct dm_integrity_c *ic, unsigned section, unsigned offset)
671 {
672         return access_page_list(ic, ic->journal, section, offset, NULL);
673 }
674
675 static struct journal_entry *access_journal_entry(struct dm_integrity_c *ic, unsigned section, unsigned n)
676 {
677         unsigned rel_sector, offset;
678         struct journal_sector *js;
679
680         access_journal_check(ic, section, n, true, "access_journal_entry");
681
682         rel_sector = n % JOURNAL_BLOCK_SECTORS;
683         offset = n / JOURNAL_BLOCK_SECTORS;
684
685         js = access_journal(ic, section, rel_sector);
686         return (struct journal_entry *)((char *)js + offset * ic->journal_entry_size);
687 }
688
689 static struct journal_sector *access_journal_data(struct dm_integrity_c *ic, unsigned section, unsigned n)
690 {
691         n <<= ic->sb->log2_sectors_per_block;
692
693         n += JOURNAL_BLOCK_SECTORS;
694
695         access_journal_check(ic, section, n, false, "access_journal_data");
696
697         return access_journal(ic, section, n);
698 }
699
700 static void section_mac(struct dm_integrity_c *ic, unsigned section, __u8 result[JOURNAL_MAC_SIZE])
701 {
702         SHASH_DESC_ON_STACK(desc, ic->journal_mac);
703         int r;
704         unsigned j, size;
705
706         desc->tfm = ic->journal_mac;
707
708         r = crypto_shash_init(desc);
709         if (unlikely(r)) {
710                 dm_integrity_io_error(ic, "crypto_shash_init", r);
711                 goto err;
712         }
713
714         for (j = 0; j < ic->journal_section_entries; j++) {
715                 struct journal_entry *je = access_journal_entry(ic, section, j);
716                 r = crypto_shash_update(desc, (__u8 *)&je->u.sector, sizeof je->u.sector);
717                 if (unlikely(r)) {
718                         dm_integrity_io_error(ic, "crypto_shash_update", r);
719                         goto err;
720                 }
721         }
722
723         size = crypto_shash_digestsize(ic->journal_mac);
724
725         if (likely(size <= JOURNAL_MAC_SIZE)) {
726                 r = crypto_shash_final(desc, result);
727                 if (unlikely(r)) {
728                         dm_integrity_io_error(ic, "crypto_shash_final", r);
729                         goto err;
730                 }
731                 memset(result + size, 0, JOURNAL_MAC_SIZE - size);
732         } else {
733                 __u8 digest[HASH_MAX_DIGESTSIZE];
734
735                 if (WARN_ON(size > sizeof(digest))) {
736                         dm_integrity_io_error(ic, "digest_size", -EINVAL);
737                         goto err;
738                 }
739                 r = crypto_shash_final(desc, digest);
740                 if (unlikely(r)) {
741                         dm_integrity_io_error(ic, "crypto_shash_final", r);
742                         goto err;
743                 }
744                 memcpy(result, digest, JOURNAL_MAC_SIZE);
745         }
746
747         return;
748 err:
749         memset(result, 0, JOURNAL_MAC_SIZE);
750 }
751
752 static void rw_section_mac(struct dm_integrity_c *ic, unsigned section, bool wr)
753 {
754         __u8 result[JOURNAL_MAC_SIZE];
755         unsigned j;
756
757         if (!ic->journal_mac)
758                 return;
759
760         section_mac(ic, section, result);
761
762         for (j = 0; j < JOURNAL_BLOCK_SECTORS; j++) {
763                 struct journal_sector *js = access_journal(ic, section, j);
764
765                 if (likely(wr))
766                         memcpy(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR);
767                 else {
768                         if (memcmp(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR))
769                                 dm_integrity_io_error(ic, "journal mac", -EILSEQ);
770                 }
771         }
772 }
773
774 static void complete_journal_op(void *context)
775 {
776         struct journal_completion *comp = context;
777         BUG_ON(!atomic_read(&comp->in_flight));
778         if (likely(atomic_dec_and_test(&comp->in_flight)))
779                 complete(&comp->comp);
780 }
781
782 static void xor_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
783                         unsigned n_sections, struct journal_completion *comp)
784 {
785         struct async_submit_ctl submit;
786         size_t n_bytes = (size_t)(n_sections * ic->journal_section_sectors) << SECTOR_SHIFT;
787         unsigned pl_index, pl_offset, section_index;
788         struct page_list *source_pl, *target_pl;
789
790         if (likely(encrypt)) {
791                 source_pl = ic->journal;
792                 target_pl = ic->journal_io;
793         } else {
794                 source_pl = ic->journal_io;
795                 target_pl = ic->journal;
796         }
797
798         page_list_location(ic, section, 0, &pl_index, &pl_offset);
799
800         atomic_add(roundup(pl_offset + n_bytes, PAGE_SIZE) >> PAGE_SHIFT, &comp->in_flight);
801
802         init_async_submit(&submit, ASYNC_TX_XOR_ZERO_DST, NULL, complete_journal_op, comp, NULL);
803
804         section_index = pl_index;
805
806         do {
807                 size_t this_step;
808                 struct page *src_pages[2];
809                 struct page *dst_page;
810
811                 while (unlikely(pl_index == section_index)) {
812                         unsigned dummy;
813                         if (likely(encrypt))
814                                 rw_section_mac(ic, section, true);
815                         section++;
816                         n_sections--;
817                         if (!n_sections)
818                                 break;
819                         page_list_location(ic, section, 0, &section_index, &dummy);
820                 }
821
822                 this_step = min(n_bytes, (size_t)PAGE_SIZE - pl_offset);
823                 dst_page = target_pl[pl_index].page;
824                 src_pages[0] = source_pl[pl_index].page;
825                 src_pages[1] = ic->journal_xor[pl_index].page;
826
827                 async_xor(dst_page, src_pages, pl_offset, 2, this_step, &submit);
828
829                 pl_index++;
830                 pl_offset = 0;
831                 n_bytes -= this_step;
832         } while (n_bytes);
833
834         BUG_ON(n_sections);
835
836         async_tx_issue_pending_all();
837 }
838
839 static void complete_journal_encrypt(struct crypto_async_request *req, int err)
840 {
841         struct journal_completion *comp = req->data;
842         if (unlikely(err)) {
843                 if (likely(err == -EINPROGRESS)) {
844                         complete(&comp->ic->crypto_backoff);
845                         return;
846                 }
847                 dm_integrity_io_error(comp->ic, "asynchronous encrypt", err);
848         }
849         complete_journal_op(comp);
850 }
851
852 static bool do_crypt(bool encrypt, struct skcipher_request *req, struct journal_completion *comp)
853 {
854         int r;
855         skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
856                                       complete_journal_encrypt, comp);
857         if (likely(encrypt))
858                 r = crypto_skcipher_encrypt(req);
859         else
860                 r = crypto_skcipher_decrypt(req);
861         if (likely(!r))
862                 return false;
863         if (likely(r == -EINPROGRESS))
864                 return true;
865         if (likely(r == -EBUSY)) {
866                 wait_for_completion(&comp->ic->crypto_backoff);
867                 reinit_completion(&comp->ic->crypto_backoff);
868                 return true;
869         }
870         dm_integrity_io_error(comp->ic, "encrypt", r);
871         return false;
872 }
873
874 static void crypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
875                           unsigned n_sections, struct journal_completion *comp)
876 {
877         struct scatterlist **source_sg;
878         struct scatterlist **target_sg;
879
880         atomic_add(2, &comp->in_flight);
881
882         if (likely(encrypt)) {
883                 source_sg = ic->journal_scatterlist;
884                 target_sg = ic->journal_io_scatterlist;
885         } else {
886                 source_sg = ic->journal_io_scatterlist;
887                 target_sg = ic->journal_scatterlist;
888         }
889
890         do {
891                 struct skcipher_request *req;
892                 unsigned ivsize;
893                 char *iv;
894
895                 if (likely(encrypt))
896                         rw_section_mac(ic, section, true);
897
898                 req = ic->sk_requests[section];
899                 ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
900                 iv = req->iv;
901
902                 memcpy(iv, iv + ivsize, ivsize);
903
904                 req->src = source_sg[section];
905                 req->dst = target_sg[section];
906
907                 if (unlikely(do_crypt(encrypt, req, comp)))
908                         atomic_inc(&comp->in_flight);
909
910                 section++;
911                 n_sections--;
912         } while (n_sections);
913
914         atomic_dec(&comp->in_flight);
915         complete_journal_op(comp);
916 }
917
918 static void encrypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
919                             unsigned n_sections, struct journal_completion *comp)
920 {
921         if (ic->journal_xor)
922                 return xor_journal(ic, encrypt, section, n_sections, comp);
923         else
924                 return crypt_journal(ic, encrypt, section, n_sections, comp);
925 }
926
927 static void complete_journal_io(unsigned long error, void *context)
928 {
929         struct journal_completion *comp = context;
930         if (unlikely(error != 0))
931                 dm_integrity_io_error(comp->ic, "writing journal", -EIO);
932         complete_journal_op(comp);
933 }
934
935 static void rw_journal_sectors(struct dm_integrity_c *ic, int op, int op_flags,
936                                unsigned sector, unsigned n_sectors, struct journal_completion *comp)
937 {
938         struct dm_io_request io_req;
939         struct dm_io_region io_loc;
940         unsigned pl_index, pl_offset;
941         int r;
942
943         if (unlikely(dm_integrity_failed(ic))) {
944                 if (comp)
945                         complete_journal_io(-1UL, comp);
946                 return;
947         }
948
949         pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
950         pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
951
952         io_req.bi_op = op;
953         io_req.bi_op_flags = op_flags;
954         io_req.mem.type = DM_IO_PAGE_LIST;
955         if (ic->journal_io)
956                 io_req.mem.ptr.pl = &ic->journal_io[pl_index];
957         else
958                 io_req.mem.ptr.pl = &ic->journal[pl_index];
959         io_req.mem.offset = pl_offset;
960         if (likely(comp != NULL)) {
961                 io_req.notify.fn = complete_journal_io;
962                 io_req.notify.context = comp;
963         } else {
964                 io_req.notify.fn = NULL;
965         }
966         io_req.client = ic->io;
967         io_loc.bdev = ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev;
968         io_loc.sector = ic->start + SB_SECTORS + sector;
969         io_loc.count = n_sectors;
970
971         r = dm_io(&io_req, 1, &io_loc, NULL);
972         if (unlikely(r)) {
973                 dm_integrity_io_error(ic, op == REQ_OP_READ ? "reading journal" : "writing journal", r);
974                 if (comp) {
975                         WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
976                         complete_journal_io(-1UL, comp);
977                 }
978         }
979 }
980
981 static void rw_journal(struct dm_integrity_c *ic, int op, int op_flags, unsigned section,
982                        unsigned n_sections, struct journal_completion *comp)
983 {
984         unsigned sector, n_sectors;
985
986         sector = section * ic->journal_section_sectors;
987         n_sectors = n_sections * ic->journal_section_sectors;
988
989         rw_journal_sectors(ic, op, op_flags, sector, n_sectors, comp);
990 }
991
992 static void write_journal(struct dm_integrity_c *ic, unsigned commit_start, unsigned commit_sections)
993 {
994         struct journal_completion io_comp;
995         struct journal_completion crypt_comp_1;
996         struct journal_completion crypt_comp_2;
997         unsigned i;
998
999         io_comp.ic = ic;
1000         init_completion(&io_comp.comp);
1001
1002         if (commit_start + commit_sections <= ic->journal_sections) {
1003                 io_comp.in_flight = (atomic_t)ATOMIC_INIT(1);
1004                 if (ic->journal_io) {
1005                         crypt_comp_1.ic = ic;
1006                         init_completion(&crypt_comp_1.comp);
1007                         crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
1008                         encrypt_journal(ic, true, commit_start, commit_sections, &crypt_comp_1);
1009                         wait_for_completion_io(&crypt_comp_1.comp);
1010                 } else {
1011                         for (i = 0; i < commit_sections; i++)
1012                                 rw_section_mac(ic, commit_start + i, true);
1013                 }
1014                 rw_journal(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, commit_start,
1015                            commit_sections, &io_comp);
1016         } else {
1017                 unsigned to_end;
1018                 io_comp.in_flight = (atomic_t)ATOMIC_INIT(2);
1019                 to_end = ic->journal_sections - commit_start;
1020                 if (ic->journal_io) {
1021                         crypt_comp_1.ic = ic;
1022                         init_completion(&crypt_comp_1.comp);
1023                         crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
1024                         encrypt_journal(ic, true, commit_start, to_end, &crypt_comp_1);
1025                         if (try_wait_for_completion(&crypt_comp_1.comp)) {
1026                                 rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
1027                                 reinit_completion(&crypt_comp_1.comp);
1028                                 crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
1029                                 encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_1);
1030                                 wait_for_completion_io(&crypt_comp_1.comp);
1031                         } else {
1032                                 crypt_comp_2.ic = ic;
1033                                 init_completion(&crypt_comp_2.comp);
1034                                 crypt_comp_2.in_flight = (atomic_t)ATOMIC_INIT(0);
1035                                 encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_2);
1036                                 wait_for_completion_io(&crypt_comp_1.comp);
1037                                 rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
1038                                 wait_for_completion_io(&crypt_comp_2.comp);
1039                         }
1040                 } else {
1041                         for (i = 0; i < to_end; i++)
1042                                 rw_section_mac(ic, commit_start + i, true);
1043                         rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
1044                         for (i = 0; i < commit_sections - to_end; i++)
1045                                 rw_section_mac(ic, i, true);
1046                 }
1047                 rw_journal(ic, REQ_OP_WRITE, REQ_FUA, 0, commit_sections - to_end, &io_comp);
1048         }
1049
1050         wait_for_completion_io(&io_comp.comp);
1051 }
1052
1053 static void copy_from_journal(struct dm_integrity_c *ic, unsigned section, unsigned offset,
1054                               unsigned n_sectors, sector_t target, io_notify_fn fn, void *data)
1055 {
1056         struct dm_io_request io_req;
1057         struct dm_io_region io_loc;
1058         int r;
1059         unsigned sector, pl_index, pl_offset;
1060
1061         BUG_ON((target | n_sectors | offset) & (unsigned)(ic->sectors_per_block - 1));
1062
1063         if (unlikely(dm_integrity_failed(ic))) {
1064                 fn(-1UL, data);
1065                 return;
1066         }
1067
1068         sector = section * ic->journal_section_sectors + JOURNAL_BLOCK_SECTORS + offset;
1069
1070         pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
1071         pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
1072
1073         io_req.bi_op = REQ_OP_WRITE;
1074         io_req.bi_op_flags = 0;
1075         io_req.mem.type = DM_IO_PAGE_LIST;
1076         io_req.mem.ptr.pl = &ic->journal[pl_index];
1077         io_req.mem.offset = pl_offset;
1078         io_req.notify.fn = fn;
1079         io_req.notify.context = data;
1080         io_req.client = ic->io;
1081         io_loc.bdev = ic->dev->bdev;
1082         io_loc.sector = target;
1083         io_loc.count = n_sectors;
1084
1085         r = dm_io(&io_req, 1, &io_loc, NULL);
1086         if (unlikely(r)) {
1087                 WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
1088                 fn(-1UL, data);
1089         }
1090 }
1091
1092 static bool ranges_overlap(struct dm_integrity_range *range1, struct dm_integrity_range *range2)
1093 {
1094         return range1->logical_sector < range2->logical_sector + range2->n_sectors &&
1095                range1->logical_sector + range1->n_sectors > range2->logical_sector;
1096 }
1097
1098 static bool add_new_range(struct dm_integrity_c *ic, struct dm_integrity_range *new_range, bool check_waiting)
1099 {
1100         struct rb_node **n = &ic->in_progress.rb_node;
1101         struct rb_node *parent;
1102
1103         BUG_ON((new_range->logical_sector | new_range->n_sectors) & (unsigned)(ic->sectors_per_block - 1));
1104
1105         if (likely(check_waiting)) {
1106                 struct dm_integrity_range *range;
1107                 list_for_each_entry(range, &ic->wait_list, wait_entry) {
1108                         if (unlikely(ranges_overlap(range, new_range)))
1109                                 return false;
1110                 }
1111         }
1112
1113         parent = NULL;
1114
1115         while (*n) {
1116                 struct dm_integrity_range *range = container_of(*n, struct dm_integrity_range, node);
1117
1118                 parent = *n;
1119                 if (new_range->logical_sector + new_range->n_sectors <= range->logical_sector) {
1120                         n = &range->node.rb_left;
1121                 } else if (new_range->logical_sector >= range->logical_sector + range->n_sectors) {
1122                         n = &range->node.rb_right;
1123                 } else {
1124                         return false;
1125                 }
1126         }
1127
1128         rb_link_node(&new_range->node, parent, n);
1129         rb_insert_color(&new_range->node, &ic->in_progress);
1130
1131         return true;
1132 }
1133
1134 static void remove_range_unlocked(struct dm_integrity_c *ic, struct dm_integrity_range *range)
1135 {
1136         rb_erase(&range->node, &ic->in_progress);
1137         while (unlikely(!list_empty(&ic->wait_list))) {
1138                 struct dm_integrity_range *last_range =
1139                         list_first_entry(&ic->wait_list, struct dm_integrity_range, wait_entry);
1140                 struct task_struct *last_range_task;
1141                 last_range_task = last_range->task;
1142                 list_del(&last_range->wait_entry);
1143                 if (!add_new_range(ic, last_range, false)) {
1144                         last_range->task = last_range_task;
1145                         list_add(&last_range->wait_entry, &ic->wait_list);
1146                         break;
1147                 }
1148                 last_range->waiting = false;
1149                 wake_up_process(last_range_task);
1150         }
1151 }
1152
1153 static void remove_range(struct dm_integrity_c *ic, struct dm_integrity_range *range)
1154 {
1155         unsigned long flags;
1156
1157         spin_lock_irqsave(&ic->endio_wait.lock, flags);
1158         remove_range_unlocked(ic, range);
1159         spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1160 }
1161
1162 static void wait_and_add_new_range(struct dm_integrity_c *ic, struct dm_integrity_range *new_range)
1163 {
1164         new_range->waiting = true;
1165         list_add_tail(&new_range->wait_entry, &ic->wait_list);
1166         new_range->task = current;
1167         do {
1168                 __set_current_state(TASK_UNINTERRUPTIBLE);
1169                 spin_unlock_irq(&ic->endio_wait.lock);
1170                 io_schedule();
1171                 spin_lock_irq(&ic->endio_wait.lock);
1172         } while (unlikely(new_range->waiting));
1173 }
1174
1175 static void add_new_range_and_wait(struct dm_integrity_c *ic, struct dm_integrity_range *new_range)
1176 {
1177         if (unlikely(!add_new_range(ic, new_range, true)))
1178                 wait_and_add_new_range(ic, new_range);
1179 }
1180
1181 static void init_journal_node(struct journal_node *node)
1182 {
1183         RB_CLEAR_NODE(&node->node);
1184         node->sector = (sector_t)-1;
1185 }
1186
1187 static void add_journal_node(struct dm_integrity_c *ic, struct journal_node *node, sector_t sector)
1188 {
1189         struct rb_node **link;
1190         struct rb_node *parent;
1191
1192         node->sector = sector;
1193         BUG_ON(!RB_EMPTY_NODE(&node->node));
1194
1195         link = &ic->journal_tree_root.rb_node;
1196         parent = NULL;
1197
1198         while (*link) {
1199                 struct journal_node *j;
1200                 parent = *link;
1201                 j = container_of(parent, struct journal_node, node);
1202                 if (sector < j->sector)
1203                         link = &j->node.rb_left;
1204                 else
1205                         link = &j->node.rb_right;
1206         }
1207
1208         rb_link_node(&node->node, parent, link);
1209         rb_insert_color(&node->node, &ic->journal_tree_root);
1210 }
1211
1212 static void remove_journal_node(struct dm_integrity_c *ic, struct journal_node *node)
1213 {
1214         BUG_ON(RB_EMPTY_NODE(&node->node));
1215         rb_erase(&node->node, &ic->journal_tree_root);
1216         init_journal_node(node);
1217 }
1218
1219 #define NOT_FOUND       (-1U)
1220
1221 static unsigned find_journal_node(struct dm_integrity_c *ic, sector_t sector, sector_t *next_sector)
1222 {
1223         struct rb_node *n = ic->journal_tree_root.rb_node;
1224         unsigned found = NOT_FOUND;
1225         *next_sector = (sector_t)-1;
1226         while (n) {
1227                 struct journal_node *j = container_of(n, struct journal_node, node);
1228                 if (sector == j->sector) {
1229                         found = j - ic->journal_tree;
1230                 }
1231                 if (sector < j->sector) {
1232                         *next_sector = j->sector;
1233                         n = j->node.rb_left;
1234                 } else {
1235                         n = j->node.rb_right;
1236                 }
1237         }
1238
1239         return found;
1240 }
1241
1242 static bool test_journal_node(struct dm_integrity_c *ic, unsigned pos, sector_t sector)
1243 {
1244         struct journal_node *node, *next_node;
1245         struct rb_node *next;
1246
1247         if (unlikely(pos >= ic->journal_entries))
1248                 return false;
1249         node = &ic->journal_tree[pos];
1250         if (unlikely(RB_EMPTY_NODE(&node->node)))
1251                 return false;
1252         if (unlikely(node->sector != sector))
1253                 return false;
1254
1255         next = rb_next(&node->node);
1256         if (unlikely(!next))
1257                 return true;
1258
1259         next_node = container_of(next, struct journal_node, node);
1260         return next_node->sector != sector;
1261 }
1262
1263 static bool find_newer_committed_node(struct dm_integrity_c *ic, struct journal_node *node)
1264 {
1265         struct rb_node *next;
1266         struct journal_node *next_node;
1267         unsigned next_section;
1268
1269         BUG_ON(RB_EMPTY_NODE(&node->node));
1270
1271         next = rb_next(&node->node);
1272         if (unlikely(!next))
1273                 return false;
1274
1275         next_node = container_of(next, struct journal_node, node);
1276
1277         if (next_node->sector != node->sector)
1278                 return false;
1279
1280         next_section = (unsigned)(next_node - ic->journal_tree) / ic->journal_section_entries;
1281         if (next_section >= ic->committed_section &&
1282             next_section < ic->committed_section + ic->n_committed_sections)
1283                 return true;
1284         if (next_section + ic->journal_sections < ic->committed_section + ic->n_committed_sections)
1285                 return true;
1286
1287         return false;
1288 }
1289
1290 #define TAG_READ        0
1291 #define TAG_WRITE       1
1292 #define TAG_CMP         2
1293
1294 static int dm_integrity_rw_tag(struct dm_integrity_c *ic, unsigned char *tag, sector_t *metadata_block,
1295                                unsigned *metadata_offset, unsigned total_size, int op)
1296 {
1297         do {
1298                 unsigned char *data, *dp;
1299                 struct dm_buffer *b;
1300                 unsigned to_copy;
1301                 int r;
1302
1303                 r = dm_integrity_failed(ic);
1304                 if (unlikely(r))
1305                         return r;
1306
1307                 data = dm_bufio_read(ic->bufio, *metadata_block, &b);
1308                 if (IS_ERR(data))
1309                         return PTR_ERR(data);
1310
1311                 to_copy = min((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - *metadata_offset, total_size);
1312                 dp = data + *metadata_offset;
1313                 if (op == TAG_READ) {
1314                         memcpy(tag, dp, to_copy);
1315                 } else if (op == TAG_WRITE) {
1316                         memcpy(dp, tag, to_copy);
1317                         dm_bufio_mark_partial_buffer_dirty(b, *metadata_offset, *metadata_offset + to_copy);
1318                 } else  {
1319                         /* e.g.: op == TAG_CMP */
1320                         if (unlikely(memcmp(dp, tag, to_copy))) {
1321                                 unsigned i;
1322
1323                                 for (i = 0; i < to_copy; i++) {
1324                                         if (dp[i] != tag[i])
1325                                                 break;
1326                                         total_size--;
1327                                 }
1328                                 dm_bufio_release(b);
1329                                 return total_size;
1330                         }
1331                 }
1332                 dm_bufio_release(b);
1333
1334                 tag += to_copy;
1335                 *metadata_offset += to_copy;
1336                 if (unlikely(*metadata_offset == 1U << SECTOR_SHIFT << ic->log2_buffer_sectors)) {
1337                         (*metadata_block)++;
1338                         *metadata_offset = 0;
1339                 }
1340                 total_size -= to_copy;
1341         } while (unlikely(total_size));
1342
1343         return 0;
1344 }
1345
1346 static void dm_integrity_flush_buffers(struct dm_integrity_c *ic)
1347 {
1348         int r;
1349         r = dm_bufio_write_dirty_buffers(ic->bufio);
1350         if (unlikely(r))
1351                 dm_integrity_io_error(ic, "writing tags", r);
1352 }
1353
1354 static void sleep_on_endio_wait(struct dm_integrity_c *ic)
1355 {
1356         DECLARE_WAITQUEUE(wait, current);
1357         __add_wait_queue(&ic->endio_wait, &wait);
1358         __set_current_state(TASK_UNINTERRUPTIBLE);
1359         spin_unlock_irq(&ic->endio_wait.lock);
1360         io_schedule();
1361         spin_lock_irq(&ic->endio_wait.lock);
1362         __remove_wait_queue(&ic->endio_wait, &wait);
1363 }
1364
1365 static void autocommit_fn(struct timer_list *t)
1366 {
1367         struct dm_integrity_c *ic = from_timer(ic, t, autocommit_timer);
1368
1369         if (likely(!dm_integrity_failed(ic)))
1370                 queue_work(ic->commit_wq, &ic->commit_work);
1371 }
1372
1373 static void schedule_autocommit(struct dm_integrity_c *ic)
1374 {
1375         if (!timer_pending(&ic->autocommit_timer))
1376                 mod_timer(&ic->autocommit_timer, jiffies + ic->autocommit_jiffies);
1377 }
1378
1379 static void submit_flush_bio(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
1380 {
1381         struct bio *bio;
1382         unsigned long flags;
1383
1384         spin_lock_irqsave(&ic->endio_wait.lock, flags);
1385         bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1386         bio_list_add(&ic->flush_bio_list, bio);
1387         spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1388
1389         queue_work(ic->commit_wq, &ic->commit_work);
1390 }
1391
1392 static void do_endio(struct dm_integrity_c *ic, struct bio *bio)
1393 {
1394         int r = dm_integrity_failed(ic);
1395         if (unlikely(r) && !bio->bi_status)
1396                 bio->bi_status = errno_to_blk_status(r);
1397         if (unlikely(ic->synchronous_mode) && bio_op(bio) == REQ_OP_WRITE) {
1398                 unsigned long flags;
1399                 spin_lock_irqsave(&ic->endio_wait.lock, flags);
1400                 bio_list_add(&ic->synchronous_bios, bio);
1401                 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
1402                 spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
1403                 return;
1404         }
1405         bio_endio(bio);
1406 }
1407
1408 static void do_endio_flush(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
1409 {
1410         struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1411
1412         if (unlikely(dio->fua) && likely(!bio->bi_status) && likely(!dm_integrity_failed(ic)))
1413                 submit_flush_bio(ic, dio);
1414         else
1415                 do_endio(ic, bio);
1416 }
1417
1418 static void dec_in_flight(struct dm_integrity_io *dio)
1419 {
1420         if (atomic_dec_and_test(&dio->in_flight)) {
1421                 struct dm_integrity_c *ic = dio->ic;
1422                 struct bio *bio;
1423
1424                 remove_range(ic, &dio->range);
1425
1426                 if (unlikely(dio->write))
1427                         schedule_autocommit(ic);
1428
1429                 bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1430
1431                 if (unlikely(dio->bi_status) && !bio->bi_status)
1432                         bio->bi_status = dio->bi_status;
1433                 if (likely(!bio->bi_status) && unlikely(bio_sectors(bio) != dio->range.n_sectors)) {
1434                         dio->range.logical_sector += dio->range.n_sectors;
1435                         bio_advance(bio, dio->range.n_sectors << SECTOR_SHIFT);
1436                         INIT_WORK(&dio->work, integrity_bio_wait);
1437                         queue_work(ic->offload_wq, &dio->work);
1438                         return;
1439                 }
1440                 do_endio_flush(ic, dio);
1441         }
1442 }
1443
1444 static void integrity_end_io(struct bio *bio)
1445 {
1446         struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
1447
1448         dm_bio_restore(&dio->bio_details, bio);
1449         if (bio->bi_integrity)
1450                 bio->bi_opf |= REQ_INTEGRITY;
1451
1452         if (dio->completion)
1453                 complete(dio->completion);
1454
1455         dec_in_flight(dio);
1456 }
1457
1458 static void integrity_sector_checksum(struct dm_integrity_c *ic, sector_t sector,
1459                                       const char *data, char *result)
1460 {
1461         __u64 sector_le = cpu_to_le64(sector);
1462         SHASH_DESC_ON_STACK(req, ic->internal_hash);
1463         int r;
1464         unsigned digest_size;
1465
1466         req->tfm = ic->internal_hash;
1467
1468         r = crypto_shash_init(req);
1469         if (unlikely(r < 0)) {
1470                 dm_integrity_io_error(ic, "crypto_shash_init", r);
1471                 goto failed;
1472         }
1473
1474         r = crypto_shash_update(req, (const __u8 *)&sector_le, sizeof sector_le);
1475         if (unlikely(r < 0)) {
1476                 dm_integrity_io_error(ic, "crypto_shash_update", r);
1477                 goto failed;
1478         }
1479
1480         r = crypto_shash_update(req, data, ic->sectors_per_block << SECTOR_SHIFT);
1481         if (unlikely(r < 0)) {
1482                 dm_integrity_io_error(ic, "crypto_shash_update", r);
1483                 goto failed;
1484         }
1485
1486         r = crypto_shash_final(req, result);
1487         if (unlikely(r < 0)) {
1488                 dm_integrity_io_error(ic, "crypto_shash_final", r);
1489                 goto failed;
1490         }
1491
1492         digest_size = crypto_shash_digestsize(ic->internal_hash);
1493         if (unlikely(digest_size < ic->tag_size))
1494                 memset(result + digest_size, 0, ic->tag_size - digest_size);
1495
1496         return;
1497
1498 failed:
1499         /* this shouldn't happen anyway, the hash functions have no reason to fail */
1500         get_random_bytes(result, ic->tag_size);
1501 }
1502
1503 static void integrity_metadata(struct work_struct *w)
1504 {
1505         struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
1506         struct dm_integrity_c *ic = dio->ic;
1507
1508         int r;
1509
1510         if (ic->internal_hash) {
1511                 struct bvec_iter iter;
1512                 struct bio_vec bv;
1513                 unsigned digest_size = crypto_shash_digestsize(ic->internal_hash);
1514                 struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1515                 char *checksums;
1516                 unsigned extra_space = unlikely(digest_size > ic->tag_size) ? digest_size - ic->tag_size : 0;
1517                 char checksums_onstack[max((size_t)HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
1518                 unsigned sectors_to_process = dio->range.n_sectors;
1519                 sector_t sector = dio->range.logical_sector;
1520
1521                 if (unlikely(ic->mode == 'R'))
1522                         goto skip_io;
1523
1524                 checksums = kmalloc((PAGE_SIZE >> SECTOR_SHIFT >> ic->sb->log2_sectors_per_block) * ic->tag_size + extra_space,
1525                                     GFP_NOIO | __GFP_NORETRY | __GFP_NOWARN);
1526                 if (!checksums) {
1527                         checksums = checksums_onstack;
1528                         if (WARN_ON(extra_space &&
1529                                     digest_size > sizeof(checksums_onstack))) {
1530                                 r = -EINVAL;
1531                                 goto error;
1532                         }
1533                 }
1534
1535                 __bio_for_each_segment(bv, bio, iter, dio->bio_details.bi_iter) {
1536                         unsigned pos;
1537                         char *mem, *checksums_ptr;
1538
1539 again:
1540                         mem = (char *)kmap_atomic(bv.bv_page) + bv.bv_offset;
1541                         pos = 0;
1542                         checksums_ptr = checksums;
1543                         do {
1544                                 integrity_sector_checksum(ic, sector, mem + pos, checksums_ptr);
1545                                 checksums_ptr += ic->tag_size;
1546                                 sectors_to_process -= ic->sectors_per_block;
1547                                 pos += ic->sectors_per_block << SECTOR_SHIFT;
1548                                 sector += ic->sectors_per_block;
1549                         } while (pos < bv.bv_len && sectors_to_process && checksums != checksums_onstack);
1550                         kunmap_atomic(mem);
1551
1552                         r = dm_integrity_rw_tag(ic, checksums, &dio->metadata_block, &dio->metadata_offset,
1553                                                 checksums_ptr - checksums, !dio->write ? TAG_CMP : TAG_WRITE);
1554                         if (unlikely(r)) {
1555                                 if (r > 0) {
1556                                         DMERR_LIMIT("Checksum failed at sector 0x%llx",
1557                                                     (unsigned long long)(sector - ((r + ic->tag_size - 1) / ic->tag_size)));
1558                                         r = -EILSEQ;
1559                                         atomic64_inc(&ic->number_of_mismatches);
1560                                 }
1561                                 if (likely(checksums != checksums_onstack))
1562                                         kfree(checksums);
1563                                 goto error;
1564                         }
1565
1566                         if (!sectors_to_process)
1567                                 break;
1568
1569                         if (unlikely(pos < bv.bv_len)) {
1570                                 bv.bv_offset += pos;
1571                                 bv.bv_len -= pos;
1572                                 goto again;
1573                         }
1574                 }
1575
1576                 if (likely(checksums != checksums_onstack))
1577                         kfree(checksums);
1578         } else {
1579                 struct bio_integrity_payload *bip = dio->bio_details.bi_integrity;
1580
1581                 if (bip) {
1582                         struct bio_vec biv;
1583                         struct bvec_iter iter;
1584                         unsigned data_to_process = dio->range.n_sectors;
1585                         sector_to_block(ic, data_to_process);
1586                         data_to_process *= ic->tag_size;
1587
1588                         bip_for_each_vec(biv, bip, iter) {
1589                                 unsigned char *tag;
1590                                 unsigned this_len;
1591
1592                                 BUG_ON(PageHighMem(biv.bv_page));
1593                                 tag = lowmem_page_address(biv.bv_page) + biv.bv_offset;
1594                                 this_len = min(biv.bv_len, data_to_process);
1595                                 r = dm_integrity_rw_tag(ic, tag, &dio->metadata_block, &dio->metadata_offset,
1596                                                         this_len, !dio->write ? TAG_READ : TAG_WRITE);
1597                                 if (unlikely(r))
1598                                         goto error;
1599                                 data_to_process -= this_len;
1600                                 if (!data_to_process)
1601                                         break;
1602                         }
1603                 }
1604         }
1605 skip_io:
1606         dec_in_flight(dio);
1607         return;
1608 error:
1609         dio->bi_status = errno_to_blk_status(r);
1610         dec_in_flight(dio);
1611 }
1612
1613 static int dm_integrity_map(struct dm_target *ti, struct bio *bio)
1614 {
1615         struct dm_integrity_c *ic = ti->private;
1616         struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
1617         struct bio_integrity_payload *bip;
1618
1619         sector_t area, offset;
1620
1621         dio->ic = ic;
1622         dio->bi_status = 0;
1623
1624         if (unlikely(bio->bi_opf & REQ_PREFLUSH)) {
1625                 submit_flush_bio(ic, dio);
1626                 return DM_MAPIO_SUBMITTED;
1627         }
1628
1629         dio->range.logical_sector = dm_target_offset(ti, bio->bi_iter.bi_sector);
1630         dio->write = bio_op(bio) == REQ_OP_WRITE;
1631         dio->fua = dio->write && bio->bi_opf & REQ_FUA;
1632         if (unlikely(dio->fua)) {
1633                 /*
1634                  * Don't pass down the FUA flag because we have to flush
1635                  * disk cache anyway.
1636                  */
1637                 bio->bi_opf &= ~REQ_FUA;
1638         }
1639         if (unlikely(dio->range.logical_sector + bio_sectors(bio) > ic->provided_data_sectors)) {
1640                 DMERR("Too big sector number: 0x%llx + 0x%x > 0x%llx",
1641                       (unsigned long long)dio->range.logical_sector, bio_sectors(bio),
1642                       (unsigned long long)ic->provided_data_sectors);
1643                 return DM_MAPIO_KILL;
1644         }
1645         if (unlikely((dio->range.logical_sector | bio_sectors(bio)) & (unsigned)(ic->sectors_per_block - 1))) {
1646                 DMERR("Bio not aligned on %u sectors: 0x%llx, 0x%x",
1647                       ic->sectors_per_block,
1648                       (unsigned long long)dio->range.logical_sector, bio_sectors(bio));
1649                 return DM_MAPIO_KILL;
1650         }
1651
1652         if (ic->sectors_per_block > 1) {
1653                 struct bvec_iter iter;
1654                 struct bio_vec bv;
1655                 bio_for_each_segment(bv, bio, iter) {
1656                         if (unlikely(bv.bv_len & ((ic->sectors_per_block << SECTOR_SHIFT) - 1))) {
1657                                 DMERR("Bio vector (%u,%u) is not aligned on %u-sector boundary",
1658                                         bv.bv_offset, bv.bv_len, ic->sectors_per_block);
1659                                 return DM_MAPIO_KILL;
1660                         }
1661                 }
1662         }
1663
1664         bip = bio_integrity(bio);
1665         if (!ic->internal_hash) {
1666                 if (bip) {
1667                         unsigned wanted_tag_size = bio_sectors(bio) >> ic->sb->log2_sectors_per_block;
1668                         if (ic->log2_tag_size >= 0)
1669                                 wanted_tag_size <<= ic->log2_tag_size;
1670                         else
1671                                 wanted_tag_size *= ic->tag_size;
1672                         if (unlikely(wanted_tag_size != bip->bip_iter.bi_size)) {
1673                                 DMERR("Invalid integrity data size %u, expected %u",
1674                                       bip->bip_iter.bi_size, wanted_tag_size);
1675                                 return DM_MAPIO_KILL;
1676                         }
1677                 }
1678         } else {
1679                 if (unlikely(bip != NULL)) {
1680                         DMERR("Unexpected integrity data when using internal hash");
1681                         return DM_MAPIO_KILL;
1682                 }
1683         }
1684
1685         if (unlikely(ic->mode == 'R') && unlikely(dio->write))
1686                 return DM_MAPIO_KILL;
1687
1688         get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
1689         dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
1690         bio->bi_iter.bi_sector = get_data_sector(ic, area, offset);
1691
1692         dm_integrity_map_continue(dio, true);
1693         return DM_MAPIO_SUBMITTED;
1694 }
1695
1696 static bool __journal_read_write(struct dm_integrity_io *dio, struct bio *bio,
1697                                  unsigned journal_section, unsigned journal_entry)
1698 {
1699         struct dm_integrity_c *ic = dio->ic;
1700         sector_t logical_sector;
1701         unsigned n_sectors;
1702
1703         logical_sector = dio->range.logical_sector;
1704         n_sectors = dio->range.n_sectors;
1705         do {
1706                 struct bio_vec bv = bio_iovec(bio);
1707                 char *mem;
1708
1709                 if (unlikely(bv.bv_len >> SECTOR_SHIFT > n_sectors))
1710                         bv.bv_len = n_sectors << SECTOR_SHIFT;
1711                 n_sectors -= bv.bv_len >> SECTOR_SHIFT;
1712                 bio_advance_iter(bio, &bio->bi_iter, bv.bv_len);
1713 retry_kmap:
1714                 mem = kmap_atomic(bv.bv_page);
1715                 if (likely(dio->write))
1716                         flush_dcache_page(bv.bv_page);
1717
1718                 do {
1719                         struct journal_entry *je = access_journal_entry(ic, journal_section, journal_entry);
1720
1721                         if (unlikely(!dio->write)) {
1722                                 struct journal_sector *js;
1723                                 char *mem_ptr;
1724                                 unsigned s;
1725
1726                                 if (unlikely(journal_entry_is_inprogress(je))) {
1727                                         flush_dcache_page(bv.bv_page);
1728                                         kunmap_atomic(mem);
1729
1730                                         __io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
1731                                         goto retry_kmap;
1732                                 }
1733                                 smp_rmb();
1734                                 BUG_ON(journal_entry_get_sector(je) != logical_sector);
1735                                 js = access_journal_data(ic, journal_section, journal_entry);
1736                                 mem_ptr = mem + bv.bv_offset;
1737                                 s = 0;
1738                                 do {
1739                                         memcpy(mem_ptr, js, JOURNAL_SECTOR_DATA);
1740                                         *(commit_id_t *)(mem_ptr + JOURNAL_SECTOR_DATA) = je->last_bytes[s];
1741                                         js++;
1742                                         mem_ptr += 1 << SECTOR_SHIFT;
1743                                 } while (++s < ic->sectors_per_block);
1744 #ifdef INTERNAL_VERIFY
1745                                 if (ic->internal_hash) {
1746                                         char checksums_onstack[max((size_t)HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
1747
1748                                         integrity_sector_checksum(ic, logical_sector, mem + bv.bv_offset, checksums_onstack);
1749                                         if (unlikely(memcmp(checksums_onstack, journal_entry_tag(ic, je), ic->tag_size))) {
1750                                                 DMERR_LIMIT("Checksum failed when reading from journal, at sector 0x%llx",
1751                                                             (unsigned long long)logical_sector);
1752                                         }
1753                                 }
1754 #endif
1755                         }
1756
1757                         if (!ic->internal_hash) {
1758                                 struct bio_integrity_payload *bip = bio_integrity(bio);
1759                                 unsigned tag_todo = ic->tag_size;
1760                                 char *tag_ptr = journal_entry_tag(ic, je);
1761
1762                                 if (bip) do {
1763                                         struct bio_vec biv = bvec_iter_bvec(bip->bip_vec, bip->bip_iter);
1764                                         unsigned tag_now = min(biv.bv_len, tag_todo);
1765                                         char *tag_addr;
1766                                         BUG_ON(PageHighMem(biv.bv_page));
1767                                         tag_addr = lowmem_page_address(biv.bv_page) + biv.bv_offset;
1768                                         if (likely(dio->write))
1769                                                 memcpy(tag_ptr, tag_addr, tag_now);
1770                                         else
1771                                                 memcpy(tag_addr, tag_ptr, tag_now);
1772                                         bvec_iter_advance(bip->bip_vec, &bip->bip_iter, tag_now);
1773                                         tag_ptr += tag_now;
1774                                         tag_todo -= tag_now;
1775                                 } while (unlikely(tag_todo)); else {
1776                                         if (likely(dio->write))
1777                                                 memset(tag_ptr, 0, tag_todo);
1778                                 }
1779                         }
1780
1781                         if (likely(dio->write)) {
1782                                 struct journal_sector *js;
1783                                 unsigned s;
1784
1785                                 js = access_journal_data(ic, journal_section, journal_entry);
1786                                 memcpy(js, mem + bv.bv_offset, ic->sectors_per_block << SECTOR_SHIFT);
1787
1788                                 s = 0;
1789                                 do {
1790                                         je->last_bytes[s] = js[s].commit_id;
1791                                 } while (++s < ic->sectors_per_block);
1792
1793                                 if (ic->internal_hash) {
1794                                         unsigned digest_size = crypto_shash_digestsize(ic->internal_hash);
1795                                         if (unlikely(digest_size > ic->tag_size)) {
1796                                                 char checksums_onstack[HASH_MAX_DIGESTSIZE];
1797                                                 integrity_sector_checksum(ic, logical_sector, (char *)js, checksums_onstack);
1798                                                 memcpy(journal_entry_tag(ic, je), checksums_onstack, ic->tag_size);
1799                                         } else
1800                                                 integrity_sector_checksum(ic, logical_sector, (char *)js, journal_entry_tag(ic, je));
1801                                 }
1802
1803                                 journal_entry_set_sector(je, logical_sector);
1804                         }
1805                         logical_sector += ic->sectors_per_block;
1806
1807                         journal_entry++;
1808                         if (unlikely(journal_entry == ic->journal_section_entries)) {
1809                                 journal_entry = 0;
1810                                 journal_section++;
1811                                 wraparound_section(ic, &journal_section);
1812                         }
1813
1814                         bv.bv_offset += ic->sectors_per_block << SECTOR_SHIFT;
1815                 } while (bv.bv_len -= ic->sectors_per_block << SECTOR_SHIFT);
1816
1817                 if (unlikely(!dio->write))
1818                         flush_dcache_page(bv.bv_page);
1819                 kunmap_atomic(mem);
1820         } while (n_sectors);
1821
1822         if (likely(dio->write)) {
1823                 smp_mb();
1824                 if (unlikely(waitqueue_active(&ic->copy_to_journal_wait)))
1825                         wake_up(&ic->copy_to_journal_wait);
1826                 if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold) {
1827                         queue_work(ic->commit_wq, &ic->commit_work);
1828                 } else {
1829                         schedule_autocommit(ic);
1830                 }
1831         } else {
1832                 remove_range(ic, &dio->range);
1833         }
1834
1835         if (unlikely(bio->bi_iter.bi_size)) {
1836                 sector_t area, offset;
1837
1838                 dio->range.logical_sector = logical_sector;
1839                 get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
1840                 dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
1841                 return true;
1842         }
1843
1844         return false;
1845 }
1846
1847 static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map)
1848 {
1849         struct dm_integrity_c *ic = dio->ic;
1850         struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
1851         unsigned journal_section, journal_entry;
1852         unsigned journal_read_pos;
1853         struct completion read_comp;
1854         bool need_sync_io = ic->internal_hash && !dio->write;
1855
1856         if (need_sync_io && from_map) {
1857                 INIT_WORK(&dio->work, integrity_bio_wait);
1858                 queue_work(ic->offload_wq, &dio->work);
1859                 return;
1860         }
1861
1862 lock_retry:
1863         spin_lock_irq(&ic->endio_wait.lock);
1864 retry:
1865         if (unlikely(dm_integrity_failed(ic))) {
1866                 spin_unlock_irq(&ic->endio_wait.lock);
1867                 do_endio(ic, bio);
1868                 return;
1869         }
1870         dio->range.n_sectors = bio_sectors(bio);
1871         journal_read_pos = NOT_FOUND;
1872         if (likely(ic->mode == 'J')) {
1873                 if (dio->write) {
1874                         unsigned next_entry, i, pos;
1875                         unsigned ws, we, range_sectors;
1876
1877                         dio->range.n_sectors = min(dio->range.n_sectors,
1878                                                    (sector_t)ic->free_sectors << ic->sb->log2_sectors_per_block);
1879                         if (unlikely(!dio->range.n_sectors)) {
1880                                 if (from_map)
1881                                         goto offload_to_thread;
1882                                 sleep_on_endio_wait(ic);
1883                                 goto retry;
1884                         }
1885                         range_sectors = dio->range.n_sectors >> ic->sb->log2_sectors_per_block;
1886                         ic->free_sectors -= range_sectors;
1887                         journal_section = ic->free_section;
1888                         journal_entry = ic->free_section_entry;
1889
1890                         next_entry = ic->free_section_entry + range_sectors;
1891                         ic->free_section_entry = next_entry % ic->journal_section_entries;
1892                         ic->free_section += next_entry / ic->journal_section_entries;
1893                         ic->n_uncommitted_sections += next_entry / ic->journal_section_entries;
1894                         wraparound_section(ic, &ic->free_section);
1895
1896                         pos = journal_section * ic->journal_section_entries + journal_entry;
1897                         ws = journal_section;
1898                         we = journal_entry;
1899                         i = 0;
1900                         do {
1901                                 struct journal_entry *je;
1902
1903                                 add_journal_node(ic, &ic->journal_tree[pos], dio->range.logical_sector + i);
1904                                 pos++;
1905                                 if (unlikely(pos >= ic->journal_entries))
1906                                         pos = 0;
1907
1908                                 je = access_journal_entry(ic, ws, we);
1909                                 BUG_ON(!journal_entry_is_unused(je));
1910                                 journal_entry_set_inprogress(je);
1911                                 we++;
1912                                 if (unlikely(we == ic->journal_section_entries)) {
1913                                         we = 0;
1914                                         ws++;
1915                                         wraparound_section(ic, &ws);
1916                                 }
1917                         } while ((i += ic->sectors_per_block) < dio->range.n_sectors);
1918
1919                         spin_unlock_irq(&ic->endio_wait.lock);
1920                         goto journal_read_write;
1921                 } else {
1922                         sector_t next_sector;
1923                         journal_read_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
1924                         if (likely(journal_read_pos == NOT_FOUND)) {
1925                                 if (unlikely(dio->range.n_sectors > next_sector - dio->range.logical_sector))
1926                                         dio->range.n_sectors = next_sector - dio->range.logical_sector;
1927                         } else {
1928                                 unsigned i;
1929                                 unsigned jp = journal_read_pos + 1;
1930                                 for (i = ic->sectors_per_block; i < dio->range.n_sectors; i += ic->sectors_per_block, jp++) {
1931                                         if (!test_journal_node(ic, jp, dio->range.logical_sector + i))
1932                                                 break;
1933                                 }
1934                                 dio->range.n_sectors = i;
1935                         }
1936                 }
1937         }
1938         if (unlikely(!add_new_range(ic, &dio->range, true))) {
1939                 /*
1940                  * We must not sleep in the request routine because it could
1941                  * stall bios on current->bio_list.
1942                  * So, we offload the bio to a workqueue if we have to sleep.
1943                  */
1944                 if (from_map) {
1945 offload_to_thread:
1946                         spin_unlock_irq(&ic->endio_wait.lock);
1947                         INIT_WORK(&dio->work, integrity_bio_wait);
1948                         queue_work(ic->wait_wq, &dio->work);
1949                         return;
1950                 }
1951                 if (journal_read_pos != NOT_FOUND)
1952                         dio->range.n_sectors = ic->sectors_per_block;
1953                 wait_and_add_new_range(ic, &dio->range);
1954                 /*
1955                  * wait_and_add_new_range drops the spinlock, so the journal
1956                  * may have been changed arbitrarily. We need to recheck.
1957                  * To simplify the code, we restrict I/O size to just one block.
1958                  */
1959                 if (journal_read_pos != NOT_FOUND) {
1960                         sector_t next_sector;
1961                         unsigned new_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
1962                         if (unlikely(new_pos != journal_read_pos)) {
1963                                 remove_range_unlocked(ic, &dio->range);
1964                                 goto retry;
1965                         }
1966                 }
1967         }
1968         spin_unlock_irq(&ic->endio_wait.lock);
1969
1970         if (unlikely(journal_read_pos != NOT_FOUND)) {
1971                 journal_section = journal_read_pos / ic->journal_section_entries;
1972                 journal_entry = journal_read_pos % ic->journal_section_entries;
1973                 goto journal_read_write;
1974         }
1975
1976         if (ic->mode == 'B' && dio->write) {
1977                 if (!block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
1978                                      dio->range.n_sectors, BITMAP_OP_TEST_ALL_SET)) {
1979                         struct bitmap_block_status *bbs;
1980
1981                         bbs = sector_to_bitmap_block(ic, dio->range.logical_sector);
1982                         spin_lock(&bbs->bio_queue_lock);
1983                         bio_list_add(&bbs->bio_queue, bio);
1984                         spin_unlock(&bbs->bio_queue_lock);
1985                         queue_work(ic->writer_wq, &bbs->work);
1986                         return;
1987                 }
1988         }
1989
1990         dio->in_flight = (atomic_t)ATOMIC_INIT(2);
1991
1992         if (need_sync_io) {
1993                 init_completion(&read_comp);
1994                 dio->completion = &read_comp;
1995         } else
1996                 dio->completion = NULL;
1997
1998         dm_bio_record(&dio->bio_details, bio);
1999         bio_set_dev(bio, ic->dev->bdev);
2000         bio->bi_integrity = NULL;
2001         bio->bi_opf &= ~REQ_INTEGRITY;
2002         bio->bi_end_io = integrity_end_io;
2003         bio->bi_iter.bi_size = dio->range.n_sectors << SECTOR_SHIFT;
2004
2005         generic_make_request(bio);
2006
2007         if (need_sync_io) {
2008                 wait_for_completion_io(&read_comp);
2009                 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
2010                     dio->range.logical_sector + dio->range.n_sectors > le64_to_cpu(ic->sb->recalc_sector))
2011                         goto skip_check;
2012                 if (ic->mode == 'B') {
2013                         if (!block_bitmap_op(ic, ic->recalc_bitmap, dio->range.logical_sector,
2014                                              dio->range.n_sectors, BITMAP_OP_TEST_ALL_CLEAR))
2015                                 goto skip_check;
2016                 }
2017
2018                 if (likely(!bio->bi_status))
2019                         integrity_metadata(&dio->work);
2020                 else
2021 skip_check:
2022                         dec_in_flight(dio);
2023
2024         } else {
2025                 INIT_WORK(&dio->work, integrity_metadata);
2026                 queue_work(ic->metadata_wq, &dio->work);
2027         }
2028
2029         return;
2030
2031 journal_read_write:
2032         if (unlikely(__journal_read_write(dio, bio, journal_section, journal_entry)))
2033                 goto lock_retry;
2034
2035         do_endio_flush(ic, dio);
2036 }
2037
2038
2039 static void integrity_bio_wait(struct work_struct *w)
2040 {
2041         struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
2042
2043         dm_integrity_map_continue(dio, false);
2044 }
2045
2046 static void pad_uncommitted(struct dm_integrity_c *ic)
2047 {
2048         if (ic->free_section_entry) {
2049                 ic->free_sectors -= ic->journal_section_entries - ic->free_section_entry;
2050                 ic->free_section_entry = 0;
2051                 ic->free_section++;
2052                 wraparound_section(ic, &ic->free_section);
2053                 ic->n_uncommitted_sections++;
2054         }
2055         if (WARN_ON(ic->journal_sections * ic->journal_section_entries !=
2056                     (ic->n_uncommitted_sections + ic->n_committed_sections) *
2057                     ic->journal_section_entries + ic->free_sectors)) {
2058                 DMCRIT("journal_sections %u, journal_section_entries %u, "
2059                        "n_uncommitted_sections %u, n_committed_sections %u, "
2060                        "journal_section_entries %u, free_sectors %u",
2061                        ic->journal_sections, ic->journal_section_entries,
2062                        ic->n_uncommitted_sections, ic->n_committed_sections,
2063                        ic->journal_section_entries, ic->free_sectors);
2064         }
2065 }
2066
2067 static void integrity_commit(struct work_struct *w)
2068 {
2069         struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, commit_work);
2070         unsigned commit_start, commit_sections;
2071         unsigned i, j, n;
2072         struct bio *flushes;
2073
2074         del_timer(&ic->autocommit_timer);
2075
2076         spin_lock_irq(&ic->endio_wait.lock);
2077         flushes = bio_list_get(&ic->flush_bio_list);
2078         if (unlikely(ic->mode != 'J')) {
2079                 spin_unlock_irq(&ic->endio_wait.lock);
2080                 dm_integrity_flush_buffers(ic);
2081                 goto release_flush_bios;
2082         }
2083
2084         pad_uncommitted(ic);
2085         commit_start = ic->uncommitted_section;
2086         commit_sections = ic->n_uncommitted_sections;
2087         spin_unlock_irq(&ic->endio_wait.lock);
2088
2089         if (!commit_sections)
2090                 goto release_flush_bios;
2091
2092         i = commit_start;
2093         for (n = 0; n < commit_sections; n++) {
2094                 for (j = 0; j < ic->journal_section_entries; j++) {
2095                         struct journal_entry *je;
2096                         je = access_journal_entry(ic, i, j);
2097                         io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
2098                 }
2099                 for (j = 0; j < ic->journal_section_sectors; j++) {
2100                         struct journal_sector *js;
2101                         js = access_journal(ic, i, j);
2102                         js->commit_id = dm_integrity_commit_id(ic, i, j, ic->commit_seq);
2103                 }
2104                 i++;
2105                 if (unlikely(i >= ic->journal_sections))
2106                         ic->commit_seq = next_commit_seq(ic->commit_seq);
2107                 wraparound_section(ic, &i);
2108         }
2109         smp_rmb();
2110
2111         write_journal(ic, commit_start, commit_sections);
2112
2113         spin_lock_irq(&ic->endio_wait.lock);
2114         ic->uncommitted_section += commit_sections;
2115         wraparound_section(ic, &ic->uncommitted_section);
2116         ic->n_uncommitted_sections -= commit_sections;
2117         ic->n_committed_sections += commit_sections;
2118         spin_unlock_irq(&ic->endio_wait.lock);
2119
2120         if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold)
2121                 queue_work(ic->writer_wq, &ic->writer_work);
2122
2123 release_flush_bios:
2124         while (flushes) {
2125                 struct bio *next = flushes->bi_next;
2126                 flushes->bi_next = NULL;
2127                 do_endio(ic, flushes);
2128                 flushes = next;
2129         }
2130 }
2131
2132 static void complete_copy_from_journal(unsigned long error, void *context)
2133 {
2134         struct journal_io *io = context;
2135         struct journal_completion *comp = io->comp;
2136         struct dm_integrity_c *ic = comp->ic;
2137         remove_range(ic, &io->range);
2138         mempool_free(io, &ic->journal_io_mempool);
2139         if (unlikely(error != 0))
2140                 dm_integrity_io_error(ic, "copying from journal", -EIO);
2141         complete_journal_op(comp);
2142 }
2143
2144 static void restore_last_bytes(struct dm_integrity_c *ic, struct journal_sector *js,
2145                                struct journal_entry *je)
2146 {
2147         unsigned s = 0;
2148         do {
2149                 js->commit_id = je->last_bytes[s];
2150                 js++;
2151         } while (++s < ic->sectors_per_block);
2152 }
2153
2154 static void do_journal_write(struct dm_integrity_c *ic, unsigned write_start,
2155                              unsigned write_sections, bool from_replay)
2156 {
2157         unsigned i, j, n;
2158         struct journal_completion comp;
2159         struct blk_plug plug;
2160
2161         blk_start_plug(&plug);
2162
2163         comp.ic = ic;
2164         comp.in_flight = (atomic_t)ATOMIC_INIT(1);
2165         init_completion(&comp.comp);
2166
2167         i = write_start;
2168         for (n = 0; n < write_sections; n++, i++, wraparound_section(ic, &i)) {
2169 #ifndef INTERNAL_VERIFY
2170                 if (unlikely(from_replay))
2171 #endif
2172                         rw_section_mac(ic, i, false);
2173                 for (j = 0; j < ic->journal_section_entries; j++) {
2174                         struct journal_entry *je = access_journal_entry(ic, i, j);
2175                         sector_t sec, area, offset;
2176                         unsigned k, l, next_loop;
2177                         sector_t metadata_block;
2178                         unsigned metadata_offset;
2179                         struct journal_io *io;
2180
2181                         if (journal_entry_is_unused(je))
2182                                 continue;
2183                         BUG_ON(unlikely(journal_entry_is_inprogress(je)) && !from_replay);
2184                         sec = journal_entry_get_sector(je);
2185                         if (unlikely(from_replay)) {
2186                                 if (unlikely(sec & (unsigned)(ic->sectors_per_block - 1))) {
2187                                         dm_integrity_io_error(ic, "invalid sector in journal", -EIO);
2188                                         sec &= ~(sector_t)(ic->sectors_per_block - 1);
2189                                 }
2190                         }
2191                         get_area_and_offset(ic, sec, &area, &offset);
2192                         restore_last_bytes(ic, access_journal_data(ic, i, j), je);
2193                         for (k = j + 1; k < ic->journal_section_entries; k++) {
2194                                 struct journal_entry *je2 = access_journal_entry(ic, i, k);
2195                                 sector_t sec2, area2, offset2;
2196                                 if (journal_entry_is_unused(je2))
2197                                         break;
2198                                 BUG_ON(unlikely(journal_entry_is_inprogress(je2)) && !from_replay);
2199                                 sec2 = journal_entry_get_sector(je2);
2200                                 get_area_and_offset(ic, sec2, &area2, &offset2);
2201                                 if (area2 != area || offset2 != offset + ((k - j) << ic->sb->log2_sectors_per_block))
2202                                         break;
2203                                 restore_last_bytes(ic, access_journal_data(ic, i, k), je2);
2204                         }
2205                         next_loop = k - 1;
2206
2207                         io = mempool_alloc(&ic->journal_io_mempool, GFP_NOIO);
2208                         io->comp = &comp;
2209                         io->range.logical_sector = sec;
2210                         io->range.n_sectors = (k - j) << ic->sb->log2_sectors_per_block;
2211
2212                         spin_lock_irq(&ic->endio_wait.lock);
2213                         add_new_range_and_wait(ic, &io->range);
2214
2215                         if (likely(!from_replay)) {
2216                                 struct journal_node *section_node = &ic->journal_tree[i * ic->journal_section_entries];
2217
2218                                 /* don't write if there is newer committed sector */
2219                                 while (j < k && find_newer_committed_node(ic, &section_node[j])) {
2220                                         struct journal_entry *je2 = access_journal_entry(ic, i, j);
2221
2222                                         journal_entry_set_unused(je2);
2223                                         remove_journal_node(ic, &section_node[j]);
2224                                         j++;
2225                                         sec += ic->sectors_per_block;
2226                                         offset += ic->sectors_per_block;
2227                                 }
2228                                 while (j < k && find_newer_committed_node(ic, &section_node[k - 1])) {
2229                                         struct journal_entry *je2 = access_journal_entry(ic, i, k - 1);
2230
2231                                         journal_entry_set_unused(je2);
2232                                         remove_journal_node(ic, &section_node[k - 1]);
2233                                         k--;
2234                                 }
2235                                 if (j == k) {
2236                                         remove_range_unlocked(ic, &io->range);
2237                                         spin_unlock_irq(&ic->endio_wait.lock);
2238                                         mempool_free(io, &ic->journal_io_mempool);
2239                                         goto skip_io;
2240                                 }
2241                                 for (l = j; l < k; l++) {
2242                                         remove_journal_node(ic, &section_node[l]);
2243                                 }
2244                         }
2245                         spin_unlock_irq(&ic->endio_wait.lock);
2246
2247                         metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
2248                         for (l = j; l < k; l++) {
2249                                 int r;
2250                                 struct journal_entry *je2 = access_journal_entry(ic, i, l);
2251
2252                                 if (
2253 #ifndef INTERNAL_VERIFY
2254                                     unlikely(from_replay) &&
2255 #endif
2256                                     ic->internal_hash) {
2257                                         char test_tag[max_t(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
2258
2259                                         integrity_sector_checksum(ic, sec + ((l - j) << ic->sb->log2_sectors_per_block),
2260                                                                   (char *)access_journal_data(ic, i, l), test_tag);
2261                                         if (unlikely(memcmp(test_tag, journal_entry_tag(ic, je2), ic->tag_size)))
2262                                                 dm_integrity_io_error(ic, "tag mismatch when replaying journal", -EILSEQ);
2263                                 }
2264
2265                                 journal_entry_set_unused(je2);
2266                                 r = dm_integrity_rw_tag(ic, journal_entry_tag(ic, je2), &metadata_block, &metadata_offset,
2267                                                         ic->tag_size, TAG_WRITE);
2268                                 if (unlikely(r)) {
2269                                         dm_integrity_io_error(ic, "reading tags", r);
2270                                 }
2271                         }
2272
2273                         atomic_inc(&comp.in_flight);
2274                         copy_from_journal(ic, i, j << ic->sb->log2_sectors_per_block,
2275                                           (k - j) << ic->sb->log2_sectors_per_block,
2276                                           get_data_sector(ic, area, offset),
2277                                           complete_copy_from_journal, io);
2278 skip_io:
2279                         j = next_loop;
2280                 }
2281         }
2282
2283         dm_bufio_write_dirty_buffers_async(ic->bufio);
2284
2285         blk_finish_plug(&plug);
2286
2287         complete_journal_op(&comp);
2288         wait_for_completion_io(&comp.comp);
2289
2290         dm_integrity_flush_buffers(ic);
2291 }
2292
2293 static void integrity_writer(struct work_struct *w)
2294 {
2295         struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, writer_work);
2296         unsigned write_start, write_sections;
2297
2298         unsigned prev_free_sectors;
2299
2300         /* the following test is not needed, but it tests the replay code */
2301         if (unlikely(dm_suspended(ic->ti)) && !ic->meta_dev)
2302                 return;
2303
2304         spin_lock_irq(&ic->endio_wait.lock);
2305         write_start = ic->committed_section;
2306         write_sections = ic->n_committed_sections;
2307         spin_unlock_irq(&ic->endio_wait.lock);
2308
2309         if (!write_sections)
2310                 return;
2311
2312         do_journal_write(ic, write_start, write_sections, false);
2313
2314         spin_lock_irq(&ic->endio_wait.lock);
2315
2316         ic->committed_section += write_sections;
2317         wraparound_section(ic, &ic->committed_section);
2318         ic->n_committed_sections -= write_sections;
2319
2320         prev_free_sectors = ic->free_sectors;
2321         ic->free_sectors += write_sections * ic->journal_section_entries;
2322         if (unlikely(!prev_free_sectors))
2323                 wake_up_locked(&ic->endio_wait);
2324
2325         spin_unlock_irq(&ic->endio_wait.lock);
2326 }
2327
2328 static void recalc_write_super(struct dm_integrity_c *ic)
2329 {
2330         int r;
2331
2332         dm_integrity_flush_buffers(ic);
2333         if (dm_integrity_failed(ic))
2334                 return;
2335
2336         r = sync_rw_sb(ic, REQ_OP_WRITE, 0);
2337         if (unlikely(r))
2338                 dm_integrity_io_error(ic, "writing superblock", r);
2339 }
2340
2341 static void integrity_recalc(struct work_struct *w)
2342 {
2343         struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, recalc_work);
2344         struct dm_integrity_range range;
2345         struct dm_io_request io_req;
2346         struct dm_io_region io_loc;
2347         sector_t area, offset;
2348         sector_t metadata_block;
2349         unsigned metadata_offset;
2350         sector_t logical_sector, n_sectors;
2351         __u8 *t;
2352         unsigned i;
2353         int r;
2354         unsigned super_counter = 0;
2355
2356         DEBUG_print("start recalculation... (position %llx)\n", le64_to_cpu(ic->sb->recalc_sector));
2357
2358         spin_lock_irq(&ic->endio_wait.lock);
2359
2360 next_chunk:
2361
2362         if (unlikely(dm_suspended(ic->ti)))
2363                 goto unlock_ret;
2364
2365         range.logical_sector = le64_to_cpu(ic->sb->recalc_sector);
2366         if (unlikely(range.logical_sector >= ic->provided_data_sectors)) {
2367                 if (ic->mode == 'B') {
2368                         DEBUG_print("queue_delayed_work: bitmap_flush_work\n");
2369                         queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
2370                 }
2371                 goto unlock_ret;
2372         }
2373
2374         get_area_and_offset(ic, range.logical_sector, &area, &offset);
2375         range.n_sectors = min((sector_t)RECALC_SECTORS, ic->provided_data_sectors - range.logical_sector);
2376         if (!ic->meta_dev)
2377                 range.n_sectors = min(range.n_sectors, ((sector_t)1U << ic->sb->log2_interleave_sectors) - (unsigned)offset);
2378
2379         add_new_range_and_wait(ic, &range);
2380         spin_unlock_irq(&ic->endio_wait.lock);
2381         logical_sector = range.logical_sector;
2382         n_sectors = range.n_sectors;
2383
2384         if (ic->mode == 'B') {
2385                 if (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector, n_sectors, BITMAP_OP_TEST_ALL_CLEAR)) {
2386                         goto advance_and_next;
2387                 }
2388                 while (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector,
2389                                        ic->sectors_per_block, BITMAP_OP_TEST_ALL_CLEAR)) {
2390                         logical_sector += ic->sectors_per_block;
2391                         n_sectors -= ic->sectors_per_block;
2392                         cond_resched();
2393                 }
2394                 while (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector + n_sectors - ic->sectors_per_block,
2395                                        ic->sectors_per_block, BITMAP_OP_TEST_ALL_CLEAR)) {
2396                         n_sectors -= ic->sectors_per_block;
2397                         cond_resched();
2398                 }
2399                 get_area_and_offset(ic, logical_sector, &area, &offset);
2400         }
2401
2402         DEBUG_print("recalculating: %lx, %lx\n", logical_sector, n_sectors);
2403
2404         if (unlikely(++super_counter == RECALC_WRITE_SUPER)) {
2405                 recalc_write_super(ic);
2406                 if (ic->mode == 'B') {
2407                         queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, ic->bitmap_flush_interval);
2408                 }
2409                 super_counter = 0;
2410         }
2411
2412         if (unlikely(dm_integrity_failed(ic)))
2413                 goto err;
2414
2415         io_req.bi_op = REQ_OP_READ;
2416         io_req.bi_op_flags = 0;
2417         io_req.mem.type = DM_IO_VMA;
2418         io_req.mem.ptr.addr = ic->recalc_buffer;
2419         io_req.notify.fn = NULL;
2420         io_req.client = ic->io;
2421         io_loc.bdev = ic->dev->bdev;
2422         io_loc.sector = get_data_sector(ic, area, offset);
2423         io_loc.count = n_sectors;
2424
2425         r = dm_io(&io_req, 1, &io_loc, NULL);
2426         if (unlikely(r)) {
2427                 dm_integrity_io_error(ic, "reading data", r);
2428                 goto err;
2429         }
2430
2431         t = ic->recalc_tags;
2432         for (i = 0; i < n_sectors; i += ic->sectors_per_block) {
2433                 integrity_sector_checksum(ic, logical_sector + i, ic->recalc_buffer + (i << SECTOR_SHIFT), t);
2434                 t += ic->tag_size;
2435         }
2436
2437         metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
2438
2439         r = dm_integrity_rw_tag(ic, ic->recalc_tags, &metadata_block, &metadata_offset, t - ic->recalc_tags, TAG_WRITE);
2440         if (unlikely(r)) {
2441                 dm_integrity_io_error(ic, "writing tags", r);
2442                 goto err;
2443         }
2444
2445 advance_and_next:
2446         cond_resched();
2447
2448         spin_lock_irq(&ic->endio_wait.lock);
2449         remove_range_unlocked(ic, &range);
2450         ic->sb->recalc_sector = cpu_to_le64(range.logical_sector + range.n_sectors);
2451         goto next_chunk;
2452
2453 err:
2454         remove_range(ic, &range);
2455         return;
2456
2457 unlock_ret:
2458         spin_unlock_irq(&ic->endio_wait.lock);
2459
2460         recalc_write_super(ic);
2461 }
2462
2463 static void bitmap_block_work(struct work_struct *w)
2464 {
2465         struct bitmap_block_status *bbs = container_of(w, struct bitmap_block_status, work);
2466         struct dm_integrity_c *ic = bbs->ic;
2467         struct bio *bio;
2468         struct bio_list bio_queue;
2469         struct bio_list waiting;
2470
2471         bio_list_init(&waiting);
2472
2473         spin_lock(&bbs->bio_queue_lock);
2474         bio_queue = bbs->bio_queue;
2475         bio_list_init(&bbs->bio_queue);
2476         spin_unlock(&bbs->bio_queue_lock);
2477
2478         while ((bio = bio_list_pop(&bio_queue))) {
2479                 struct dm_integrity_io *dio;
2480
2481                 dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
2482
2483                 if (block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
2484                                     dio->range.n_sectors, BITMAP_OP_TEST_ALL_SET)) {
2485                         remove_range(ic, &dio->range);
2486                         INIT_WORK(&dio->work, integrity_bio_wait);
2487                         queue_work(ic->offload_wq, &dio->work);
2488                 } else {
2489                         block_bitmap_op(ic, ic->journal, dio->range.logical_sector,
2490                                         dio->range.n_sectors, BITMAP_OP_SET);
2491                         bio_list_add(&waiting, bio);
2492                 }
2493         }
2494
2495         if (bio_list_empty(&waiting))
2496                 return;
2497
2498         rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC,
2499                            bbs->idx * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT),
2500                            BITMAP_BLOCK_SIZE >> SECTOR_SHIFT, NULL);
2501
2502         while ((bio = bio_list_pop(&waiting))) {
2503                 struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
2504
2505                 block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
2506                                 dio->range.n_sectors, BITMAP_OP_SET);
2507
2508                 remove_range(ic, &dio->range);
2509                 INIT_WORK(&dio->work, integrity_bio_wait);
2510                 queue_work(ic->offload_wq, &dio->work);
2511         }
2512
2513         queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, ic->bitmap_flush_interval);
2514 }
2515
2516 static void bitmap_flush_work(struct work_struct *work)
2517 {
2518         struct dm_integrity_c *ic = container_of(work, struct dm_integrity_c, bitmap_flush_work.work);
2519         struct dm_integrity_range range;
2520         unsigned long limit;
2521         struct bio *bio;
2522
2523         dm_integrity_flush_buffers(ic);
2524
2525         range.logical_sector = 0;
2526         range.n_sectors = ic->provided_data_sectors;
2527
2528         spin_lock_irq(&ic->endio_wait.lock);
2529         add_new_range_and_wait(ic, &range);
2530         spin_unlock_irq(&ic->endio_wait.lock);
2531
2532         dm_integrity_flush_buffers(ic);
2533         if (ic->meta_dev)
2534                 blkdev_issue_flush(ic->dev->bdev, GFP_NOIO, NULL);
2535
2536         limit = ic->provided_data_sectors;
2537         if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
2538                 limit = le64_to_cpu(ic->sb->recalc_sector)
2539                         >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit)
2540                         << (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
2541         }
2542         /*DEBUG_print("zeroing journal\n");*/
2543         block_bitmap_op(ic, ic->journal, 0, limit, BITMAP_OP_CLEAR);
2544         block_bitmap_op(ic, ic->may_write_bitmap, 0, limit, BITMAP_OP_CLEAR);
2545
2546         rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, 0,
2547                            ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
2548
2549         spin_lock_irq(&ic->endio_wait.lock);
2550         remove_range_unlocked(ic, &range);
2551         while (unlikely((bio = bio_list_pop(&ic->synchronous_bios)) != NULL)) {
2552                 bio_endio(bio);
2553                 spin_unlock_irq(&ic->endio_wait.lock);
2554                 spin_lock_irq(&ic->endio_wait.lock);
2555         }
2556         spin_unlock_irq(&ic->endio_wait.lock);
2557 }
2558
2559
2560 static void init_journal(struct dm_integrity_c *ic, unsigned start_section,
2561                          unsigned n_sections, unsigned char commit_seq)
2562 {
2563         unsigned i, j, n;
2564
2565         if (!n_sections)
2566                 return;
2567
2568         for (n = 0; n < n_sections; n++) {
2569                 i = start_section + n;
2570                 wraparound_section(ic, &i);
2571                 for (j = 0; j < ic->journal_section_sectors; j++) {
2572                         struct journal_sector *js = access_journal(ic, i, j);
2573                         memset(&js->entries, 0, JOURNAL_SECTOR_DATA);
2574                         js->commit_id = dm_integrity_commit_id(ic, i, j, commit_seq);
2575                 }
2576                 for (j = 0; j < ic->journal_section_entries; j++) {
2577                         struct journal_entry *je = access_journal_entry(ic, i, j);
2578                         journal_entry_set_unused(je);
2579                 }
2580         }
2581
2582         write_journal(ic, start_section, n_sections);
2583 }
2584
2585 static int find_commit_seq(struct dm_integrity_c *ic, unsigned i, unsigned j, commit_id_t id)
2586 {
2587         unsigned char k;
2588         for (k = 0; k < N_COMMIT_IDS; k++) {
2589                 if (dm_integrity_commit_id(ic, i, j, k) == id)
2590                         return k;
2591         }
2592         dm_integrity_io_error(ic, "journal commit id", -EIO);
2593         return -EIO;
2594 }
2595
2596 static void replay_journal(struct dm_integrity_c *ic)
2597 {
2598         unsigned i, j;
2599         bool used_commit_ids[N_COMMIT_IDS];
2600         unsigned max_commit_id_sections[N_COMMIT_IDS];
2601         unsigned write_start, write_sections;
2602         unsigned continue_section;
2603         bool journal_empty;
2604         unsigned char unused, last_used, want_commit_seq;
2605
2606         if (ic->mode == 'R')
2607                 return;
2608
2609         if (ic->journal_uptodate)
2610                 return;
2611
2612         last_used = 0;
2613         write_start = 0;
2614
2615         if (!ic->just_formatted) {
2616                 DEBUG_print("reading journal\n");
2617                 rw_journal(ic, REQ_OP_READ, 0, 0, ic->journal_sections, NULL);
2618                 if (ic->journal_io)
2619                         DEBUG_bytes(lowmem_page_address(ic->journal_io[0].page), 64, "read journal");
2620                 if (ic->journal_io) {
2621                         struct journal_completion crypt_comp;
2622                         crypt_comp.ic = ic;
2623                         init_completion(&crypt_comp.comp);
2624                         crypt_comp.in_flight = (atomic_t)ATOMIC_INIT(0);
2625                         encrypt_journal(ic, false, 0, ic->journal_sections, &crypt_comp);
2626                         wait_for_completion(&crypt_comp.comp);
2627                 }
2628                 DEBUG_bytes(lowmem_page_address(ic->journal[0].page), 64, "decrypted journal");
2629         }
2630
2631         if (dm_integrity_failed(ic))
2632                 goto clear_journal;
2633
2634         journal_empty = true;
2635         memset(used_commit_ids, 0, sizeof used_commit_ids);
2636         memset(max_commit_id_sections, 0, sizeof max_commit_id_sections);
2637         for (i = 0; i < ic->journal_sections; i++) {
2638                 for (j = 0; j < ic->journal_section_sectors; j++) {
2639                         int k;
2640                         struct journal_sector *js = access_journal(ic, i, j);
2641                         k = find_commit_seq(ic, i, j, js->commit_id);
2642                         if (k < 0)
2643                                 goto clear_journal;
2644                         used_commit_ids[k] = true;
2645                         max_commit_id_sections[k] = i;
2646                 }
2647                 if (journal_empty) {
2648                         for (j = 0; j < ic->journal_section_entries; j++) {
2649                                 struct journal_entry *je = access_journal_entry(ic, i, j);
2650                                 if (!journal_entry_is_unused(je)) {
2651                                         journal_empty = false;
2652                                         break;
2653                                 }
2654                         }
2655                 }
2656         }
2657
2658         if (!used_commit_ids[N_COMMIT_IDS - 1]) {
2659                 unused = N_COMMIT_IDS - 1;
2660                 while (unused && !used_commit_ids[unused - 1])
2661                         unused--;
2662         } else {
2663                 for (unused = 0; unused < N_COMMIT_IDS; unused++)
2664                         if (!used_commit_ids[unused])
2665                                 break;
2666                 if (unused == N_COMMIT_IDS) {
2667                         dm_integrity_io_error(ic, "journal commit ids", -EIO);
2668                         goto clear_journal;
2669                 }
2670         }
2671         DEBUG_print("first unused commit seq %d [%d,%d,%d,%d]\n",
2672                     unused, used_commit_ids[0], used_commit_ids[1],
2673                     used_commit_ids[2], used_commit_ids[3]);
2674
2675         last_used = prev_commit_seq(unused);
2676         want_commit_seq = prev_commit_seq(last_used);
2677
2678         if (!used_commit_ids[want_commit_seq] && used_commit_ids[prev_commit_seq(want_commit_seq)])
2679                 journal_empty = true;
2680
2681         write_start = max_commit_id_sections[last_used] + 1;
2682         if (unlikely(write_start >= ic->journal_sections))
2683                 want_commit_seq = next_commit_seq(want_commit_seq);
2684         wraparound_section(ic, &write_start);
2685
2686         i = write_start;
2687         for (write_sections = 0; write_sections < ic->journal_sections; write_sections++) {
2688                 for (j = 0; j < ic->journal_section_sectors; j++) {
2689                         struct journal_sector *js = access_journal(ic, i, j);
2690
2691                         if (js->commit_id != dm_integrity_commit_id(ic, i, j, want_commit_seq)) {
2692                                 /*
2693                                  * This could be caused by crash during writing.
2694                                  * We won't replay the inconsistent part of the
2695                                  * journal.
2696                                  */
2697                                 DEBUG_print("commit id mismatch at position (%u, %u): %d != %d\n",
2698                                             i, j, find_commit_seq(ic, i, j, js->commit_id), want_commit_seq);
2699                                 goto brk;
2700                         }
2701                 }
2702                 i++;
2703                 if (unlikely(i >= ic->journal_sections))
2704                         want_commit_seq = next_commit_seq(want_commit_seq);
2705                 wraparound_section(ic, &i);
2706         }
2707 brk:
2708
2709         if (!journal_empty) {
2710                 DEBUG_print("replaying %u sections, starting at %u, commit seq %d\n",
2711                             write_sections, write_start, want_commit_seq);
2712                 do_journal_write(ic, write_start, write_sections, true);
2713         }
2714
2715         if (write_sections == ic->journal_sections && (ic->mode == 'J' || journal_empty)) {
2716                 continue_section = write_start;
2717                 ic->commit_seq = want_commit_seq;
2718                 DEBUG_print("continuing from section %u, commit seq %d\n", write_start, ic->commit_seq);
2719         } else {
2720                 unsigned s;
2721                 unsigned char erase_seq;
2722 clear_journal:
2723                 DEBUG_print("clearing journal\n");
2724
2725                 erase_seq = prev_commit_seq(prev_commit_seq(last_used));
2726                 s = write_start;
2727                 init_journal(ic, s, 1, erase_seq);
2728                 s++;
2729                 wraparound_section(ic, &s);
2730                 if (ic->journal_sections >= 2) {
2731                         init_journal(ic, s, ic->journal_sections - 2, erase_seq);
2732                         s += ic->journal_sections - 2;
2733                         wraparound_section(ic, &s);
2734                         init_journal(ic, s, 1, erase_seq);
2735                 }
2736
2737                 continue_section = 0;
2738                 ic->commit_seq = next_commit_seq(erase_seq);
2739         }
2740
2741         ic->committed_section = continue_section;
2742         ic->n_committed_sections = 0;
2743
2744         ic->uncommitted_section = continue_section;
2745         ic->n_uncommitted_sections = 0;
2746
2747         ic->free_section = continue_section;
2748         ic->free_section_entry = 0;
2749         ic->free_sectors = ic->journal_entries;
2750
2751         ic->journal_tree_root = RB_ROOT;
2752         for (i = 0; i < ic->journal_entries; i++)
2753                 init_journal_node(&ic->journal_tree[i]);
2754 }
2755
2756 static void dm_integrity_enter_synchronous_mode(struct dm_integrity_c *ic)
2757 {
2758         DEBUG_print("dm_integrity_enter_synchronous_mode\n");
2759
2760         if (ic->mode == 'B') {
2761                 ic->bitmap_flush_interval = msecs_to_jiffies(10) + 1;
2762                 ic->synchronous_mode = 1;
2763
2764                 cancel_delayed_work_sync(&ic->bitmap_flush_work);
2765                 queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
2766                 flush_workqueue(ic->commit_wq);
2767         }
2768 }
2769
2770 static int dm_integrity_reboot(struct notifier_block *n, unsigned long code, void *x)
2771 {
2772         struct dm_integrity_c *ic = container_of(n, struct dm_integrity_c, reboot_notifier);
2773
2774         DEBUG_print("dm_integrity_reboot\n");
2775
2776         dm_integrity_enter_synchronous_mode(ic);
2777
2778         return NOTIFY_DONE;
2779 }
2780
2781 static void dm_integrity_postsuspend(struct dm_target *ti)
2782 {
2783         struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2784         int r;
2785
2786         WARN_ON(unregister_reboot_notifier(&ic->reboot_notifier));
2787
2788         del_timer_sync(&ic->autocommit_timer);
2789
2790         if (ic->recalc_wq)
2791                 drain_workqueue(ic->recalc_wq);
2792
2793         if (ic->mode == 'B')
2794                 cancel_delayed_work_sync(&ic->bitmap_flush_work);
2795
2796         queue_work(ic->commit_wq, &ic->commit_work);
2797         drain_workqueue(ic->commit_wq);
2798
2799         if (ic->mode == 'J') {
2800                 if (ic->meta_dev)
2801                         queue_work(ic->writer_wq, &ic->writer_work);
2802                 drain_workqueue(ic->writer_wq);
2803                 dm_integrity_flush_buffers(ic);
2804         }
2805
2806         if (ic->mode == 'B') {
2807                 dm_integrity_flush_buffers(ic);
2808 #if 1
2809                 /* set to 0 to test bitmap replay code */
2810                 init_journal(ic, 0, ic->journal_sections, 0);
2811                 ic->sb->flags &= ~cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
2812                 r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
2813                 if (unlikely(r))
2814                         dm_integrity_io_error(ic, "writing superblock", r);
2815 #endif
2816         }
2817
2818         BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
2819
2820         ic->journal_uptodate = true;
2821 }
2822
2823 static void dm_integrity_resume(struct dm_target *ti)
2824 {
2825         struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2826         int r;
2827         DEBUG_print("resume\n");
2828
2829         if (ic->sb->flags & cpu_to_le32(SB_FLAG_DIRTY_BITMAP)) {
2830                 DEBUG_print("resume dirty_bitmap\n");
2831                 rw_journal_sectors(ic, REQ_OP_READ, 0, 0,
2832                                    ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
2833                 if (ic->mode == 'B') {
2834                         if (ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit) {
2835                                 block_bitmap_copy(ic, ic->recalc_bitmap, ic->journal);
2836                                 block_bitmap_copy(ic, ic->may_write_bitmap, ic->journal);
2837                                 if (!block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors,
2838                                                      BITMAP_OP_TEST_ALL_CLEAR)) {
2839                                         ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
2840                                         ic->sb->recalc_sector = cpu_to_le64(0);
2841                                 }
2842                         } else {
2843                                 DEBUG_print("non-matching blocks_per_bitmap_bit: %u, %u\n",
2844                                             ic->sb->log2_blocks_per_bitmap_bit, ic->log2_blocks_per_bitmap_bit);
2845                                 ic->sb->log2_blocks_per_bitmap_bit = ic->log2_blocks_per_bitmap_bit;
2846                                 block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_SET);
2847                                 block_bitmap_op(ic, ic->may_write_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_SET);
2848                                 block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_SET);
2849                                 rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, 0,
2850                                                    ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
2851                                 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
2852                                 ic->sb->recalc_sector = cpu_to_le64(0);
2853                         }
2854                 } else {
2855                         if (!(ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit &&
2856                               block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_TEST_ALL_CLEAR))) {
2857                                 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
2858                                 ic->sb->recalc_sector = cpu_to_le64(0);
2859                         }
2860                         init_journal(ic, 0, ic->journal_sections, 0);
2861                         replay_journal(ic);
2862                         ic->sb->flags &= ~cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
2863                 }
2864                 r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
2865                 if (unlikely(r))
2866                         dm_integrity_io_error(ic, "writing superblock", r);
2867         } else {
2868                 replay_journal(ic);
2869                 if (ic->mode == 'B') {
2870                         ic->sb->flags |= cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
2871                         ic->sb->log2_blocks_per_bitmap_bit = ic->log2_blocks_per_bitmap_bit;
2872                         r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
2873                         if (unlikely(r))
2874                                 dm_integrity_io_error(ic, "writing superblock", r);
2875
2876                         block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
2877                         block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
2878                         block_bitmap_op(ic, ic->may_write_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
2879                         if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
2880                             le64_to_cpu(ic->sb->recalc_sector) < ic->provided_data_sectors) {
2881                                 block_bitmap_op(ic, ic->journal, le64_to_cpu(ic->sb->recalc_sector),
2882                                                 ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
2883                                 block_bitmap_op(ic, ic->recalc_bitmap, le64_to_cpu(ic->sb->recalc_sector),
2884                                                 ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
2885                                 block_bitmap_op(ic, ic->may_write_bitmap, le64_to_cpu(ic->sb->recalc_sector),
2886                                                 ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
2887                         }
2888                         rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, 0,
2889                                            ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
2890                 }
2891         }
2892
2893         DEBUG_print("testing recalc: %x\n", ic->sb->flags);
2894         if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
2895                 __u64 recalc_pos = le64_to_cpu(ic->sb->recalc_sector);
2896                 DEBUG_print("recalc pos: %lx / %lx\n", (long)recalc_pos, ic->provided_data_sectors);
2897                 if (recalc_pos < ic->provided_data_sectors) {
2898                         queue_work(ic->recalc_wq, &ic->recalc_work);
2899                 } else if (recalc_pos > ic->provided_data_sectors) {
2900                         ic->sb->recalc_sector = cpu_to_le64(ic->provided_data_sectors);
2901                         recalc_write_super(ic);
2902                 }
2903         }
2904
2905         ic->reboot_notifier.notifier_call = dm_integrity_reboot;
2906         ic->reboot_notifier.next = NULL;
2907         ic->reboot_notifier.priority = INT_MAX - 1;     /* be notified after md and before hardware drivers */
2908         WARN_ON(register_reboot_notifier(&ic->reboot_notifier));
2909
2910 #if 0
2911         /* set to 1 to stress test synchronous mode */
2912         dm_integrity_enter_synchronous_mode(ic);
2913 #endif
2914 }
2915
2916 static void dm_integrity_status(struct dm_target *ti, status_type_t type,
2917                                 unsigned status_flags, char *result, unsigned maxlen)
2918 {
2919         struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
2920         unsigned arg_count;
2921         size_t sz = 0;
2922
2923         switch (type) {
2924         case STATUSTYPE_INFO:
2925                 DMEMIT("%llu %llu",
2926                         (unsigned long long)atomic64_read(&ic->number_of_mismatches),
2927                         (unsigned long long)ic->provided_data_sectors);
2928                 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
2929                         DMEMIT(" %llu", (unsigned long long)le64_to_cpu(ic->sb->recalc_sector));
2930                 else
2931                         DMEMIT(" -");
2932                 break;
2933
2934         case STATUSTYPE_TABLE: {
2935                 __u64 watermark_percentage = (__u64)(ic->journal_entries - ic->free_sectors_threshold) * 100;
2936                 watermark_percentage += ic->journal_entries / 2;
2937                 do_div(watermark_percentage, ic->journal_entries);
2938                 arg_count = 3;
2939                 arg_count += !!ic->meta_dev;
2940                 arg_count += ic->sectors_per_block != 1;
2941                 arg_count += !!(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING));
2942                 arg_count += ic->mode == 'J';
2943                 arg_count += ic->mode == 'J';
2944                 arg_count += ic->mode == 'B';
2945                 arg_count += ic->mode == 'B';
2946                 arg_count += !!ic->internal_hash_alg.alg_string;
2947                 arg_count += !!ic->journal_crypt_alg.alg_string;
2948                 arg_count += !!ic->journal_mac_alg.alg_string;
2949                 DMEMIT("%s %llu %u %c %u", ic->dev->name, (unsigned long long)ic->start,
2950                        ic->tag_size, ic->mode, arg_count);
2951                 if (ic->meta_dev)
2952                         DMEMIT(" meta_device:%s", ic->meta_dev->name);
2953                 if (ic->sectors_per_block != 1)
2954                         DMEMIT(" block_size:%u", ic->sectors_per_block << SECTOR_SHIFT);
2955                 if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
2956                         DMEMIT(" recalculate");
2957                 DMEMIT(" journal_sectors:%u", ic->initial_sectors - SB_SECTORS);
2958                 DMEMIT(" interleave_sectors:%u", 1U << ic->sb->log2_interleave_sectors);
2959                 DMEMIT(" buffer_sectors:%u", 1U << ic->log2_buffer_sectors);
2960                 if (ic->mode == 'J') {
2961                         DMEMIT(" journal_watermark:%u", (unsigned)watermark_percentage);
2962                         DMEMIT(" commit_time:%u", ic->autocommit_msec);
2963                 }
2964                 if (ic->mode == 'B') {
2965                         DMEMIT(" sectors_per_bit:%llu", (unsigned long long)ic->sectors_per_block << ic->log2_blocks_per_bitmap_bit);
2966                         DMEMIT(" bitmap_flush_interval:%u", jiffies_to_msecs(ic->bitmap_flush_interval));
2967                 }
2968
2969 #define EMIT_ALG(a, n)                                                  \
2970                 do {                                                    \
2971                         if (ic->a.alg_string) {                         \
2972                                 DMEMIT(" %s:%s", n, ic->a.alg_string);  \
2973                                 if (ic->a.key_string)                   \
2974                                         DMEMIT(":%s", ic->a.key_string);\
2975                         }                                               \
2976                 } while (0)
2977                 EMIT_ALG(internal_hash_alg, "internal_hash");
2978                 EMIT_ALG(journal_crypt_alg, "journal_crypt");
2979                 EMIT_ALG(journal_mac_alg, "journal_mac");
2980                 break;
2981         }
2982         }
2983 }
2984
2985 static int dm_integrity_iterate_devices(struct dm_target *ti,
2986                                         iterate_devices_callout_fn fn, void *data)
2987 {
2988         struct dm_integrity_c *ic = ti->private;
2989
2990         if (!ic->meta_dev)
2991                 return fn(ti, ic->dev, ic->start + ic->initial_sectors + ic->metadata_run, ti->len, data);
2992         else
2993                 return fn(ti, ic->dev, 0, ti->len, data);
2994 }
2995
2996 static void dm_integrity_io_hints(struct dm_target *ti, struct queue_limits *limits)
2997 {
2998         struct dm_integrity_c *ic = ti->private;
2999
3000         if (ic->sectors_per_block > 1) {
3001                 limits->logical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
3002                 limits->physical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
3003                 blk_limits_io_min(limits, ic->sectors_per_block << SECTOR_SHIFT);
3004         }
3005 }
3006
3007 static void calculate_journal_section_size(struct dm_integrity_c *ic)
3008 {
3009         unsigned sector_space = JOURNAL_SECTOR_DATA;
3010
3011         ic->journal_sections = le32_to_cpu(ic->sb->journal_sections);
3012         ic->journal_entry_size = roundup(offsetof(struct journal_entry, last_bytes[ic->sectors_per_block]) + ic->tag_size,
3013                                          JOURNAL_ENTRY_ROUNDUP);
3014
3015         if (ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC))
3016                 sector_space -= JOURNAL_MAC_PER_SECTOR;
3017         ic->journal_entries_per_sector = sector_space / ic->journal_entry_size;
3018         ic->journal_section_entries = ic->journal_entries_per_sector * JOURNAL_BLOCK_SECTORS;
3019         ic->journal_section_sectors = (ic->journal_section_entries << ic->sb->log2_sectors_per_block) + JOURNAL_BLOCK_SECTORS;
3020         ic->journal_entries = ic->journal_section_entries * ic->journal_sections;
3021 }
3022
3023 static int calculate_device_limits(struct dm_integrity_c *ic)
3024 {
3025         __u64 initial_sectors;
3026
3027         calculate_journal_section_size(ic);
3028         initial_sectors = SB_SECTORS + (__u64)ic->journal_section_sectors * ic->journal_sections;
3029         if (initial_sectors + METADATA_PADDING_SECTORS >= ic->meta_device_sectors || initial_sectors > UINT_MAX)
3030                 return -EINVAL;
3031         ic->initial_sectors = initial_sectors;
3032
3033         if (!ic->meta_dev) {
3034                 sector_t last_sector, last_area, last_offset;
3035
3036                 ic->metadata_run = roundup((__u64)ic->tag_size << (ic->sb->log2_interleave_sectors - ic->sb->log2_sectors_per_block),
3037                                            (__u64)(1 << SECTOR_SHIFT << METADATA_PADDING_SECTORS)) >> SECTOR_SHIFT;
3038                 if (!(ic->metadata_run & (ic->metadata_run - 1)))
3039                         ic->log2_metadata_run = __ffs(ic->metadata_run);
3040                 else
3041                         ic->log2_metadata_run = -1;
3042
3043                 get_area_and_offset(ic, ic->provided_data_sectors - 1, &last_area, &last_offset);
3044                 last_sector = get_data_sector(ic, last_area, last_offset);
3045                 if (last_sector < ic->start || last_sector >= ic->meta_device_sectors)
3046                         return -EINVAL;
3047         } else {
3048                 __u64 meta_size = (ic->provided_data_sectors >> ic->sb->log2_sectors_per_block) * ic->tag_size;
3049                 meta_size = (meta_size + ((1U << (ic->log2_buffer_sectors + SECTOR_SHIFT)) - 1))
3050                                 >> (ic->log2_buffer_sectors + SECTOR_SHIFT);
3051                 meta_size <<= ic->log2_buffer_sectors;
3052                 if (ic->initial_sectors + meta_size < ic->initial_sectors ||
3053                     ic->initial_sectors + meta_size > ic->meta_device_sectors)
3054                         return -EINVAL;
3055                 ic->metadata_run = 1;
3056                 ic->log2_metadata_run = 0;
3057         }
3058
3059         return 0;
3060 }
3061
3062 static int initialize_superblock(struct dm_integrity_c *ic, unsigned journal_sectors, unsigned interleave_sectors)
3063 {
3064         unsigned journal_sections;
3065         int test_bit;
3066
3067         memset(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT);
3068         memcpy(ic->sb->magic, SB_MAGIC, 8);
3069         ic->sb->integrity_tag_size = cpu_to_le16(ic->tag_size);
3070         ic->sb->log2_sectors_per_block = __ffs(ic->sectors_per_block);
3071         if (ic->journal_mac_alg.alg_string)
3072                 ic->sb->flags |= cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC);
3073
3074         calculate_journal_section_size(ic);
3075         journal_sections = journal_sectors / ic->journal_section_sectors;
3076         if (!journal_sections)
3077                 journal_sections = 1;
3078
3079         if (!ic->meta_dev) {
3080                 ic->sb->journal_sections = cpu_to_le32(journal_sections);
3081                 if (!interleave_sectors)
3082                         interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
3083                 ic->sb->log2_interleave_sectors = __fls(interleave_sectors);
3084                 ic->sb->log2_interleave_sectors = max((__u8)MIN_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
3085                 ic->sb->log2_interleave_sectors = min((__u8)MAX_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
3086
3087                 ic->provided_data_sectors = 0;
3088                 for (test_bit = fls64(ic->meta_device_sectors) - 1; test_bit >= 3; test_bit--) {
3089                         __u64 prev_data_sectors = ic->provided_data_sectors;
3090
3091                         ic->provided_data_sectors |= (sector_t)1 << test_bit;
3092                         if (calculate_device_limits(ic))
3093                                 ic->provided_data_sectors = prev_data_sectors;
3094                 }
3095                 if (!ic->provided_data_sectors)
3096                         return -EINVAL;
3097         } else {
3098                 ic->sb->log2_interleave_sectors = 0;
3099                 ic->provided_data_sectors = ic->data_device_sectors;
3100                 ic->provided_data_sectors &= ~(sector_t)(ic->sectors_per_block - 1);
3101
3102 try_smaller_buffer:
3103                 ic->sb->journal_sections = cpu_to_le32(0);
3104                 for (test_bit = fls(journal_sections) - 1; test_bit >= 0; test_bit--) {
3105                         __u32 prev_journal_sections = le32_to_cpu(ic->sb->journal_sections);
3106                         __u32 test_journal_sections = prev_journal_sections | (1U << test_bit);
3107                         if (test_journal_sections > journal_sections)
3108                                 continue;
3109                         ic->sb->journal_sections = cpu_to_le32(test_journal_sections);
3110                         if (calculate_device_limits(ic))
3111                                 ic->sb->journal_sections = cpu_to_le32(prev_journal_sections);
3112
3113                 }
3114                 if (!le32_to_cpu(ic->sb->journal_sections)) {
3115                         if (ic->log2_buffer_sectors > 3) {
3116                                 ic->log2_buffer_sectors--;
3117                                 goto try_smaller_buffer;
3118                         }
3119                         return -EINVAL;
3120                 }
3121         }
3122
3123         ic->sb->provided_data_sectors = cpu_to_le64(ic->provided_data_sectors);
3124
3125         sb_set_version(ic);
3126
3127         return 0;
3128 }
3129
3130 static void dm_integrity_set(struct dm_target *ti, struct dm_integrity_c *ic)
3131 {
3132         struct gendisk *disk = dm_disk(dm_table_get_md(ti->table));
3133         struct blk_integrity bi;
3134
3135         memset(&bi, 0, sizeof(bi));
3136         bi.profile = &dm_integrity_profile;
3137         bi.tuple_size = ic->tag_size;
3138         bi.tag_size = bi.tuple_size;
3139         bi.interval_exp = ic->sb->log2_sectors_per_block + SECTOR_SHIFT;
3140
3141         blk_integrity_register(disk, &bi);
3142         blk_queue_max_integrity_segments(disk->queue, UINT_MAX);
3143 }
3144
3145 static void dm_integrity_free_page_list(struct page_list *pl)
3146 {
3147         unsigned i;
3148
3149         if (!pl)
3150                 return;
3151         for (i = 0; pl[i].page; i++)
3152                 __free_page(pl[i].page);
3153         kvfree(pl);
3154 }
3155
3156 static struct page_list *dm_integrity_alloc_page_list(unsigned n_pages)
3157 {
3158         struct page_list *pl;
3159         unsigned i;
3160
3161         pl = kvmalloc_array(n_pages + 1, sizeof(struct page_list), GFP_KERNEL | __GFP_ZERO);
3162         if (!pl)
3163                 return NULL;
3164
3165         for (i = 0; i < n_pages; i++) {
3166                 pl[i].page = alloc_page(GFP_KERNEL);
3167                 if (!pl[i].page) {
3168                         dm_integrity_free_page_list(pl);
3169                         return NULL;
3170                 }
3171                 if (i)
3172                         pl[i - 1].next = &pl[i];
3173         }
3174         pl[i].page = NULL;
3175         pl[i].next = NULL;
3176
3177         return pl;
3178 }
3179
3180 static void dm_integrity_free_journal_scatterlist(struct dm_integrity_c *ic, struct scatterlist **sl)
3181 {
3182         unsigned i;
3183         for (i = 0; i < ic->journal_sections; i++)
3184                 kvfree(sl[i]);
3185         kvfree(sl);
3186 }
3187
3188 static struct scatterlist **dm_integrity_alloc_journal_scatterlist(struct dm_integrity_c *ic,
3189                                                                    struct page_list *pl)
3190 {
3191         struct scatterlist **sl;
3192         unsigned i;
3193
3194         sl = kvmalloc_array(ic->journal_sections,
3195                             sizeof(struct scatterlist *),
3196                             GFP_KERNEL | __GFP_ZERO);
3197         if (!sl)
3198                 return NULL;
3199
3200         for (i = 0; i < ic->journal_sections; i++) {
3201                 struct scatterlist *s;
3202                 unsigned start_index, start_offset;
3203                 unsigned end_index, end_offset;
3204                 unsigned n_pages;
3205                 unsigned idx;
3206
3207                 page_list_location(ic, i, 0, &start_index, &start_offset);
3208                 page_list_location(ic, i, ic->journal_section_sectors - 1,
3209                                    &end_index, &end_offset);
3210
3211                 n_pages = (end_index - start_index + 1);
3212
3213                 s = kvmalloc_array(n_pages, sizeof(struct scatterlist),
3214                                    GFP_KERNEL);
3215                 if (!s) {
3216                         dm_integrity_free_journal_scatterlist(ic, sl);
3217                         return NULL;
3218                 }
3219
3220                 sg_init_table(s, n_pages);
3221                 for (idx = start_index; idx <= end_index; idx++) {
3222                         char *va = lowmem_page_address(pl[idx].page);
3223                         unsigned start = 0, end = PAGE_SIZE;
3224                         if (idx == start_index)
3225                                 start = start_offset;
3226                         if (idx == end_index)
3227                                 end = end_offset + (1 << SECTOR_SHIFT);
3228                         sg_set_buf(&s[idx - start_index], va + start, end - start);
3229                 }
3230
3231                 sl[i] = s;
3232         }
3233
3234         return sl;
3235 }
3236
3237 static void free_alg(struct alg_spec *a)
3238 {
3239         kzfree(a->alg_string);
3240         kzfree(a->key);
3241         memset(a, 0, sizeof *a);
3242 }
3243
3244 static int get_alg_and_key(const char *arg, struct alg_spec *a, char **error, char *error_inval)
3245 {
3246         char *k;
3247
3248         free_alg(a);
3249
3250         a->alg_string = kstrdup(strchr(arg, ':') + 1, GFP_KERNEL);
3251         if (!a->alg_string)
3252                 goto nomem;
3253
3254         k = strchr(a->alg_string, ':');
3255         if (k) {
3256                 *k = 0;
3257                 a->key_string = k + 1;
3258                 if (strlen(a->key_string) & 1)
3259                         goto inval;
3260
3261                 a->key_size = strlen(a->key_string) / 2;
3262                 a->key = kmalloc(a->key_size, GFP_KERNEL);
3263                 if (!a->key)
3264                         goto nomem;
3265                 if (hex2bin(a->key, a->key_string, a->key_size))
3266                         goto inval;
3267         }
3268
3269         return 0;
3270 inval:
3271         *error = error_inval;
3272         return -EINVAL;
3273 nomem:
3274         *error = "Out of memory for an argument";
3275         return -ENOMEM;
3276 }
3277
3278 static int get_mac(struct crypto_shash **hash, struct alg_spec *a, char **error,
3279                    char *error_alg, char *error_key)
3280 {
3281         int r;
3282
3283         if (a->alg_string) {
3284                 *hash = crypto_alloc_shash(a->alg_string, 0, 0);
3285                 if (IS_ERR(*hash)) {
3286                         *error = error_alg;
3287                         r = PTR_ERR(*hash);
3288                         *hash = NULL;
3289                         return r;
3290                 }
3291
3292                 if (a->key) {
3293                         r = crypto_shash_setkey(*hash, a->key, a->key_size);
3294                         if (r) {
3295                                 *error = error_key;
3296                                 return r;
3297                         }
3298                 } else if (crypto_shash_get_flags(*hash) & CRYPTO_TFM_NEED_KEY) {
3299                         *error = error_key;
3300                         return -ENOKEY;
3301                 }
3302         }
3303
3304         return 0;
3305 }
3306
3307 static int create_journal(struct dm_integrity_c *ic, char **error)
3308 {
3309         int r = 0;
3310         unsigned i;
3311         __u64 journal_pages, journal_desc_size, journal_tree_size;
3312         unsigned char *crypt_data = NULL, *crypt_iv = NULL;
3313         struct skcipher_request *req = NULL;
3314
3315         ic->commit_ids[0] = cpu_to_le64(0x1111111111111111ULL);
3316         ic->commit_ids[1] = cpu_to_le64(0x2222222222222222ULL);
3317         ic->commit_ids[2] = cpu_to_le64(0x3333333333333333ULL);
3318         ic->commit_ids[3] = cpu_to_le64(0x4444444444444444ULL);
3319
3320         journal_pages = roundup((__u64)ic->journal_sections * ic->journal_section_sectors,
3321                                 PAGE_SIZE >> SECTOR_SHIFT) >> (PAGE_SHIFT - SECTOR_SHIFT);
3322         journal_desc_size = journal_pages * sizeof(struct page_list);
3323         if (journal_pages >= totalram_pages() - totalhigh_pages() || journal_desc_size > ULONG_MAX) {
3324                 *error = "Journal doesn't fit into memory";
3325                 r = -ENOMEM;
3326                 goto bad;
3327         }
3328         ic->journal_pages = journal_pages;
3329
3330         ic->journal = dm_integrity_alloc_page_list(ic->journal_pages);
3331         if (!ic->journal) {
3332                 *error = "Could not allocate memory for journal";
3333                 r = -ENOMEM;
3334                 goto bad;
3335         }
3336         if (ic->journal_crypt_alg.alg_string) {
3337                 unsigned ivsize, blocksize;
3338                 struct journal_completion comp;
3339
3340                 comp.ic = ic;
3341                 ic->journal_crypt = crypto_alloc_skcipher(ic->journal_crypt_alg.alg_string, 0, 0);
3342                 if (IS_ERR(ic->journal_crypt)) {
3343                         *error = "Invalid journal cipher";
3344                         r = PTR_ERR(ic->journal_crypt);
3345                         ic->journal_crypt = NULL;
3346                         goto bad;
3347                 }
3348                 ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
3349                 blocksize = crypto_skcipher_blocksize(ic->journal_crypt);
3350
3351                 if (ic->journal_crypt_alg.key) {
3352                         r = crypto_skcipher_setkey(ic->journal_crypt, ic->journal_crypt_alg.key,
3353                                                    ic->journal_crypt_alg.key_size);
3354                         if (r) {
3355                                 *error = "Error setting encryption key";
3356                                 goto bad;
3357                         }
3358                 }
3359                 DEBUG_print("cipher %s, block size %u iv size %u\n",
3360                             ic->journal_crypt_alg.alg_string, blocksize, ivsize);
3361
3362                 ic->journal_io = dm_integrity_alloc_page_list(ic->journal_pages);
3363                 if (!ic->journal_io) {
3364                         *error = "Could not allocate memory for journal io";
3365                         r = -ENOMEM;
3366                         goto bad;
3367                 }
3368
3369                 if (blocksize == 1) {
3370                         struct scatterlist *sg;
3371
3372                         req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
3373                         if (!req) {
3374                                 *error = "Could not allocate crypt request";
3375                                 r = -ENOMEM;
3376                                 goto bad;
3377                         }
3378
3379                         crypt_iv = kzalloc(ivsize, GFP_KERNEL);
3380                         if (!crypt_iv) {
3381                                 *error = "Could not allocate iv";
3382                                 r = -ENOMEM;
3383                                 goto bad;
3384                         }
3385
3386                         ic->journal_xor = dm_integrity_alloc_page_list(ic->journal_pages);
3387                         if (!ic->journal_xor) {
3388                                 *error = "Could not allocate memory for journal xor";
3389                                 r = -ENOMEM;
3390                                 goto bad;
3391                         }
3392
3393                         sg = kvmalloc_array(ic->journal_pages + 1,
3394                                             sizeof(struct scatterlist),
3395                                             GFP_KERNEL);
3396                         if (!sg) {
3397                                 *error = "Unable to allocate sg list";
3398                                 r = -ENOMEM;
3399                                 goto bad;
3400                         }
3401                         sg_init_table(sg, ic->journal_pages + 1);
3402                         for (i = 0; i < ic->journal_pages; i++) {
3403                                 char *va = lowmem_page_address(ic->journal_xor[i].page);
3404                                 clear_page(va);
3405                                 sg_set_buf(&sg[i], va, PAGE_SIZE);
3406                         }
3407                         sg_set_buf(&sg[i], &ic->commit_ids, sizeof ic->commit_ids);
3408
3409                         skcipher_request_set_crypt(req, sg, sg,
3410                                                    PAGE_SIZE * ic->journal_pages + sizeof ic->commit_ids, crypt_iv);
3411                         init_completion(&comp.comp);
3412                         comp.in_flight = (atomic_t)ATOMIC_INIT(1);
3413                         if (do_crypt(true, req, &comp))
3414                                 wait_for_completion(&comp.comp);
3415                         kvfree(sg);
3416                         r = dm_integrity_failed(ic);
3417                         if (r) {
3418                                 *error = "Unable to encrypt journal";
3419                                 goto bad;
3420                         }
3421                         DEBUG_bytes(lowmem_page_address(ic->journal_xor[0].page), 64, "xor data");
3422
3423                         crypto_free_skcipher(ic->journal_crypt);
3424                         ic->journal_crypt = NULL;
3425                 } else {
3426                         unsigned crypt_len = roundup(ivsize, blocksize);
3427
3428                         req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
3429                         if (!req) {
3430                                 *error = "Could not allocate crypt request";
3431                                 r = -ENOMEM;
3432                                 goto bad;
3433                         }
3434
3435                         crypt_iv = kmalloc(ivsize, GFP_KERNEL);
3436                         if (!crypt_iv) {
3437                                 *error = "Could not allocate iv";
3438                                 r = -ENOMEM;
3439                                 goto bad;
3440                         }
3441
3442                         crypt_data = kmalloc(crypt_len, GFP_KERNEL);
3443                         if (!crypt_data) {
3444                                 *error = "Unable to allocate crypt data";
3445                                 r = -ENOMEM;
3446                                 goto bad;
3447                         }
3448
3449                         ic->journal_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal);
3450                         if (!ic->journal_scatterlist) {
3451                                 *error = "Unable to allocate sg list";
3452                                 r = -ENOMEM;
3453                                 goto bad;
3454                         }
3455                         ic->journal_io_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal_io);
3456                         if (!ic->journal_io_scatterlist) {
3457                                 *error = "Unable to allocate sg list";
3458                                 r = -ENOMEM;
3459                                 goto bad;
3460                         }
3461                         ic->sk_requests = kvmalloc_array(ic->journal_sections,
3462                                                          sizeof(struct skcipher_request *),
3463                                                          GFP_KERNEL | __GFP_ZERO);
3464                         if (!ic->sk_requests) {
3465                                 *error = "Unable to allocate sk requests";
3466                                 r = -ENOMEM;
3467                                 goto bad;
3468                         }
3469                         for (i = 0; i < ic->journal_sections; i++) {
3470                                 struct scatterlist sg;
3471                                 struct skcipher_request *section_req;
3472                                 __u32 section_le = cpu_to_le32(i);
3473
3474                                 memset(crypt_iv, 0x00, ivsize);
3475                                 memset(crypt_data, 0x00, crypt_len);
3476                                 memcpy(crypt_data, &section_le, min((size_t)crypt_len, sizeof(section_le)));
3477
3478                                 sg_init_one(&sg, crypt_data, crypt_len);
3479                                 skcipher_request_set_crypt(req, &sg, &sg, crypt_len, crypt_iv);
3480                                 init_completion(&comp.comp);
3481                                 comp.in_flight = (atomic_t)ATOMIC_INIT(1);
3482                                 if (do_crypt(true, req, &comp))
3483                                         wait_for_completion(&comp.comp);
3484
3485                                 r = dm_integrity_failed(ic);
3486                                 if (r) {
3487                                         *error = "Unable to generate iv";
3488                                         goto bad;
3489                                 }
3490
3491                                 section_req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
3492                                 if (!section_req) {
3493                                         *error = "Unable to allocate crypt request";
3494                                         r = -ENOMEM;
3495                                         goto bad;
3496                                 }
3497                                 section_req->iv = kmalloc_array(ivsize, 2,
3498                                                                 GFP_KERNEL);
3499                                 if (!section_req->iv) {
3500                                         skcipher_request_free(section_req);
3501                                         *error = "Unable to allocate iv";
3502                                         r = -ENOMEM;
3503                                         goto bad;
3504                                 }
3505                                 memcpy(section_req->iv + ivsize, crypt_data, ivsize);
3506                                 section_req->cryptlen = (size_t)ic->journal_section_sectors << SECTOR_SHIFT;
3507                                 ic->sk_requests[i] = section_req;
3508                                 DEBUG_bytes(crypt_data, ivsize, "iv(%u)", i);
3509                         }
3510                 }
3511         }
3512
3513         for (i = 0; i < N_COMMIT_IDS; i++) {
3514                 unsigned j;
3515 retest_commit_id:
3516                 for (j = 0; j < i; j++) {
3517                         if (ic->commit_ids[j] == ic->commit_ids[i]) {
3518                                 ic->commit_ids[i] = cpu_to_le64(le64_to_cpu(ic->commit_ids[i]) + 1);
3519                                 goto retest_commit_id;
3520                         }
3521                 }
3522                 DEBUG_print("commit id %u: %016llx\n", i, ic->commit_ids[i]);
3523         }
3524
3525         journal_tree_size = (__u64)ic->journal_entries * sizeof(struct journal_node);
3526         if (journal_tree_size > ULONG_MAX) {
3527                 *error = "Journal doesn't fit into memory";
3528                 r = -ENOMEM;
3529                 goto bad;
3530         }
3531         ic->journal_tree = kvmalloc(journal_tree_size, GFP_KERNEL);
3532         if (!ic->journal_tree) {
3533                 *error = "Could not allocate memory for journal tree";
3534                 r = -ENOMEM;
3535         }
3536 bad:
3537         kfree(crypt_data);
3538         kfree(crypt_iv);
3539         skcipher_request_free(req);
3540
3541         return r;
3542 }
3543
3544 /*
3545  * Construct a integrity mapping
3546  *
3547  * Arguments:
3548  *      device
3549  *      offset from the start of the device
3550  *      tag size
3551  *      D - direct writes, J - journal writes, B - bitmap mode, R - recovery mode
3552  *      number of optional arguments
3553  *      optional arguments:
3554  *              journal_sectors
3555  *              interleave_sectors
3556  *              buffer_sectors
3557  *              journal_watermark
3558  *              commit_time
3559  *              meta_device
3560  *              block_size
3561  *              sectors_per_bit
3562  *              bitmap_flush_interval
3563  *              internal_hash
3564  *              journal_crypt
3565  *              journal_mac
3566  *              recalculate
3567  */
3568 static int dm_integrity_ctr(struct dm_target *ti, unsigned argc, char **argv)
3569 {
3570         struct dm_integrity_c *ic;
3571         char dummy;
3572         int r;
3573         unsigned extra_args;
3574         struct dm_arg_set as;
3575         static const struct dm_arg _args[] = {
3576                 {0, 9, "Invalid number of feature args"},
3577         };
3578         unsigned journal_sectors, interleave_sectors, buffer_sectors, journal_watermark, sync_msec;
3579         bool should_write_sb;
3580         __u64 threshold;
3581         unsigned long long start;
3582         __s8 log2_sectors_per_bitmap_bit = -1;
3583         __s8 log2_blocks_per_bitmap_bit;
3584         __u64 bits_in_journal;
3585         __u64 n_bitmap_bits;
3586
3587 #define DIRECT_ARGUMENTS        4
3588
3589         if (argc <= DIRECT_ARGUMENTS) {
3590                 ti->error = "Invalid argument count";
3591                 return -EINVAL;
3592         }
3593
3594         ic = kzalloc(sizeof(struct dm_integrity_c), GFP_KERNEL);
3595         if (!ic) {
3596                 ti->error = "Cannot allocate integrity context";
3597                 return -ENOMEM;
3598         }
3599         ti->private = ic;
3600         ti->per_io_data_size = sizeof(struct dm_integrity_io);
3601         ic->ti = ti;
3602
3603         ic->in_progress = RB_ROOT;
3604         INIT_LIST_HEAD(&ic->wait_list);
3605         init_waitqueue_head(&ic->endio_wait);
3606         bio_list_init(&ic->flush_bio_list);
3607         init_waitqueue_head(&ic->copy_to_journal_wait);
3608         init_completion(&ic->crypto_backoff);
3609         atomic64_set(&ic->number_of_mismatches, 0);
3610         ic->bitmap_flush_interval = BITMAP_FLUSH_INTERVAL;
3611
3612         r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &ic->dev);
3613         if (r) {
3614                 ti->error = "Device lookup failed";
3615                 goto bad;
3616         }
3617
3618         if (sscanf(argv[1], "%llu%c", &start, &dummy) != 1 || start != (sector_t)start) {
3619                 ti->error = "Invalid starting offset";
3620                 r = -EINVAL;
3621                 goto bad;
3622         }
3623         ic->start = start;
3624
3625         if (strcmp(argv[2], "-")) {
3626                 if (sscanf(argv[2], "%u%c", &ic->tag_size, &dummy) != 1 || !ic->tag_size) {
3627                         ti->error = "Invalid tag size";
3628                         r = -EINVAL;
3629                         goto bad;
3630                 }
3631         }
3632
3633         if (!strcmp(argv[3], "J") || !strcmp(argv[3], "B") ||
3634             !strcmp(argv[3], "D") || !strcmp(argv[3], "R")) {
3635                 ic->mode = argv[3][0];
3636         } else {
3637                 ti->error = "Invalid mode (expecting J, B, D, R)";
3638                 r = -EINVAL;
3639                 goto bad;
3640         }
3641
3642         journal_sectors = 0;
3643         interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
3644         buffer_sectors = DEFAULT_BUFFER_SECTORS;
3645         journal_watermark = DEFAULT_JOURNAL_WATERMARK;
3646         sync_msec = DEFAULT_SYNC_MSEC;
3647         ic->sectors_per_block = 1;
3648
3649         as.argc = argc - DIRECT_ARGUMENTS;
3650         as.argv = argv + DIRECT_ARGUMENTS;
3651         r = dm_read_arg_group(_args, &as, &extra_args, &ti->error);
3652         if (r)
3653                 goto bad;
3654
3655         while (extra_args--) {
3656                 const char *opt_string;
3657                 unsigned val;
3658                 unsigned long long llval;
3659                 opt_string = dm_shift_arg(&as);
3660                 if (!opt_string) {
3661                         r = -EINVAL;
3662                         ti->error = "Not enough feature arguments";
3663                         goto bad;
3664                 }
3665                 if (sscanf(opt_string, "journal_sectors:%u%c", &val, &dummy) == 1)
3666                         journal_sectors = val ? val : 1;
3667                 else if (sscanf(opt_string, "interleave_sectors:%u%c", &val, &dummy) == 1)
3668                         interleave_sectors = val;
3669                 else if (sscanf(opt_string, "buffer_sectors:%u%c", &val, &dummy) == 1)
3670                         buffer_sectors = val;
3671                 else if (sscanf(opt_string, "journal_watermark:%u%c", &val, &dummy) == 1 && val <= 100)
3672                         journal_watermark = val;
3673                 else if (sscanf(opt_string, "commit_time:%u%c", &val, &dummy) == 1)
3674                         sync_msec = val;
3675                 else if (!strncmp(opt_string, "meta_device:", strlen("meta_device:"))) {
3676                         if (ic->meta_dev) {
3677                                 dm_put_device(ti, ic->meta_dev);
3678                                 ic->meta_dev = NULL;
3679                         }
3680                         r = dm_get_device(ti, strchr(opt_string, ':') + 1,
3681                                           dm_table_get_mode(ti->table), &ic->meta_dev);
3682                         if (r) {
3683                                 ti->error = "Device lookup failed";
3684                                 goto bad;
3685                         }
3686                 } else if (sscanf(opt_string, "block_size:%u%c", &val, &dummy) == 1) {
3687                         if (val < 1 << SECTOR_SHIFT ||
3688                             val > MAX_SECTORS_PER_BLOCK << SECTOR_SHIFT ||
3689                             (val & (val -1))) {
3690                                 r = -EINVAL;
3691                                 ti->error = "Invalid block_size argument";
3692                                 goto bad;
3693                         }
3694                         ic->sectors_per_block = val >> SECTOR_SHIFT;
3695                 } else if (sscanf(opt_string, "sectors_per_bit:%llu%c", &llval, &dummy) == 1) {
3696                         log2_sectors_per_bitmap_bit = !llval ? 0 : __ilog2_u64(llval);
3697                 } else if (sscanf(opt_string, "bitmap_flush_interval:%u%c", &val, &dummy) == 1) {
3698                         if (val >= (uint64_t)UINT_MAX * 1000 / HZ) {
3699                                 r = -EINVAL;
3700                                 ti->error = "Invalid bitmap_flush_interval argument";
3701                         }
3702                         ic->bitmap_flush_interval = msecs_to_jiffies(val);
3703                 } else if (!strncmp(opt_string, "internal_hash:", strlen("internal_hash:"))) {
3704                         r = get_alg_and_key(opt_string, &ic->internal_hash_alg, &ti->error,
3705                                             "Invalid internal_hash argument");
3706                         if (r)
3707                                 goto bad;
3708                 } else if (!strncmp(opt_string, "journal_crypt:", strlen("journal_crypt:"))) {
3709                         r = get_alg_and_key(opt_string, &ic->journal_crypt_alg, &ti->error,
3710                                             "Invalid journal_crypt argument");
3711                         if (r)
3712                                 goto bad;
3713                 } else if (!strncmp(opt_string, "journal_mac:", strlen("journal_mac:"))) {
3714                         r = get_alg_and_key(opt_string, &ic->journal_mac_alg,  &ti->error,
3715                                             "Invalid journal_mac argument");
3716                         if (r)
3717                                 goto bad;
3718                 } else if (!strcmp(opt_string, "recalculate")) {
3719                         ic->recalculate_flag = true;
3720                 } else {
3721                         r = -EINVAL;
3722                         ti->error = "Invalid argument";
3723                         goto bad;
3724                 }
3725         }
3726
3727         ic->data_device_sectors = i_size_read(ic->dev->bdev->bd_inode) >> SECTOR_SHIFT;
3728         if (!ic->meta_dev)
3729                 ic->meta_device_sectors = ic->data_device_sectors;
3730         else
3731                 ic->meta_device_sectors = i_size_read(ic->meta_dev->bdev->bd_inode) >> SECTOR_SHIFT;
3732
3733         if (!journal_sectors) {
3734                 journal_sectors = min((sector_t)DEFAULT_MAX_JOURNAL_SECTORS,
3735                                       ic->data_device_sectors >> DEFAULT_JOURNAL_SIZE_FACTOR);
3736         }
3737
3738         if (!buffer_sectors)
3739                 buffer_sectors = 1;
3740         ic->log2_buffer_sectors = min((int)__fls(buffer_sectors), 31 - SECTOR_SHIFT);
3741
3742         r = get_mac(&ic->internal_hash, &ic->internal_hash_alg, &ti->error,
3743                     "Invalid internal hash", "Error setting internal hash key");
3744         if (r)
3745                 goto bad;
3746
3747         r = get_mac(&ic->journal_mac, &ic->journal_mac_alg, &ti->error,
3748                     "Invalid journal mac", "Error setting journal mac key");
3749         if (r)
3750                 goto bad;
3751
3752         if (!ic->tag_size) {
3753                 if (!ic->internal_hash) {
3754                         ti->error = "Unknown tag size";
3755                         r = -EINVAL;
3756                         goto bad;
3757                 }
3758                 ic->tag_size = crypto_shash_digestsize(ic->internal_hash);
3759         }
3760         if (ic->tag_size > MAX_TAG_SIZE) {
3761                 ti->error = "Too big tag size";
3762                 r = -EINVAL;
3763                 goto bad;
3764         }
3765         if (!(ic->tag_size & (ic->tag_size - 1)))
3766                 ic->log2_tag_size = __ffs(ic->tag_size);
3767         else
3768                 ic->log2_tag_size = -1;
3769
3770         if (ic->mode == 'B' && !ic->internal_hash) {
3771                 r = -EINVAL;
3772                 ti->error = "Bitmap mode can be only used with internal hash";
3773                 goto bad;
3774         }
3775
3776         ic->autocommit_jiffies = msecs_to_jiffies(sync_msec);
3777         ic->autocommit_msec = sync_msec;
3778         timer_setup(&ic->autocommit_timer, autocommit_fn, 0);
3779
3780         ic->io = dm_io_client_create();
3781         if (IS_ERR(ic->io)) {
3782                 r = PTR_ERR(ic->io);
3783                 ic->io = NULL;
3784                 ti->error = "Cannot allocate dm io";
3785                 goto bad;
3786         }
3787
3788         r = mempool_init_slab_pool(&ic->journal_io_mempool, JOURNAL_IO_MEMPOOL, journal_io_cache);
3789         if (r) {
3790                 ti->error = "Cannot allocate mempool";
3791                 goto bad;
3792         }
3793
3794         ic->metadata_wq = alloc_workqueue("dm-integrity-metadata",
3795                                           WQ_MEM_RECLAIM, METADATA_WORKQUEUE_MAX_ACTIVE);
3796         if (!ic->metadata_wq) {
3797                 ti->error = "Cannot allocate workqueue";
3798                 r = -ENOMEM;
3799                 goto bad;
3800         }
3801
3802         /*
3803          * If this workqueue were percpu, it would cause bio reordering
3804          * and reduced performance.
3805          */
3806         ic->wait_wq = alloc_workqueue("dm-integrity-wait", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
3807         if (!ic->wait_wq) {
3808                 ti->error = "Cannot allocate workqueue";
3809                 r = -ENOMEM;
3810                 goto bad;
3811         }
3812
3813         ic->offload_wq = alloc_workqueue("dm-integrity-offload", WQ_MEM_RECLAIM,
3814                                           METADATA_WORKQUEUE_MAX_ACTIVE);
3815         if (!ic->offload_wq) {
3816                 ti->error = "Cannot allocate workqueue";
3817                 r = -ENOMEM;
3818                 goto bad;
3819         }
3820
3821         ic->commit_wq = alloc_workqueue("dm-integrity-commit", WQ_MEM_RECLAIM, 1);
3822         if (!ic->commit_wq) {
3823                 ti->error = "Cannot allocate workqueue";
3824                 r = -ENOMEM;
3825                 goto bad;
3826         }
3827         INIT_WORK(&ic->commit_work, integrity_commit);
3828
3829         if (ic->mode == 'J' || ic->mode == 'B') {
3830                 ic->writer_wq = alloc_workqueue("dm-integrity-writer", WQ_MEM_RECLAIM, 1);
3831                 if (!ic->writer_wq) {
3832                         ti->error = "Cannot allocate workqueue";
3833                         r = -ENOMEM;
3834                         goto bad;
3835                 }
3836                 INIT_WORK(&ic->writer_work, integrity_writer);
3837         }
3838
3839         ic->sb = alloc_pages_exact(SB_SECTORS << SECTOR_SHIFT, GFP_KERNEL);
3840         if (!ic->sb) {
3841                 r = -ENOMEM;
3842                 ti->error = "Cannot allocate superblock area";
3843                 goto bad;
3844         }
3845
3846         r = sync_rw_sb(ic, REQ_OP_READ, 0);
3847         if (r) {
3848                 ti->error = "Error reading superblock";
3849                 goto bad;
3850         }
3851         should_write_sb = false;
3852         if (memcmp(ic->sb->magic, SB_MAGIC, 8)) {
3853                 if (ic->mode != 'R') {
3854                         if (memchr_inv(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT)) {
3855                                 r = -EINVAL;
3856                                 ti->error = "The device is not initialized";
3857                                 goto bad;
3858                         }
3859                 }
3860
3861                 r = initialize_superblock(ic, journal_sectors, interleave_sectors);
3862                 if (r) {
3863                         ti->error = "Could not initialize superblock";
3864                         goto bad;
3865                 }
3866                 if (ic->mode != 'R')
3867                         should_write_sb = true;
3868         }
3869
3870         if (!ic->sb->version || ic->sb->version > SB_VERSION_3) {
3871                 r = -EINVAL;
3872                 ti->error = "Unknown version";
3873                 goto bad;
3874         }
3875         if (le16_to_cpu(ic->sb->integrity_tag_size) != ic->tag_size) {
3876                 r = -EINVAL;
3877                 ti->error = "Tag size doesn't match the information in superblock";
3878                 goto bad;
3879         }
3880         if (ic->sb->log2_sectors_per_block != __ffs(ic->sectors_per_block)) {
3881                 r = -EINVAL;
3882                 ti->error = "Block size doesn't match the information in superblock";
3883                 goto bad;
3884         }
3885         if (!le32_to_cpu(ic->sb->journal_sections)) {
3886                 r = -EINVAL;
3887                 ti->error = "Corrupted superblock, journal_sections is 0";
3888                 goto bad;
3889         }
3890         /* make sure that ti->max_io_len doesn't overflow */
3891         if (!ic->meta_dev) {
3892                 if (ic->sb->log2_interleave_sectors < MIN_LOG2_INTERLEAVE_SECTORS ||
3893                     ic->sb->log2_interleave_sectors > MAX_LOG2_INTERLEAVE_SECTORS) {
3894                         r = -EINVAL;
3895                         ti->error = "Invalid interleave_sectors in the superblock";
3896                         goto bad;
3897                 }
3898         } else {
3899                 if (ic->sb->log2_interleave_sectors) {
3900                         r = -EINVAL;
3901                         ti->error = "Invalid interleave_sectors in the superblock";
3902                         goto bad;
3903                 }
3904         }
3905         ic->provided_data_sectors = le64_to_cpu(ic->sb->provided_data_sectors);
3906         if (ic->provided_data_sectors != le64_to_cpu(ic->sb->provided_data_sectors)) {
3907                 /* test for overflow */
3908                 r = -EINVAL;
3909                 ti->error = "The superblock has 64-bit device size, but the kernel was compiled with 32-bit sectors";
3910                 goto bad;
3911         }
3912         if (!!(ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC)) != !!ic->journal_mac_alg.alg_string) {
3913                 r = -EINVAL;
3914                 ti->error = "Journal mac mismatch";
3915                 goto bad;
3916         }
3917
3918 try_smaller_buffer:
3919         r = calculate_device_limits(ic);
3920         if (r) {
3921                 if (ic->meta_dev) {
3922                         if (ic->log2_buffer_sectors > 3) {
3923                                 ic->log2_buffer_sectors--;
3924                                 goto try_smaller_buffer;
3925                         }
3926                 }
3927                 ti->error = "The device is too small";
3928                 goto bad;
3929         }
3930
3931         if (log2_sectors_per_bitmap_bit < 0)
3932                 log2_sectors_per_bitmap_bit = __fls(DEFAULT_SECTORS_PER_BITMAP_BIT);
3933         if (log2_sectors_per_bitmap_bit < ic->sb->log2_sectors_per_block)
3934                 log2_sectors_per_bitmap_bit = ic->sb->log2_sectors_per_block;
3935
3936         bits_in_journal = ((__u64)ic->journal_section_sectors * ic->journal_sections) << (SECTOR_SHIFT + 3);
3937         if (bits_in_journal > UINT_MAX)
3938                 bits_in_journal = UINT_MAX;
3939         while (bits_in_journal < (ic->provided_data_sectors + ((sector_t)1 << log2_sectors_per_bitmap_bit) - 1) >> log2_sectors_per_bitmap_bit)
3940                 log2_sectors_per_bitmap_bit++;
3941
3942         log2_blocks_per_bitmap_bit = log2_sectors_per_bitmap_bit - ic->sb->log2_sectors_per_block;
3943         ic->log2_blocks_per_bitmap_bit = log2_blocks_per_bitmap_bit;
3944         if (should_write_sb) {
3945                 ic->sb->log2_blocks_per_bitmap_bit = log2_blocks_per_bitmap_bit;
3946         }
3947         n_bitmap_bits = ((ic->provided_data_sectors >> ic->sb->log2_sectors_per_block)
3948                                 + (((sector_t)1 << log2_blocks_per_bitmap_bit) - 1)) >> log2_blocks_per_bitmap_bit;
3949         ic->n_bitmap_blocks = DIV_ROUND_UP(n_bitmap_bits, BITMAP_BLOCK_SIZE * 8);
3950
3951         if (!ic->meta_dev)
3952                 ic->log2_buffer_sectors = min(ic->log2_buffer_sectors, (__u8)__ffs(ic->metadata_run));
3953
3954         if (ti->len > ic->provided_data_sectors) {
3955                 r = -EINVAL;
3956                 ti->error = "Not enough provided sectors for requested mapping size";
3957                 goto bad;
3958         }
3959
3960
3961         threshold = (__u64)ic->journal_entries * (100 - journal_watermark);
3962         threshold += 50;
3963         do_div(threshold, 100);
3964         ic->free_sectors_threshold = threshold;
3965
3966         DEBUG_print("initialized:\n");
3967         DEBUG_print("   integrity_tag_size %u\n", le16_to_cpu(ic->sb->integrity_tag_size));
3968         DEBUG_print("   journal_entry_size %u\n", ic->journal_entry_size);
3969         DEBUG_print("   journal_entries_per_sector %u\n", ic->journal_entries_per_sector);
3970         DEBUG_print("   journal_section_entries %u\n", ic->journal_section_entries);
3971         DEBUG_print("   journal_section_sectors %u\n", ic->journal_section_sectors);
3972         DEBUG_print("   journal_sections %u\n", (unsigned)le32_to_cpu(ic->sb->journal_sections));
3973         DEBUG_print("   journal_entries %u\n", ic->journal_entries);
3974         DEBUG_print("   log2_interleave_sectors %d\n", ic->sb->log2_interleave_sectors);
3975         DEBUG_print("   data_device_sectors 0x%llx\n", i_size_read(ic->dev->bdev->bd_inode) >> SECTOR_SHIFT);
3976         DEBUG_print("   initial_sectors 0x%x\n", ic->initial_sectors);
3977         DEBUG_print("   metadata_run 0x%x\n", ic->metadata_run);
3978         DEBUG_print("   log2_metadata_run %d\n", ic->log2_metadata_run);
3979         DEBUG_print("   provided_data_sectors 0x%llx (%llu)\n", (unsigned long long)ic->provided_data_sectors,
3980                     (unsigned long long)ic->provided_data_sectors);
3981         DEBUG_print("   log2_buffer_sectors %u\n", ic->log2_buffer_sectors);
3982         DEBUG_print("   bits_in_journal %llu\n", (unsigned long long)bits_in_journal);
3983
3984         if (ic->recalculate_flag && !(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))) {
3985                 ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
3986                 ic->sb->recalc_sector = cpu_to_le64(0);
3987         }
3988
3989         if (ic->internal_hash) {
3990                 ic->recalc_wq = alloc_workqueue("dm-integrity-recalc", WQ_MEM_RECLAIM, 1);
3991                 if (!ic->recalc_wq ) {
3992                         ti->error = "Cannot allocate workqueue";
3993                         r = -ENOMEM;
3994                         goto bad;
3995                 }
3996                 INIT_WORK(&ic->recalc_work, integrity_recalc);
3997                 ic->recalc_buffer = vmalloc(RECALC_SECTORS << SECTOR_SHIFT);
3998                 if (!ic->recalc_buffer) {
3999                         ti->error = "Cannot allocate buffer for recalculating";
4000                         r = -ENOMEM;
4001                         goto bad;
4002                 }
4003                 ic->recalc_tags = kvmalloc_array(RECALC_SECTORS >> ic->sb->log2_sectors_per_block,
4004                                                  ic->tag_size, GFP_KERNEL);
4005                 if (!ic->recalc_tags) {
4006                         ti->error = "Cannot allocate tags for recalculating";
4007                         r = -ENOMEM;
4008                         goto bad;
4009                 }
4010         }
4011
4012         ic->bufio = dm_bufio_client_create(ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev,
4013                         1U << (SECTOR_SHIFT + ic->log2_buffer_sectors), 1, 0, NULL, NULL);
4014         if (IS_ERR(ic->bufio)) {
4015                 r = PTR_ERR(ic->bufio);
4016                 ti->error = "Cannot initialize dm-bufio";
4017                 ic->bufio = NULL;
4018                 goto bad;
4019         }
4020         dm_bufio_set_sector_offset(ic->bufio, ic->start + ic->initial_sectors);
4021
4022         if (ic->mode != 'R') {
4023                 r = create_journal(ic, &ti->error);
4024                 if (r)
4025                         goto bad;
4026
4027         }
4028
4029         if (ic->mode == 'B') {
4030                 unsigned i;
4031                 unsigned n_bitmap_pages = DIV_ROUND_UP(ic->n_bitmap_blocks, PAGE_SIZE / BITMAP_BLOCK_SIZE);
4032
4033                 ic->recalc_bitmap = dm_integrity_alloc_page_list(n_bitmap_pages);
4034                 if (!ic->recalc_bitmap) {
4035                         r = -ENOMEM;
4036                         goto bad;
4037                 }
4038                 ic->may_write_bitmap = dm_integrity_alloc_page_list(n_bitmap_pages);
4039                 if (!ic->may_write_bitmap) {
4040                         r = -ENOMEM;
4041                         goto bad;
4042                 }
4043                 ic->bbs = kvmalloc_array(ic->n_bitmap_blocks, sizeof(struct bitmap_block_status), GFP_KERNEL);
4044                 if (!ic->bbs) {
4045                         r = -ENOMEM;
4046                         goto bad;
4047                 }
4048                 INIT_DELAYED_WORK(&ic->bitmap_flush_work, bitmap_flush_work);
4049                 for (i = 0; i < ic->n_bitmap_blocks; i++) {
4050                         struct bitmap_block_status *bbs = &ic->bbs[i];
4051                         unsigned sector, pl_index, pl_offset;
4052
4053                         INIT_WORK(&bbs->work, bitmap_block_work);
4054                         bbs->ic = ic;
4055                         bbs->idx = i;
4056                         bio_list_init(&bbs->bio_queue);
4057                         spin_lock_init(&bbs->bio_queue_lock);
4058
4059                         sector = i * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT);
4060                         pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
4061                         pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
4062
4063                         bbs->bitmap = lowmem_page_address(ic->journal[pl_index].page) + pl_offset;
4064                 }
4065         }
4066
4067         if (should_write_sb) {
4068                 int r;
4069
4070                 init_journal(ic, 0, ic->journal_sections, 0);
4071                 r = dm_integrity_failed(ic);
4072                 if (unlikely(r)) {
4073                         ti->error = "Error initializing journal";
4074                         goto bad;
4075                 }
4076                 r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
4077                 if (r) {
4078                         ti->error = "Error initializing superblock";
4079                         goto bad;
4080                 }
4081                 ic->just_formatted = true;
4082         }
4083
4084         if (!ic->meta_dev) {
4085                 r = dm_set_target_max_io_len(ti, 1U << ic->sb->log2_interleave_sectors);
4086                 if (r)
4087                         goto bad;
4088         }
4089         if (ic->mode == 'B') {
4090                 unsigned max_io_len = ((sector_t)ic->sectors_per_block << ic->log2_blocks_per_bitmap_bit) * (BITMAP_BLOCK_SIZE * 8);
4091                 if (!max_io_len)
4092                         max_io_len = 1U << 31;
4093                 DEBUG_print("max_io_len: old %u, new %u\n", ti->max_io_len, max_io_len);
4094                 if (!ti->max_io_len || ti->max_io_len > max_io_len) {
4095                         r = dm_set_target_max_io_len(ti, max_io_len);
4096                         if (r)
4097                                 goto bad;
4098                 }
4099         }
4100
4101         if (!ic->internal_hash)
4102                 dm_integrity_set(ti, ic);
4103
4104         ti->num_flush_bios = 1;
4105         ti->flush_supported = true;
4106
4107         return 0;
4108
4109 bad:
4110         dm_integrity_dtr(ti);
4111         return r;
4112 }
4113
4114 static void dm_integrity_dtr(struct dm_target *ti)
4115 {
4116         struct dm_integrity_c *ic = ti->private;
4117
4118         BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
4119         BUG_ON(!list_empty(&ic->wait_list));
4120
4121         if (ic->metadata_wq)
4122                 destroy_workqueue(ic->metadata_wq);
4123         if (ic->wait_wq)
4124                 destroy_workqueue(ic->wait_wq);
4125         if (ic->offload_wq)
4126                 destroy_workqueue(ic->offload_wq);
4127         if (ic->commit_wq)
4128                 destroy_workqueue(ic->commit_wq);
4129         if (ic->writer_wq)
4130                 destroy_workqueue(ic->writer_wq);
4131         if (ic->recalc_wq)
4132                 destroy_workqueue(ic->recalc_wq);
4133         vfree(ic->recalc_buffer);
4134         kvfree(ic->recalc_tags);
4135         kvfree(ic->bbs);
4136         if (ic->bufio)
4137                 dm_bufio_client_destroy(ic->bufio);
4138         mempool_exit(&ic->journal_io_mempool);
4139         if (ic->io)
4140                 dm_io_client_destroy(ic->io);
4141         if (ic->dev)
4142                 dm_put_device(ti, ic->dev);
4143         if (ic->meta_dev)
4144                 dm_put_device(ti, ic->meta_dev);
4145         dm_integrity_free_page_list(ic->journal);
4146         dm_integrity_free_page_list(ic->journal_io);
4147         dm_integrity_free_page_list(ic->journal_xor);
4148         dm_integrity_free_page_list(ic->recalc_bitmap);
4149         dm_integrity_free_page_list(ic->may_write_bitmap);
4150         if (ic->journal_scatterlist)
4151                 dm_integrity_free_journal_scatterlist(ic, ic->journal_scatterlist);
4152         if (ic->journal_io_scatterlist)
4153                 dm_integrity_free_journal_scatterlist(ic, ic->journal_io_scatterlist);
4154         if (ic->sk_requests) {
4155                 unsigned i;
4156
4157                 for (i = 0; i < ic->journal_sections; i++) {
4158                         struct skcipher_request *req = ic->sk_requests[i];
4159                         if (req) {
4160                                 kzfree(req->iv);
4161                                 skcipher_request_free(req);
4162                         }
4163                 }
4164                 kvfree(ic->sk_requests);
4165         }
4166         kvfree(ic->journal_tree);
4167         if (ic->sb)
4168                 free_pages_exact(ic->sb, SB_SECTORS << SECTOR_SHIFT);
4169
4170         if (ic->internal_hash)
4171                 crypto_free_shash(ic->internal_hash);
4172         free_alg(&ic->internal_hash_alg);
4173
4174         if (ic->journal_crypt)
4175                 crypto_free_skcipher(ic->journal_crypt);
4176         free_alg(&ic->journal_crypt_alg);
4177
4178         if (ic->journal_mac)
4179                 crypto_free_shash(ic->journal_mac);
4180         free_alg(&ic->journal_mac_alg);
4181
4182         kfree(ic);
4183 }
4184
4185 static struct target_type integrity_target = {
4186         .name                   = "integrity",
4187         .version                = {1, 3, 0},
4188         .module                 = THIS_MODULE,
4189         .features               = DM_TARGET_SINGLETON | DM_TARGET_INTEGRITY,
4190         .ctr                    = dm_integrity_ctr,
4191         .dtr                    = dm_integrity_dtr,
4192         .map                    = dm_integrity_map,
4193         .postsuspend            = dm_integrity_postsuspend,
4194         .resume                 = dm_integrity_resume,
4195         .status                 = dm_integrity_status,
4196         .iterate_devices        = dm_integrity_iterate_devices,
4197         .io_hints               = dm_integrity_io_hints,
4198 };
4199
4200 static int __init dm_integrity_init(void)
4201 {
4202         int r;
4203
4204         journal_io_cache = kmem_cache_create("integrity_journal_io",
4205                                              sizeof(struct journal_io), 0, 0, NULL);
4206         if (!journal_io_cache) {
4207                 DMERR("can't allocate journal io cache");
4208                 return -ENOMEM;
4209         }
4210
4211         r = dm_register_target(&integrity_target);
4212
4213         if (r < 0)
4214                 DMERR("register failed %d", r);
4215
4216         return r;
4217 }
4218
4219 static void __exit dm_integrity_exit(void)
4220 {
4221         dm_unregister_target(&integrity_target);
4222         kmem_cache_destroy(journal_io_cache);
4223 }
4224
4225 module_init(dm_integrity_init);
4226 module_exit(dm_integrity_exit);
4227
4228 MODULE_AUTHOR("Milan Broz");
4229 MODULE_AUTHOR("Mikulas Patocka");
4230 MODULE_DESCRIPTION(DM_NAME " target for integrity tags extension");
4231 MODULE_LICENSE("GPL");