Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * Copyright (C) 2012 Red Hat, Inc.
0004  *
0005  * Author: Mikulas Patocka <mpatocka@redhat.com>
0006  *
0007  * Based on Chromium dm-verity driver (C) 2011 The Chromium OS Authors
0008  *
0009  * In the file "/sys/module/dm_verity/parameters/prefetch_cluster" you can set
0010  * default prefetch value. Data are read in "prefetch_cluster" chunks from the
0011  * hash device. Setting this greatly improves performance when data and hash
0012  * are on the same disk on different partitions on devices with poor random
0013  * access behavior.
0014  */
0015 
0016 #include "dm-verity.h"
0017 #include "dm-verity-fec.h"
0018 #include "dm-verity-verify-sig.h"
0019 #include <linux/module.h>
0020 #include <linux/reboot.h>
0021 #include <linux/scatterlist.h>
0022 #include <linux/string.h>
0023 #include <linux/jump_label.h>
0024 
0025 #define DM_MSG_PREFIX           "verity"
0026 
0027 #define DM_VERITY_ENV_LENGTH        42
0028 #define DM_VERITY_ENV_VAR_NAME      "DM_VERITY_ERR_BLOCK_NR"
0029 
0030 #define DM_VERITY_DEFAULT_PREFETCH_SIZE 262144
0031 
0032 #define DM_VERITY_MAX_CORRUPTED_ERRS    100
0033 
0034 #define DM_VERITY_OPT_LOGGING       "ignore_corruption"
0035 #define DM_VERITY_OPT_RESTART       "restart_on_corruption"
0036 #define DM_VERITY_OPT_PANIC     "panic_on_corruption"
0037 #define DM_VERITY_OPT_IGN_ZEROES    "ignore_zero_blocks"
0038 #define DM_VERITY_OPT_AT_MOST_ONCE  "check_at_most_once"
0039 #define DM_VERITY_OPT_TASKLET_VERIFY    "try_verify_in_tasklet"
0040 
0041 #define DM_VERITY_OPTS_MAX      (4 + DM_VERITY_OPTS_FEC + \
0042                      DM_VERITY_ROOT_HASH_VERIFICATION_OPTS)
0043 
0044 static unsigned dm_verity_prefetch_cluster = DM_VERITY_DEFAULT_PREFETCH_SIZE;
0045 
0046 module_param_named(prefetch_cluster, dm_verity_prefetch_cluster, uint, S_IRUGO | S_IWUSR);
0047 
0048 static DEFINE_STATIC_KEY_FALSE(use_tasklet_enabled);
0049 
0050 struct dm_verity_prefetch_work {
0051     struct work_struct work;
0052     struct dm_verity *v;
0053     sector_t block;
0054     unsigned n_blocks;
0055 };
0056 
0057 /*
0058  * Auxiliary structure appended to each dm-bufio buffer. If the value
0059  * hash_verified is nonzero, hash of the block has been verified.
0060  *
0061  * The variable hash_verified is set to 0 when allocating the buffer, then
0062  * it can be changed to 1 and it is never reset to 0 again.
0063  *
0064  * There is no lock around this value, a race condition can at worst cause
0065  * that multiple processes verify the hash of the same buffer simultaneously
0066  * and write 1 to hash_verified simultaneously.
0067  * This condition is harmless, so we don't need locking.
0068  */
0069 struct buffer_aux {
0070     int hash_verified;
0071 };
0072 
0073 /*
0074  * Initialize struct buffer_aux for a freshly created buffer.
0075  */
0076 static void dm_bufio_alloc_callback(struct dm_buffer *buf)
0077 {
0078     struct buffer_aux *aux = dm_bufio_get_aux_data(buf);
0079 
0080     aux->hash_verified = 0;
0081 }
0082 
0083 /*
0084  * Translate input sector number to the sector number on the target device.
0085  */
0086 static sector_t verity_map_sector(struct dm_verity *v, sector_t bi_sector)
0087 {
0088     return v->data_start + dm_target_offset(v->ti, bi_sector);
0089 }
0090 
0091 /*
0092  * Return hash position of a specified block at a specified tree level
0093  * (0 is the lowest level).
0094  * The lowest "hash_per_block_bits"-bits of the result denote hash position
0095  * inside a hash block. The remaining bits denote location of the hash block.
0096  */
0097 static sector_t verity_position_at_level(struct dm_verity *v, sector_t block,
0098                      int level)
0099 {
0100     return block >> (level * v->hash_per_block_bits);
0101 }
0102 
0103 static int verity_hash_update(struct dm_verity *v, struct ahash_request *req,
0104                 const u8 *data, size_t len,
0105                 struct crypto_wait *wait)
0106 {
0107     struct scatterlist sg;
0108 
0109     if (likely(!is_vmalloc_addr(data))) {
0110         sg_init_one(&sg, data, len);
0111         ahash_request_set_crypt(req, &sg, NULL, len);
0112         return crypto_wait_req(crypto_ahash_update(req), wait);
0113     } else {
0114         do {
0115             int r;
0116             size_t this_step = min_t(size_t, len, PAGE_SIZE - offset_in_page(data));
0117             flush_kernel_vmap_range((void *)data, this_step);
0118             sg_init_table(&sg, 1);
0119             sg_set_page(&sg, vmalloc_to_page(data), this_step, offset_in_page(data));
0120             ahash_request_set_crypt(req, &sg, NULL, this_step);
0121             r = crypto_wait_req(crypto_ahash_update(req), wait);
0122             if (unlikely(r))
0123                 return r;
0124             data += this_step;
0125             len -= this_step;
0126         } while (len);
0127         return 0;
0128     }
0129 }
0130 
0131 /*
0132  * Wrapper for crypto_ahash_init, which handles verity salting.
0133  */
0134 static int verity_hash_init(struct dm_verity *v, struct ahash_request *req,
0135                 struct crypto_wait *wait)
0136 {
0137     int r;
0138 
0139     ahash_request_set_tfm(req, v->tfm);
0140     ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP |
0141                     CRYPTO_TFM_REQ_MAY_BACKLOG,
0142                     crypto_req_done, (void *)wait);
0143     crypto_init_wait(wait);
0144 
0145     r = crypto_wait_req(crypto_ahash_init(req), wait);
0146 
0147     if (unlikely(r < 0)) {
0148         DMERR("crypto_ahash_init failed: %d", r);
0149         return r;
0150     }
0151 
0152     if (likely(v->salt_size && (v->version >= 1)))
0153         r = verity_hash_update(v, req, v->salt, v->salt_size, wait);
0154 
0155     return r;
0156 }
0157 
0158 static int verity_hash_final(struct dm_verity *v, struct ahash_request *req,
0159                  u8 *digest, struct crypto_wait *wait)
0160 {
0161     int r;
0162 
0163     if (unlikely(v->salt_size && (!v->version))) {
0164         r = verity_hash_update(v, req, v->salt, v->salt_size, wait);
0165 
0166         if (r < 0) {
0167             DMERR("verity_hash_final failed updating salt: %d", r);
0168             goto out;
0169         }
0170     }
0171 
0172     ahash_request_set_crypt(req, NULL, digest, 0);
0173     r = crypto_wait_req(crypto_ahash_final(req), wait);
0174 out:
0175     return r;
0176 }
0177 
0178 int verity_hash(struct dm_verity *v, struct ahash_request *req,
0179         const u8 *data, size_t len, u8 *digest)
0180 {
0181     int r;
0182     struct crypto_wait wait;
0183 
0184     r = verity_hash_init(v, req, &wait);
0185     if (unlikely(r < 0))
0186         goto out;
0187 
0188     r = verity_hash_update(v, req, data, len, &wait);
0189     if (unlikely(r < 0))
0190         goto out;
0191 
0192     r = verity_hash_final(v, req, digest, &wait);
0193 
0194 out:
0195     return r;
0196 }
0197 
0198 static void verity_hash_at_level(struct dm_verity *v, sector_t block, int level,
0199                  sector_t *hash_block, unsigned *offset)
0200 {
0201     sector_t position = verity_position_at_level(v, block, level);
0202     unsigned idx;
0203 
0204     *hash_block = v->hash_level_block[level] + (position >> v->hash_per_block_bits);
0205 
0206     if (!offset)
0207         return;
0208 
0209     idx = position & ((1 << v->hash_per_block_bits) - 1);
0210     if (!v->version)
0211         *offset = idx * v->digest_size;
0212     else
0213         *offset = idx << (v->hash_dev_block_bits - v->hash_per_block_bits);
0214 }
0215 
0216 /*
0217  * Handle verification errors.
0218  */
0219 static int verity_handle_err(struct dm_verity *v, enum verity_block_type type,
0220                  unsigned long long block)
0221 {
0222     char verity_env[DM_VERITY_ENV_LENGTH];
0223     char *envp[] = { verity_env, NULL };
0224     const char *type_str = "";
0225     struct mapped_device *md = dm_table_get_md(v->ti->table);
0226 
0227     /* Corruption should be visible in device status in all modes */
0228     v->hash_failed = true;
0229 
0230     if (v->corrupted_errs >= DM_VERITY_MAX_CORRUPTED_ERRS)
0231         goto out;
0232 
0233     v->corrupted_errs++;
0234 
0235     switch (type) {
0236     case DM_VERITY_BLOCK_TYPE_DATA:
0237         type_str = "data";
0238         break;
0239     case DM_VERITY_BLOCK_TYPE_METADATA:
0240         type_str = "metadata";
0241         break;
0242     default:
0243         BUG();
0244     }
0245 
0246     DMERR_LIMIT("%s: %s block %llu is corrupted", v->data_dev->name,
0247             type_str, block);
0248 
0249     if (v->corrupted_errs == DM_VERITY_MAX_CORRUPTED_ERRS)
0250         DMERR("%s: reached maximum errors", v->data_dev->name);
0251 
0252     snprintf(verity_env, DM_VERITY_ENV_LENGTH, "%s=%d,%llu",
0253         DM_VERITY_ENV_VAR_NAME, type, block);
0254 
0255     kobject_uevent_env(&disk_to_dev(dm_disk(md))->kobj, KOBJ_CHANGE, envp);
0256 
0257 out:
0258     if (v->mode == DM_VERITY_MODE_LOGGING)
0259         return 0;
0260 
0261     if (v->mode == DM_VERITY_MODE_RESTART)
0262         kernel_restart("dm-verity device corrupted");
0263 
0264     if (v->mode == DM_VERITY_MODE_PANIC)
0265         panic("dm-verity device corrupted");
0266 
0267     return 1;
0268 }
0269 
0270 /*
0271  * Verify hash of a metadata block pertaining to the specified data block
0272  * ("block" argument) at a specified level ("level" argument).
0273  *
0274  * On successful return, verity_io_want_digest(v, io) contains the hash value
0275  * for a lower tree level or for the data block (if we're at the lowest level).
0276  *
0277  * If "skip_unverified" is true, unverified buffer is skipped and 1 is returned.
0278  * If "skip_unverified" is false, unverified buffer is hashed and verified
0279  * against current value of verity_io_want_digest(v, io).
0280  */
0281 static int verity_verify_level(struct dm_verity *v, struct dm_verity_io *io,
0282                    sector_t block, int level, bool skip_unverified,
0283                    u8 *want_digest)
0284 {
0285     struct dm_buffer *buf;
0286     struct buffer_aux *aux;
0287     u8 *data;
0288     int r;
0289     sector_t hash_block;
0290     unsigned offset;
0291 
0292     verity_hash_at_level(v, block, level, &hash_block, &offset);
0293 
0294     if (static_branch_unlikely(&use_tasklet_enabled) && io->in_tasklet) {
0295         data = dm_bufio_get(v->bufio, hash_block, &buf);
0296         if (data == NULL) {
0297             /*
0298              * In tasklet and the hash was not in the bufio cache.
0299              * Return early and resume execution from a work-queue
0300              * to read the hash from disk.
0301              */
0302             return -EAGAIN;
0303         }
0304     } else
0305         data = dm_bufio_read(v->bufio, hash_block, &buf);
0306 
0307     if (IS_ERR(data))
0308         return PTR_ERR(data);
0309 
0310     aux = dm_bufio_get_aux_data(buf);
0311 
0312     if (!aux->hash_verified) {
0313         if (skip_unverified) {
0314             r = 1;
0315             goto release_ret_r;
0316         }
0317 
0318         r = verity_hash(v, verity_io_hash_req(v, io),
0319                 data, 1 << v->hash_dev_block_bits,
0320                 verity_io_real_digest(v, io));
0321         if (unlikely(r < 0))
0322             goto release_ret_r;
0323 
0324         if (likely(memcmp(verity_io_real_digest(v, io), want_digest,
0325                   v->digest_size) == 0))
0326             aux->hash_verified = 1;
0327         else if (static_branch_unlikely(&use_tasklet_enabled) &&
0328              io->in_tasklet) {
0329             /*
0330              * Error handling code (FEC included) cannot be run in a
0331              * tasklet since it may sleep, so fallback to work-queue.
0332              */
0333             r = -EAGAIN;
0334             goto release_ret_r;
0335         }
0336         else if (verity_fec_decode(v, io,
0337                        DM_VERITY_BLOCK_TYPE_METADATA,
0338                        hash_block, data, NULL) == 0)
0339             aux->hash_verified = 1;
0340         else if (verity_handle_err(v,
0341                        DM_VERITY_BLOCK_TYPE_METADATA,
0342                        hash_block)) {
0343             r = -EIO;
0344             goto release_ret_r;
0345         }
0346     }
0347 
0348     data += offset;
0349     memcpy(want_digest, data, v->digest_size);
0350     r = 0;
0351 
0352 release_ret_r:
0353     dm_bufio_release(buf);
0354     return r;
0355 }
0356 
0357 /*
0358  * Find a hash for a given block, write it to digest and verify the integrity
0359  * of the hash tree if necessary.
0360  */
0361 int verity_hash_for_block(struct dm_verity *v, struct dm_verity_io *io,
0362               sector_t block, u8 *digest, bool *is_zero)
0363 {
0364     int r = 0, i;
0365 
0366     if (likely(v->levels)) {
0367         /*
0368          * First, we try to get the requested hash for
0369          * the current block. If the hash block itself is
0370          * verified, zero is returned. If it isn't, this
0371          * function returns 1 and we fall back to whole
0372          * chain verification.
0373          */
0374         r = verity_verify_level(v, io, block, 0, true, digest);
0375         if (likely(r <= 0))
0376             goto out;
0377     }
0378 
0379     memcpy(digest, v->root_digest, v->digest_size);
0380 
0381     for (i = v->levels - 1; i >= 0; i--) {
0382         r = verity_verify_level(v, io, block, i, false, digest);
0383         if (unlikely(r))
0384             goto out;
0385     }
0386 out:
0387     if (!r && v->zero_digest)
0388         *is_zero = !memcmp(v->zero_digest, digest, v->digest_size);
0389     else
0390         *is_zero = false;
0391 
0392     return r;
0393 }
0394 
0395 /*
0396  * Calculates the digest for the given bio
0397  */
0398 static int verity_for_io_block(struct dm_verity *v, struct dm_verity_io *io,
0399                    struct bvec_iter *iter, struct crypto_wait *wait)
0400 {
0401     unsigned int todo = 1 << v->data_dev_block_bits;
0402     struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_io_data_size);
0403     struct scatterlist sg;
0404     struct ahash_request *req = verity_io_hash_req(v, io);
0405 
0406     do {
0407         int r;
0408         unsigned int len;
0409         struct bio_vec bv = bio_iter_iovec(bio, *iter);
0410 
0411         sg_init_table(&sg, 1);
0412 
0413         len = bv.bv_len;
0414 
0415         if (likely(len >= todo))
0416             len = todo;
0417         /*
0418          * Operating on a single page at a time looks suboptimal
0419          * until you consider the typical block size is 4,096B.
0420          * Going through this loops twice should be very rare.
0421          */
0422         sg_set_page(&sg, bv.bv_page, len, bv.bv_offset);
0423         ahash_request_set_crypt(req, &sg, NULL, len);
0424         r = crypto_wait_req(crypto_ahash_update(req), wait);
0425 
0426         if (unlikely(r < 0)) {
0427             DMERR("verity_for_io_block crypto op failed: %d", r);
0428             return r;
0429         }
0430 
0431         bio_advance_iter(bio, iter, len);
0432         todo -= len;
0433     } while (todo);
0434 
0435     return 0;
0436 }
0437 
0438 /*
0439  * Calls function process for 1 << v->data_dev_block_bits bytes in the bio_vec
0440  * starting from iter.
0441  */
0442 int verity_for_bv_block(struct dm_verity *v, struct dm_verity_io *io,
0443             struct bvec_iter *iter,
0444             int (*process)(struct dm_verity *v,
0445                        struct dm_verity_io *io, u8 *data,
0446                        size_t len))
0447 {
0448     unsigned todo = 1 << v->data_dev_block_bits;
0449     struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_io_data_size);
0450 
0451     do {
0452         int r;
0453         u8 *page;
0454         unsigned len;
0455         struct bio_vec bv = bio_iter_iovec(bio, *iter);
0456 
0457         page = bvec_kmap_local(&bv);
0458         len = bv.bv_len;
0459 
0460         if (likely(len >= todo))
0461             len = todo;
0462 
0463         r = process(v, io, page, len);
0464         kunmap_local(page);
0465 
0466         if (r < 0)
0467             return r;
0468 
0469         bio_advance_iter(bio, iter, len);
0470         todo -= len;
0471     } while (todo);
0472 
0473     return 0;
0474 }
0475 
0476 static int verity_bv_zero(struct dm_verity *v, struct dm_verity_io *io,
0477               u8 *data, size_t len)
0478 {
0479     memset(data, 0, len);
0480     return 0;
0481 }
0482 
0483 /*
0484  * Moves the bio iter one data block forward.
0485  */
0486 static inline void verity_bv_skip_block(struct dm_verity *v,
0487                     struct dm_verity_io *io,
0488                     struct bvec_iter *iter)
0489 {
0490     struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_io_data_size);
0491 
0492     bio_advance_iter(bio, iter, 1 << v->data_dev_block_bits);
0493 }
0494 
0495 /*
0496  * Verify one "dm_verity_io" structure.
0497  */
0498 static int verity_verify_io(struct dm_verity_io *io)
0499 {
0500     bool is_zero;
0501     struct dm_verity *v = io->v;
0502 #if defined(CONFIG_DM_VERITY_FEC)
0503     struct bvec_iter start;
0504 #endif
0505     struct bvec_iter iter_copy;
0506     struct bvec_iter *iter;
0507     struct crypto_wait wait;
0508     struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_io_data_size);
0509     unsigned int b;
0510 
0511     if (static_branch_unlikely(&use_tasklet_enabled) && io->in_tasklet) {
0512         /*
0513          * Copy the iterator in case we need to restart
0514          * verification in a work-queue.
0515          */
0516         iter_copy = io->iter;
0517         iter = &iter_copy;
0518     } else
0519         iter = &io->iter;
0520 
0521     for (b = 0; b < io->n_blocks; b++) {
0522         int r;
0523         sector_t cur_block = io->block + b;
0524         struct ahash_request *req = verity_io_hash_req(v, io);
0525 
0526         if (v->validated_blocks &&
0527             likely(test_bit(cur_block, v->validated_blocks))) {
0528             verity_bv_skip_block(v, io, iter);
0529             continue;
0530         }
0531 
0532         r = verity_hash_for_block(v, io, cur_block,
0533                       verity_io_want_digest(v, io),
0534                       &is_zero);
0535         if (unlikely(r < 0))
0536             return r;
0537 
0538         if (is_zero) {
0539             /*
0540              * If we expect a zero block, don't validate, just
0541              * return zeros.
0542              */
0543             r = verity_for_bv_block(v, io, iter,
0544                         verity_bv_zero);
0545             if (unlikely(r < 0))
0546                 return r;
0547 
0548             continue;
0549         }
0550 
0551         r = verity_hash_init(v, req, &wait);
0552         if (unlikely(r < 0))
0553             return r;
0554 
0555 #if defined(CONFIG_DM_VERITY_FEC)
0556         if (verity_fec_is_enabled(v))
0557             start = *iter;
0558 #endif
0559         r = verity_for_io_block(v, io, iter, &wait);
0560         if (unlikely(r < 0))
0561             return r;
0562 
0563         r = verity_hash_final(v, req, verity_io_real_digest(v, io),
0564                     &wait);
0565         if (unlikely(r < 0))
0566             return r;
0567 
0568         if (likely(memcmp(verity_io_real_digest(v, io),
0569                   verity_io_want_digest(v, io), v->digest_size) == 0)) {
0570             if (v->validated_blocks)
0571                 set_bit(cur_block, v->validated_blocks);
0572             continue;
0573         } else if (static_branch_unlikely(&use_tasklet_enabled) &&
0574                io->in_tasklet) {
0575             /*
0576              * Error handling code (FEC included) cannot be run in a
0577              * tasklet since it may sleep, so fallback to work-queue.
0578              */
0579             return -EAGAIN;
0580 #if defined(CONFIG_DM_VERITY_FEC)
0581         } else if (verity_fec_decode(v, io, DM_VERITY_BLOCK_TYPE_DATA,
0582                          cur_block, NULL, &start) == 0) {
0583             continue;
0584 #endif
0585         } else {
0586             if (bio->bi_status) {
0587                 /*
0588                  * Error correction failed; Just return error
0589                  */
0590                 return -EIO;
0591             }
0592             if (verity_handle_err(v, DM_VERITY_BLOCK_TYPE_DATA,
0593                           cur_block))
0594                 return -EIO;
0595         }
0596     }
0597 
0598     return 0;
0599 }
0600 
0601 /*
0602  * Skip verity work in response to I/O error when system is shutting down.
0603  */
0604 static inline bool verity_is_system_shutting_down(void)
0605 {
0606     return system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF
0607         || system_state == SYSTEM_RESTART;
0608 }
0609 
0610 /*
0611  * End one "io" structure with a given error.
0612  */
0613 static void verity_finish_io(struct dm_verity_io *io, blk_status_t status)
0614 {
0615     struct dm_verity *v = io->v;
0616     struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_io_data_size);
0617 
0618     bio->bi_end_io = io->orig_bi_end_io;
0619     bio->bi_status = status;
0620 
0621     if (!static_branch_unlikely(&use_tasklet_enabled) || !io->in_tasklet)
0622         verity_fec_finish_io(io);
0623 
0624     bio_endio(bio);
0625 }
0626 
0627 static void verity_work(struct work_struct *w)
0628 {
0629     struct dm_verity_io *io = container_of(w, struct dm_verity_io, work);
0630 
0631     io->in_tasklet = false;
0632 
0633     verity_fec_init_io(io);
0634     verity_finish_io(io, errno_to_blk_status(verity_verify_io(io)));
0635 }
0636 
0637 static void verity_tasklet(unsigned long data)
0638 {
0639     struct dm_verity_io *io = (struct dm_verity_io *)data;
0640     int err;
0641 
0642     io->in_tasklet = true;
0643     err = verity_verify_io(io);
0644     if (err == -EAGAIN) {
0645         /* fallback to retrying with work-queue */
0646         INIT_WORK(&io->work, verity_work);
0647         queue_work(io->v->verify_wq, &io->work);
0648         return;
0649     }
0650 
0651     verity_finish_io(io, errno_to_blk_status(err));
0652 }
0653 
0654 static void verity_end_io(struct bio *bio)
0655 {
0656     struct dm_verity_io *io = bio->bi_private;
0657 
0658     if (bio->bi_status &&
0659         (!verity_fec_is_enabled(io->v) || verity_is_system_shutting_down())) {
0660         verity_finish_io(io, bio->bi_status);
0661         return;
0662     }
0663 
0664     if (static_branch_unlikely(&use_tasklet_enabled) && io->v->use_tasklet) {
0665         tasklet_init(&io->tasklet, verity_tasklet, (unsigned long)io);
0666         tasklet_schedule(&io->tasklet);
0667     } else {
0668         INIT_WORK(&io->work, verity_work);
0669         queue_work(io->v->verify_wq, &io->work);
0670     }
0671 }
0672 
0673 /*
0674  * Prefetch buffers for the specified io.
0675  * The root buffer is not prefetched, it is assumed that it will be cached
0676  * all the time.
0677  */
0678 static void verity_prefetch_io(struct work_struct *work)
0679 {
0680     struct dm_verity_prefetch_work *pw =
0681         container_of(work, struct dm_verity_prefetch_work, work);
0682     struct dm_verity *v = pw->v;
0683     int i;
0684 
0685     for (i = v->levels - 2; i >= 0; i--) {
0686         sector_t hash_block_start;
0687         sector_t hash_block_end;
0688         verity_hash_at_level(v, pw->block, i, &hash_block_start, NULL);
0689         verity_hash_at_level(v, pw->block + pw->n_blocks - 1, i, &hash_block_end, NULL);
0690         if (!i) {
0691             unsigned cluster = READ_ONCE(dm_verity_prefetch_cluster);
0692 
0693             cluster >>= v->data_dev_block_bits;
0694             if (unlikely(!cluster))
0695                 goto no_prefetch_cluster;
0696 
0697             if (unlikely(cluster & (cluster - 1)))
0698                 cluster = 1 << __fls(cluster);
0699 
0700             hash_block_start &= ~(sector_t)(cluster - 1);
0701             hash_block_end |= cluster - 1;
0702             if (unlikely(hash_block_end >= v->hash_blocks))
0703                 hash_block_end = v->hash_blocks - 1;
0704         }
0705 no_prefetch_cluster:
0706         dm_bufio_prefetch(v->bufio, hash_block_start,
0707                   hash_block_end - hash_block_start + 1);
0708     }
0709 
0710     kfree(pw);
0711 }
0712 
0713 static void verity_submit_prefetch(struct dm_verity *v, struct dm_verity_io *io)
0714 {
0715     sector_t block = io->block;
0716     unsigned int n_blocks = io->n_blocks;
0717     struct dm_verity_prefetch_work *pw;
0718 
0719     if (v->validated_blocks) {
0720         while (n_blocks && test_bit(block, v->validated_blocks)) {
0721             block++;
0722             n_blocks--;
0723         }
0724         while (n_blocks && test_bit(block + n_blocks - 1,
0725                         v->validated_blocks))
0726             n_blocks--;
0727         if (!n_blocks)
0728             return;
0729     }
0730 
0731     pw = kmalloc(sizeof(struct dm_verity_prefetch_work),
0732         GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
0733 
0734     if (!pw)
0735         return;
0736 
0737     INIT_WORK(&pw->work, verity_prefetch_io);
0738     pw->v = v;
0739     pw->block = block;
0740     pw->n_blocks = n_blocks;
0741     queue_work(v->verify_wq, &pw->work);
0742 }
0743 
0744 /*
0745  * Bio map function. It allocates dm_verity_io structure and bio vector and
0746  * fills them. Then it issues prefetches and the I/O.
0747  */
0748 static int verity_map(struct dm_target *ti, struct bio *bio)
0749 {
0750     struct dm_verity *v = ti->private;
0751     struct dm_verity_io *io;
0752 
0753     bio_set_dev(bio, v->data_dev->bdev);
0754     bio->bi_iter.bi_sector = verity_map_sector(v, bio->bi_iter.bi_sector);
0755 
0756     if (((unsigned)bio->bi_iter.bi_sector | bio_sectors(bio)) &
0757         ((1 << (v->data_dev_block_bits - SECTOR_SHIFT)) - 1)) {
0758         DMERR_LIMIT("unaligned io");
0759         return DM_MAPIO_KILL;
0760     }
0761 
0762     if (bio_end_sector(bio) >>
0763         (v->data_dev_block_bits - SECTOR_SHIFT) > v->data_blocks) {
0764         DMERR_LIMIT("io out of range");
0765         return DM_MAPIO_KILL;
0766     }
0767 
0768     if (bio_data_dir(bio) == WRITE)
0769         return DM_MAPIO_KILL;
0770 
0771     io = dm_per_bio_data(bio, ti->per_io_data_size);
0772     io->v = v;
0773     io->orig_bi_end_io = bio->bi_end_io;
0774     io->block = bio->bi_iter.bi_sector >> (v->data_dev_block_bits - SECTOR_SHIFT);
0775     io->n_blocks = bio->bi_iter.bi_size >> v->data_dev_block_bits;
0776 
0777     bio->bi_end_io = verity_end_io;
0778     bio->bi_private = io;
0779     io->iter = bio->bi_iter;
0780 
0781     verity_submit_prefetch(v, io);
0782 
0783     submit_bio_noacct(bio);
0784 
0785     return DM_MAPIO_SUBMITTED;
0786 }
0787 
0788 /*
0789  * Status: V (valid) or C (corruption found)
0790  */
0791 static void verity_status(struct dm_target *ti, status_type_t type,
0792               unsigned status_flags, char *result, unsigned maxlen)
0793 {
0794     struct dm_verity *v = ti->private;
0795     unsigned args = 0;
0796     unsigned sz = 0;
0797     unsigned x;
0798 
0799     switch (type) {
0800     case STATUSTYPE_INFO:
0801         DMEMIT("%c", v->hash_failed ? 'C' : 'V');
0802         break;
0803     case STATUSTYPE_TABLE:
0804         DMEMIT("%u %s %s %u %u %llu %llu %s ",
0805             v->version,
0806             v->data_dev->name,
0807             v->hash_dev->name,
0808             1 << v->data_dev_block_bits,
0809             1 << v->hash_dev_block_bits,
0810             (unsigned long long)v->data_blocks,
0811             (unsigned long long)v->hash_start,
0812             v->alg_name
0813             );
0814         for (x = 0; x < v->digest_size; x++)
0815             DMEMIT("%02x", v->root_digest[x]);
0816         DMEMIT(" ");
0817         if (!v->salt_size)
0818             DMEMIT("-");
0819         else
0820             for (x = 0; x < v->salt_size; x++)
0821                 DMEMIT("%02x", v->salt[x]);
0822         if (v->mode != DM_VERITY_MODE_EIO)
0823             args++;
0824         if (verity_fec_is_enabled(v))
0825             args += DM_VERITY_OPTS_FEC;
0826         if (v->zero_digest)
0827             args++;
0828         if (v->validated_blocks)
0829             args++;
0830         if (v->use_tasklet)
0831             args++;
0832         if (v->signature_key_desc)
0833             args += DM_VERITY_ROOT_HASH_VERIFICATION_OPTS;
0834         if (!args)
0835             return;
0836         DMEMIT(" %u", args);
0837         if (v->mode != DM_VERITY_MODE_EIO) {
0838             DMEMIT(" ");
0839             switch (v->mode) {
0840             case DM_VERITY_MODE_LOGGING:
0841                 DMEMIT(DM_VERITY_OPT_LOGGING);
0842                 break;
0843             case DM_VERITY_MODE_RESTART:
0844                 DMEMIT(DM_VERITY_OPT_RESTART);
0845                 break;
0846             case DM_VERITY_MODE_PANIC:
0847                 DMEMIT(DM_VERITY_OPT_PANIC);
0848                 break;
0849             default:
0850                 BUG();
0851             }
0852         }
0853         if (v->zero_digest)
0854             DMEMIT(" " DM_VERITY_OPT_IGN_ZEROES);
0855         if (v->validated_blocks)
0856             DMEMIT(" " DM_VERITY_OPT_AT_MOST_ONCE);
0857         if (v->use_tasklet)
0858             DMEMIT(" " DM_VERITY_OPT_TASKLET_VERIFY);
0859         sz = verity_fec_status_table(v, sz, result, maxlen);
0860         if (v->signature_key_desc)
0861             DMEMIT(" " DM_VERITY_ROOT_HASH_VERIFICATION_OPT_SIG_KEY
0862                 " %s", v->signature_key_desc);
0863         break;
0864 
0865     case STATUSTYPE_IMA:
0866         DMEMIT_TARGET_NAME_VERSION(ti->type);
0867         DMEMIT(",hash_failed=%c", v->hash_failed ? 'C' : 'V');
0868         DMEMIT(",verity_version=%u", v->version);
0869         DMEMIT(",data_device_name=%s", v->data_dev->name);
0870         DMEMIT(",hash_device_name=%s", v->hash_dev->name);
0871         DMEMIT(",verity_algorithm=%s", v->alg_name);
0872 
0873         DMEMIT(",root_digest=");
0874         for (x = 0; x < v->digest_size; x++)
0875             DMEMIT("%02x", v->root_digest[x]);
0876 
0877         DMEMIT(",salt=");
0878         if (!v->salt_size)
0879             DMEMIT("-");
0880         else
0881             for (x = 0; x < v->salt_size; x++)
0882                 DMEMIT("%02x", v->salt[x]);
0883 
0884         DMEMIT(",ignore_zero_blocks=%c", v->zero_digest ? 'y' : 'n');
0885         DMEMIT(",check_at_most_once=%c", v->validated_blocks ? 'y' : 'n');
0886         if (v->signature_key_desc)
0887             DMEMIT(",root_hash_sig_key_desc=%s", v->signature_key_desc);
0888 
0889         if (v->mode != DM_VERITY_MODE_EIO) {
0890             DMEMIT(",verity_mode=");
0891             switch (v->mode) {
0892             case DM_VERITY_MODE_LOGGING:
0893                 DMEMIT(DM_VERITY_OPT_LOGGING);
0894                 break;
0895             case DM_VERITY_MODE_RESTART:
0896                 DMEMIT(DM_VERITY_OPT_RESTART);
0897                 break;
0898             case DM_VERITY_MODE_PANIC:
0899                 DMEMIT(DM_VERITY_OPT_PANIC);
0900                 break;
0901             default:
0902                 DMEMIT("invalid");
0903             }
0904         }
0905         DMEMIT(";");
0906         break;
0907     }
0908 }
0909 
0910 static int verity_prepare_ioctl(struct dm_target *ti, struct block_device **bdev)
0911 {
0912     struct dm_verity *v = ti->private;
0913 
0914     *bdev = v->data_dev->bdev;
0915 
0916     if (v->data_start || ti->len != bdev_nr_sectors(v->data_dev->bdev))
0917         return 1;
0918     return 0;
0919 }
0920 
0921 static int verity_iterate_devices(struct dm_target *ti,
0922                   iterate_devices_callout_fn fn, void *data)
0923 {
0924     struct dm_verity *v = ti->private;
0925 
0926     return fn(ti, v->data_dev, v->data_start, ti->len, data);
0927 }
0928 
0929 static void verity_io_hints(struct dm_target *ti, struct queue_limits *limits)
0930 {
0931     struct dm_verity *v = ti->private;
0932 
0933     if (limits->logical_block_size < 1 << v->data_dev_block_bits)
0934         limits->logical_block_size = 1 << v->data_dev_block_bits;
0935 
0936     if (limits->physical_block_size < 1 << v->data_dev_block_bits)
0937         limits->physical_block_size = 1 << v->data_dev_block_bits;
0938 
0939     blk_limits_io_min(limits, limits->logical_block_size);
0940 }
0941 
0942 static void verity_dtr(struct dm_target *ti)
0943 {
0944     struct dm_verity *v = ti->private;
0945 
0946     if (v->verify_wq)
0947         destroy_workqueue(v->verify_wq);
0948 
0949     if (v->bufio)
0950         dm_bufio_client_destroy(v->bufio);
0951 
0952     kvfree(v->validated_blocks);
0953     kfree(v->salt);
0954     kfree(v->root_digest);
0955     kfree(v->zero_digest);
0956 
0957     if (v->tfm)
0958         crypto_free_ahash(v->tfm);
0959 
0960     kfree(v->alg_name);
0961 
0962     if (v->hash_dev)
0963         dm_put_device(ti, v->hash_dev);
0964 
0965     if (v->data_dev)
0966         dm_put_device(ti, v->data_dev);
0967 
0968     verity_fec_dtr(v);
0969 
0970     kfree(v->signature_key_desc);
0971 
0972     if (v->use_tasklet)
0973         static_branch_dec(&use_tasklet_enabled);
0974 
0975     kfree(v);
0976 }
0977 
0978 static int verity_alloc_most_once(struct dm_verity *v)
0979 {
0980     struct dm_target *ti = v->ti;
0981 
0982     /* the bitset can only handle INT_MAX blocks */
0983     if (v->data_blocks > INT_MAX) {
0984         ti->error = "device too large to use check_at_most_once";
0985         return -E2BIG;
0986     }
0987 
0988     v->validated_blocks = kvcalloc(BITS_TO_LONGS(v->data_blocks),
0989                        sizeof(unsigned long),
0990                        GFP_KERNEL);
0991     if (!v->validated_blocks) {
0992         ti->error = "failed to allocate bitset for check_at_most_once";
0993         return -ENOMEM;
0994     }
0995 
0996     return 0;
0997 }
0998 
0999 static int verity_alloc_zero_digest(struct dm_verity *v)
1000 {
1001     int r = -ENOMEM;
1002     struct ahash_request *req;
1003     u8 *zero_data;
1004 
1005     v->zero_digest = kmalloc(v->digest_size, GFP_KERNEL);
1006 
1007     if (!v->zero_digest)
1008         return r;
1009 
1010     req = kmalloc(v->ahash_reqsize, GFP_KERNEL);
1011 
1012     if (!req)
1013         return r; /* verity_dtr will free zero_digest */
1014 
1015     zero_data = kzalloc(1 << v->data_dev_block_bits, GFP_KERNEL);
1016 
1017     if (!zero_data)
1018         goto out;
1019 
1020     r = verity_hash(v, req, zero_data, 1 << v->data_dev_block_bits,
1021             v->zero_digest);
1022 
1023 out:
1024     kfree(req);
1025     kfree(zero_data);
1026 
1027     return r;
1028 }
1029 
1030 static inline bool verity_is_verity_mode(const char *arg_name)
1031 {
1032     return (!strcasecmp(arg_name, DM_VERITY_OPT_LOGGING) ||
1033         !strcasecmp(arg_name, DM_VERITY_OPT_RESTART) ||
1034         !strcasecmp(arg_name, DM_VERITY_OPT_PANIC));
1035 }
1036 
1037 static int verity_parse_verity_mode(struct dm_verity *v, const char *arg_name)
1038 {
1039     if (v->mode)
1040         return -EINVAL;
1041 
1042     if (!strcasecmp(arg_name, DM_VERITY_OPT_LOGGING))
1043         v->mode = DM_VERITY_MODE_LOGGING;
1044     else if (!strcasecmp(arg_name, DM_VERITY_OPT_RESTART))
1045         v->mode = DM_VERITY_MODE_RESTART;
1046     else if (!strcasecmp(arg_name, DM_VERITY_OPT_PANIC))
1047         v->mode = DM_VERITY_MODE_PANIC;
1048 
1049     return 0;
1050 }
1051 
1052 static int verity_parse_opt_args(struct dm_arg_set *as, struct dm_verity *v,
1053                  struct dm_verity_sig_opts *verify_args,
1054                  bool only_modifier_opts)
1055 {
1056     int r = 0;
1057     unsigned argc;
1058     struct dm_target *ti = v->ti;
1059     const char *arg_name;
1060 
1061     static const struct dm_arg _args[] = {
1062         {0, DM_VERITY_OPTS_MAX, "Invalid number of feature args"},
1063     };
1064 
1065     r = dm_read_arg_group(_args, as, &argc, &ti->error);
1066     if (r)
1067         return -EINVAL;
1068 
1069     if (!argc)
1070         return 0;
1071 
1072     do {
1073         arg_name = dm_shift_arg(as);
1074         argc--;
1075 
1076         if (verity_is_verity_mode(arg_name)) {
1077             if (only_modifier_opts)
1078                 continue;
1079             r = verity_parse_verity_mode(v, arg_name);
1080             if (r) {
1081                 ti->error = "Conflicting error handling parameters";
1082                 return r;
1083             }
1084             continue;
1085 
1086         } else if (!strcasecmp(arg_name, DM_VERITY_OPT_IGN_ZEROES)) {
1087             if (only_modifier_opts)
1088                 continue;
1089             r = verity_alloc_zero_digest(v);
1090             if (r) {
1091                 ti->error = "Cannot allocate zero digest";
1092                 return r;
1093             }
1094             continue;
1095 
1096         } else if (!strcasecmp(arg_name, DM_VERITY_OPT_AT_MOST_ONCE)) {
1097             if (only_modifier_opts)
1098                 continue;
1099             r = verity_alloc_most_once(v);
1100             if (r)
1101                 return r;
1102             continue;
1103 
1104         } else if (!strcasecmp(arg_name, DM_VERITY_OPT_TASKLET_VERIFY)) {
1105             v->use_tasklet = true;
1106             static_branch_inc(&use_tasklet_enabled);
1107             continue;
1108 
1109         } else if (verity_is_fec_opt_arg(arg_name)) {
1110             if (only_modifier_opts)
1111                 continue;
1112             r = verity_fec_parse_opt_args(as, v, &argc, arg_name);
1113             if (r)
1114                 return r;
1115             continue;
1116 
1117         } else if (verity_verify_is_sig_opt_arg(arg_name)) {
1118             if (only_modifier_opts)
1119                 continue;
1120             r = verity_verify_sig_parse_opt_args(as, v,
1121                                  verify_args,
1122                                  &argc, arg_name);
1123             if (r)
1124                 return r;
1125             continue;
1126 
1127         } else if (only_modifier_opts) {
1128             /*
1129              * Ignore unrecognized opt, could easily be an extra
1130              * argument to an option whose parsing was skipped.
1131              * Normal parsing (@only_modifier_opts=false) will
1132              * properly parse all options (and their extra args).
1133              */
1134             continue;
1135         }
1136 
1137         DMERR("Unrecognized verity feature request: %s", arg_name);
1138         ti->error = "Unrecognized verity feature request";
1139         return -EINVAL;
1140     } while (argc && !r);
1141 
1142     return r;
1143 }
1144 
1145 /*
1146  * Target parameters:
1147  *  <version>   The current format is version 1.
1148  *          Vsn 0 is compatible with original Chromium OS releases.
1149  *  <data device>
1150  *  <hash device>
1151  *  <data block size>
1152  *  <hash block size>
1153  *  <the number of data blocks>
1154  *  <hash start block>
1155  *  <algorithm>
1156  *  <digest>
1157  *  <salt>      Hex string or "-" if no salt.
1158  */
1159 static int verity_ctr(struct dm_target *ti, unsigned argc, char **argv)
1160 {
1161     struct dm_verity *v;
1162     struct dm_verity_sig_opts verify_args = {0};
1163     struct dm_arg_set as;
1164     unsigned int num;
1165     unsigned int wq_flags;
1166     unsigned long long num_ll;
1167     int r;
1168     int i;
1169     sector_t hash_position;
1170     char dummy;
1171     char *root_hash_digest_to_validate;
1172 
1173     v = kzalloc(sizeof(struct dm_verity), GFP_KERNEL);
1174     if (!v) {
1175         ti->error = "Cannot allocate verity structure";
1176         return -ENOMEM;
1177     }
1178     ti->private = v;
1179     v->ti = ti;
1180 
1181     r = verity_fec_ctr_alloc(v);
1182     if (r)
1183         goto bad;
1184 
1185     if ((dm_table_get_mode(ti->table) & ~FMODE_READ)) {
1186         ti->error = "Device must be readonly";
1187         r = -EINVAL;
1188         goto bad;
1189     }
1190 
1191     if (argc < 10) {
1192         ti->error = "Not enough arguments";
1193         r = -EINVAL;
1194         goto bad;
1195     }
1196 
1197     /* Parse optional parameters that modify primary args */
1198     if (argc > 10) {
1199         as.argc = argc - 10;
1200         as.argv = argv + 10;
1201         r = verity_parse_opt_args(&as, v, &verify_args, true);
1202         if (r < 0)
1203             goto bad;
1204     }
1205 
1206     if (sscanf(argv[0], "%u%c", &num, &dummy) != 1 ||
1207         num > 1) {
1208         ti->error = "Invalid version";
1209         r = -EINVAL;
1210         goto bad;
1211     }
1212     v->version = num;
1213 
1214     r = dm_get_device(ti, argv[1], FMODE_READ, &v->data_dev);
1215     if (r) {
1216         ti->error = "Data device lookup failed";
1217         goto bad;
1218     }
1219 
1220     r = dm_get_device(ti, argv[2], FMODE_READ, &v->hash_dev);
1221     if (r) {
1222         ti->error = "Hash device lookup failed";
1223         goto bad;
1224     }
1225 
1226     if (sscanf(argv[3], "%u%c", &num, &dummy) != 1 ||
1227         !num || (num & (num - 1)) ||
1228         num < bdev_logical_block_size(v->data_dev->bdev) ||
1229         num > PAGE_SIZE) {
1230         ti->error = "Invalid data device block size";
1231         r = -EINVAL;
1232         goto bad;
1233     }
1234     v->data_dev_block_bits = __ffs(num);
1235 
1236     if (sscanf(argv[4], "%u%c", &num, &dummy) != 1 ||
1237         !num || (num & (num - 1)) ||
1238         num < bdev_logical_block_size(v->hash_dev->bdev) ||
1239         num > INT_MAX) {
1240         ti->error = "Invalid hash device block size";
1241         r = -EINVAL;
1242         goto bad;
1243     }
1244     v->hash_dev_block_bits = __ffs(num);
1245 
1246     if (sscanf(argv[5], "%llu%c", &num_ll, &dummy) != 1 ||
1247         (sector_t)(num_ll << (v->data_dev_block_bits - SECTOR_SHIFT))
1248         >> (v->data_dev_block_bits - SECTOR_SHIFT) != num_ll) {
1249         ti->error = "Invalid data blocks";
1250         r = -EINVAL;
1251         goto bad;
1252     }
1253     v->data_blocks = num_ll;
1254 
1255     if (ti->len > (v->data_blocks << (v->data_dev_block_bits - SECTOR_SHIFT))) {
1256         ti->error = "Data device is too small";
1257         r = -EINVAL;
1258         goto bad;
1259     }
1260 
1261     if (sscanf(argv[6], "%llu%c", &num_ll, &dummy) != 1 ||
1262         (sector_t)(num_ll << (v->hash_dev_block_bits - SECTOR_SHIFT))
1263         >> (v->hash_dev_block_bits - SECTOR_SHIFT) != num_ll) {
1264         ti->error = "Invalid hash start";
1265         r = -EINVAL;
1266         goto bad;
1267     }
1268     v->hash_start = num_ll;
1269 
1270     v->alg_name = kstrdup(argv[7], GFP_KERNEL);
1271     if (!v->alg_name) {
1272         ti->error = "Cannot allocate algorithm name";
1273         r = -ENOMEM;
1274         goto bad;
1275     }
1276 
1277     v->tfm = crypto_alloc_ahash(v->alg_name, 0,
1278                     v->use_tasklet ? CRYPTO_ALG_ASYNC : 0);
1279     if (IS_ERR(v->tfm)) {
1280         ti->error = "Cannot initialize hash function";
1281         r = PTR_ERR(v->tfm);
1282         v->tfm = NULL;
1283         goto bad;
1284     }
1285 
1286     /*
1287      * dm-verity performance can vary greatly depending on which hash
1288      * algorithm implementation is used.  Help people debug performance
1289      * problems by logging the ->cra_driver_name.
1290      */
1291     DMINFO("%s using implementation \"%s\"", v->alg_name,
1292            crypto_hash_alg_common(v->tfm)->base.cra_driver_name);
1293 
1294     v->digest_size = crypto_ahash_digestsize(v->tfm);
1295     if ((1 << v->hash_dev_block_bits) < v->digest_size * 2) {
1296         ti->error = "Digest size too big";
1297         r = -EINVAL;
1298         goto bad;
1299     }
1300     v->ahash_reqsize = sizeof(struct ahash_request) +
1301         crypto_ahash_reqsize(v->tfm);
1302 
1303     v->root_digest = kmalloc(v->digest_size, GFP_KERNEL);
1304     if (!v->root_digest) {
1305         ti->error = "Cannot allocate root digest";
1306         r = -ENOMEM;
1307         goto bad;
1308     }
1309     if (strlen(argv[8]) != v->digest_size * 2 ||
1310         hex2bin(v->root_digest, argv[8], v->digest_size)) {
1311         ti->error = "Invalid root digest";
1312         r = -EINVAL;
1313         goto bad;
1314     }
1315     root_hash_digest_to_validate = argv[8];
1316 
1317     if (strcmp(argv[9], "-")) {
1318         v->salt_size = strlen(argv[9]) / 2;
1319         v->salt = kmalloc(v->salt_size, GFP_KERNEL);
1320         if (!v->salt) {
1321             ti->error = "Cannot allocate salt";
1322             r = -ENOMEM;
1323             goto bad;
1324         }
1325         if (strlen(argv[9]) != v->salt_size * 2 ||
1326             hex2bin(v->salt, argv[9], v->salt_size)) {
1327             ti->error = "Invalid salt";
1328             r = -EINVAL;
1329             goto bad;
1330         }
1331     }
1332 
1333     argv += 10;
1334     argc -= 10;
1335 
1336     /* Optional parameters */
1337     if (argc) {
1338         as.argc = argc;
1339         as.argv = argv;
1340         r = verity_parse_opt_args(&as, v, &verify_args, false);
1341         if (r < 0)
1342             goto bad;
1343     }
1344 
1345     /* Root hash signature is  a optional parameter*/
1346     r = verity_verify_root_hash(root_hash_digest_to_validate,
1347                     strlen(root_hash_digest_to_validate),
1348                     verify_args.sig,
1349                     verify_args.sig_size);
1350     if (r < 0) {
1351         ti->error = "Root hash verification failed";
1352         goto bad;
1353     }
1354     v->hash_per_block_bits =
1355         __fls((1 << v->hash_dev_block_bits) / v->digest_size);
1356 
1357     v->levels = 0;
1358     if (v->data_blocks)
1359         while (v->hash_per_block_bits * v->levels < 64 &&
1360                (unsigned long long)(v->data_blocks - 1) >>
1361                (v->hash_per_block_bits * v->levels))
1362             v->levels++;
1363 
1364     if (v->levels > DM_VERITY_MAX_LEVELS) {
1365         ti->error = "Too many tree levels";
1366         r = -E2BIG;
1367         goto bad;
1368     }
1369 
1370     hash_position = v->hash_start;
1371     for (i = v->levels - 1; i >= 0; i--) {
1372         sector_t s;
1373         v->hash_level_block[i] = hash_position;
1374         s = (v->data_blocks + ((sector_t)1 << ((i + 1) * v->hash_per_block_bits)) - 1)
1375                     >> ((i + 1) * v->hash_per_block_bits);
1376         if (hash_position + s < hash_position) {
1377             ti->error = "Hash device offset overflow";
1378             r = -E2BIG;
1379             goto bad;
1380         }
1381         hash_position += s;
1382     }
1383     v->hash_blocks = hash_position;
1384 
1385     v->bufio = dm_bufio_client_create(v->hash_dev->bdev,
1386         1 << v->hash_dev_block_bits, 1, sizeof(struct buffer_aux),
1387         dm_bufio_alloc_callback, NULL,
1388         v->use_tasklet ? DM_BUFIO_CLIENT_NO_SLEEP : 0);
1389     if (IS_ERR(v->bufio)) {
1390         ti->error = "Cannot initialize dm-bufio";
1391         r = PTR_ERR(v->bufio);
1392         v->bufio = NULL;
1393         goto bad;
1394     }
1395 
1396     if (dm_bufio_get_device_size(v->bufio) < v->hash_blocks) {
1397         ti->error = "Hash device is too small";
1398         r = -E2BIG;
1399         goto bad;
1400     }
1401 
1402     /* WQ_UNBOUND greatly improves performance when running on ramdisk */
1403     wq_flags = WQ_MEM_RECLAIM | WQ_UNBOUND;
1404     if (v->use_tasklet) {
1405         /*
1406          * Allow verify_wq to preempt softirq since verification in
1407          * tasklet will fall-back to using it for error handling
1408          * (or if the bufio cache doesn't have required hashes).
1409          */
1410         wq_flags |= WQ_HIGHPRI;
1411     }
1412     v->verify_wq = alloc_workqueue("kverityd", wq_flags, num_online_cpus());
1413     if (!v->verify_wq) {
1414         ti->error = "Cannot allocate workqueue";
1415         r = -ENOMEM;
1416         goto bad;
1417     }
1418 
1419     ti->per_io_data_size = sizeof(struct dm_verity_io) +
1420                 v->ahash_reqsize + v->digest_size * 2;
1421 
1422     r = verity_fec_ctr(v);
1423     if (r)
1424         goto bad;
1425 
1426     ti->per_io_data_size = roundup(ti->per_io_data_size,
1427                        __alignof__(struct dm_verity_io));
1428 
1429     verity_verify_sig_opts_cleanup(&verify_args);
1430 
1431     return 0;
1432 
1433 bad:
1434 
1435     verity_verify_sig_opts_cleanup(&verify_args);
1436     verity_dtr(ti);
1437 
1438     return r;
1439 }
1440 
1441 /*
1442  * Check whether a DM target is a verity target.
1443  */
1444 bool dm_is_verity_target(struct dm_target *ti)
1445 {
1446     return ti->type->module == THIS_MODULE;
1447 }
1448 
1449 /*
1450  * Get the root digest of a verity target.
1451  *
1452  * Returns a copy of the root digest, the caller is responsible for
1453  * freeing the memory of the digest.
1454  */
1455 int dm_verity_get_root_digest(struct dm_target *ti, u8 **root_digest, unsigned int *digest_size)
1456 {
1457     struct dm_verity *v = ti->private;
1458 
1459     if (!dm_is_verity_target(ti))
1460         return -EINVAL;
1461 
1462     *root_digest = kmemdup(v->root_digest, v->digest_size, GFP_KERNEL);
1463     if (*root_digest == NULL)
1464         return -ENOMEM;
1465 
1466     *digest_size = v->digest_size;
1467 
1468     return 0;
1469 }
1470 
1471 static struct target_type verity_target = {
1472     .name       = "verity",
1473     .features   = DM_TARGET_IMMUTABLE,
1474     .version    = {1, 9, 0},
1475     .module     = THIS_MODULE,
1476     .ctr        = verity_ctr,
1477     .dtr        = verity_dtr,
1478     .map        = verity_map,
1479     .status     = verity_status,
1480     .prepare_ioctl  = verity_prepare_ioctl,
1481     .iterate_devices = verity_iterate_devices,
1482     .io_hints   = verity_io_hints,
1483 };
1484 
1485 static int __init dm_verity_init(void)
1486 {
1487     int r;
1488 
1489     r = dm_register_target(&verity_target);
1490     if (r < 0)
1491         DMERR("register failed %d", r);
1492 
1493     return r;
1494 }
1495 
1496 static void __exit dm_verity_exit(void)
1497 {
1498     dm_unregister_target(&verity_target);
1499 }
1500 
1501 module_init(dm_verity_init);
1502 module_exit(dm_verity_exit);
1503 
1504 MODULE_AUTHOR("Mikulas Patocka <mpatocka@redhat.com>");
1505 MODULE_AUTHOR("Mandeep Baines <msb@chromium.org>");
1506 MODULE_AUTHOR("Will Drewry <wad@chromium.org>");
1507 MODULE_DESCRIPTION(DM_NAME " target for transparent disk integrity checking");
1508 MODULE_LICENSE("GPL");