OSDN Git Service

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