1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Copyright 2019 Google LLC
4 */
5
6 /**
7 * DOC: blk-crypto profiles
8 *
9 * 'struct blk_crypto_profile' contains all generic inline encryption-related
10 * state for a particular inline encryption device. blk_crypto_profile serves
11 * as the way that drivers for inline encryption hardware expose their crypto
12 * capabilities and certain functions (e.g., functions to program and evict
13 * keys) to upper layers. Device drivers that want to support inline encryption
14 * construct a crypto profile, then associate it with the disk's request_queue.
15 *
16 * If the device has keyslots, then its blk_crypto_profile also handles managing
17 * these keyslots in a device-independent way, using the driver-provided
18 * functions to program and evict keys as needed. This includes keeping track
19 * of which key and how many I/O requests are using each keyslot, getting
20 * keyslots for I/O requests, and handling key eviction requests.
21 *
22 * For more information, see Documentation/block/inline-encryption.rst.
23 */
24
25 #define pr_fmt(fmt) "blk-crypto: " fmt
26
27 #include <linux/blk-crypto-profile.h>
28 #include <linux/device.h>
29 #include <linux/atomic.h>
30 #include <linux/mutex.h>
31 #include <linux/pm_runtime.h>
32 #include <linux/wait.h>
33 #include <linux/blkdev.h>
34 #include <linux/blk-integrity.h>
35 #include "blk-crypto-internal.h"
36
37 struct blk_crypto_keyslot {
38 atomic_t slot_refs;
39 struct list_head idle_slot_node;
40 struct hlist_node hash_node;
41 const struct blk_crypto_key *key;
42 struct blk_crypto_profile *profile;
43 };
44
blk_crypto_hw_enter(struct blk_crypto_profile * profile)45 static inline void blk_crypto_hw_enter(struct blk_crypto_profile *profile)
46 {
47 /*
48 * Calling into the driver requires profile->lock held and the device
49 * resumed. But we must resume the device first, since that can acquire
50 * and release profile->lock via blk_crypto_reprogram_all_keys().
51 */
52 if (profile->dev)
53 pm_runtime_get_sync(profile->dev);
54 down_write(&profile->lock);
55 }
56
blk_crypto_hw_exit(struct blk_crypto_profile * profile)57 static inline void blk_crypto_hw_exit(struct blk_crypto_profile *profile)
58 {
59 up_write(&profile->lock);
60 if (profile->dev)
61 pm_runtime_put_sync(profile->dev);
62 }
63
64 /**
65 * blk_crypto_profile_init() - Initialize a blk_crypto_profile
66 * @profile: the blk_crypto_profile to initialize
67 * @num_slots: the number of keyslots
68 *
69 * Storage drivers must call this when starting to set up a blk_crypto_profile,
70 * before filling in additional fields.
71 *
72 * Return: 0 on success, or else a negative error code.
73 */
blk_crypto_profile_init(struct blk_crypto_profile * profile,unsigned int num_slots)74 int blk_crypto_profile_init(struct blk_crypto_profile *profile,
75 unsigned int num_slots)
76 {
77 unsigned int slot;
78 unsigned int i;
79 unsigned int slot_hashtable_size;
80
81 memset(profile, 0, sizeof(*profile));
82
83 /*
84 * profile->lock of an underlying device can nest inside profile->lock
85 * of a device-mapper device, so use a dynamic lock class to avoid
86 * false-positive lockdep reports.
87 */
88 #ifdef CONFIG_LOCKDEP
89 lockdep_register_key(&profile->lockdep_key);
90 __init_rwsem(&profile->lock, "&profile->lock", &profile->lockdep_key);
91 #else
92 init_rwsem(&profile->lock);
93 #endif
94
95 if (num_slots == 0)
96 return 0;
97
98 /* Initialize keyslot management data. */
99
100 profile->slots = kvcalloc(num_slots, sizeof(profile->slots[0]),
101 GFP_KERNEL);
102 if (!profile->slots)
103 goto err_destroy;
104
105 profile->num_slots = num_slots;
106
107 init_waitqueue_head(&profile->idle_slots_wait_queue);
108 INIT_LIST_HEAD(&profile->idle_slots);
109
110 for (slot = 0; slot < num_slots; slot++) {
111 profile->slots[slot].profile = profile;
112 list_add_tail(&profile->slots[slot].idle_slot_node,
113 &profile->idle_slots);
114 }
115
116 spin_lock_init(&profile->idle_slots_lock);
117
118 slot_hashtable_size = roundup_pow_of_two(num_slots);
119 /*
120 * hash_ptr() assumes bits != 0, so ensure the hash table has at least 2
121 * buckets. This only makes a difference when there is only 1 keyslot.
122 */
123 if (slot_hashtable_size < 2)
124 slot_hashtable_size = 2;
125
126 profile->log_slot_ht_size = ilog2(slot_hashtable_size);
127 profile->slot_hashtable =
128 kvmalloc_array(slot_hashtable_size,
129 sizeof(profile->slot_hashtable[0]), GFP_KERNEL);
130 if (!profile->slot_hashtable)
131 goto err_destroy;
132 for (i = 0; i < slot_hashtable_size; i++)
133 INIT_HLIST_HEAD(&profile->slot_hashtable[i]);
134
135 return 0;
136
137 err_destroy:
138 blk_crypto_profile_destroy(profile);
139 return -ENOMEM;
140 }
141 EXPORT_SYMBOL_GPL(blk_crypto_profile_init);
142
blk_crypto_profile_destroy_callback(void * profile)143 static void blk_crypto_profile_destroy_callback(void *profile)
144 {
145 blk_crypto_profile_destroy(profile);
146 }
147
148 /**
149 * devm_blk_crypto_profile_init() - Resource-managed blk_crypto_profile_init()
150 * @dev: the device which owns the blk_crypto_profile
151 * @profile: the blk_crypto_profile to initialize
152 * @num_slots: the number of keyslots
153 *
154 * Like blk_crypto_profile_init(), but causes blk_crypto_profile_destroy() to be
155 * called automatically on driver detach.
156 *
157 * Return: 0 on success, or else a negative error code.
158 */
devm_blk_crypto_profile_init(struct device * dev,struct blk_crypto_profile * profile,unsigned int num_slots)159 int devm_blk_crypto_profile_init(struct device *dev,
160 struct blk_crypto_profile *profile,
161 unsigned int num_slots)
162 {
163 int err = blk_crypto_profile_init(profile, num_slots);
164
165 if (err)
166 return err;
167
168 return devm_add_action_or_reset(dev,
169 blk_crypto_profile_destroy_callback,
170 profile);
171 }
172 EXPORT_SYMBOL_GPL(devm_blk_crypto_profile_init);
173
174 static inline struct hlist_head *
blk_crypto_hash_bucket_for_key(struct blk_crypto_profile * profile,const struct blk_crypto_key * key)175 blk_crypto_hash_bucket_for_key(struct blk_crypto_profile *profile,
176 const struct blk_crypto_key *key)
177 {
178 return &profile->slot_hashtable[
179 hash_ptr(key, profile->log_slot_ht_size)];
180 }
181
182 static void
blk_crypto_remove_slot_from_lru_list(struct blk_crypto_keyslot * slot)183 blk_crypto_remove_slot_from_lru_list(struct blk_crypto_keyslot *slot)
184 {
185 struct blk_crypto_profile *profile = slot->profile;
186 unsigned long flags;
187
188 spin_lock_irqsave(&profile->idle_slots_lock, flags);
189 list_del(&slot->idle_slot_node);
190 spin_unlock_irqrestore(&profile->idle_slots_lock, flags);
191 }
192
193 static struct blk_crypto_keyslot *
blk_crypto_find_keyslot(struct blk_crypto_profile * profile,const struct blk_crypto_key * key)194 blk_crypto_find_keyslot(struct blk_crypto_profile *profile,
195 const struct blk_crypto_key *key)
196 {
197 const struct hlist_head *head =
198 blk_crypto_hash_bucket_for_key(profile, key);
199 struct blk_crypto_keyslot *slotp;
200
201 hlist_for_each_entry(slotp, head, hash_node) {
202 if (slotp->key == key)
203 return slotp;
204 }
205 return NULL;
206 }
207
208 static struct blk_crypto_keyslot *
blk_crypto_find_and_grab_keyslot(struct blk_crypto_profile * profile,const struct blk_crypto_key * key)209 blk_crypto_find_and_grab_keyslot(struct blk_crypto_profile *profile,
210 const struct blk_crypto_key *key)
211 {
212 struct blk_crypto_keyslot *slot;
213
214 slot = blk_crypto_find_keyslot(profile, key);
215 if (!slot)
216 return NULL;
217 if (atomic_inc_return(&slot->slot_refs) == 1) {
218 /* Took first reference to this slot; remove it from LRU list */
219 blk_crypto_remove_slot_from_lru_list(slot);
220 }
221 return slot;
222 }
223
224 /**
225 * blk_crypto_keyslot_index() - Get the index of a keyslot
226 * @slot: a keyslot that blk_crypto_get_keyslot() returned
227 *
228 * Return: the 0-based index of the keyslot within the device's keyslots.
229 */
blk_crypto_keyslot_index(struct blk_crypto_keyslot * slot)230 unsigned int blk_crypto_keyslot_index(struct blk_crypto_keyslot *slot)
231 {
232 return slot - slot->profile->slots;
233 }
234 EXPORT_SYMBOL_GPL(blk_crypto_keyslot_index);
235
236 /**
237 * blk_crypto_get_keyslot() - Get a keyslot for a key, if needed.
238 * @profile: the crypto profile of the device the key will be used on
239 * @key: the key that will be used
240 * @slot_ptr: If a keyslot is allocated, an opaque pointer to the keyslot struct
241 * will be stored here; otherwise NULL will be stored here.
242 *
243 * If the device has keyslots, this gets a keyslot that's been programmed with
244 * the specified key. If the key is already in a slot, this reuses it;
245 * otherwise this waits for a slot to become idle and programs the key into it.
246 *
247 * This must be paired with a call to blk_crypto_put_keyslot().
248 *
249 * Context: Process context. Takes and releases profile->lock.
250 * Return: BLK_STS_OK on success, meaning that either a keyslot was allocated or
251 * one wasn't needed; or a blk_status_t error on failure.
252 */
blk_crypto_get_keyslot(struct blk_crypto_profile * profile,const struct blk_crypto_key * key,struct blk_crypto_keyslot ** slot_ptr)253 blk_status_t blk_crypto_get_keyslot(struct blk_crypto_profile *profile,
254 const struct blk_crypto_key *key,
255 struct blk_crypto_keyslot **slot_ptr)
256 {
257 struct blk_crypto_keyslot *slot;
258 int slot_idx;
259 int err;
260
261 *slot_ptr = NULL;
262
263 /*
264 * If the device has no concept of "keyslots", then there is no need to
265 * get one.
266 */
267 if (profile->num_slots == 0)
268 return BLK_STS_OK;
269
270 down_read(&profile->lock);
271 slot = blk_crypto_find_and_grab_keyslot(profile, key);
272 up_read(&profile->lock);
273 if (slot)
274 goto success;
275
276 for (;;) {
277 blk_crypto_hw_enter(profile);
278 slot = blk_crypto_find_and_grab_keyslot(profile, key);
279 if (slot) {
280 blk_crypto_hw_exit(profile);
281 goto success;
282 }
283
284 /*
285 * If we're here, that means there wasn't a slot that was
286 * already programmed with the key. So try to program it.
287 */
288 if (!list_empty(&profile->idle_slots))
289 break;
290
291 blk_crypto_hw_exit(profile);
292 wait_event(profile->idle_slots_wait_queue,
293 !list_empty(&profile->idle_slots));
294 }
295
296 slot = list_first_entry(&profile->idle_slots, struct blk_crypto_keyslot,
297 idle_slot_node);
298 slot_idx = blk_crypto_keyslot_index(slot);
299
300 err = profile->ll_ops.keyslot_program(profile, key, slot_idx);
301 if (err) {
302 wake_up(&profile->idle_slots_wait_queue);
303 blk_crypto_hw_exit(profile);
304 return errno_to_blk_status(err);
305 }
306
307 /* Move this slot to the hash list for the new key. */
308 if (slot->key)
309 hlist_del(&slot->hash_node);
310 slot->key = key;
311 hlist_add_head(&slot->hash_node,
312 blk_crypto_hash_bucket_for_key(profile, key));
313
314 atomic_set(&slot->slot_refs, 1);
315
316 blk_crypto_remove_slot_from_lru_list(slot);
317
318 blk_crypto_hw_exit(profile);
319 success:
320 *slot_ptr = slot;
321 return BLK_STS_OK;
322 }
323
324 /**
325 * blk_crypto_put_keyslot() - Release a reference to a keyslot
326 * @slot: The keyslot to release the reference of (may be NULL).
327 *
328 * Context: Any context.
329 */
blk_crypto_put_keyslot(struct blk_crypto_keyslot * slot)330 void blk_crypto_put_keyslot(struct blk_crypto_keyslot *slot)
331 {
332 struct blk_crypto_profile *profile;
333 unsigned long flags;
334
335 if (!slot)
336 return;
337
338 profile = slot->profile;
339
340 if (atomic_dec_and_lock_irqsave(&slot->slot_refs,
341 &profile->idle_slots_lock, flags)) {
342 list_add_tail(&slot->idle_slot_node, &profile->idle_slots);
343 spin_unlock_irqrestore(&profile->idle_slots_lock, flags);
344 wake_up(&profile->idle_slots_wait_queue);
345 }
346 }
347
348 /**
349 * __blk_crypto_cfg_supported() - Check whether the given crypto profile
350 * supports the given crypto configuration.
351 * @profile: the crypto profile to check
352 * @cfg: the crypto configuration to check for
353 *
354 * Return: %true if @profile supports the given @cfg.
355 */
__blk_crypto_cfg_supported(struct blk_crypto_profile * profile,const struct blk_crypto_config * cfg)356 bool __blk_crypto_cfg_supported(struct blk_crypto_profile *profile,
357 const struct blk_crypto_config *cfg)
358 {
359 if (!profile)
360 return false;
361 if (!(profile->modes_supported[cfg->crypto_mode] & cfg->data_unit_size))
362 return false;
363 if (profile->max_dun_bytes_supported < cfg->dun_bytes)
364 return false;
365 if (!(profile->key_types_supported & cfg->key_type))
366 return false;
367 return true;
368 }
369
370 /*
371 * This is an internal function that evicts a key from an inline encryption
372 * device that can be either a real device or the blk-crypto-fallback "device".
373 * It is used only by blk_crypto_evict_key(); see that function for details.
374 */
__blk_crypto_evict_key(struct blk_crypto_profile * profile,const struct blk_crypto_key * key)375 int __blk_crypto_evict_key(struct blk_crypto_profile *profile,
376 const struct blk_crypto_key *key)
377 {
378 struct blk_crypto_keyslot *slot;
379 int err;
380
381 if (profile->num_slots == 0) {
382 if (profile->ll_ops.keyslot_evict) {
383 blk_crypto_hw_enter(profile);
384 err = profile->ll_ops.keyslot_evict(profile, key, -1);
385 blk_crypto_hw_exit(profile);
386 return err;
387 }
388 return 0;
389 }
390
391 blk_crypto_hw_enter(profile);
392 slot = blk_crypto_find_keyslot(profile, key);
393 if (!slot) {
394 /*
395 * Not an error, since a key not in use by I/O is not guaranteed
396 * to be in a keyslot. There can be more keys than keyslots.
397 */
398 err = 0;
399 goto out;
400 }
401
402 if (WARN_ON_ONCE(atomic_read(&slot->slot_refs) != 0)) {
403 /* BUG: key is still in use by I/O */
404 err = -EBUSY;
405 goto out_remove;
406 }
407 err = profile->ll_ops.keyslot_evict(profile, key,
408 blk_crypto_keyslot_index(slot));
409 out_remove:
410 /*
411 * Callers free the key even on error, so unlink the key from the hash
412 * table and clear slot->key even on error.
413 */
414 hlist_del(&slot->hash_node);
415 slot->key = NULL;
416 out:
417 blk_crypto_hw_exit(profile);
418 return err;
419 }
420
421 /**
422 * blk_crypto_reprogram_all_keys() - Re-program all keyslots.
423 * @profile: The crypto profile
424 *
425 * Re-program all keyslots that are supposed to have a key programmed. This is
426 * intended only for use by drivers for hardware that loses its keys on reset.
427 *
428 * Context: Process context. Takes and releases profile->lock.
429 */
blk_crypto_reprogram_all_keys(struct blk_crypto_profile * profile)430 void blk_crypto_reprogram_all_keys(struct blk_crypto_profile *profile)
431 {
432 unsigned int slot;
433
434 if (profile->num_slots == 0)
435 return;
436
437 /* This is for device initialization, so don't resume the device */
438 down_write(&profile->lock);
439 for (slot = 0; slot < profile->num_slots; slot++) {
440 const struct blk_crypto_key *key = profile->slots[slot].key;
441 int err;
442
443 if (!key)
444 continue;
445
446 err = profile->ll_ops.keyslot_program(profile, key, slot);
447 WARN_ON(err);
448 }
449 up_write(&profile->lock);
450 }
451 EXPORT_SYMBOL_GPL(blk_crypto_reprogram_all_keys);
452
blk_crypto_profile_destroy(struct blk_crypto_profile * profile)453 void blk_crypto_profile_destroy(struct blk_crypto_profile *profile)
454 {
455 if (!profile)
456 return;
457 #ifdef CONFIG_LOCKDEP
458 lockdep_unregister_key(&profile->lockdep_key);
459 #endif
460 kvfree(profile->slot_hashtable);
461 kvfree_sensitive(profile->slots,
462 sizeof(profile->slots[0]) * profile->num_slots);
463 memzero_explicit(profile, sizeof(*profile));
464 }
465 EXPORT_SYMBOL_GPL(blk_crypto_profile_destroy);
466
blk_crypto_register(struct blk_crypto_profile * profile,struct request_queue * q)467 bool blk_crypto_register(struct blk_crypto_profile *profile,
468 struct request_queue *q)
469 {
470 if (blk_integrity_queue_supports_integrity(q)) {
471 pr_warn("Integrity and hardware inline encryption are not supported together. Disabling hardware inline encryption.\n");
472 return false;
473 }
474 q->crypto_profile = profile;
475 return true;
476 }
477 EXPORT_SYMBOL_GPL(blk_crypto_register);
478
479 /**
480 * blk_crypto_derive_sw_secret() - Derive software secret from wrapped key
481 * @bdev: a block device that supports hardware-wrapped keys
482 * @eph_key: the hardware-wrapped key in ephemerally-wrapped form
483 * @eph_key_size: size of @eph_key in bytes
484 * @sw_secret: (output) the software secret
485 *
486 * Given a hardware-wrapped key in ephemerally-wrapped form (the same form that
487 * it is used for I/O), ask the hardware to derive the secret which software can
488 * use for cryptographic tasks other than inline encryption. This secret is
489 * guaranteed to be cryptographically isolated from the inline encryption key,
490 * i.e. derived with a different KDF context.
491 *
492 * Return: 0 on success, -EOPNOTSUPP if the block device doesn't support
493 * hardware-wrapped keys, -EBADMSG if the key isn't a valid
494 * hardware-wrapped key, or another -errno code.
495 */
blk_crypto_derive_sw_secret(struct block_device * bdev,const u8 * eph_key,size_t eph_key_size,u8 sw_secret[BLK_CRYPTO_SW_SECRET_SIZE])496 int blk_crypto_derive_sw_secret(struct block_device *bdev,
497 const u8 *eph_key, size_t eph_key_size,
498 u8 sw_secret[BLK_CRYPTO_SW_SECRET_SIZE])
499 {
500 struct blk_crypto_profile *profile =
501 bdev_get_queue(bdev)->crypto_profile;
502 int err;
503
504 if (!profile)
505 return -EOPNOTSUPP;
506 if (!(profile->key_types_supported & BLK_CRYPTO_KEY_TYPE_HW_WRAPPED))
507 return -EOPNOTSUPP;
508 if (!profile->ll_ops.derive_sw_secret)
509 return -EOPNOTSUPP;
510 blk_crypto_hw_enter(profile);
511 err = profile->ll_ops.derive_sw_secret(profile, eph_key, eph_key_size,
512 sw_secret);
513 blk_crypto_hw_exit(profile);
514 return err;
515 }
516 EXPORT_SYMBOL_GPL(blk_crypto_derive_sw_secret);
517
518 /**
519 * blk_crypto_intersect_capabilities() - restrict supported crypto capabilities
520 * by child device
521 * @parent: the crypto profile for the parent device
522 * @child: the crypto profile for the child device, or NULL
523 *
524 * This clears all crypto capabilities in @parent that aren't set in @child. If
525 * @child is NULL, then this clears all parent capabilities.
526 *
527 * Only use this when setting up the crypto profile for a layered device, before
528 * it's been exposed yet.
529 */
blk_crypto_intersect_capabilities(struct blk_crypto_profile * parent,const struct blk_crypto_profile * child)530 void blk_crypto_intersect_capabilities(struct blk_crypto_profile *parent,
531 const struct blk_crypto_profile *child)
532 {
533 if (child) {
534 unsigned int i;
535
536 parent->max_dun_bytes_supported =
537 min(parent->max_dun_bytes_supported,
538 child->max_dun_bytes_supported);
539 for (i = 0; i < ARRAY_SIZE(child->modes_supported); i++)
540 parent->modes_supported[i] &= child->modes_supported[i];
541 parent->key_types_supported &= child->key_types_supported;
542 } else {
543 parent->max_dun_bytes_supported = 0;
544 memset(parent->modes_supported, 0,
545 sizeof(parent->modes_supported));
546 parent->key_types_supported = 0;
547 }
548 }
549 EXPORT_SYMBOL_GPL(blk_crypto_intersect_capabilities);
550
551 /**
552 * blk_crypto_has_capabilities() - Check whether @target supports at least all
553 * the crypto capabilities that @reference does.
554 * @target: the target profile
555 * @reference: the reference profile
556 *
557 * Return: %true if @target supports all the crypto capabilities of @reference.
558 */
blk_crypto_has_capabilities(const struct blk_crypto_profile * target,const struct blk_crypto_profile * reference)559 bool blk_crypto_has_capabilities(const struct blk_crypto_profile *target,
560 const struct blk_crypto_profile *reference)
561 {
562 int i;
563
564 if (!reference)
565 return true;
566
567 if (!target)
568 return false;
569
570 for (i = 0; i < ARRAY_SIZE(target->modes_supported); i++) {
571 if (reference->modes_supported[i] & ~target->modes_supported[i])
572 return false;
573 }
574
575 if (reference->max_dun_bytes_supported >
576 target->max_dun_bytes_supported)
577 return false;
578
579 if (reference->key_types_supported & ~target->key_types_supported)
580 return false;
581
582 return true;
583 }
584 EXPORT_SYMBOL_GPL(blk_crypto_has_capabilities);
585
586 /**
587 * blk_crypto_update_capabilities() - Update the capabilities of a crypto
588 * profile to match those of another crypto
589 * profile.
590 * @dst: The crypto profile whose capabilities to update.
591 * @src: The crypto profile whose capabilities this function will update @dst's
592 * capabilities to.
593 *
594 * Blk-crypto requires that crypto capabilities that were
595 * advertised when a bio was created continue to be supported by the
596 * device until that bio is ended. This is turn means that a device cannot
597 * shrink its advertised crypto capabilities without any explicit
598 * synchronization with upper layers. So if there's no such explicit
599 * synchronization, @src must support all the crypto capabilities that
600 * @dst does (i.e. we need blk_crypto_has_capabilities(@src, @dst)).
601 *
602 * Note also that as long as the crypto capabilities are being expanded, the
603 * order of updates becoming visible is not important because it's alright
604 * for blk-crypto to see stale values - they only cause blk-crypto to
605 * believe that a crypto capability isn't supported when it actually is (which
606 * might result in blk-crypto-fallback being used if available, or the bio being
607 * failed).
608 */
blk_crypto_update_capabilities(struct blk_crypto_profile * dst,const struct blk_crypto_profile * src)609 void blk_crypto_update_capabilities(struct blk_crypto_profile *dst,
610 const struct blk_crypto_profile *src)
611 {
612 memcpy(dst->modes_supported, src->modes_supported,
613 sizeof(dst->modes_supported));
614
615 dst->max_dun_bytes_supported = src->max_dun_bytes_supported;
616 dst->key_types_supported = src->key_types_supported;
617 }
618 EXPORT_SYMBOL_GPL(blk_crypto_update_capabilities);
619