UPSTREAM: dm verity: add support for forward error correction
[firefly-linux-kernel-4.4.55.git] / drivers / md / dm-verity-target.c
1 /*
2  * Copyright (C) 2012 Red Hat, Inc.
3  *
4  * Author: Mikulas Patocka <mpatocka@redhat.com>
5  *
6  * Based on Chromium dm-verity driver (C) 2011 The Chromium OS Authors
7  *
8  * This file is released under the GPLv2.
9  *
10  * In the file "/sys/module/dm_verity/parameters/prefetch_cluster" you can set
11  * default prefetch value. Data are read in "prefetch_cluster" chunks from the
12  * hash device. Setting this greatly improves performance when data and hash
13  * are on the same disk on different partitions on devices with poor random
14  * access behavior.
15  */
16
17 #include "dm-verity.h"
18 #include "dm-verity-fec.h"
19
20 #include <linux/module.h>
21 #include <linux/reboot.h>
22
23 #define DM_MSG_PREFIX                   "verity"
24
25 #define DM_VERITY_ENV_LENGTH            42
26 #define DM_VERITY_ENV_VAR_NAME          "DM_VERITY_ERR_BLOCK_NR"
27
28 #define DM_VERITY_DEFAULT_PREFETCH_SIZE 262144
29
30 #define DM_VERITY_MAX_CORRUPTED_ERRS    100
31
32 #define DM_VERITY_OPT_LOGGING           "ignore_corruption"
33 #define DM_VERITY_OPT_RESTART           "restart_on_corruption"
34
35 #define DM_VERITY_OPTS_MAX              (1 + DM_VERITY_OPTS_FEC)
36
37 static unsigned dm_verity_prefetch_cluster = DM_VERITY_DEFAULT_PREFETCH_SIZE;
38
39 module_param_named(prefetch_cluster, dm_verity_prefetch_cluster, uint, S_IRUGO | S_IWUSR);
40
41 struct dm_verity_prefetch_work {
42         struct work_struct work;
43         struct dm_verity *v;
44         sector_t block;
45         unsigned n_blocks;
46 };
47
48 /*
49  * Auxiliary structure appended to each dm-bufio buffer. If the value
50  * hash_verified is nonzero, hash of the block has been verified.
51  *
52  * The variable hash_verified is set to 0 when allocating the buffer, then
53  * it can be changed to 1 and it is never reset to 0 again.
54  *
55  * There is no lock around this value, a race condition can at worst cause
56  * that multiple processes verify the hash of the same buffer simultaneously
57  * and write 1 to hash_verified simultaneously.
58  * This condition is harmless, so we don't need locking.
59  */
60 struct buffer_aux {
61         int hash_verified;
62 };
63
64 /*
65  * Initialize struct buffer_aux for a freshly created buffer.
66  */
67 static void dm_bufio_alloc_callback(struct dm_buffer *buf)
68 {
69         struct buffer_aux *aux = dm_bufio_get_aux_data(buf);
70
71         aux->hash_verified = 0;
72 }
73
74 /*
75  * Translate input sector number to the sector number on the target device.
76  */
77 static sector_t verity_map_sector(struct dm_verity *v, sector_t bi_sector)
78 {
79         return v->data_start + dm_target_offset(v->ti, bi_sector);
80 }
81
82 /*
83  * Return hash position of a specified block at a specified tree level
84  * (0 is the lowest level).
85  * The lowest "hash_per_block_bits"-bits of the result denote hash position
86  * inside a hash block. The remaining bits denote location of the hash block.
87  */
88 static sector_t verity_position_at_level(struct dm_verity *v, sector_t block,
89                                          int level)
90 {
91         return block >> (level * v->hash_per_block_bits);
92 }
93
94 /*
95  * Wrapper for crypto_shash_init, which handles verity salting.
96  */
97 static int verity_hash_init(struct dm_verity *v, struct shash_desc *desc)
98 {
99         int r;
100
101         desc->tfm = v->tfm;
102         desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
103
104         r = crypto_shash_init(desc);
105
106         if (unlikely(r < 0)) {
107                 DMERR("crypto_shash_init failed: %d", r);
108                 return r;
109         }
110
111         if (likely(v->version >= 1)) {
112                 r = crypto_shash_update(desc, v->salt, v->salt_size);
113
114                 if (unlikely(r < 0)) {
115                         DMERR("crypto_shash_update failed: %d", r);
116                         return r;
117                 }
118         }
119
120         return 0;
121 }
122
123 static int verity_hash_update(struct dm_verity *v, struct shash_desc *desc,
124                               const u8 *data, size_t len)
125 {
126         int r = crypto_shash_update(desc, data, len);
127
128         if (unlikely(r < 0))
129                 DMERR("crypto_shash_update failed: %d", r);
130
131         return r;
132 }
133
134 static int verity_hash_final(struct dm_verity *v, struct shash_desc *desc,
135                              u8 *digest)
136 {
137         int r;
138
139         if (unlikely(!v->version)) {
140                 r = crypto_shash_update(desc, v->salt, v->salt_size);
141
142                 if (r < 0) {
143                         DMERR("crypto_shash_update failed: %d", r);
144                         return r;
145                 }
146         }
147
148         r = crypto_shash_final(desc, digest);
149
150         if (unlikely(r < 0))
151                 DMERR("crypto_shash_final failed: %d", r);
152
153         return r;
154 }
155
156 int verity_hash(struct dm_verity *v, struct shash_desc *desc,
157                 const u8 *data, size_t len, u8 *digest)
158 {
159         int r;
160
161         r = verity_hash_init(v, desc);
162         if (unlikely(r < 0))
163                 return r;
164
165         r = verity_hash_update(v, desc, data, len);
166         if (unlikely(r < 0))
167                 return r;
168
169         return verity_hash_final(v, desc, digest);
170 }
171
172 static void verity_hash_at_level(struct dm_verity *v, sector_t block, int level,
173                                  sector_t *hash_block, unsigned *offset)
174 {
175         sector_t position = verity_position_at_level(v, block, level);
176         unsigned idx;
177
178         *hash_block = v->hash_level_block[level] + (position >> v->hash_per_block_bits);
179
180         if (!offset)
181                 return;
182
183         idx = position & ((1 << v->hash_per_block_bits) - 1);
184         if (!v->version)
185                 *offset = idx * v->digest_size;
186         else
187                 *offset = idx << (v->hash_dev_block_bits - v->hash_per_block_bits);
188 }
189
190 /*
191  * Handle verification errors.
192  */
193 static int verity_handle_err(struct dm_verity *v, enum verity_block_type type,
194                              unsigned long long block)
195 {
196         char verity_env[DM_VERITY_ENV_LENGTH];
197         char *envp[] = { verity_env, NULL };
198         const char *type_str = "";
199         struct mapped_device *md = dm_table_get_md(v->ti->table);
200
201         /* Corruption should be visible in device status in all modes */
202         v->hash_failed = 1;
203
204         if (v->corrupted_errs >= DM_VERITY_MAX_CORRUPTED_ERRS)
205                 goto out;
206
207         v->corrupted_errs++;
208
209         switch (type) {
210         case DM_VERITY_BLOCK_TYPE_DATA:
211                 type_str = "data";
212                 break;
213         case DM_VERITY_BLOCK_TYPE_METADATA:
214                 type_str = "metadata";
215                 break;
216         default:
217                 BUG();
218         }
219
220         DMERR("%s: %s block %llu is corrupted", v->data_dev->name, type_str,
221                 block);
222
223         if (v->corrupted_errs == DM_VERITY_MAX_CORRUPTED_ERRS)
224                 DMERR("%s: reached maximum errors", v->data_dev->name);
225
226         snprintf(verity_env, DM_VERITY_ENV_LENGTH, "%s=%d,%llu",
227                 DM_VERITY_ENV_VAR_NAME, type, block);
228
229         kobject_uevent_env(&disk_to_dev(dm_disk(md))->kobj, KOBJ_CHANGE, envp);
230
231 out:
232         if (v->mode == DM_VERITY_MODE_LOGGING)
233                 return 0;
234
235         if (v->mode == DM_VERITY_MODE_RESTART)
236                 kernel_restart("dm-verity device corrupted");
237
238         return 1;
239 }
240
241 /*
242  * Verify hash of a metadata block pertaining to the specified data block
243  * ("block" argument) at a specified level ("level" argument).
244  *
245  * On successful return, verity_io_want_digest(v, io) contains the hash value
246  * for a lower tree level or for the data block (if we're at the lowest level).
247  *
248  * If "skip_unverified" is true, unverified buffer is skipped and 1 is returned.
249  * If "skip_unverified" is false, unverified buffer is hashed and verified
250  * against current value of verity_io_want_digest(v, io).
251  */
252 static int verity_verify_level(struct dm_verity *v, struct dm_verity_io *io,
253                                sector_t block, int level, bool skip_unverified,
254                                u8 *want_digest)
255 {
256         struct dm_buffer *buf;
257         struct buffer_aux *aux;
258         u8 *data;
259         int r;
260         sector_t hash_block;
261         unsigned offset;
262
263         verity_hash_at_level(v, block, level, &hash_block, &offset);
264
265         data = dm_bufio_read(v->bufio, hash_block, &buf);
266         if (IS_ERR(data))
267                 return PTR_ERR(data);
268
269         aux = dm_bufio_get_aux_data(buf);
270
271         if (!aux->hash_verified) {
272                 if (skip_unverified) {
273                         r = 1;
274                         goto release_ret_r;
275                 }
276
277                 r = verity_hash(v, verity_io_hash_desc(v, io),
278                                 data, 1 << v->hash_dev_block_bits,
279                                 verity_io_real_digest(v, io));
280                 if (unlikely(r < 0))
281                         goto release_ret_r;
282
283                 if (likely(memcmp(verity_io_real_digest(v, io), want_digest,
284                                   v->digest_size) == 0))
285                         aux->hash_verified = 1;
286                 else if (verity_fec_decode(v, io,
287                                            DM_VERITY_BLOCK_TYPE_METADATA,
288                                            hash_block, data, NULL) == 0)
289                         aux->hash_verified = 1;
290                 else if (verity_handle_err(v,
291                                            DM_VERITY_BLOCK_TYPE_METADATA,
292                                            hash_block)) {
293                         r = -EIO;
294                         goto release_ret_r;
295                 }
296         }
297
298         data += offset;
299         memcpy(want_digest, data, v->digest_size);
300         r = 0;
301
302 release_ret_r:
303         dm_bufio_release(buf);
304         return r;
305 }
306
307 /*
308  * Find a hash for a given block, write it to digest and verify the integrity
309  * of the hash tree if necessary.
310  */
311 int verity_hash_for_block(struct dm_verity *v, struct dm_verity_io *io,
312                           sector_t block, u8 *digest)
313 {
314         int i;
315         int r;
316
317         if (likely(v->levels)) {
318                 /*
319                  * First, we try to get the requested hash for
320                  * the current block. If the hash block itself is
321                  * verified, zero is returned. If it isn't, this
322                  * function returns 1 and we fall back to whole
323                  * chain verification.
324                  */
325                 r = verity_verify_level(v, io, block, 0, true, digest);
326                 if (likely(r <= 0))
327                         return r;
328         }
329
330         memcpy(digest, v->root_digest, v->digest_size);
331
332         for (i = v->levels - 1; i >= 0; i--) {
333                 r = verity_verify_level(v, io, block, i, false, digest);
334                 if (unlikely(r))
335                         return r;
336         }
337
338         return 0;
339 }
340
341 /*
342  * Calls function process for 1 << v->data_dev_block_bits bytes in the bio_vec
343  * starting from iter.
344  */
345 int verity_for_bv_block(struct dm_verity *v, struct dm_verity_io *io,
346                         struct bvec_iter *iter,
347                         int (*process)(struct dm_verity *v,
348                                        struct dm_verity_io *io, u8 *data,
349                                        size_t len))
350 {
351         unsigned todo = 1 << v->data_dev_block_bits;
352         struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_bio_data_size);
353
354         do {
355                 int r;
356                 u8 *page;
357                 unsigned len;
358                 struct bio_vec bv = bio_iter_iovec(bio, *iter);
359
360                 page = kmap_atomic(bv.bv_page);
361                 len = bv.bv_len;
362
363                 if (likely(len >= todo))
364                         len = todo;
365
366                 r = process(v, io, page + bv.bv_offset, len);
367                 kunmap_atomic(page);
368
369                 if (r < 0)
370                         return r;
371
372                 bio_advance_iter(bio, iter, len);
373                 todo -= len;
374         } while (todo);
375
376         return 0;
377 }
378
379 static int verity_bv_hash_update(struct dm_verity *v, struct dm_verity_io *io,
380                                  u8 *data, size_t len)
381 {
382         return verity_hash_update(v, verity_io_hash_desc(v, io), data, len);
383 }
384
385 /*
386  * Verify one "dm_verity_io" structure.
387  */
388 static int verity_verify_io(struct dm_verity_io *io)
389 {
390         struct dm_verity *v = io->v;
391         struct bvec_iter start;
392         unsigned b;
393
394         for (b = 0; b < io->n_blocks; b++) {
395                 int r;
396                 struct shash_desc *desc = verity_io_hash_desc(v, io);
397
398                 r = verity_hash_for_block(v, io, io->block + b,
399                                           verity_io_want_digest(v, io));
400                 if (unlikely(r < 0))
401                         return r;
402
403                 r = verity_hash_init(v, desc);
404                 if (unlikely(r < 0))
405                         return r;
406
407                 start = io->iter;
408                 r = verity_for_bv_block(v, io, &io->iter, verity_bv_hash_update);
409                 if (unlikely(r < 0))
410                         return r;
411
412                 r = verity_hash_final(v, desc, verity_io_real_digest(v, io));
413                 if (unlikely(r < 0))
414                         return r;
415
416                 if (likely(memcmp(verity_io_real_digest(v, io),
417                                   verity_io_want_digest(v, io), v->digest_size) == 0))
418                         continue;
419                 else if (verity_fec_decode(v, io, DM_VERITY_BLOCK_TYPE_DATA,
420                                            io->block + b, NULL, &start) == 0)
421                         continue;
422                 else if (verity_handle_err(v, DM_VERITY_BLOCK_TYPE_DATA,
423                                            io->block + b))
424                         return -EIO;
425         }
426
427         return 0;
428 }
429
430 /*
431  * End one "io" structure with a given error.
432  */
433 static void verity_finish_io(struct dm_verity_io *io, int error)
434 {
435         struct dm_verity *v = io->v;
436         struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_bio_data_size);
437
438         bio->bi_end_io = io->orig_bi_end_io;
439         bio->bi_error = error;
440
441         verity_fec_finish_io(io);
442
443         bio_endio(bio);
444 }
445
446 static void verity_work(struct work_struct *w)
447 {
448         struct dm_verity_io *io = container_of(w, struct dm_verity_io, work);
449
450         verity_finish_io(io, verity_verify_io(io));
451 }
452
453 static void verity_end_io(struct bio *bio)
454 {
455         struct dm_verity_io *io = bio->bi_private;
456
457         if (bio->bi_error && !verity_fec_is_enabled(io->v)) {
458                 verity_finish_io(io, bio->bi_error);
459                 return;
460         }
461
462         INIT_WORK(&io->work, verity_work);
463         queue_work(io->v->verify_wq, &io->work);
464 }
465
466 /*
467  * Prefetch buffers for the specified io.
468  * The root buffer is not prefetched, it is assumed that it will be cached
469  * all the time.
470  */
471 static void verity_prefetch_io(struct work_struct *work)
472 {
473         struct dm_verity_prefetch_work *pw =
474                 container_of(work, struct dm_verity_prefetch_work, work);
475         struct dm_verity *v = pw->v;
476         int i;
477
478         for (i = v->levels - 2; i >= 0; i--) {
479                 sector_t hash_block_start;
480                 sector_t hash_block_end;
481                 verity_hash_at_level(v, pw->block, i, &hash_block_start, NULL);
482                 verity_hash_at_level(v, pw->block + pw->n_blocks - 1, i, &hash_block_end, NULL);
483                 if (!i) {
484                         unsigned cluster = ACCESS_ONCE(dm_verity_prefetch_cluster);
485
486                         cluster >>= v->data_dev_block_bits;
487                         if (unlikely(!cluster))
488                                 goto no_prefetch_cluster;
489
490                         if (unlikely(cluster & (cluster - 1)))
491                                 cluster = 1 << __fls(cluster);
492
493                         hash_block_start &= ~(sector_t)(cluster - 1);
494                         hash_block_end |= cluster - 1;
495                         if (unlikely(hash_block_end >= v->hash_blocks))
496                                 hash_block_end = v->hash_blocks - 1;
497                 }
498 no_prefetch_cluster:
499                 dm_bufio_prefetch(v->bufio, hash_block_start,
500                                   hash_block_end - hash_block_start + 1);
501         }
502
503         kfree(pw);
504 }
505
506 static void verity_submit_prefetch(struct dm_verity *v, struct dm_verity_io *io)
507 {
508         struct dm_verity_prefetch_work *pw;
509
510         pw = kmalloc(sizeof(struct dm_verity_prefetch_work),
511                 GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
512
513         if (!pw)
514                 return;
515
516         INIT_WORK(&pw->work, verity_prefetch_io);
517         pw->v = v;
518         pw->block = io->block;
519         pw->n_blocks = io->n_blocks;
520         queue_work(v->verify_wq, &pw->work);
521 }
522
523 /*
524  * Bio map function. It allocates dm_verity_io structure and bio vector and
525  * fills them. Then it issues prefetches and the I/O.
526  */
527 static int verity_map(struct dm_target *ti, struct bio *bio)
528 {
529         struct dm_verity *v = ti->private;
530         struct dm_verity_io *io;
531
532         bio->bi_bdev = v->data_dev->bdev;
533         bio->bi_iter.bi_sector = verity_map_sector(v, bio->bi_iter.bi_sector);
534
535         if (((unsigned)bio->bi_iter.bi_sector | bio_sectors(bio)) &
536             ((1 << (v->data_dev_block_bits - SECTOR_SHIFT)) - 1)) {
537                 DMERR_LIMIT("unaligned io");
538                 return -EIO;
539         }
540
541         if (bio_end_sector(bio) >>
542             (v->data_dev_block_bits - SECTOR_SHIFT) > v->data_blocks) {
543                 DMERR_LIMIT("io out of range");
544                 return -EIO;
545         }
546
547         if (bio_data_dir(bio) == WRITE)
548                 return -EIO;
549
550         io = dm_per_bio_data(bio, ti->per_bio_data_size);
551         io->v = v;
552         io->orig_bi_end_io = bio->bi_end_io;
553         io->block = bio->bi_iter.bi_sector >> (v->data_dev_block_bits - SECTOR_SHIFT);
554         io->n_blocks = bio->bi_iter.bi_size >> v->data_dev_block_bits;
555
556         bio->bi_end_io = verity_end_io;
557         bio->bi_private = io;
558         io->iter = bio->bi_iter;
559
560         verity_fec_init_io(io);
561
562         verity_submit_prefetch(v, io);
563
564         generic_make_request(bio);
565
566         return DM_MAPIO_SUBMITTED;
567 }
568
569 /*
570  * Status: V (valid) or C (corruption found)
571  */
572 static void verity_status(struct dm_target *ti, status_type_t type,
573                           unsigned status_flags, char *result, unsigned maxlen)
574 {
575         struct dm_verity *v = ti->private;
576         unsigned args = 0;
577         unsigned sz = 0;
578         unsigned x;
579
580         switch (type) {
581         case STATUSTYPE_INFO:
582                 DMEMIT("%c", v->hash_failed ? 'C' : 'V');
583                 break;
584         case STATUSTYPE_TABLE:
585                 DMEMIT("%u %s %s %u %u %llu %llu %s ",
586                         v->version,
587                         v->data_dev->name,
588                         v->hash_dev->name,
589                         1 << v->data_dev_block_bits,
590                         1 << v->hash_dev_block_bits,
591                         (unsigned long long)v->data_blocks,
592                         (unsigned long long)v->hash_start,
593                         v->alg_name
594                         );
595                 for (x = 0; x < v->digest_size; x++)
596                         DMEMIT("%02x", v->root_digest[x]);
597                 DMEMIT(" ");
598                 if (!v->salt_size)
599                         DMEMIT("-");
600                 else
601                         for (x = 0; x < v->salt_size; x++)
602                                 DMEMIT("%02x", v->salt[x]);
603                 if (v->mode != DM_VERITY_MODE_EIO)
604                         args++;
605                 if (verity_fec_is_enabled(v))
606                         args += DM_VERITY_OPTS_FEC;
607                 if (!args)
608                         return;
609                 DMEMIT(" %u", args);
610                 if (v->mode != DM_VERITY_MODE_EIO) {
611                         DMEMIT(" ");
612                         switch (v->mode) {
613                         case DM_VERITY_MODE_LOGGING:
614                                 DMEMIT(DM_VERITY_OPT_LOGGING);
615                                 break;
616                         case DM_VERITY_MODE_RESTART:
617                                 DMEMIT(DM_VERITY_OPT_RESTART);
618                                 break;
619                         default:
620                                 BUG();
621                         }
622                 }
623                 sz = verity_fec_status_table(v, sz, result, maxlen);
624                 break;
625         }
626 }
627
628 static int verity_prepare_ioctl(struct dm_target *ti,
629                 struct block_device **bdev, fmode_t *mode)
630 {
631         struct dm_verity *v = ti->private;
632
633         *bdev = v->data_dev->bdev;
634
635         if (v->data_start ||
636             ti->len != i_size_read(v->data_dev->bdev->bd_inode) >> SECTOR_SHIFT)
637                 return 1;
638         return 0;
639 }
640
641 static int verity_iterate_devices(struct dm_target *ti,
642                                   iterate_devices_callout_fn fn, void *data)
643 {
644         struct dm_verity *v = ti->private;
645
646         return fn(ti, v->data_dev, v->data_start, ti->len, data);
647 }
648
649 static void verity_io_hints(struct dm_target *ti, struct queue_limits *limits)
650 {
651         struct dm_verity *v = ti->private;
652
653         if (limits->logical_block_size < 1 << v->data_dev_block_bits)
654                 limits->logical_block_size = 1 << v->data_dev_block_bits;
655
656         if (limits->physical_block_size < 1 << v->data_dev_block_bits)
657                 limits->physical_block_size = 1 << v->data_dev_block_bits;
658
659         blk_limits_io_min(limits, limits->logical_block_size);
660 }
661
662 static void verity_dtr(struct dm_target *ti)
663 {
664         struct dm_verity *v = ti->private;
665
666         if (v->verify_wq)
667                 destroy_workqueue(v->verify_wq);
668
669         if (v->bufio)
670                 dm_bufio_client_destroy(v->bufio);
671
672         kfree(v->salt);
673         kfree(v->root_digest);
674
675         if (v->tfm)
676                 crypto_free_shash(v->tfm);
677
678         kfree(v->alg_name);
679
680         if (v->hash_dev)
681                 dm_put_device(ti, v->hash_dev);
682
683         if (v->data_dev)
684                 dm_put_device(ti, v->data_dev);
685
686         verity_fec_dtr(v);
687
688         kfree(v);
689 }
690
691 static int verity_parse_opt_args(struct dm_arg_set *as, struct dm_verity *v)
692 {
693         int r;
694         unsigned argc;
695         struct dm_target *ti = v->ti;
696         const char *arg_name;
697
698         static struct dm_arg _args[] = {
699                 {0, DM_VERITY_OPTS_MAX, "Invalid number of feature args"},
700         };
701
702         r = dm_read_arg_group(_args, as, &argc, &ti->error);
703         if (r)
704                 return -EINVAL;
705
706         if (!argc)
707                 return 0;
708
709         do {
710                 arg_name = dm_shift_arg(as);
711                 argc--;
712
713                 if (!strcasecmp(arg_name, DM_VERITY_OPT_LOGGING)) {
714                         v->mode = DM_VERITY_MODE_LOGGING;
715                         continue;
716
717                 } else if (!strcasecmp(arg_name, DM_VERITY_OPT_RESTART)) {
718                         v->mode = DM_VERITY_MODE_RESTART;
719                         continue;
720
721                 } else if (verity_is_fec_opt_arg(arg_name)) {
722                         r = verity_fec_parse_opt_args(as, v, &argc, arg_name);
723                         if (r)
724                                 return r;
725                         continue;
726                 }
727
728                 ti->error = "Unrecognized verity feature request";
729                 return -EINVAL;
730         } while (argc && !r);
731
732         return r;
733 }
734
735 /*
736  * Target parameters:
737  *      <version>       The current format is version 1.
738  *                      Vsn 0 is compatible with original Chromium OS releases.
739  *      <data device>
740  *      <hash device>
741  *      <data block size>
742  *      <hash block size>
743  *      <the number of data blocks>
744  *      <hash start block>
745  *      <algorithm>
746  *      <digest>
747  *      <salt>          Hex string or "-" if no salt.
748  */
749 static int verity_ctr(struct dm_target *ti, unsigned argc, char **argv)
750 {
751         struct dm_verity *v;
752         struct dm_arg_set as;
753         unsigned int num;
754         unsigned long long num_ll;
755         int r;
756         int i;
757         sector_t hash_position;
758         char dummy;
759
760         v = kzalloc(sizeof(struct dm_verity), GFP_KERNEL);
761         if (!v) {
762                 ti->error = "Cannot allocate verity structure";
763                 return -ENOMEM;
764         }
765         ti->private = v;
766         v->ti = ti;
767
768         r = verity_fec_ctr_alloc(v);
769         if (r)
770                 goto bad;
771
772         if ((dm_table_get_mode(ti->table) & ~FMODE_READ)) {
773                 ti->error = "Device must be readonly";
774                 r = -EINVAL;
775                 goto bad;
776         }
777
778         if (argc < 10) {
779                 ti->error = "Not enough arguments";
780                 r = -EINVAL;
781                 goto bad;
782         }
783
784         if (sscanf(argv[0], "%u%c", &num, &dummy) != 1 ||
785             num > 1) {
786                 ti->error = "Invalid version";
787                 r = -EINVAL;
788                 goto bad;
789         }
790         v->version = num;
791
792         r = dm_get_device(ti, argv[1], FMODE_READ, &v->data_dev);
793         if (r) {
794                 ti->error = "Data device lookup failed";
795                 goto bad;
796         }
797
798         r = dm_get_device(ti, argv[2], FMODE_READ, &v->hash_dev);
799         if (r) {
800                 ti->error = "Data device lookup failed";
801                 goto bad;
802         }
803
804         if (sscanf(argv[3], "%u%c", &num, &dummy) != 1 ||
805             !num || (num & (num - 1)) ||
806             num < bdev_logical_block_size(v->data_dev->bdev) ||
807             num > PAGE_SIZE) {
808                 ti->error = "Invalid data device block size";
809                 r = -EINVAL;
810                 goto bad;
811         }
812         v->data_dev_block_bits = __ffs(num);
813
814         if (sscanf(argv[4], "%u%c", &num, &dummy) != 1 ||
815             !num || (num & (num - 1)) ||
816             num < bdev_logical_block_size(v->hash_dev->bdev) ||
817             num > INT_MAX) {
818                 ti->error = "Invalid hash device block size";
819                 r = -EINVAL;
820                 goto bad;
821         }
822         v->hash_dev_block_bits = __ffs(num);
823
824         if (sscanf(argv[5], "%llu%c", &num_ll, &dummy) != 1 ||
825             (sector_t)(num_ll << (v->data_dev_block_bits - SECTOR_SHIFT))
826             >> (v->data_dev_block_bits - SECTOR_SHIFT) != num_ll) {
827                 ti->error = "Invalid data blocks";
828                 r = -EINVAL;
829                 goto bad;
830         }
831         v->data_blocks = num_ll;
832
833         if (ti->len > (v->data_blocks << (v->data_dev_block_bits - SECTOR_SHIFT))) {
834                 ti->error = "Data device is too small";
835                 r = -EINVAL;
836                 goto bad;
837         }
838
839         if (sscanf(argv[6], "%llu%c", &num_ll, &dummy) != 1 ||
840             (sector_t)(num_ll << (v->hash_dev_block_bits - SECTOR_SHIFT))
841             >> (v->hash_dev_block_bits - SECTOR_SHIFT) != num_ll) {
842                 ti->error = "Invalid hash start";
843                 r = -EINVAL;
844                 goto bad;
845         }
846         v->hash_start = num_ll;
847
848         v->alg_name = kstrdup(argv[7], GFP_KERNEL);
849         if (!v->alg_name) {
850                 ti->error = "Cannot allocate algorithm name";
851                 r = -ENOMEM;
852                 goto bad;
853         }
854
855         v->tfm = crypto_alloc_shash(v->alg_name, 0, 0);
856         if (IS_ERR(v->tfm)) {
857                 ti->error = "Cannot initialize hash function";
858                 r = PTR_ERR(v->tfm);
859                 v->tfm = NULL;
860                 goto bad;
861         }
862         v->digest_size = crypto_shash_digestsize(v->tfm);
863         if ((1 << v->hash_dev_block_bits) < v->digest_size * 2) {
864                 ti->error = "Digest size too big";
865                 r = -EINVAL;
866                 goto bad;
867         }
868         v->shash_descsize =
869                 sizeof(struct shash_desc) + crypto_shash_descsize(v->tfm);
870
871         v->root_digest = kmalloc(v->digest_size, GFP_KERNEL);
872         if (!v->root_digest) {
873                 ti->error = "Cannot allocate root digest";
874                 r = -ENOMEM;
875                 goto bad;
876         }
877         if (strlen(argv[8]) != v->digest_size * 2 ||
878             hex2bin(v->root_digest, argv[8], v->digest_size)) {
879                 ti->error = "Invalid root digest";
880                 r = -EINVAL;
881                 goto bad;
882         }
883
884         if (strcmp(argv[9], "-")) {
885                 v->salt_size = strlen(argv[9]) / 2;
886                 v->salt = kmalloc(v->salt_size, GFP_KERNEL);
887                 if (!v->salt) {
888                         ti->error = "Cannot allocate salt";
889                         r = -ENOMEM;
890                         goto bad;
891                 }
892                 if (strlen(argv[9]) != v->salt_size * 2 ||
893                     hex2bin(v->salt, argv[9], v->salt_size)) {
894                         ti->error = "Invalid salt";
895                         r = -EINVAL;
896                         goto bad;
897                 }
898         }
899
900         argv += 10;
901         argc -= 10;
902
903         /* Optional parameters */
904         if (argc) {
905                 as.argc = argc;
906                 as.argv = argv;
907
908                 r = verity_parse_opt_args(&as, v);
909                 if (r < 0)
910                         goto bad;
911         }
912
913         v->hash_per_block_bits =
914                 __fls((1 << v->hash_dev_block_bits) / v->digest_size);
915
916         v->levels = 0;
917         if (v->data_blocks)
918                 while (v->hash_per_block_bits * v->levels < 64 &&
919                        (unsigned long long)(v->data_blocks - 1) >>
920                        (v->hash_per_block_bits * v->levels))
921                         v->levels++;
922
923         if (v->levels > DM_VERITY_MAX_LEVELS) {
924                 ti->error = "Too many tree levels";
925                 r = -E2BIG;
926                 goto bad;
927         }
928
929         hash_position = v->hash_start;
930         for (i = v->levels - 1; i >= 0; i--) {
931                 sector_t s;
932                 v->hash_level_block[i] = hash_position;
933                 s = (v->data_blocks + ((sector_t)1 << ((i + 1) * v->hash_per_block_bits)) - 1)
934                                         >> ((i + 1) * v->hash_per_block_bits);
935                 if (hash_position + s < hash_position) {
936                         ti->error = "Hash device offset overflow";
937                         r = -E2BIG;
938                         goto bad;
939                 }
940                 hash_position += s;
941         }
942         v->hash_blocks = hash_position;
943
944         v->bufio = dm_bufio_client_create(v->hash_dev->bdev,
945                 1 << v->hash_dev_block_bits, 1, sizeof(struct buffer_aux),
946                 dm_bufio_alloc_callback, NULL);
947         if (IS_ERR(v->bufio)) {
948                 ti->error = "Cannot initialize dm-bufio";
949                 r = PTR_ERR(v->bufio);
950                 v->bufio = NULL;
951                 goto bad;
952         }
953
954         if (dm_bufio_get_device_size(v->bufio) < v->hash_blocks) {
955                 ti->error = "Hash device is too small";
956                 r = -E2BIG;
957                 goto bad;
958         }
959
960         /* WQ_UNBOUND greatly improves performance when running on ramdisk */
961         v->verify_wq = alloc_workqueue("kverityd", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND, num_online_cpus());
962         if (!v->verify_wq) {
963                 ti->error = "Cannot allocate workqueue";
964                 r = -ENOMEM;
965                 goto bad;
966         }
967
968         ti->per_bio_data_size = sizeof(struct dm_verity_io) +
969                                 v->shash_descsize + v->digest_size * 2;
970
971         r = verity_fec_ctr(v);
972         if (r)
973                 goto bad;
974
975         ti->per_bio_data_size = roundup(ti->per_bio_data_size,
976                                         __alignof__(struct dm_verity_io));
977
978         return 0;
979
980 bad:
981         verity_dtr(ti);
982
983         return r;
984 }
985
986 static struct target_type verity_target = {
987         .name           = "verity",
988         .version        = {1, 3, 0},
989         .module         = THIS_MODULE,
990         .ctr            = verity_ctr,
991         .dtr            = verity_dtr,
992         .map            = verity_map,
993         .status         = verity_status,
994         .prepare_ioctl  = verity_prepare_ioctl,
995         .iterate_devices = verity_iterate_devices,
996         .io_hints       = verity_io_hints,
997 };
998
999 static int __init dm_verity_init(void)
1000 {
1001         int r;
1002
1003         r = dm_register_target(&verity_target);
1004         if (r < 0)
1005                 DMERR("register failed %d", r);
1006
1007         return r;
1008 }
1009
1010 static void __exit dm_verity_exit(void)
1011 {
1012         dm_unregister_target(&verity_target);
1013 }
1014
1015 module_init(dm_verity_init);
1016 module_exit(dm_verity_exit);
1017
1018 MODULE_AUTHOR("Mikulas Patocka <mpatocka@redhat.com>");
1019 MODULE_AUTHOR("Mandeep Baines <msb@chromium.org>");
1020 MODULE_AUTHOR("Will Drewry <wad@chromium.org>");
1021 MODULE_DESCRIPTION(DM_NAME " target for transparent disk integrity checking");
1022 MODULE_LICENSE("GPL");