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