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