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