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