xref: /linux/drivers/md/dm-verity-target.c (revision 03b18887703c5fa342896e52e873812ea33d964b)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2012 Red Hat, Inc.
4  *
5  * Author: Mikulas Patocka <mpatocka@redhat.com>
6  *
7  * Based on Chromium dm-verity driver (C) 2011 The Chromium OS Authors
8  *
9  * In the file "/sys/module/dm_verity/parameters/prefetch_cluster" you can set
10  * default prefetch value. Data are read in "prefetch_cluster" chunks from the
11  * hash device. Setting this greatly improves performance when data and hash
12  * are on the same disk on different partitions on devices with poor random
13  * access behavior.
14  */
15 
16 #include "dm-verity.h"
17 #include "dm-verity-fec.h"
18 #include "dm-verity-verify-sig.h"
19 #include <linux/module.h>
20 #include <linux/reboot.h>
21 #include <linux/scatterlist.h>
22 #include <linux/string.h>
23 #include <linux/jump_label.h>
24 
25 #define DM_MSG_PREFIX			"verity"
26 
27 #define DM_VERITY_ENV_LENGTH		42
28 #define DM_VERITY_ENV_VAR_NAME		"DM_VERITY_ERR_BLOCK_NR"
29 
30 #define DM_VERITY_DEFAULT_PREFETCH_SIZE	262144
31 
32 #define DM_VERITY_MAX_CORRUPTED_ERRS	100
33 
34 #define DM_VERITY_OPT_LOGGING		"ignore_corruption"
35 #define DM_VERITY_OPT_RESTART		"restart_on_corruption"
36 #define DM_VERITY_OPT_PANIC		"panic_on_corruption"
37 #define DM_VERITY_OPT_IGN_ZEROES	"ignore_zero_blocks"
38 #define DM_VERITY_OPT_AT_MOST_ONCE	"check_at_most_once"
39 #define DM_VERITY_OPT_TASKLET_VERIFY	"try_verify_in_tasklet"
40 
41 #define DM_VERITY_OPTS_MAX		(4 + DM_VERITY_OPTS_FEC + \
42 					 DM_VERITY_ROOT_HASH_VERIFICATION_OPTS)
43 
44 static unsigned int dm_verity_prefetch_cluster = DM_VERITY_DEFAULT_PREFETCH_SIZE;
45 
46 module_param_named(prefetch_cluster, dm_verity_prefetch_cluster, uint, S_IRUGO | S_IWUSR);
47 
48 static DEFINE_STATIC_KEY_FALSE(use_tasklet_enabled);
49 
50 struct dm_verity_prefetch_work {
51 	struct work_struct work;
52 	struct dm_verity *v;
53 	sector_t block;
54 	unsigned int n_blocks;
55 };
56 
57 /*
58  * Auxiliary structure appended to each dm-bufio buffer. If the value
59  * hash_verified is nonzero, hash of the block has been verified.
60  *
61  * The variable hash_verified is set to 0 when allocating the buffer, then
62  * it can be changed to 1 and it is never reset to 0 again.
63  *
64  * There is no lock around this value, a race condition can at worst cause
65  * that multiple processes verify the hash of the same buffer simultaneously
66  * and write 1 to hash_verified simultaneously.
67  * This condition is harmless, so we don't need locking.
68  */
69 struct buffer_aux {
70 	int hash_verified;
71 };
72 
73 /*
74  * Initialize struct buffer_aux for a freshly created buffer.
75  */
76 static void dm_bufio_alloc_callback(struct dm_buffer *buf)
77 {
78 	struct buffer_aux *aux = dm_bufio_get_aux_data(buf);
79 
80 	aux->hash_verified = 0;
81 }
82 
83 /*
84  * Translate input sector number to the sector number on the target device.
85  */
86 static sector_t verity_map_sector(struct dm_verity *v, sector_t bi_sector)
87 {
88 	return v->data_start + dm_target_offset(v->ti, bi_sector);
89 }
90 
91 /*
92  * Return hash position of a specified block at a specified tree level
93  * (0 is the lowest level).
94  * The lowest "hash_per_block_bits"-bits of the result denote hash position
95  * inside a hash block. The remaining bits denote location of the hash block.
96  */
97 static sector_t verity_position_at_level(struct dm_verity *v, sector_t block,
98 					 int level)
99 {
100 	return block >> (level * v->hash_per_block_bits);
101 }
102 
103 static int verity_hash_update(struct dm_verity *v, struct ahash_request *req,
104 				const u8 *data, size_t len,
105 				struct crypto_wait *wait)
106 {
107 	struct scatterlist sg;
108 
109 	if (likely(!is_vmalloc_addr(data))) {
110 		sg_init_one(&sg, data, len);
111 		ahash_request_set_crypt(req, &sg, NULL, len);
112 		return crypto_wait_req(crypto_ahash_update(req), wait);
113 	} else {
114 		do {
115 			int r;
116 			size_t this_step = min_t(size_t, len, PAGE_SIZE - offset_in_page(data));
117 			flush_kernel_vmap_range((void *)data, this_step);
118 			sg_init_table(&sg, 1);
119 			sg_set_page(&sg, vmalloc_to_page(data), this_step, offset_in_page(data));
120 			ahash_request_set_crypt(req, &sg, NULL, this_step);
121 			r = crypto_wait_req(crypto_ahash_update(req), wait);
122 			if (unlikely(r))
123 				return r;
124 			data += this_step;
125 			len -= this_step;
126 		} while (len);
127 		return 0;
128 	}
129 }
130 
131 /*
132  * Wrapper for crypto_ahash_init, which handles verity salting.
133  */
134 static int verity_hash_init(struct dm_verity *v, struct ahash_request *req,
135 				struct crypto_wait *wait)
136 {
137 	int r;
138 
139 	ahash_request_set_tfm(req, v->tfm);
140 	ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP |
141 					CRYPTO_TFM_REQ_MAY_BACKLOG,
142 					crypto_req_done, (void *)wait);
143 	crypto_init_wait(wait);
144 
145 	r = crypto_wait_req(crypto_ahash_init(req), wait);
146 
147 	if (unlikely(r < 0)) {
148 		DMERR("crypto_ahash_init failed: %d", r);
149 		return r;
150 	}
151 
152 	if (likely(v->salt_size && (v->version >= 1)))
153 		r = verity_hash_update(v, req, v->salt, v->salt_size, wait);
154 
155 	return r;
156 }
157 
158 static int verity_hash_final(struct dm_verity *v, struct ahash_request *req,
159 			     u8 *digest, struct crypto_wait *wait)
160 {
161 	int r;
162 
163 	if (unlikely(v->salt_size && (!v->version))) {
164 		r = verity_hash_update(v, req, v->salt, v->salt_size, wait);
165 
166 		if (r < 0) {
167 			DMERR("verity_hash_final failed updating salt: %d", r);
168 			goto out;
169 		}
170 	}
171 
172 	ahash_request_set_crypt(req, NULL, digest, 0);
173 	r = crypto_wait_req(crypto_ahash_final(req), wait);
174 out:
175 	return r;
176 }
177 
178 int verity_hash(struct dm_verity *v, struct ahash_request *req,
179 		const u8 *data, size_t len, u8 *digest)
180 {
181 	int r;
182 	struct crypto_wait wait;
183 
184 	r = verity_hash_init(v, req, &wait);
185 	if (unlikely(r < 0))
186 		goto out;
187 
188 	r = verity_hash_update(v, req, data, len, &wait);
189 	if (unlikely(r < 0))
190 		goto out;
191 
192 	r = verity_hash_final(v, req, digest, &wait);
193 
194 out:
195 	return r;
196 }
197 
198 static void verity_hash_at_level(struct dm_verity *v, sector_t block, int level,
199 				 sector_t *hash_block, unsigned int *offset)
200 {
201 	sector_t position = verity_position_at_level(v, block, level);
202 	unsigned int idx;
203 
204 	*hash_block = v->hash_level_block[level] + (position >> v->hash_per_block_bits);
205 
206 	if (!offset)
207 		return;
208 
209 	idx = position & ((1 << v->hash_per_block_bits) - 1);
210 	if (!v->version)
211 		*offset = idx * v->digest_size;
212 	else
213 		*offset = idx << (v->hash_dev_block_bits - v->hash_per_block_bits);
214 }
215 
216 /*
217  * Handle verification errors.
218  */
219 static int verity_handle_err(struct dm_verity *v, enum verity_block_type type,
220 			     unsigned long long block)
221 {
222 	char verity_env[DM_VERITY_ENV_LENGTH];
223 	char *envp[] = { verity_env, NULL };
224 	const char *type_str = "";
225 	struct mapped_device *md = dm_table_get_md(v->ti->table);
226 
227 	/* Corruption should be visible in device status in all modes */
228 	v->hash_failed = true;
229 
230 	if (v->corrupted_errs >= DM_VERITY_MAX_CORRUPTED_ERRS)
231 		goto out;
232 
233 	v->corrupted_errs++;
234 
235 	switch (type) {
236 	case DM_VERITY_BLOCK_TYPE_DATA:
237 		type_str = "data";
238 		break;
239 	case DM_VERITY_BLOCK_TYPE_METADATA:
240 		type_str = "metadata";
241 		break;
242 	default:
243 		BUG();
244 	}
245 
246 	DMERR_LIMIT("%s: %s block %llu is corrupted", v->data_dev->name,
247 		    type_str, block);
248 
249 	if (v->corrupted_errs == DM_VERITY_MAX_CORRUPTED_ERRS)
250 		DMERR("%s: reached maximum errors", v->data_dev->name);
251 
252 	snprintf(verity_env, DM_VERITY_ENV_LENGTH, "%s=%d,%llu",
253 		DM_VERITY_ENV_VAR_NAME, type, block);
254 
255 	kobject_uevent_env(&disk_to_dev(dm_disk(md))->kobj, KOBJ_CHANGE, envp);
256 
257 out:
258 	if (v->mode == DM_VERITY_MODE_LOGGING)
259 		return 0;
260 
261 	if (v->mode == DM_VERITY_MODE_RESTART)
262 		kernel_restart("dm-verity device corrupted");
263 
264 	if (v->mode == DM_VERITY_MODE_PANIC)
265 		panic("dm-verity device corrupted");
266 
267 	return 1;
268 }
269 
270 /*
271  * Verify hash of a metadata block pertaining to the specified data block
272  * ("block" argument) at a specified level ("level" argument).
273  *
274  * On successful return, verity_io_want_digest(v, io) contains the hash value
275  * for a lower tree level or for the data block (if we're at the lowest level).
276  *
277  * If "skip_unverified" is true, unverified buffer is skipped and 1 is returned.
278  * If "skip_unverified" is false, unverified buffer is hashed and verified
279  * against current value of verity_io_want_digest(v, io).
280  */
281 static int verity_verify_level(struct dm_verity *v, struct dm_verity_io *io,
282 			       sector_t block, int level, bool skip_unverified,
283 			       u8 *want_digest)
284 {
285 	struct dm_buffer *buf;
286 	struct buffer_aux *aux;
287 	u8 *data;
288 	int r;
289 	sector_t hash_block;
290 	unsigned int offset;
291 
292 	verity_hash_at_level(v, block, level, &hash_block, &offset);
293 
294 	if (static_branch_unlikely(&use_tasklet_enabled) && io->in_tasklet) {
295 		data = dm_bufio_get(v->bufio, hash_block, &buf);
296 		if (data == NULL) {
297 			/*
298 			 * In tasklet and the hash was not in the bufio cache.
299 			 * Return early and resume execution from a work-queue
300 			 * to read the hash from disk.
301 			 */
302 			return -EAGAIN;
303 		}
304 	} else
305 		data = dm_bufio_read(v->bufio, hash_block, &buf);
306 
307 	if (IS_ERR(data))
308 		return PTR_ERR(data);
309 
310 	aux = dm_bufio_get_aux_data(buf);
311 
312 	if (!aux->hash_verified) {
313 		if (skip_unverified) {
314 			r = 1;
315 			goto release_ret_r;
316 		}
317 
318 		r = verity_hash(v, verity_io_hash_req(v, io),
319 				data, 1 << v->hash_dev_block_bits,
320 				verity_io_real_digest(v, io));
321 		if (unlikely(r < 0))
322 			goto release_ret_r;
323 
324 		if (likely(memcmp(verity_io_real_digest(v, io), want_digest,
325 				  v->digest_size) == 0))
326 			aux->hash_verified = 1;
327 		else if (static_branch_unlikely(&use_tasklet_enabled) &&
328 			 io->in_tasklet) {
329 			/*
330 			 * Error handling code (FEC included) cannot be run in a
331 			 * tasklet since it may sleep, so fallback to work-queue.
332 			 */
333 			r = -EAGAIN;
334 			goto release_ret_r;
335 		} else if (verity_fec_decode(v, io, DM_VERITY_BLOCK_TYPE_METADATA,
336 					     hash_block, data, NULL) == 0)
337 			aux->hash_verified = 1;
338 		else if (verity_handle_err(v,
339 					   DM_VERITY_BLOCK_TYPE_METADATA,
340 					   hash_block)) {
341 			r = -EIO;
342 			goto release_ret_r;
343 		}
344 	}
345 
346 	data += offset;
347 	memcpy(want_digest, data, v->digest_size);
348 	r = 0;
349 
350 release_ret_r:
351 	dm_bufio_release(buf);
352 	return r;
353 }
354 
355 /*
356  * Find a hash for a given block, write it to digest and verify the integrity
357  * of the hash tree if necessary.
358  */
359 int verity_hash_for_block(struct dm_verity *v, struct dm_verity_io *io,
360 			  sector_t block, u8 *digest, bool *is_zero)
361 {
362 	int r = 0, i;
363 
364 	if (likely(v->levels)) {
365 		/*
366 		 * First, we try to get the requested hash for
367 		 * the current block. If the hash block itself is
368 		 * verified, zero is returned. If it isn't, this
369 		 * function returns 1 and we fall back to whole
370 		 * chain verification.
371 		 */
372 		r = verity_verify_level(v, io, block, 0, true, digest);
373 		if (likely(r <= 0))
374 			goto out;
375 	}
376 
377 	memcpy(digest, v->root_digest, v->digest_size);
378 
379 	for (i = v->levels - 1; i >= 0; i--) {
380 		r = verity_verify_level(v, io, block, i, false, digest);
381 		if (unlikely(r))
382 			goto out;
383 	}
384 out:
385 	if (!r && v->zero_digest)
386 		*is_zero = !memcmp(v->zero_digest, digest, v->digest_size);
387 	else
388 		*is_zero = false;
389 
390 	return r;
391 }
392 
393 /*
394  * Calculates the digest for the given bio
395  */
396 static int verity_for_io_block(struct dm_verity *v, struct dm_verity_io *io,
397 			       struct bvec_iter *iter, struct crypto_wait *wait)
398 {
399 	unsigned int todo = 1 << v->data_dev_block_bits;
400 	struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_io_data_size);
401 	struct scatterlist sg;
402 	struct ahash_request *req = verity_io_hash_req(v, io);
403 
404 	do {
405 		int r;
406 		unsigned int len;
407 		struct bio_vec bv = bio_iter_iovec(bio, *iter);
408 
409 		sg_init_table(&sg, 1);
410 
411 		len = bv.bv_len;
412 
413 		if (likely(len >= todo))
414 			len = todo;
415 		/*
416 		 * Operating on a single page at a time looks suboptimal
417 		 * until you consider the typical block size is 4,096B.
418 		 * Going through this loops twice should be very rare.
419 		 */
420 		sg_set_page(&sg, bv.bv_page, len, bv.bv_offset);
421 		ahash_request_set_crypt(req, &sg, NULL, len);
422 		r = crypto_wait_req(crypto_ahash_update(req), wait);
423 
424 		if (unlikely(r < 0)) {
425 			DMERR("verity_for_io_block crypto op failed: %d", r);
426 			return r;
427 		}
428 
429 		bio_advance_iter(bio, iter, len);
430 		todo -= len;
431 	} while (todo);
432 
433 	return 0;
434 }
435 
436 /*
437  * Calls function process for 1 << v->data_dev_block_bits bytes in the bio_vec
438  * starting from iter.
439  */
440 int verity_for_bv_block(struct dm_verity *v, struct dm_verity_io *io,
441 			struct bvec_iter *iter,
442 			int (*process)(struct dm_verity *v,
443 				       struct dm_verity_io *io, u8 *data,
444 				       size_t len))
445 {
446 	unsigned int todo = 1 << v->data_dev_block_bits;
447 	struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_io_data_size);
448 
449 	do {
450 		int r;
451 		u8 *page;
452 		unsigned int len;
453 		struct bio_vec bv = bio_iter_iovec(bio, *iter);
454 
455 		page = bvec_kmap_local(&bv);
456 		len = bv.bv_len;
457 
458 		if (likely(len >= todo))
459 			len = todo;
460 
461 		r = process(v, io, page, len);
462 		kunmap_local(page);
463 
464 		if (r < 0)
465 			return r;
466 
467 		bio_advance_iter(bio, iter, len);
468 		todo -= len;
469 	} while (todo);
470 
471 	return 0;
472 }
473 
474 static int verity_bv_zero(struct dm_verity *v, struct dm_verity_io *io,
475 			  u8 *data, size_t len)
476 {
477 	memset(data, 0, len);
478 	return 0;
479 }
480 
481 /*
482  * Moves the bio iter one data block forward.
483  */
484 static inline void verity_bv_skip_block(struct dm_verity *v,
485 					struct dm_verity_io *io,
486 					struct bvec_iter *iter)
487 {
488 	struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_io_data_size);
489 
490 	bio_advance_iter(bio, iter, 1 << v->data_dev_block_bits);
491 }
492 
493 /*
494  * Verify one "dm_verity_io" structure.
495  */
496 static int verity_verify_io(struct dm_verity_io *io)
497 {
498 	bool is_zero;
499 	struct dm_verity *v = io->v;
500 #if defined(CONFIG_DM_VERITY_FEC)
501 	struct bvec_iter start;
502 #endif
503 	struct bvec_iter iter_copy;
504 	struct bvec_iter *iter;
505 	struct crypto_wait wait;
506 	struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_io_data_size);
507 	unsigned int b;
508 
509 	if (static_branch_unlikely(&use_tasklet_enabled) && io->in_tasklet) {
510 		/*
511 		 * Copy the iterator in case we need to restart
512 		 * verification in a work-queue.
513 		 */
514 		iter_copy = io->iter;
515 		iter = &iter_copy;
516 	} else
517 		iter = &io->iter;
518 
519 	for (b = 0; b < io->n_blocks; b++) {
520 		int r;
521 		sector_t cur_block = io->block + b;
522 		struct ahash_request *req = verity_io_hash_req(v, io);
523 
524 		if (v->validated_blocks &&
525 		    likely(test_bit(cur_block, v->validated_blocks))) {
526 			verity_bv_skip_block(v, io, iter);
527 			continue;
528 		}
529 
530 		r = verity_hash_for_block(v, io, cur_block,
531 					  verity_io_want_digest(v, io),
532 					  &is_zero);
533 		if (unlikely(r < 0))
534 			return r;
535 
536 		if (is_zero) {
537 			/*
538 			 * If we expect a zero block, don't validate, just
539 			 * return zeros.
540 			 */
541 			r = verity_for_bv_block(v, io, iter,
542 						verity_bv_zero);
543 			if (unlikely(r < 0))
544 				return r;
545 
546 			continue;
547 		}
548 
549 		r = verity_hash_init(v, req, &wait);
550 		if (unlikely(r < 0))
551 			return r;
552 
553 #if defined(CONFIG_DM_VERITY_FEC)
554 		if (verity_fec_is_enabled(v))
555 			start = *iter;
556 #endif
557 		r = verity_for_io_block(v, io, iter, &wait);
558 		if (unlikely(r < 0))
559 			return r;
560 
561 		r = verity_hash_final(v, req, verity_io_real_digest(v, io),
562 					&wait);
563 		if (unlikely(r < 0))
564 			return r;
565 
566 		if (likely(memcmp(verity_io_real_digest(v, io),
567 				  verity_io_want_digest(v, io), v->digest_size) == 0)) {
568 			if (v->validated_blocks)
569 				set_bit(cur_block, v->validated_blocks);
570 			continue;
571 		} else if (static_branch_unlikely(&use_tasklet_enabled) &&
572 			   io->in_tasklet) {
573 			/*
574 			 * Error handling code (FEC included) cannot be run in a
575 			 * tasklet since it may sleep, so fallback to work-queue.
576 			 */
577 			return -EAGAIN;
578 #if defined(CONFIG_DM_VERITY_FEC)
579 		} else if (verity_fec_decode(v, io, DM_VERITY_BLOCK_TYPE_DATA,
580 					     cur_block, NULL, &start) == 0) {
581 			continue;
582 #endif
583 		} else {
584 			if (bio->bi_status) {
585 				/*
586 				 * Error correction failed; Just return error
587 				 */
588 				return -EIO;
589 			}
590 			if (verity_handle_err(v, DM_VERITY_BLOCK_TYPE_DATA,
591 					      cur_block))
592 				return -EIO;
593 		}
594 	}
595 
596 	return 0;
597 }
598 
599 /*
600  * Skip verity work in response to I/O error when system is shutting down.
601  */
602 static inline bool verity_is_system_shutting_down(void)
603 {
604 	return system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF
605 		|| system_state == SYSTEM_RESTART;
606 }
607 
608 /*
609  * End one "io" structure with a given error.
610  */
611 static void verity_finish_io(struct dm_verity_io *io, blk_status_t status)
612 {
613 	struct dm_verity *v = io->v;
614 	struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_io_data_size);
615 
616 	bio->bi_end_io = io->orig_bi_end_io;
617 	bio->bi_status = status;
618 
619 	if (!static_branch_unlikely(&use_tasklet_enabled) || !io->in_tasklet)
620 		verity_fec_finish_io(io);
621 
622 	bio_endio(bio);
623 }
624 
625 static void verity_work(struct work_struct *w)
626 {
627 	struct dm_verity_io *io = container_of(w, struct dm_verity_io, work);
628 
629 	io->in_tasklet = false;
630 
631 	verity_fec_init_io(io);
632 	verity_finish_io(io, errno_to_blk_status(verity_verify_io(io)));
633 }
634 
635 static void verity_tasklet(unsigned long data)
636 {
637 	struct dm_verity_io *io = (struct dm_verity_io *)data;
638 	int err;
639 
640 	io->in_tasklet = true;
641 	err = verity_verify_io(io);
642 	if (err == -EAGAIN) {
643 		/* fallback to retrying with work-queue */
644 		INIT_WORK(&io->work, verity_work);
645 		queue_work(io->v->verify_wq, &io->work);
646 		return;
647 	}
648 
649 	verity_finish_io(io, errno_to_blk_status(err));
650 }
651 
652 static void verity_end_io(struct bio *bio)
653 {
654 	struct dm_verity_io *io = bio->bi_private;
655 
656 	if (bio->bi_status &&
657 	    (!verity_fec_is_enabled(io->v) || verity_is_system_shutting_down())) {
658 		verity_finish_io(io, bio->bi_status);
659 		return;
660 	}
661 
662 	if (static_branch_unlikely(&use_tasklet_enabled) && io->v->use_tasklet) {
663 		tasklet_init(&io->tasklet, verity_tasklet, (unsigned long)io);
664 		tasklet_schedule(&io->tasklet);
665 	} else {
666 		INIT_WORK(&io->work, verity_work);
667 		queue_work(io->v->verify_wq, &io->work);
668 	}
669 }
670 
671 /*
672  * Prefetch buffers for the specified io.
673  * The root buffer is not prefetched, it is assumed that it will be cached
674  * all the time.
675  */
676 static void verity_prefetch_io(struct work_struct *work)
677 {
678 	struct dm_verity_prefetch_work *pw =
679 		container_of(work, struct dm_verity_prefetch_work, work);
680 	struct dm_verity *v = pw->v;
681 	int i;
682 
683 	for (i = v->levels - 2; i >= 0; i--) {
684 		sector_t hash_block_start;
685 		sector_t hash_block_end;
686 		verity_hash_at_level(v, pw->block, i, &hash_block_start, NULL);
687 		verity_hash_at_level(v, pw->block + pw->n_blocks - 1, i, &hash_block_end, NULL);
688 		if (!i) {
689 			unsigned int cluster = READ_ONCE(dm_verity_prefetch_cluster);
690 
691 			cluster >>= v->data_dev_block_bits;
692 			if (unlikely(!cluster))
693 				goto no_prefetch_cluster;
694 
695 			if (unlikely(cluster & (cluster - 1)))
696 				cluster = 1 << __fls(cluster);
697 
698 			hash_block_start &= ~(sector_t)(cluster - 1);
699 			hash_block_end |= cluster - 1;
700 			if (unlikely(hash_block_end >= v->hash_blocks))
701 				hash_block_end = v->hash_blocks - 1;
702 		}
703 no_prefetch_cluster:
704 		dm_bufio_prefetch(v->bufio, hash_block_start,
705 				  hash_block_end - hash_block_start + 1);
706 	}
707 
708 	kfree(pw);
709 }
710 
711 static void verity_submit_prefetch(struct dm_verity *v, struct dm_verity_io *io)
712 {
713 	sector_t block = io->block;
714 	unsigned int n_blocks = io->n_blocks;
715 	struct dm_verity_prefetch_work *pw;
716 
717 	if (v->validated_blocks) {
718 		while (n_blocks && test_bit(block, v->validated_blocks)) {
719 			block++;
720 			n_blocks--;
721 		}
722 		while (n_blocks && test_bit(block + n_blocks - 1,
723 					    v->validated_blocks))
724 			n_blocks--;
725 		if (!n_blocks)
726 			return;
727 	}
728 
729 	pw = kmalloc(sizeof(struct dm_verity_prefetch_work),
730 		GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
731 
732 	if (!pw)
733 		return;
734 
735 	INIT_WORK(&pw->work, verity_prefetch_io);
736 	pw->v = v;
737 	pw->block = block;
738 	pw->n_blocks = n_blocks;
739 	queue_work(v->verify_wq, &pw->work);
740 }
741 
742 /*
743  * Bio map function. It allocates dm_verity_io structure and bio vector and
744  * fills them. Then it issues prefetches and the I/O.
745  */
746 static int verity_map(struct dm_target *ti, struct bio *bio)
747 {
748 	struct dm_verity *v = ti->private;
749 	struct dm_verity_io *io;
750 
751 	bio_set_dev(bio, v->data_dev->bdev);
752 	bio->bi_iter.bi_sector = verity_map_sector(v, bio->bi_iter.bi_sector);
753 
754 	if (((unsigned int)bio->bi_iter.bi_sector | bio_sectors(bio)) &
755 	    ((1 << (v->data_dev_block_bits - SECTOR_SHIFT)) - 1)) {
756 		DMERR_LIMIT("unaligned io");
757 		return DM_MAPIO_KILL;
758 	}
759 
760 	if (bio_end_sector(bio) >>
761 	    (v->data_dev_block_bits - SECTOR_SHIFT) > v->data_blocks) {
762 		DMERR_LIMIT("io out of range");
763 		return DM_MAPIO_KILL;
764 	}
765 
766 	if (bio_data_dir(bio) == WRITE)
767 		return DM_MAPIO_KILL;
768 
769 	io = dm_per_bio_data(bio, ti->per_io_data_size);
770 	io->v = v;
771 	io->orig_bi_end_io = bio->bi_end_io;
772 	io->block = bio->bi_iter.bi_sector >> (v->data_dev_block_bits - SECTOR_SHIFT);
773 	io->n_blocks = bio->bi_iter.bi_size >> v->data_dev_block_bits;
774 
775 	bio->bi_end_io = verity_end_io;
776 	bio->bi_private = io;
777 	io->iter = bio->bi_iter;
778 
779 	verity_submit_prefetch(v, io);
780 
781 	submit_bio_noacct(bio);
782 
783 	return DM_MAPIO_SUBMITTED;
784 }
785 
786 /*
787  * Status: V (valid) or C (corruption found)
788  */
789 static void verity_status(struct dm_target *ti, status_type_t type,
790 			  unsigned int status_flags, char *result, unsigned int maxlen)
791 {
792 	struct dm_verity *v = ti->private;
793 	unsigned int args = 0;
794 	unsigned int sz = 0;
795 	unsigned int x;
796 
797 	switch (type) {
798 	case STATUSTYPE_INFO:
799 		DMEMIT("%c", v->hash_failed ? 'C' : 'V');
800 		break;
801 	case STATUSTYPE_TABLE:
802 		DMEMIT("%u %s %s %u %u %llu %llu %s ",
803 			v->version,
804 			v->data_dev->name,
805 			v->hash_dev->name,
806 			1 << v->data_dev_block_bits,
807 			1 << v->hash_dev_block_bits,
808 			(unsigned long long)v->data_blocks,
809 			(unsigned long long)v->hash_start,
810 			v->alg_name
811 			);
812 		for (x = 0; x < v->digest_size; x++)
813 			DMEMIT("%02x", v->root_digest[x]);
814 		DMEMIT(" ");
815 		if (!v->salt_size)
816 			DMEMIT("-");
817 		else
818 			for (x = 0; x < v->salt_size; x++)
819 				DMEMIT("%02x", v->salt[x]);
820 		if (v->mode != DM_VERITY_MODE_EIO)
821 			args++;
822 		if (verity_fec_is_enabled(v))
823 			args += DM_VERITY_OPTS_FEC;
824 		if (v->zero_digest)
825 			args++;
826 		if (v->validated_blocks)
827 			args++;
828 		if (v->use_tasklet)
829 			args++;
830 		if (v->signature_key_desc)
831 			args += DM_VERITY_ROOT_HASH_VERIFICATION_OPTS;
832 		if (!args)
833 			return;
834 		DMEMIT(" %u", args);
835 		if (v->mode != DM_VERITY_MODE_EIO) {
836 			DMEMIT(" ");
837 			switch (v->mode) {
838 			case DM_VERITY_MODE_LOGGING:
839 				DMEMIT(DM_VERITY_OPT_LOGGING);
840 				break;
841 			case DM_VERITY_MODE_RESTART:
842 				DMEMIT(DM_VERITY_OPT_RESTART);
843 				break;
844 			case DM_VERITY_MODE_PANIC:
845 				DMEMIT(DM_VERITY_OPT_PANIC);
846 				break;
847 			default:
848 				BUG();
849 			}
850 		}
851 		if (v->zero_digest)
852 			DMEMIT(" " DM_VERITY_OPT_IGN_ZEROES);
853 		if (v->validated_blocks)
854 			DMEMIT(" " DM_VERITY_OPT_AT_MOST_ONCE);
855 		if (v->use_tasklet)
856 			DMEMIT(" " DM_VERITY_OPT_TASKLET_VERIFY);
857 		sz = verity_fec_status_table(v, sz, result, maxlen);
858 		if (v->signature_key_desc)
859 			DMEMIT(" " DM_VERITY_ROOT_HASH_VERIFICATION_OPT_SIG_KEY
860 				" %s", v->signature_key_desc);
861 		break;
862 
863 	case STATUSTYPE_IMA:
864 		DMEMIT_TARGET_NAME_VERSION(ti->type);
865 		DMEMIT(",hash_failed=%c", v->hash_failed ? 'C' : 'V');
866 		DMEMIT(",verity_version=%u", v->version);
867 		DMEMIT(",data_device_name=%s", v->data_dev->name);
868 		DMEMIT(",hash_device_name=%s", v->hash_dev->name);
869 		DMEMIT(",verity_algorithm=%s", v->alg_name);
870 
871 		DMEMIT(",root_digest=");
872 		for (x = 0; x < v->digest_size; x++)
873 			DMEMIT("%02x", v->root_digest[x]);
874 
875 		DMEMIT(",salt=");
876 		if (!v->salt_size)
877 			DMEMIT("-");
878 		else
879 			for (x = 0; x < v->salt_size; x++)
880 				DMEMIT("%02x", v->salt[x]);
881 
882 		DMEMIT(",ignore_zero_blocks=%c", v->zero_digest ? 'y' : 'n');
883 		DMEMIT(",check_at_most_once=%c", v->validated_blocks ? 'y' : 'n');
884 		if (v->signature_key_desc)
885 			DMEMIT(",root_hash_sig_key_desc=%s", v->signature_key_desc);
886 
887 		if (v->mode != DM_VERITY_MODE_EIO) {
888 			DMEMIT(",verity_mode=");
889 			switch (v->mode) {
890 			case DM_VERITY_MODE_LOGGING:
891 				DMEMIT(DM_VERITY_OPT_LOGGING);
892 				break;
893 			case DM_VERITY_MODE_RESTART:
894 				DMEMIT(DM_VERITY_OPT_RESTART);
895 				break;
896 			case DM_VERITY_MODE_PANIC:
897 				DMEMIT(DM_VERITY_OPT_PANIC);
898 				break;
899 			default:
900 				DMEMIT("invalid");
901 			}
902 		}
903 		DMEMIT(";");
904 		break;
905 	}
906 }
907 
908 static int verity_prepare_ioctl(struct dm_target *ti, struct block_device **bdev)
909 {
910 	struct dm_verity *v = ti->private;
911 
912 	*bdev = v->data_dev->bdev;
913 
914 	if (v->data_start || ti->len != bdev_nr_sectors(v->data_dev->bdev))
915 		return 1;
916 	return 0;
917 }
918 
919 static int verity_iterate_devices(struct dm_target *ti,
920 				  iterate_devices_callout_fn fn, void *data)
921 {
922 	struct dm_verity *v = ti->private;
923 
924 	return fn(ti, v->data_dev, v->data_start, ti->len, data);
925 }
926 
927 static void verity_io_hints(struct dm_target *ti, struct queue_limits *limits)
928 {
929 	struct dm_verity *v = ti->private;
930 
931 	if (limits->logical_block_size < 1 << v->data_dev_block_bits)
932 		limits->logical_block_size = 1 << v->data_dev_block_bits;
933 
934 	if (limits->physical_block_size < 1 << v->data_dev_block_bits)
935 		limits->physical_block_size = 1 << v->data_dev_block_bits;
936 
937 	blk_limits_io_min(limits, limits->logical_block_size);
938 }
939 
940 static void verity_dtr(struct dm_target *ti)
941 {
942 	struct dm_verity *v = ti->private;
943 
944 	if (v->verify_wq)
945 		destroy_workqueue(v->verify_wq);
946 
947 	if (v->bufio)
948 		dm_bufio_client_destroy(v->bufio);
949 
950 	kvfree(v->validated_blocks);
951 	kfree(v->salt);
952 	kfree(v->root_digest);
953 	kfree(v->zero_digest);
954 
955 	if (v->tfm)
956 		crypto_free_ahash(v->tfm);
957 
958 	kfree(v->alg_name);
959 
960 	if (v->hash_dev)
961 		dm_put_device(ti, v->hash_dev);
962 
963 	if (v->data_dev)
964 		dm_put_device(ti, v->data_dev);
965 
966 	verity_fec_dtr(v);
967 
968 	kfree(v->signature_key_desc);
969 
970 	if (v->use_tasklet)
971 		static_branch_dec(&use_tasklet_enabled);
972 
973 	kfree(v);
974 }
975 
976 static int verity_alloc_most_once(struct dm_verity *v)
977 {
978 	struct dm_target *ti = v->ti;
979 
980 	/* the bitset can only handle INT_MAX blocks */
981 	if (v->data_blocks > INT_MAX) {
982 		ti->error = "device too large to use check_at_most_once";
983 		return -E2BIG;
984 	}
985 
986 	v->validated_blocks = kvcalloc(BITS_TO_LONGS(v->data_blocks),
987 				       sizeof(unsigned long),
988 				       GFP_KERNEL);
989 	if (!v->validated_blocks) {
990 		ti->error = "failed to allocate bitset for check_at_most_once";
991 		return -ENOMEM;
992 	}
993 
994 	return 0;
995 }
996 
997 static int verity_alloc_zero_digest(struct dm_verity *v)
998 {
999 	int r = -ENOMEM;
1000 	struct ahash_request *req;
1001 	u8 *zero_data;
1002 
1003 	v->zero_digest = kmalloc(v->digest_size, GFP_KERNEL);
1004 
1005 	if (!v->zero_digest)
1006 		return r;
1007 
1008 	req = kmalloc(v->ahash_reqsize, GFP_KERNEL);
1009 
1010 	if (!req)
1011 		return r; /* verity_dtr will free zero_digest */
1012 
1013 	zero_data = kzalloc(1 << v->data_dev_block_bits, GFP_KERNEL);
1014 
1015 	if (!zero_data)
1016 		goto out;
1017 
1018 	r = verity_hash(v, req, zero_data, 1 << v->data_dev_block_bits,
1019 			v->zero_digest);
1020 
1021 out:
1022 	kfree(req);
1023 	kfree(zero_data);
1024 
1025 	return r;
1026 }
1027 
1028 static inline bool verity_is_verity_mode(const char *arg_name)
1029 {
1030 	return (!strcasecmp(arg_name, DM_VERITY_OPT_LOGGING) ||
1031 		!strcasecmp(arg_name, DM_VERITY_OPT_RESTART) ||
1032 		!strcasecmp(arg_name, DM_VERITY_OPT_PANIC));
1033 }
1034 
1035 static int verity_parse_verity_mode(struct dm_verity *v, const char *arg_name)
1036 {
1037 	if (v->mode)
1038 		return -EINVAL;
1039 
1040 	if (!strcasecmp(arg_name, DM_VERITY_OPT_LOGGING))
1041 		v->mode = DM_VERITY_MODE_LOGGING;
1042 	else if (!strcasecmp(arg_name, DM_VERITY_OPT_RESTART))
1043 		v->mode = DM_VERITY_MODE_RESTART;
1044 	else if (!strcasecmp(arg_name, DM_VERITY_OPT_PANIC))
1045 		v->mode = DM_VERITY_MODE_PANIC;
1046 
1047 	return 0;
1048 }
1049 
1050 static int verity_parse_opt_args(struct dm_arg_set *as, struct dm_verity *v,
1051 				 struct dm_verity_sig_opts *verify_args,
1052 				 bool only_modifier_opts)
1053 {
1054 	int r = 0;
1055 	unsigned int argc;
1056 	struct dm_target *ti = v->ti;
1057 	const char *arg_name;
1058 
1059 	static const struct dm_arg _args[] = {
1060 		{0, DM_VERITY_OPTS_MAX, "Invalid number of feature args"},
1061 	};
1062 
1063 	r = dm_read_arg_group(_args, as, &argc, &ti->error);
1064 	if (r)
1065 		return -EINVAL;
1066 
1067 	if (!argc)
1068 		return 0;
1069 
1070 	do {
1071 		arg_name = dm_shift_arg(as);
1072 		argc--;
1073 
1074 		if (verity_is_verity_mode(arg_name)) {
1075 			if (only_modifier_opts)
1076 				continue;
1077 			r = verity_parse_verity_mode(v, arg_name);
1078 			if (r) {
1079 				ti->error = "Conflicting error handling parameters";
1080 				return r;
1081 			}
1082 			continue;
1083 
1084 		} else if (!strcasecmp(arg_name, DM_VERITY_OPT_IGN_ZEROES)) {
1085 			if (only_modifier_opts)
1086 				continue;
1087 			r = verity_alloc_zero_digest(v);
1088 			if (r) {
1089 				ti->error = "Cannot allocate zero digest";
1090 				return r;
1091 			}
1092 			continue;
1093 
1094 		} else if (!strcasecmp(arg_name, DM_VERITY_OPT_AT_MOST_ONCE)) {
1095 			if (only_modifier_opts)
1096 				continue;
1097 			r = verity_alloc_most_once(v);
1098 			if (r)
1099 				return r;
1100 			continue;
1101 
1102 		} else if (!strcasecmp(arg_name, DM_VERITY_OPT_TASKLET_VERIFY)) {
1103 			v->use_tasklet = true;
1104 			static_branch_inc(&use_tasklet_enabled);
1105 			continue;
1106 
1107 		} else if (verity_is_fec_opt_arg(arg_name)) {
1108 			if (only_modifier_opts)
1109 				continue;
1110 			r = verity_fec_parse_opt_args(as, v, &argc, arg_name);
1111 			if (r)
1112 				return r;
1113 			continue;
1114 
1115 		} else if (verity_verify_is_sig_opt_arg(arg_name)) {
1116 			if (only_modifier_opts)
1117 				continue;
1118 			r = verity_verify_sig_parse_opt_args(as, v,
1119 							     verify_args,
1120 							     &argc, arg_name);
1121 			if (r)
1122 				return r;
1123 			continue;
1124 
1125 		} else if (only_modifier_opts) {
1126 			/*
1127 			 * Ignore unrecognized opt, could easily be an extra
1128 			 * argument to an option whose parsing was skipped.
1129 			 * Normal parsing (@only_modifier_opts=false) will
1130 			 * properly parse all options (and their extra args).
1131 			 */
1132 			continue;
1133 		}
1134 
1135 		DMERR("Unrecognized verity feature request: %s", arg_name);
1136 		ti->error = "Unrecognized verity feature request";
1137 		return -EINVAL;
1138 	} while (argc && !r);
1139 
1140 	return r;
1141 }
1142 
1143 /*
1144  * Target parameters:
1145  *	<version>	The current format is version 1.
1146  *			Vsn 0 is compatible with original Chromium OS releases.
1147  *	<data device>
1148  *	<hash device>
1149  *	<data block size>
1150  *	<hash block size>
1151  *	<the number of data blocks>
1152  *	<hash start block>
1153  *	<algorithm>
1154  *	<digest>
1155  *	<salt>		Hex string or "-" if no salt.
1156  */
1157 static int verity_ctr(struct dm_target *ti, unsigned int argc, char **argv)
1158 {
1159 	struct dm_verity *v;
1160 	struct dm_verity_sig_opts verify_args = {0};
1161 	struct dm_arg_set as;
1162 	unsigned int num;
1163 	unsigned long long num_ll;
1164 	int r;
1165 	int i;
1166 	sector_t hash_position;
1167 	char dummy;
1168 	char *root_hash_digest_to_validate;
1169 
1170 	v = kzalloc(sizeof(struct dm_verity), GFP_KERNEL);
1171 	if (!v) {
1172 		ti->error = "Cannot allocate verity structure";
1173 		return -ENOMEM;
1174 	}
1175 	ti->private = v;
1176 	v->ti = ti;
1177 
1178 	r = verity_fec_ctr_alloc(v);
1179 	if (r)
1180 		goto bad;
1181 
1182 	if ((dm_table_get_mode(ti->table) & ~FMODE_READ)) {
1183 		ti->error = "Device must be readonly";
1184 		r = -EINVAL;
1185 		goto bad;
1186 	}
1187 
1188 	if (argc < 10) {
1189 		ti->error = "Not enough arguments";
1190 		r = -EINVAL;
1191 		goto bad;
1192 	}
1193 
1194 	/* Parse optional parameters that modify primary args */
1195 	if (argc > 10) {
1196 		as.argc = argc - 10;
1197 		as.argv = argv + 10;
1198 		r = verity_parse_opt_args(&as, v, &verify_args, true);
1199 		if (r < 0)
1200 			goto bad;
1201 	}
1202 
1203 	if (sscanf(argv[0], "%u%c", &num, &dummy) != 1 ||
1204 	    num > 1) {
1205 		ti->error = "Invalid version";
1206 		r = -EINVAL;
1207 		goto bad;
1208 	}
1209 	v->version = num;
1210 
1211 	r = dm_get_device(ti, argv[1], FMODE_READ, &v->data_dev);
1212 	if (r) {
1213 		ti->error = "Data device lookup failed";
1214 		goto bad;
1215 	}
1216 
1217 	r = dm_get_device(ti, argv[2], FMODE_READ, &v->hash_dev);
1218 	if (r) {
1219 		ti->error = "Hash device lookup failed";
1220 		goto bad;
1221 	}
1222 
1223 	if (sscanf(argv[3], "%u%c", &num, &dummy) != 1 ||
1224 	    !num || (num & (num - 1)) ||
1225 	    num < bdev_logical_block_size(v->data_dev->bdev) ||
1226 	    num > PAGE_SIZE) {
1227 		ti->error = "Invalid data device block size";
1228 		r = -EINVAL;
1229 		goto bad;
1230 	}
1231 	v->data_dev_block_bits = __ffs(num);
1232 
1233 	if (sscanf(argv[4], "%u%c", &num, &dummy) != 1 ||
1234 	    !num || (num & (num - 1)) ||
1235 	    num < bdev_logical_block_size(v->hash_dev->bdev) ||
1236 	    num > INT_MAX) {
1237 		ti->error = "Invalid hash device block size";
1238 		r = -EINVAL;
1239 		goto bad;
1240 	}
1241 	v->hash_dev_block_bits = __ffs(num);
1242 
1243 	if (sscanf(argv[5], "%llu%c", &num_ll, &dummy) != 1 ||
1244 	    (sector_t)(num_ll << (v->data_dev_block_bits - SECTOR_SHIFT))
1245 	    >> (v->data_dev_block_bits - SECTOR_SHIFT) != num_ll) {
1246 		ti->error = "Invalid data blocks";
1247 		r = -EINVAL;
1248 		goto bad;
1249 	}
1250 	v->data_blocks = num_ll;
1251 
1252 	if (ti->len > (v->data_blocks << (v->data_dev_block_bits - SECTOR_SHIFT))) {
1253 		ti->error = "Data device is too small";
1254 		r = -EINVAL;
1255 		goto bad;
1256 	}
1257 
1258 	if (sscanf(argv[6], "%llu%c", &num_ll, &dummy) != 1 ||
1259 	    (sector_t)(num_ll << (v->hash_dev_block_bits - SECTOR_SHIFT))
1260 	    >> (v->hash_dev_block_bits - SECTOR_SHIFT) != num_ll) {
1261 		ti->error = "Invalid hash start";
1262 		r = -EINVAL;
1263 		goto bad;
1264 	}
1265 	v->hash_start = num_ll;
1266 
1267 	v->alg_name = kstrdup(argv[7], GFP_KERNEL);
1268 	if (!v->alg_name) {
1269 		ti->error = "Cannot allocate algorithm name";
1270 		r = -ENOMEM;
1271 		goto bad;
1272 	}
1273 
1274 	v->tfm = crypto_alloc_ahash(v->alg_name, 0,
1275 				    v->use_tasklet ? CRYPTO_ALG_ASYNC : 0);
1276 	if (IS_ERR(v->tfm)) {
1277 		ti->error = "Cannot initialize hash function";
1278 		r = PTR_ERR(v->tfm);
1279 		v->tfm = NULL;
1280 		goto bad;
1281 	}
1282 
1283 	/*
1284 	 * dm-verity performance can vary greatly depending on which hash
1285 	 * algorithm implementation is used.  Help people debug performance
1286 	 * problems by logging the ->cra_driver_name.
1287 	 */
1288 	DMINFO("%s using implementation \"%s\"", v->alg_name,
1289 	       crypto_hash_alg_common(v->tfm)->base.cra_driver_name);
1290 
1291 	v->digest_size = crypto_ahash_digestsize(v->tfm);
1292 	if ((1 << v->hash_dev_block_bits) < v->digest_size * 2) {
1293 		ti->error = "Digest size too big";
1294 		r = -EINVAL;
1295 		goto bad;
1296 	}
1297 	v->ahash_reqsize = sizeof(struct ahash_request) +
1298 		crypto_ahash_reqsize(v->tfm);
1299 
1300 	v->root_digest = kmalloc(v->digest_size, GFP_KERNEL);
1301 	if (!v->root_digest) {
1302 		ti->error = "Cannot allocate root digest";
1303 		r = -ENOMEM;
1304 		goto bad;
1305 	}
1306 	if (strlen(argv[8]) != v->digest_size * 2 ||
1307 	    hex2bin(v->root_digest, argv[8], v->digest_size)) {
1308 		ti->error = "Invalid root digest";
1309 		r = -EINVAL;
1310 		goto bad;
1311 	}
1312 	root_hash_digest_to_validate = argv[8];
1313 
1314 	if (strcmp(argv[9], "-")) {
1315 		v->salt_size = strlen(argv[9]) / 2;
1316 		v->salt = kmalloc(v->salt_size, GFP_KERNEL);
1317 		if (!v->salt) {
1318 			ti->error = "Cannot allocate salt";
1319 			r = -ENOMEM;
1320 			goto bad;
1321 		}
1322 		if (strlen(argv[9]) != v->salt_size * 2 ||
1323 		    hex2bin(v->salt, argv[9], v->salt_size)) {
1324 			ti->error = "Invalid salt";
1325 			r = -EINVAL;
1326 			goto bad;
1327 		}
1328 	}
1329 
1330 	argv += 10;
1331 	argc -= 10;
1332 
1333 	/* Optional parameters */
1334 	if (argc) {
1335 		as.argc = argc;
1336 		as.argv = argv;
1337 		r = verity_parse_opt_args(&as, v, &verify_args, false);
1338 		if (r < 0)
1339 			goto bad;
1340 	}
1341 
1342 	/* Root hash signature is  a optional parameter*/
1343 	r = verity_verify_root_hash(root_hash_digest_to_validate,
1344 				    strlen(root_hash_digest_to_validate),
1345 				    verify_args.sig,
1346 				    verify_args.sig_size);
1347 	if (r < 0) {
1348 		ti->error = "Root hash verification failed";
1349 		goto bad;
1350 	}
1351 	v->hash_per_block_bits =
1352 		__fls((1 << v->hash_dev_block_bits) / v->digest_size);
1353 
1354 	v->levels = 0;
1355 	if (v->data_blocks)
1356 		while (v->hash_per_block_bits * v->levels < 64 &&
1357 		       (unsigned long long)(v->data_blocks - 1) >>
1358 		       (v->hash_per_block_bits * v->levels))
1359 			v->levels++;
1360 
1361 	if (v->levels > DM_VERITY_MAX_LEVELS) {
1362 		ti->error = "Too many tree levels";
1363 		r = -E2BIG;
1364 		goto bad;
1365 	}
1366 
1367 	hash_position = v->hash_start;
1368 	for (i = v->levels - 1; i >= 0; i--) {
1369 		sector_t s;
1370 		v->hash_level_block[i] = hash_position;
1371 		s = (v->data_blocks + ((sector_t)1 << ((i + 1) * v->hash_per_block_bits)) - 1)
1372 					>> ((i + 1) * v->hash_per_block_bits);
1373 		if (hash_position + s < hash_position) {
1374 			ti->error = "Hash device offset overflow";
1375 			r = -E2BIG;
1376 			goto bad;
1377 		}
1378 		hash_position += s;
1379 	}
1380 	v->hash_blocks = hash_position;
1381 
1382 	v->bufio = dm_bufio_client_create(v->hash_dev->bdev,
1383 		1 << v->hash_dev_block_bits, 1, sizeof(struct buffer_aux),
1384 		dm_bufio_alloc_callback, NULL,
1385 		v->use_tasklet ? DM_BUFIO_CLIENT_NO_SLEEP : 0);
1386 	if (IS_ERR(v->bufio)) {
1387 		ti->error = "Cannot initialize dm-bufio";
1388 		r = PTR_ERR(v->bufio);
1389 		v->bufio = NULL;
1390 		goto bad;
1391 	}
1392 
1393 	if (dm_bufio_get_device_size(v->bufio) < v->hash_blocks) {
1394 		ti->error = "Hash device is too small";
1395 		r = -E2BIG;
1396 		goto bad;
1397 	}
1398 
1399 	/*
1400 	 * Using WQ_HIGHPRI improves throughput and completion latency by
1401 	 * reducing wait times when reading from a dm-verity device.
1402 	 *
1403 	 * Also as required for the "try_verify_in_tasklet" feature: WQ_HIGHPRI
1404 	 * allows verify_wq to preempt softirq since verification in tasklet
1405 	 * will fall-back to using it for error handling (or if the bufio cache
1406 	 * doesn't have required hashes).
1407 	 */
1408 	v->verify_wq = alloc_workqueue("kverityd", WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
1409 	if (!v->verify_wq) {
1410 		ti->error = "Cannot allocate workqueue";
1411 		r = -ENOMEM;
1412 		goto bad;
1413 	}
1414 
1415 	ti->per_io_data_size = sizeof(struct dm_verity_io) +
1416 				v->ahash_reqsize + v->digest_size * 2;
1417 
1418 	r = verity_fec_ctr(v);
1419 	if (r)
1420 		goto bad;
1421 
1422 	ti->per_io_data_size = roundup(ti->per_io_data_size,
1423 				       __alignof__(struct dm_verity_io));
1424 
1425 	verity_verify_sig_opts_cleanup(&verify_args);
1426 
1427 	return 0;
1428 
1429 bad:
1430 
1431 	verity_verify_sig_opts_cleanup(&verify_args);
1432 	verity_dtr(ti);
1433 
1434 	return r;
1435 }
1436 
1437 /*
1438  * Check whether a DM target is a verity target.
1439  */
1440 bool dm_is_verity_target(struct dm_target *ti)
1441 {
1442 	return ti->type->module == THIS_MODULE;
1443 }
1444 
1445 /*
1446  * Get the verity mode (error behavior) of a verity target.
1447  *
1448  * Returns the verity mode of the target, or -EINVAL if 'ti' is not a verity
1449  * target.
1450  */
1451 int dm_verity_get_mode(struct dm_target *ti)
1452 {
1453 	struct dm_verity *v = ti->private;
1454 
1455 	if (!dm_is_verity_target(ti))
1456 		return -EINVAL;
1457 
1458 	return v->mode;
1459 }
1460 
1461 /*
1462  * Get the root digest of a verity target.
1463  *
1464  * Returns a copy of the root digest, the caller is responsible for
1465  * freeing the memory of the digest.
1466  */
1467 int dm_verity_get_root_digest(struct dm_target *ti, u8 **root_digest, unsigned int *digest_size)
1468 {
1469 	struct dm_verity *v = ti->private;
1470 
1471 	if (!dm_is_verity_target(ti))
1472 		return -EINVAL;
1473 
1474 	*root_digest = kmemdup(v->root_digest, v->digest_size, GFP_KERNEL);
1475 	if (*root_digest == NULL)
1476 		return -ENOMEM;
1477 
1478 	*digest_size = v->digest_size;
1479 
1480 	return 0;
1481 }
1482 
1483 static struct target_type verity_target = {
1484 	.name		= "verity",
1485 	.features	= DM_TARGET_IMMUTABLE,
1486 	.version	= {1, 9, 0},
1487 	.module		= THIS_MODULE,
1488 	.ctr		= verity_ctr,
1489 	.dtr		= verity_dtr,
1490 	.map		= verity_map,
1491 	.status		= verity_status,
1492 	.prepare_ioctl	= verity_prepare_ioctl,
1493 	.iterate_devices = verity_iterate_devices,
1494 	.io_hints	= verity_io_hints,
1495 };
1496 
1497 static int __init dm_verity_init(void)
1498 {
1499 	int r;
1500 
1501 	r = dm_register_target(&verity_target);
1502 	if (r < 0)
1503 		DMERR("register failed %d", r);
1504 
1505 	return r;
1506 }
1507 
1508 static void __exit dm_verity_exit(void)
1509 {
1510 	dm_unregister_target(&verity_target);
1511 }
1512 
1513 module_init(dm_verity_init);
1514 module_exit(dm_verity_exit);
1515 
1516 MODULE_AUTHOR("Mikulas Patocka <mpatocka@redhat.com>");
1517 MODULE_AUTHOR("Mandeep Baines <msb@chromium.org>");
1518 MODULE_AUTHOR("Will Drewry <wad@chromium.org>");
1519 MODULE_DESCRIPTION(DM_NAME " target for transparent disk integrity checking");
1520 MODULE_LICENSE("GPL");
1521