1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright 2019 Google LLC
7 * Refer to Documentation/block/inline-encryption.rst for detailed explanation.
10 #define pr_fmt(fmt) "blk-crypto: " fmt
12 #include <linux/bio.h>
13 #include <linux/blkdev.h>
14 #include <linux/keyslot-manager.h>
15 #include <linux/module.h>
16 #include <linux/slab.h>
18 #include "blk-crypto-internal.h"
20 const struct blk_crypto_mode blk_crypto_modes[] = {
21 [BLK_ENCRYPTION_MODE_AES_256_XTS] = {
22 .cipher_str = "xts(aes)",
26 [BLK_ENCRYPTION_MODE_AES_128_CBC_ESSIV] = {
27 .cipher_str = "essiv(cbc(aes),sha256)",
31 [BLK_ENCRYPTION_MODE_ADIANTUM] = {
32 .cipher_str = "adiantum(xchacha12,aes)",
39 * This number needs to be at least (the number of threads doing IO
40 * concurrently) * (maximum recursive depth of a bio), so that we don't
41 * deadlock on crypt_ctx allocations. The default is chosen to be the same
42 * as the default number of post read contexts in both EXT4 and F2FS.
44 static int num_prealloc_crypt_ctxs = 128;
46 module_param(num_prealloc_crypt_ctxs, int, 0444);
47 MODULE_PARM_DESC(num_prealloc_crypt_ctxs,
48 "Number of bio crypto contexts to preallocate");
50 static struct kmem_cache *bio_crypt_ctx_cache;
51 static mempool_t *bio_crypt_ctx_pool;
53 static int __init bio_crypt_ctx_init(void)
57 bio_crypt_ctx_cache = KMEM_CACHE(bio_crypt_ctx, 0);
58 if (!bio_crypt_ctx_cache)
61 bio_crypt_ctx_pool = mempool_create_slab_pool(num_prealloc_crypt_ctxs,
63 if (!bio_crypt_ctx_pool)
66 /* This is assumed in various places. */
67 BUILD_BUG_ON(BLK_ENCRYPTION_MODE_INVALID != 0);
69 /* Sanity check that no algorithm exceeds the defined limits. */
70 for (i = 0; i < BLK_ENCRYPTION_MODE_MAX; i++) {
71 BUG_ON(blk_crypto_modes[i].keysize > BLK_CRYPTO_MAX_KEY_SIZE);
72 BUG_ON(blk_crypto_modes[i].ivsize > BLK_CRYPTO_MAX_IV_SIZE);
77 panic("Failed to allocate mem for bio crypt ctxs\n");
79 subsys_initcall(bio_crypt_ctx_init);
81 void bio_crypt_set_ctx(struct bio *bio, const struct blk_crypto_key *key,
82 const u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE], gfp_t gfp_mask)
84 struct bio_crypt_ctx *bc = mempool_alloc(bio_crypt_ctx_pool, gfp_mask);
87 memcpy(bc->bc_dun, dun, sizeof(bc->bc_dun));
89 bio->bi_crypt_context = bc;
92 void __bio_crypt_free_ctx(struct bio *bio)
94 mempool_free(bio->bi_crypt_context, bio_crypt_ctx_pool);
95 bio->bi_crypt_context = NULL;
98 void __bio_crypt_clone(struct bio *dst, struct bio *src, gfp_t gfp_mask)
100 dst->bi_crypt_context = mempool_alloc(bio_crypt_ctx_pool, gfp_mask);
101 *dst->bi_crypt_context = *src->bi_crypt_context;
103 EXPORT_SYMBOL_GPL(__bio_crypt_clone);
105 /* Increments @dun by @inc, treating @dun as a multi-limb integer. */
106 void bio_crypt_dun_increment(u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE],
111 for (i = 0; inc && i < BLK_CRYPTO_DUN_ARRAY_SIZE; i++) {
114 * If the addition in this limb overflowed, then we need to
115 * carry 1 into the next limb. Else the carry is 0.
124 void __bio_crypt_advance(struct bio *bio, unsigned int bytes)
126 struct bio_crypt_ctx *bc = bio->bi_crypt_context;
128 bio_crypt_dun_increment(bc->bc_dun,
129 bytes >> bc->bc_key->data_unit_size_bits);
133 * Returns true if @bc->bc_dun plus @bytes converted to data units is equal to
134 * @next_dun, treating the DUNs as multi-limb integers.
136 bool bio_crypt_dun_is_contiguous(const struct bio_crypt_ctx *bc,
138 const u64 next_dun[BLK_CRYPTO_DUN_ARRAY_SIZE])
141 unsigned int carry = bytes >> bc->bc_key->data_unit_size_bits;
143 for (i = 0; i < BLK_CRYPTO_DUN_ARRAY_SIZE; i++) {
144 if (bc->bc_dun[i] + carry != next_dun[i])
147 * If the addition in this limb overflowed, then we need to
148 * carry 1 into the next limb. Else the carry is 0.
150 if ((bc->bc_dun[i] + carry) < carry)
156 /* If the DUN wrapped through 0, don't treat it as contiguous. */
161 * Checks that two bio crypt contexts are compatible - i.e. that
162 * they are mergeable except for data_unit_num continuity.
164 static bool bio_crypt_ctx_compatible(struct bio_crypt_ctx *bc1,
165 struct bio_crypt_ctx *bc2)
170 return bc2 && bc1->bc_key == bc2->bc_key;
173 bool bio_crypt_rq_ctx_compatible(struct request *rq, struct bio *bio)
175 return bio_crypt_ctx_compatible(rq->crypt_ctx, bio->bi_crypt_context);
179 * Checks that two bio crypt contexts are compatible, and also
180 * that their data_unit_nums are continuous (and can hence be merged)
181 * in the order @bc1 followed by @bc2.
183 bool bio_crypt_ctx_mergeable(struct bio_crypt_ctx *bc1, unsigned int bc1_bytes,
184 struct bio_crypt_ctx *bc2)
186 if (!bio_crypt_ctx_compatible(bc1, bc2))
189 return !bc1 || bio_crypt_dun_is_contiguous(bc1, bc1_bytes, bc2->bc_dun);
192 /* Check that all I/O segments are data unit aligned. */
193 static bool bio_crypt_check_alignment(struct bio *bio)
195 const unsigned int data_unit_size =
196 bio->bi_crypt_context->bc_key->crypto_cfg.data_unit_size;
197 struct bvec_iter iter;
200 bio_for_each_segment(bv, bio, iter) {
201 if (!IS_ALIGNED(bv.bv_len | bv.bv_offset, data_unit_size))
208 blk_status_t __blk_crypto_init_request(struct request *rq)
210 return blk_ksm_get_slot_for_key(rq->q->ksm, rq->crypt_ctx->bc_key,
215 * __blk_crypto_free_request - Uninitialize the crypto fields of a request.
217 * @rq: The request whose crypto fields to uninitialize.
219 * Completely uninitializes the crypto fields of a request. If a keyslot has
220 * been programmed into some inline encryption hardware, that keyslot is
221 * released. The rq->crypt_ctx is also freed.
223 void __blk_crypto_free_request(struct request *rq)
225 blk_ksm_put_slot(rq->crypt_keyslot);
226 mempool_free(rq->crypt_ctx, bio_crypt_ctx_pool);
227 blk_crypto_rq_set_defaults(rq);
231 * __blk_crypto_bio_prep - Prepare bio for inline encryption
233 * @bio_ptr: pointer to original bio pointer
235 * If the bio crypt context provided for the bio is supported by the underlying
236 * device's inline encryption hardware, do nothing.
238 * Otherwise, try to perform en/decryption for this bio by falling back to the
239 * kernel crypto API. When the crypto API fallback is used for encryption,
240 * blk-crypto may choose to split the bio into 2 - the first one that will
241 * continue to be processed and the second one that will be resubmitted via
242 * submit_bio_noacct. A bounce bio will be allocated to encrypt the contents
243 * of the aforementioned "first one", and *bio_ptr will be updated to this
246 * Caller must ensure bio has bio_crypt_ctx.
248 * Return: true on success; false on error (and bio->bi_status will be set
249 * appropriately, and bio_endio() will have been called so bio
250 * submission should abort).
252 bool __blk_crypto_bio_prep(struct bio **bio_ptr)
254 struct bio *bio = *bio_ptr;
255 const struct blk_crypto_key *bc_key = bio->bi_crypt_context->bc_key;
257 /* Error if bio has no data. */
258 if (WARN_ON_ONCE(!bio_has_data(bio))) {
259 bio->bi_status = BLK_STS_IOERR;
263 if (!bio_crypt_check_alignment(bio)) {
264 bio->bi_status = BLK_STS_IOERR;
269 * Success if device supports the encryption context, or if we succeeded
270 * in falling back to the crypto API.
272 if (blk_ksm_crypto_cfg_supported(bio->bi_disk->queue->ksm,
273 &bc_key->crypto_cfg))
276 if (blk_crypto_fallback_bio_prep(bio_ptr))
284 * __blk_crypto_rq_bio_prep - Prepare a request's crypt_ctx when its first bio
287 * @rq: The request to prepare
288 * @bio: The first bio being inserted into the request
289 * @gfp_mask: gfp mask
291 void __blk_crypto_rq_bio_prep(struct request *rq, struct bio *bio,
295 rq->crypt_ctx = mempool_alloc(bio_crypt_ctx_pool, gfp_mask);
296 *rq->crypt_ctx = *bio->bi_crypt_context;
300 * blk_crypto_init_key() - Prepare a key for use with blk-crypto
301 * @blk_key: Pointer to the blk_crypto_key to initialize.
302 * @raw_key: Pointer to the raw key. Must be the correct length for the chosen
303 * @crypto_mode; see blk_crypto_modes[].
304 * @crypto_mode: identifier for the encryption algorithm to use
305 * @dun_bytes: number of bytes that will be used to specify the DUN when this
307 * @data_unit_size: the data unit size to use for en/decryption
309 * Return: 0 on success, -errno on failure. The caller is responsible for
310 * zeroizing both blk_key and raw_key when done with them.
312 int blk_crypto_init_key(struct blk_crypto_key *blk_key, const u8 *raw_key,
313 enum blk_crypto_mode_num crypto_mode,
314 unsigned int dun_bytes,
315 unsigned int data_unit_size)
317 const struct blk_crypto_mode *mode;
319 memset(blk_key, 0, sizeof(*blk_key));
321 if (crypto_mode >= ARRAY_SIZE(blk_crypto_modes))
324 mode = &blk_crypto_modes[crypto_mode];
325 if (mode->keysize == 0)
328 if (dun_bytes == 0 || dun_bytes > BLK_CRYPTO_MAX_IV_SIZE)
331 if (!is_power_of_2(data_unit_size))
334 blk_key->crypto_cfg.crypto_mode = crypto_mode;
335 blk_key->crypto_cfg.dun_bytes = dun_bytes;
336 blk_key->crypto_cfg.data_unit_size = data_unit_size;
337 blk_key->data_unit_size_bits = ilog2(data_unit_size);
338 blk_key->size = mode->keysize;
339 memcpy(blk_key->raw, raw_key, mode->keysize);
345 * Check if bios with @cfg can be en/decrypted by blk-crypto (i.e. either the
346 * request queue it's submitted to supports inline crypto, or the
347 * blk-crypto-fallback is enabled and supports the cfg).
349 bool blk_crypto_config_supported(struct request_queue *q,
350 const struct blk_crypto_config *cfg)
352 return IS_ENABLED(CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK) ||
353 blk_ksm_crypto_cfg_supported(q->ksm, cfg);
357 * blk_crypto_start_using_key() - Start using a blk_crypto_key on a device
358 * @key: A key to use on the device
359 * @q: the request queue for the device
361 * Upper layers must call this function to ensure that either the hardware
362 * supports the key's crypto settings, or the crypto API fallback has transforms
363 * for the needed mode allocated and ready to go. This function may allocate
364 * an skcipher, and *should not* be called from the data path, since that might
367 * Return: 0 on success; -ENOPKG if the hardware doesn't support the key and
368 * blk-crypto-fallback is either disabled or the needed algorithm
369 * is disabled in the crypto API; or another -errno code.
371 int blk_crypto_start_using_key(const struct blk_crypto_key *key,
372 struct request_queue *q)
374 if (blk_ksm_crypto_cfg_supported(q->ksm, &key->crypto_cfg))
376 return blk_crypto_fallback_start_using_mode(key->crypto_cfg.crypto_mode);
380 * blk_crypto_evict_key() - Evict a key from any inline encryption hardware
381 * it may have been programmed into
382 * @q: The request queue who's associated inline encryption hardware this key
383 * might have been programmed into
384 * @key: The key to evict
386 * Upper layers (filesystems) must call this function to ensure that a key is
387 * evicted from any hardware that it might have been programmed into. The key
388 * must not be in use by any in-flight IO when this function is called.
390 * Return: 0 on success or if key is not present in the q's ksm, -err on error.
392 int blk_crypto_evict_key(struct request_queue *q,
393 const struct blk_crypto_key *key)
395 if (blk_ksm_crypto_cfg_supported(q->ksm, &key->crypto_cfg))
396 return blk_ksm_evict_key(q->ksm, key);
399 * If the request queue's associated inline encryption hardware didn't
400 * have support for the key, then the key might have been programmed
401 * into the fallback keyslot manager, so try to evict from there.
403 return blk_crypto_fallback_evict_key(key);