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