block/keyslot-manager: Introduce functions for device mapper support
[platform/kernel/linux-starfive.git] / block / keyslot-manager.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright 2019 Google LLC
4  */
5
6 /**
7  * DOC: The Keyslot Manager
8  *
9  * Many devices with inline encryption support have a limited number of "slots"
10  * into which encryption contexts may be programmed, and requests can be tagged
11  * with a slot number to specify the key to use for en/decryption.
12  *
13  * As the number of slots is limited, and programming keys is expensive on
14  * many inline encryption hardware, we don't want to program the same key into
15  * multiple slots - if multiple requests are using the same key, we want to
16  * program just one slot with that key and use that slot for all requests.
17  *
18  * The keyslot manager manages these keyslots appropriately, and also acts as
19  * an abstraction between the inline encryption hardware and the upper layers.
20  *
21  * Lower layer devices will set up a keyslot manager in their request queue
22  * and tell it how to perform device specific operations like programming/
23  * evicting keys from keyslots.
24  *
25  * Upper layers will call blk_ksm_get_slot_for_key() to program a
26  * key into some slot in the inline encryption hardware.
27  */
28
29 #define pr_fmt(fmt) "blk-crypto: " fmt
30
31 #include <linux/keyslot-manager.h>
32 #include <linux/atomic.h>
33 #include <linux/mutex.h>
34 #include <linux/pm_runtime.h>
35 #include <linux/wait.h>
36 #include <linux/blkdev.h>
37
38 struct blk_ksm_keyslot {
39         atomic_t slot_refs;
40         struct list_head idle_slot_node;
41         struct hlist_node hash_node;
42         const struct blk_crypto_key *key;
43         struct blk_keyslot_manager *ksm;
44 };
45
46 static inline void blk_ksm_hw_enter(struct blk_keyslot_manager *ksm)
47 {
48         /*
49          * Calling into the driver requires ksm->lock held and the device
50          * resumed.  But we must resume the device first, since that can acquire
51          * and release ksm->lock via blk_ksm_reprogram_all_keys().
52          */
53         if (ksm->dev)
54                 pm_runtime_get_sync(ksm->dev);
55         down_write(&ksm->lock);
56 }
57
58 static inline void blk_ksm_hw_exit(struct blk_keyslot_manager *ksm)
59 {
60         up_write(&ksm->lock);
61         if (ksm->dev)
62                 pm_runtime_put_sync(ksm->dev);
63 }
64
65 static inline bool blk_ksm_is_passthrough(struct blk_keyslot_manager *ksm)
66 {
67         return ksm->num_slots == 0;
68 }
69
70 /**
71  * blk_ksm_init() - Initialize a keyslot manager
72  * @ksm: The keyslot_manager to initialize.
73  * @num_slots: The number of key slots to manage.
74  *
75  * Allocate memory for keyslots and initialize a keyslot manager. Called by
76  * e.g. storage drivers to set up a keyslot manager in their request_queue.
77  *
78  * Return: 0 on success, or else a negative error code.
79  */
80 int blk_ksm_init(struct blk_keyslot_manager *ksm, unsigned int num_slots)
81 {
82         unsigned int slot;
83         unsigned int i;
84         unsigned int slot_hashtable_size;
85
86         memset(ksm, 0, sizeof(*ksm));
87
88         if (num_slots == 0)
89                 return -EINVAL;
90
91         ksm->slots = kvcalloc(num_slots, sizeof(ksm->slots[0]), GFP_KERNEL);
92         if (!ksm->slots)
93                 return -ENOMEM;
94
95         ksm->num_slots = num_slots;
96
97         init_rwsem(&ksm->lock);
98
99         init_waitqueue_head(&ksm->idle_slots_wait_queue);
100         INIT_LIST_HEAD(&ksm->idle_slots);
101
102         for (slot = 0; slot < num_slots; slot++) {
103                 ksm->slots[slot].ksm = ksm;
104                 list_add_tail(&ksm->slots[slot].idle_slot_node,
105                               &ksm->idle_slots);
106         }
107
108         spin_lock_init(&ksm->idle_slots_lock);
109
110         slot_hashtable_size = roundup_pow_of_two(num_slots);
111         /*
112          * hash_ptr() assumes bits != 0, so ensure the hash table has at least 2
113          * buckets.  This only makes a difference when there is only 1 keyslot.
114          */
115         if (slot_hashtable_size < 2)
116                 slot_hashtable_size = 2;
117
118         ksm->log_slot_ht_size = ilog2(slot_hashtable_size);
119         ksm->slot_hashtable = kvmalloc_array(slot_hashtable_size,
120                                              sizeof(ksm->slot_hashtable[0]),
121                                              GFP_KERNEL);
122         if (!ksm->slot_hashtable)
123                 goto err_destroy_ksm;
124         for (i = 0; i < slot_hashtable_size; i++)
125                 INIT_HLIST_HEAD(&ksm->slot_hashtable[i]);
126
127         return 0;
128
129 err_destroy_ksm:
130         blk_ksm_destroy(ksm);
131         return -ENOMEM;
132 }
133 EXPORT_SYMBOL_GPL(blk_ksm_init);
134
135 static inline struct hlist_head *
136 blk_ksm_hash_bucket_for_key(struct blk_keyslot_manager *ksm,
137                             const struct blk_crypto_key *key)
138 {
139         return &ksm->slot_hashtable[hash_ptr(key, ksm->log_slot_ht_size)];
140 }
141
142 static void blk_ksm_remove_slot_from_lru_list(struct blk_ksm_keyslot *slot)
143 {
144         struct blk_keyslot_manager *ksm = slot->ksm;
145         unsigned long flags;
146
147         spin_lock_irqsave(&ksm->idle_slots_lock, flags);
148         list_del(&slot->idle_slot_node);
149         spin_unlock_irqrestore(&ksm->idle_slots_lock, flags);
150 }
151
152 static struct blk_ksm_keyslot *blk_ksm_find_keyslot(
153                                         struct blk_keyslot_manager *ksm,
154                                         const struct blk_crypto_key *key)
155 {
156         const struct hlist_head *head = blk_ksm_hash_bucket_for_key(ksm, key);
157         struct blk_ksm_keyslot *slotp;
158
159         hlist_for_each_entry(slotp, head, hash_node) {
160                 if (slotp->key == key)
161                         return slotp;
162         }
163         return NULL;
164 }
165
166 static struct blk_ksm_keyslot *blk_ksm_find_and_grab_keyslot(
167                                         struct blk_keyslot_manager *ksm,
168                                         const struct blk_crypto_key *key)
169 {
170         struct blk_ksm_keyslot *slot;
171
172         slot = blk_ksm_find_keyslot(ksm, key);
173         if (!slot)
174                 return NULL;
175         if (atomic_inc_return(&slot->slot_refs) == 1) {
176                 /* Took first reference to this slot; remove it from LRU list */
177                 blk_ksm_remove_slot_from_lru_list(slot);
178         }
179         return slot;
180 }
181
182 unsigned int blk_ksm_get_slot_idx(struct blk_ksm_keyslot *slot)
183 {
184         return slot - slot->ksm->slots;
185 }
186 EXPORT_SYMBOL_GPL(blk_ksm_get_slot_idx);
187
188 /**
189  * blk_ksm_get_slot_for_key() - Program a key into a keyslot.
190  * @ksm: The keyslot manager to program the key into.
191  * @key: Pointer to the key object to program, including the raw key, crypto
192  *       mode, and data unit size.
193  * @slot_ptr: A pointer to return the pointer of the allocated keyslot.
194  *
195  * Get a keyslot that's been programmed with the specified key.  If one already
196  * exists, return it with incremented refcount.  Otherwise, wait for a keyslot
197  * to become idle and program it.
198  *
199  * Context: Process context. Takes and releases ksm->lock.
200  * Return: BLK_STS_OK on success (and keyslot is set to the pointer of the
201  *         allocated keyslot), or some other blk_status_t otherwise (and
202  *         keyslot is set to NULL).
203  */
204 blk_status_t blk_ksm_get_slot_for_key(struct blk_keyslot_manager *ksm,
205                                       const struct blk_crypto_key *key,
206                                       struct blk_ksm_keyslot **slot_ptr)
207 {
208         struct blk_ksm_keyslot *slot;
209         int slot_idx;
210         int err;
211
212         *slot_ptr = NULL;
213
214         if (blk_ksm_is_passthrough(ksm))
215                 return BLK_STS_OK;
216
217         down_read(&ksm->lock);
218         slot = blk_ksm_find_and_grab_keyslot(ksm, key);
219         up_read(&ksm->lock);
220         if (slot)
221                 goto success;
222
223         for (;;) {
224                 blk_ksm_hw_enter(ksm);
225                 slot = blk_ksm_find_and_grab_keyslot(ksm, key);
226                 if (slot) {
227                         blk_ksm_hw_exit(ksm);
228                         goto success;
229                 }
230
231                 /*
232                  * If we're here, that means there wasn't a slot that was
233                  * already programmed with the key. So try to program it.
234                  */
235                 if (!list_empty(&ksm->idle_slots))
236                         break;
237
238                 blk_ksm_hw_exit(ksm);
239                 wait_event(ksm->idle_slots_wait_queue,
240                            !list_empty(&ksm->idle_slots));
241         }
242
243         slot = list_first_entry(&ksm->idle_slots, struct blk_ksm_keyslot,
244                                 idle_slot_node);
245         slot_idx = blk_ksm_get_slot_idx(slot);
246
247         err = ksm->ksm_ll_ops.keyslot_program(ksm, key, slot_idx);
248         if (err) {
249                 wake_up(&ksm->idle_slots_wait_queue);
250                 blk_ksm_hw_exit(ksm);
251                 return errno_to_blk_status(err);
252         }
253
254         /* Move this slot to the hash list for the new key. */
255         if (slot->key)
256                 hlist_del(&slot->hash_node);
257         slot->key = key;
258         hlist_add_head(&slot->hash_node, blk_ksm_hash_bucket_for_key(ksm, key));
259
260         atomic_set(&slot->slot_refs, 1);
261
262         blk_ksm_remove_slot_from_lru_list(slot);
263
264         blk_ksm_hw_exit(ksm);
265 success:
266         *slot_ptr = slot;
267         return BLK_STS_OK;
268 }
269
270 /**
271  * blk_ksm_put_slot() - Release a reference to a slot
272  * @slot: The keyslot to release the reference of.
273  *
274  * Context: Any context.
275  */
276 void blk_ksm_put_slot(struct blk_ksm_keyslot *slot)
277 {
278         struct blk_keyslot_manager *ksm;
279         unsigned long flags;
280
281         if (!slot)
282                 return;
283
284         ksm = slot->ksm;
285
286         if (atomic_dec_and_lock_irqsave(&slot->slot_refs,
287                                         &ksm->idle_slots_lock, flags)) {
288                 list_add_tail(&slot->idle_slot_node, &ksm->idle_slots);
289                 spin_unlock_irqrestore(&ksm->idle_slots_lock, flags);
290                 wake_up(&ksm->idle_slots_wait_queue);
291         }
292 }
293
294 /**
295  * blk_ksm_crypto_cfg_supported() - Find out if a crypto configuration is
296  *                                  supported by a ksm.
297  * @ksm: The keyslot manager to check
298  * @cfg: The crypto configuration to check for.
299  *
300  * Checks for crypto_mode/data unit size/dun bytes support.
301  *
302  * Return: Whether or not this ksm supports the specified crypto config.
303  */
304 bool blk_ksm_crypto_cfg_supported(struct blk_keyslot_manager *ksm,
305                                   const struct blk_crypto_config *cfg)
306 {
307         if (!ksm)
308                 return false;
309         if (!(ksm->crypto_modes_supported[cfg->crypto_mode] &
310               cfg->data_unit_size))
311                 return false;
312         if (ksm->max_dun_bytes_supported < cfg->dun_bytes)
313                 return false;
314         return true;
315 }
316
317 /**
318  * blk_ksm_evict_key() - Evict a key from the lower layer device.
319  * @ksm: The keyslot manager to evict from
320  * @key: The key to evict
321  *
322  * Find the keyslot that the specified key was programmed into, and evict that
323  * slot from the lower layer device. The slot must not be in use by any
324  * in-flight IO when this function is called.
325  *
326  * Context: Process context. Takes and releases ksm->lock.
327  * Return: 0 on success or if there's no keyslot with the specified key, -EBUSY
328  *         if the keyslot is still in use, or another -errno value on other
329  *         error.
330  */
331 int blk_ksm_evict_key(struct blk_keyslot_manager *ksm,
332                       const struct blk_crypto_key *key)
333 {
334         struct blk_ksm_keyslot *slot;
335         int err = 0;
336
337         if (blk_ksm_is_passthrough(ksm)) {
338                 if (ksm->ksm_ll_ops.keyslot_evict) {
339                         blk_ksm_hw_enter(ksm);
340                         err = ksm->ksm_ll_ops.keyslot_evict(ksm, key, -1);
341                         blk_ksm_hw_exit(ksm);
342                         return err;
343                 }
344                 return 0;
345         }
346
347         blk_ksm_hw_enter(ksm);
348         slot = blk_ksm_find_keyslot(ksm, key);
349         if (!slot)
350                 goto out_unlock;
351
352         if (WARN_ON_ONCE(atomic_read(&slot->slot_refs) != 0)) {
353                 err = -EBUSY;
354                 goto out_unlock;
355         }
356         err = ksm->ksm_ll_ops.keyslot_evict(ksm, key,
357                                             blk_ksm_get_slot_idx(slot));
358         if (err)
359                 goto out_unlock;
360
361         hlist_del(&slot->hash_node);
362         slot->key = NULL;
363         err = 0;
364 out_unlock:
365         blk_ksm_hw_exit(ksm);
366         return err;
367 }
368
369 /**
370  * blk_ksm_reprogram_all_keys() - Re-program all keyslots.
371  * @ksm: The keyslot manager
372  *
373  * Re-program all keyslots that are supposed to have a key programmed.  This is
374  * intended only for use by drivers for hardware that loses its keys on reset.
375  *
376  * Context: Process context. Takes and releases ksm->lock.
377  */
378 void blk_ksm_reprogram_all_keys(struct blk_keyslot_manager *ksm)
379 {
380         unsigned int slot;
381
382         if (blk_ksm_is_passthrough(ksm))
383                 return;
384
385         /* This is for device initialization, so don't resume the device */
386         down_write(&ksm->lock);
387         for (slot = 0; slot < ksm->num_slots; slot++) {
388                 const struct blk_crypto_key *key = ksm->slots[slot].key;
389                 int err;
390
391                 if (!key)
392                         continue;
393
394                 err = ksm->ksm_ll_ops.keyslot_program(ksm, key, slot);
395                 WARN_ON(err);
396         }
397         up_write(&ksm->lock);
398 }
399 EXPORT_SYMBOL_GPL(blk_ksm_reprogram_all_keys);
400
401 void blk_ksm_destroy(struct blk_keyslot_manager *ksm)
402 {
403         if (!ksm)
404                 return;
405         kvfree(ksm->slot_hashtable);
406         kvfree_sensitive(ksm->slots, sizeof(ksm->slots[0]) * ksm->num_slots);
407         memzero_explicit(ksm, sizeof(*ksm));
408 }
409 EXPORT_SYMBOL_GPL(blk_ksm_destroy);
410
411 bool blk_ksm_register(struct blk_keyslot_manager *ksm, struct request_queue *q)
412 {
413         if (blk_integrity_queue_supports_integrity(q)) {
414                 pr_warn("Integrity and hardware inline encryption are not supported together. Disabling hardware inline encryption.\n");
415                 return false;
416         }
417         q->ksm = ksm;
418         return true;
419 }
420 EXPORT_SYMBOL_GPL(blk_ksm_register);
421
422 void blk_ksm_unregister(struct request_queue *q)
423 {
424         q->ksm = NULL;
425 }
426
427 /**
428  * blk_ksm_intersect_modes() - restrict supported modes by child device
429  * @parent: The keyslot manager for parent device
430  * @child: The keyslot manager for child device, or NULL
431  *
432  * Clear any crypto mode support bits in @parent that aren't set in @child.
433  * If @child is NULL, then all parent bits are cleared.
434  *
435  * Only use this when setting up the keyslot manager for a layered device,
436  * before it's been exposed yet.
437  */
438 void blk_ksm_intersect_modes(struct blk_keyslot_manager *parent,
439                              const struct blk_keyslot_manager *child)
440 {
441         if (child) {
442                 unsigned int i;
443
444                 parent->max_dun_bytes_supported =
445                         min(parent->max_dun_bytes_supported,
446                             child->max_dun_bytes_supported);
447                 for (i = 0; i < ARRAY_SIZE(child->crypto_modes_supported);
448                      i++) {
449                         parent->crypto_modes_supported[i] &=
450                                 child->crypto_modes_supported[i];
451                 }
452         } else {
453                 parent->max_dun_bytes_supported = 0;
454                 memset(parent->crypto_modes_supported, 0,
455                        sizeof(parent->crypto_modes_supported));
456         }
457 }
458 EXPORT_SYMBOL_GPL(blk_ksm_intersect_modes);
459
460 /**
461  * blk_ksm_is_superset() - Check if a KSM supports a superset of crypto modes
462  *                         and DUN bytes that another KSM supports. Here,
463  *                         "superset" refers to the mathematical meaning of the
464  *                         word - i.e. if two KSMs have the *same* capabilities,
465  *                         they *are* considered supersets of each other.
466  * @ksm_superset: The KSM that we want to verify is a superset
467  * @ksm_subset: The KSM that we want to verify is a subset
468  *
469  * Return: True if @ksm_superset supports a superset of the crypto modes and DUN
470  *         bytes that @ksm_subset supports.
471  */
472 bool blk_ksm_is_superset(struct blk_keyslot_manager *ksm_superset,
473                          struct blk_keyslot_manager *ksm_subset)
474 {
475         int i;
476
477         if (!ksm_subset)
478                 return true;
479
480         if (!ksm_superset)
481                 return false;
482
483         for (i = 0; i < ARRAY_SIZE(ksm_superset->crypto_modes_supported); i++) {
484                 if (ksm_subset->crypto_modes_supported[i] &
485                     (~ksm_superset->crypto_modes_supported[i])) {
486                         return false;
487                 }
488         }
489
490         if (ksm_subset->max_dun_bytes_supported >
491             ksm_superset->max_dun_bytes_supported) {
492                 return false;
493         }
494
495         return true;
496 }
497 EXPORT_SYMBOL_GPL(blk_ksm_is_superset);
498
499 /**
500  * blk_ksm_update_capabilities() - Update the restrictions of a KSM to those of
501  *                                 another KSM
502  * @target_ksm: The KSM whose restrictions to update.
503  * @reference_ksm: The KSM to whose restrictions this function will update
504  *                 @target_ksm's restrictions to.
505  *
506  * Blk-crypto requires that crypto capabilities that were
507  * advertised when a bio was created continue to be supported by the
508  * device until that bio is ended. This is turn means that a device cannot
509  * shrink its advertised crypto capabilities without any explicit
510  * synchronization with upper layers. So if there's no such explicit
511  * synchronization, @reference_ksm must support all the crypto capabilities that
512  * @target_ksm does
513  * (i.e. we need blk_ksm_is_superset(@reference_ksm, @target_ksm) == true).
514  *
515  * Note also that as long as the crypto capabilities are being expanded, the
516  * order of updates becoming visible is not important because it's alright
517  * for blk-crypto to see stale values - they only cause blk-crypto to
518  * believe that a crypto capability isn't supported when it actually is (which
519  * might result in blk-crypto-fallback being used if available, or the bio being
520  * failed).
521  */
522 void blk_ksm_update_capabilities(struct blk_keyslot_manager *target_ksm,
523                                  struct blk_keyslot_manager *reference_ksm)
524 {
525         memcpy(target_ksm->crypto_modes_supported,
526                reference_ksm->crypto_modes_supported,
527                sizeof(target_ksm->crypto_modes_supported));
528
529         target_ksm->max_dun_bytes_supported =
530                                 reference_ksm->max_dun_bytes_supported;
531 }
532 EXPORT_SYMBOL_GPL(blk_ksm_update_capabilities);
533
534 /**
535  * blk_ksm_init_passthrough() - Init a passthrough keyslot manager
536  * @ksm: The keyslot manager to init
537  *
538  * Initialize a passthrough keyslot manager.
539  * Called by e.g. storage drivers to set up a keyslot manager in their
540  * request_queue, when the storage driver wants to manage its keys by itself.
541  * This is useful for inline encryption hardware that doesn't have the concept
542  * of keyslots, and for layered devices.
543  */
544 void blk_ksm_init_passthrough(struct blk_keyslot_manager *ksm)
545 {
546         memset(ksm, 0, sizeof(*ksm));
547         init_rwsem(&ksm->lock);
548 }
549 EXPORT_SYMBOL_GPL(blk_ksm_init_passthrough);