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/blk-crypto-profile.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 .name = "AES-256-XTS",
23 .cipher_str = "xts(aes)",
27 [BLK_ENCRYPTION_MODE_AES_128_CBC_ESSIV] = {
28 .name = "AES-128-CBC-ESSIV",
29 .cipher_str = "essiv(cbc(aes),sha256)",
33 [BLK_ENCRYPTION_MODE_ADIANTUM] = {
35 .cipher_str = "adiantum(xchacha12,aes)",
39 [BLK_ENCRYPTION_MODE_SM4_XTS] = {
41 .cipher_str = "xts(sm4)",
48 * This number needs to be at least (the number of threads doing IO
49 * concurrently) * (maximum recursive depth of a bio), so that we don't
50 * deadlock on crypt_ctx allocations. The default is chosen to be the same
51 * as the default number of post read contexts in both EXT4 and F2FS.
53 static int num_prealloc_crypt_ctxs = 128;
55 module_param(num_prealloc_crypt_ctxs, int, 0444);
56 MODULE_PARM_DESC(num_prealloc_crypt_ctxs,
57 "Number of bio crypto contexts to preallocate");
59 static struct kmem_cache *bio_crypt_ctx_cache;
60 static mempool_t *bio_crypt_ctx_pool;
62 static int __init bio_crypt_ctx_init(void)
66 bio_crypt_ctx_cache = KMEM_CACHE(bio_crypt_ctx, 0);
67 if (!bio_crypt_ctx_cache)
70 bio_crypt_ctx_pool = mempool_create_slab_pool(num_prealloc_crypt_ctxs,
72 if (!bio_crypt_ctx_pool)
75 /* This is assumed in various places. */
76 BUILD_BUG_ON(BLK_ENCRYPTION_MODE_INVALID != 0);
78 /* Sanity check that no algorithm exceeds the defined limits. */
79 for (i = 0; i < BLK_ENCRYPTION_MODE_MAX; i++) {
80 BUG_ON(blk_crypto_modes[i].keysize > BLK_CRYPTO_MAX_KEY_SIZE);
81 BUG_ON(blk_crypto_modes[i].ivsize > BLK_CRYPTO_MAX_IV_SIZE);
86 panic("Failed to allocate mem for bio crypt ctxs\n");
88 subsys_initcall(bio_crypt_ctx_init);
90 void bio_crypt_set_ctx(struct bio *bio, const struct blk_crypto_key *key,
91 const u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE], gfp_t gfp_mask)
93 struct bio_crypt_ctx *bc;
96 * The caller must use a gfp_mask that contains __GFP_DIRECT_RECLAIM so
97 * that the mempool_alloc() can't fail.
99 WARN_ON_ONCE(!(gfp_mask & __GFP_DIRECT_RECLAIM));
101 bc = mempool_alloc(bio_crypt_ctx_pool, gfp_mask);
104 memcpy(bc->bc_dun, dun, sizeof(bc->bc_dun));
106 bio->bi_crypt_context = bc;
109 void __bio_crypt_free_ctx(struct bio *bio)
111 mempool_free(bio->bi_crypt_context, bio_crypt_ctx_pool);
112 bio->bi_crypt_context = NULL;
115 int __bio_crypt_clone(struct bio *dst, struct bio *src, gfp_t gfp_mask)
117 dst->bi_crypt_context = mempool_alloc(bio_crypt_ctx_pool, gfp_mask);
118 if (!dst->bi_crypt_context)
120 *dst->bi_crypt_context = *src->bi_crypt_context;
124 /* Increments @dun by @inc, treating @dun as a multi-limb integer. */
125 void bio_crypt_dun_increment(u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE],
130 for (i = 0; inc && i < BLK_CRYPTO_DUN_ARRAY_SIZE; i++) {
133 * If the addition in this limb overflowed, then we need to
134 * carry 1 into the next limb. Else the carry is 0.
143 void __bio_crypt_advance(struct bio *bio, unsigned int bytes)
145 struct bio_crypt_ctx *bc = bio->bi_crypt_context;
147 bio_crypt_dun_increment(bc->bc_dun,
148 bytes >> bc->bc_key->data_unit_size_bits);
152 * Returns true if @bc->bc_dun plus @bytes converted to data units is equal to
153 * @next_dun, treating the DUNs as multi-limb integers.
155 bool bio_crypt_dun_is_contiguous(const struct bio_crypt_ctx *bc,
157 const u64 next_dun[BLK_CRYPTO_DUN_ARRAY_SIZE])
160 unsigned int carry = bytes >> bc->bc_key->data_unit_size_bits;
162 for (i = 0; i < BLK_CRYPTO_DUN_ARRAY_SIZE; i++) {
163 if (bc->bc_dun[i] + carry != next_dun[i])
166 * If the addition in this limb overflowed, then we need to
167 * carry 1 into the next limb. Else the carry is 0.
169 if ((bc->bc_dun[i] + carry) < carry)
175 /* If the DUN wrapped through 0, don't treat it as contiguous. */
180 * Checks that two bio crypt contexts are compatible - i.e. that
181 * they are mergeable except for data_unit_num continuity.
183 static bool bio_crypt_ctx_compatible(struct bio_crypt_ctx *bc1,
184 struct bio_crypt_ctx *bc2)
189 return bc2 && bc1->bc_key == bc2->bc_key;
192 bool bio_crypt_rq_ctx_compatible(struct request *rq, struct bio *bio)
194 return bio_crypt_ctx_compatible(rq->crypt_ctx, bio->bi_crypt_context);
198 * Checks that two bio crypt contexts are compatible, and also
199 * that their data_unit_nums are continuous (and can hence be merged)
200 * in the order @bc1 followed by @bc2.
202 bool bio_crypt_ctx_mergeable(struct bio_crypt_ctx *bc1, unsigned int bc1_bytes,
203 struct bio_crypt_ctx *bc2)
205 if (!bio_crypt_ctx_compatible(bc1, bc2))
208 return !bc1 || bio_crypt_dun_is_contiguous(bc1, bc1_bytes, bc2->bc_dun);
211 /* Check that all I/O segments are data unit aligned. */
212 static bool bio_crypt_check_alignment(struct bio *bio)
214 const unsigned int data_unit_size =
215 bio->bi_crypt_context->bc_key->crypto_cfg.data_unit_size;
216 struct bvec_iter iter;
219 bio_for_each_segment(bv, bio, iter) {
220 if (!IS_ALIGNED(bv.bv_len | bv.bv_offset, data_unit_size))
227 blk_status_t __blk_crypto_init_request(struct request *rq)
229 return blk_crypto_get_keyslot(rq->q->crypto_profile,
230 rq->crypt_ctx->bc_key,
235 * __blk_crypto_free_request - Uninitialize the crypto fields of a request.
237 * @rq: The request whose crypto fields to uninitialize.
239 * Completely uninitializes the crypto fields of a request. If a keyslot has
240 * been programmed into some inline encryption hardware, that keyslot is
241 * released. The rq->crypt_ctx is also freed.
243 void __blk_crypto_free_request(struct request *rq)
245 blk_crypto_put_keyslot(rq->crypt_keyslot);
246 mempool_free(rq->crypt_ctx, bio_crypt_ctx_pool);
247 blk_crypto_rq_set_defaults(rq);
251 * __blk_crypto_bio_prep - Prepare bio for inline encryption
253 * @bio_ptr: pointer to original bio pointer
255 * If the bio crypt context provided for the bio is supported by the underlying
256 * device's inline encryption hardware, do nothing.
258 * Otherwise, try to perform en/decryption for this bio by falling back to the
259 * kernel crypto API. When the crypto API fallback is used for encryption,
260 * blk-crypto may choose to split the bio into 2 - the first one that will
261 * continue to be processed and the second one that will be resubmitted via
262 * submit_bio_noacct. A bounce bio will be allocated to encrypt the contents
263 * of the aforementioned "first one", and *bio_ptr will be updated to this
266 * Caller must ensure bio has bio_crypt_ctx.
268 * Return: true on success; false on error (and bio->bi_status will be set
269 * appropriately, and bio_endio() will have been called so bio
270 * submission should abort).
272 bool __blk_crypto_bio_prep(struct bio **bio_ptr)
274 struct bio *bio = *bio_ptr;
275 const struct blk_crypto_key *bc_key = bio->bi_crypt_context->bc_key;
276 struct blk_crypto_profile *profile;
278 /* Error if bio has no data. */
279 if (WARN_ON_ONCE(!bio_has_data(bio))) {
280 bio->bi_status = BLK_STS_IOERR;
284 if (!bio_crypt_check_alignment(bio)) {
285 bio->bi_status = BLK_STS_IOERR;
290 * Success if device supports the encryption context, or if we succeeded
291 * in falling back to the crypto API.
293 profile = bdev_get_queue(bio->bi_bdev)->crypto_profile;
294 if (__blk_crypto_cfg_supported(profile, &bc_key->crypto_cfg))
297 if (blk_crypto_fallback_bio_prep(bio_ptr))
304 int __blk_crypto_rq_bio_prep(struct request *rq, struct bio *bio,
307 if (!rq->crypt_ctx) {
308 rq->crypt_ctx = mempool_alloc(bio_crypt_ctx_pool, gfp_mask);
312 *rq->crypt_ctx = *bio->bi_crypt_context;
317 * blk_crypto_init_key() - Prepare a key for use with blk-crypto
318 * @blk_key: Pointer to the blk_crypto_key to initialize.
319 * @raw_key: Pointer to the raw key. Must be the correct length for the chosen
320 * @crypto_mode; see blk_crypto_modes[].
321 * @crypto_mode: identifier for the encryption algorithm to use
322 * @dun_bytes: number of bytes that will be used to specify the DUN when this
324 * @data_unit_size: the data unit size to use for en/decryption
326 * Return: 0 on success, -errno on failure. The caller is responsible for
327 * zeroizing both blk_key and raw_key when done with them.
329 int blk_crypto_init_key(struct blk_crypto_key *blk_key, const u8 *raw_key,
330 enum blk_crypto_mode_num crypto_mode,
331 unsigned int dun_bytes,
332 unsigned int data_unit_size)
334 const struct blk_crypto_mode *mode;
336 memset(blk_key, 0, sizeof(*blk_key));
338 if (crypto_mode >= ARRAY_SIZE(blk_crypto_modes))
341 mode = &blk_crypto_modes[crypto_mode];
342 if (mode->keysize == 0)
345 if (dun_bytes == 0 || dun_bytes > mode->ivsize)
348 if (!is_power_of_2(data_unit_size))
351 blk_key->crypto_cfg.crypto_mode = crypto_mode;
352 blk_key->crypto_cfg.dun_bytes = dun_bytes;
353 blk_key->crypto_cfg.data_unit_size = data_unit_size;
354 blk_key->data_unit_size_bits = ilog2(data_unit_size);
355 blk_key->size = mode->keysize;
356 memcpy(blk_key->raw, raw_key, mode->keysize);
362 * Check if bios with @cfg can be en/decrypted by blk-crypto (i.e. either the
363 * request queue it's submitted to supports inline crypto, or the
364 * blk-crypto-fallback is enabled and supports the cfg).
366 bool blk_crypto_config_supported(struct request_queue *q,
367 const struct blk_crypto_config *cfg)
369 return IS_ENABLED(CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK) ||
370 __blk_crypto_cfg_supported(q->crypto_profile, cfg);
374 * blk_crypto_start_using_key() - Start using a blk_crypto_key on a device
375 * @key: A key to use on the device
376 * @q: the request queue for the device
378 * Upper layers must call this function to ensure that either the hardware
379 * supports the key's crypto settings, or the crypto API fallback has transforms
380 * for the needed mode allocated and ready to go. This function may allocate
381 * an skcipher, and *should not* be called from the data path, since that might
384 * Return: 0 on success; -ENOPKG if the hardware doesn't support the key and
385 * blk-crypto-fallback is either disabled or the needed algorithm
386 * is disabled in the crypto API; or another -errno code.
388 int blk_crypto_start_using_key(const struct blk_crypto_key *key,
389 struct request_queue *q)
391 if (__blk_crypto_cfg_supported(q->crypto_profile, &key->crypto_cfg))
393 return blk_crypto_fallback_start_using_mode(key->crypto_cfg.crypto_mode);
397 * blk_crypto_evict_key() - Evict a key from any inline encryption hardware
398 * it may have been programmed into
399 * @q: The request queue who's associated inline encryption hardware this key
400 * might have been programmed into
401 * @key: The key to evict
403 * Upper layers (filesystems) must call this function to ensure that a key is
404 * evicted from any hardware that it might have been programmed into. The key
405 * must not be in use by any in-flight IO when this function is called.
407 * Return: 0 on success or if the key wasn't in any keyslot; -errno on error.
409 int blk_crypto_evict_key(struct request_queue *q,
410 const struct blk_crypto_key *key)
412 if (__blk_crypto_cfg_supported(q->crypto_profile, &key->crypto_cfg))
413 return __blk_crypto_evict_key(q->crypto_profile, key);
416 * If the request_queue didn't support the key, then blk-crypto-fallback
417 * may have been used, so try to evict the key from blk-crypto-fallback.
419 return blk_crypto_fallback_evict_key(key);
421 EXPORT_SYMBOL_GPL(blk_crypto_evict_key);