Merge tag 'backlight-next-5.12' of git://git.kernel.org/pub/scm/linux/kernel/git...
[linux-2.6-microblaze.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/device.h>
33 #include <linux/atomic.h>
34 #include <linux/mutex.h>
35 #include <linux/pm_runtime.h>
36 #include <linux/wait.h>
37 #include <linux/blkdev.h>
38
39 struct blk_ksm_keyslot {
40         atomic_t slot_refs;
41         struct list_head idle_slot_node;
42         struct hlist_node hash_node;
43         const struct blk_crypto_key *key;
44         struct blk_keyslot_manager *ksm;
45 };
46
47 static inline void blk_ksm_hw_enter(struct blk_keyslot_manager *ksm)
48 {
49         /*
50          * Calling into the driver requires ksm->lock held and the device
51          * resumed.  But we must resume the device first, since that can acquire
52          * and release ksm->lock via blk_ksm_reprogram_all_keys().
53          */
54         if (ksm->dev)
55                 pm_runtime_get_sync(ksm->dev);
56         down_write(&ksm->lock);
57 }
58
59 static inline void blk_ksm_hw_exit(struct blk_keyslot_manager *ksm)
60 {
61         up_write(&ksm->lock);
62         if (ksm->dev)
63                 pm_runtime_put_sync(ksm->dev);
64 }
65
66 /**
67  * blk_ksm_init() - Initialize a keyslot manager
68  * @ksm: The keyslot_manager to initialize.
69  * @num_slots: The number of key slots to manage.
70  *
71  * Allocate memory for keyslots and initialize a keyslot manager. Called by
72  * e.g. storage drivers to set up a keyslot manager in their request_queue.
73  *
74  * Return: 0 on success, or else a negative error code.
75  */
76 int blk_ksm_init(struct blk_keyslot_manager *ksm, unsigned int num_slots)
77 {
78         unsigned int slot;
79         unsigned int i;
80         unsigned int slot_hashtable_size;
81
82         memset(ksm, 0, sizeof(*ksm));
83
84         if (num_slots == 0)
85                 return -EINVAL;
86
87         ksm->slots = kvcalloc(num_slots, sizeof(ksm->slots[0]), GFP_KERNEL);
88         if (!ksm->slots)
89                 return -ENOMEM;
90
91         ksm->num_slots = num_slots;
92
93         init_rwsem(&ksm->lock);
94
95         init_waitqueue_head(&ksm->idle_slots_wait_queue);
96         INIT_LIST_HEAD(&ksm->idle_slots);
97
98         for (slot = 0; slot < num_slots; slot++) {
99                 ksm->slots[slot].ksm = ksm;
100                 list_add_tail(&ksm->slots[slot].idle_slot_node,
101                               &ksm->idle_slots);
102         }
103
104         spin_lock_init(&ksm->idle_slots_lock);
105
106         slot_hashtable_size = roundup_pow_of_two(num_slots);
107         /*
108          * hash_ptr() assumes bits != 0, so ensure the hash table has at least 2
109          * buckets.  This only makes a difference when there is only 1 keyslot.
110          */
111         if (slot_hashtable_size < 2)
112                 slot_hashtable_size = 2;
113
114         ksm->log_slot_ht_size = ilog2(slot_hashtable_size);
115         ksm->slot_hashtable = kvmalloc_array(slot_hashtable_size,
116                                              sizeof(ksm->slot_hashtable[0]),
117                                              GFP_KERNEL);
118         if (!ksm->slot_hashtable)
119                 goto err_destroy_ksm;
120         for (i = 0; i < slot_hashtable_size; i++)
121                 INIT_HLIST_HEAD(&ksm->slot_hashtable[i]);
122
123         return 0;
124
125 err_destroy_ksm:
126         blk_ksm_destroy(ksm);
127         return -ENOMEM;
128 }
129 EXPORT_SYMBOL_GPL(blk_ksm_init);
130
131 static void blk_ksm_destroy_callback(void *ksm)
132 {
133         blk_ksm_destroy(ksm);
134 }
135
136 /**
137  * devm_blk_ksm_init() - Resource-managed blk_ksm_init()
138  * @dev: The device which owns the blk_keyslot_manager.
139  * @ksm: The blk_keyslot_manager to initialize.
140  * @num_slots: The number of key slots to manage.
141  *
142  * Like blk_ksm_init(), but causes blk_ksm_destroy() to be called automatically
143  * on driver detach.
144  *
145  * Return: 0 on success, or else a negative error code.
146  */
147 int devm_blk_ksm_init(struct device *dev, struct blk_keyslot_manager *ksm,
148                       unsigned int num_slots)
149 {
150         int err = blk_ksm_init(ksm, num_slots);
151
152         if (err)
153                 return err;
154
155         return devm_add_action_or_reset(dev, blk_ksm_destroy_callback, ksm);
156 }
157 EXPORT_SYMBOL_GPL(devm_blk_ksm_init);
158
159 static inline struct hlist_head *
160 blk_ksm_hash_bucket_for_key(struct blk_keyslot_manager *ksm,
161                             const struct blk_crypto_key *key)
162 {
163         return &ksm->slot_hashtable[hash_ptr(key, ksm->log_slot_ht_size)];
164 }
165
166 static void blk_ksm_remove_slot_from_lru_list(struct blk_ksm_keyslot *slot)
167 {
168         struct blk_keyslot_manager *ksm = slot->ksm;
169         unsigned long flags;
170
171         spin_lock_irqsave(&ksm->idle_slots_lock, flags);
172         list_del(&slot->idle_slot_node);
173         spin_unlock_irqrestore(&ksm->idle_slots_lock, flags);
174 }
175
176 static struct blk_ksm_keyslot *blk_ksm_find_keyslot(
177                                         struct blk_keyslot_manager *ksm,
178                                         const struct blk_crypto_key *key)
179 {
180         const struct hlist_head *head = blk_ksm_hash_bucket_for_key(ksm, key);
181         struct blk_ksm_keyslot *slotp;
182
183         hlist_for_each_entry(slotp, head, hash_node) {
184                 if (slotp->key == key)
185                         return slotp;
186         }
187         return NULL;
188 }
189
190 static struct blk_ksm_keyslot *blk_ksm_find_and_grab_keyslot(
191                                         struct blk_keyslot_manager *ksm,
192                                         const struct blk_crypto_key *key)
193 {
194         struct blk_ksm_keyslot *slot;
195
196         slot = blk_ksm_find_keyslot(ksm, key);
197         if (!slot)
198                 return NULL;
199         if (atomic_inc_return(&slot->slot_refs) == 1) {
200                 /* Took first reference to this slot; remove it from LRU list */
201                 blk_ksm_remove_slot_from_lru_list(slot);
202         }
203         return slot;
204 }
205
206 unsigned int blk_ksm_get_slot_idx(struct blk_ksm_keyslot *slot)
207 {
208         return slot - slot->ksm->slots;
209 }
210 EXPORT_SYMBOL_GPL(blk_ksm_get_slot_idx);
211
212 /**
213  * blk_ksm_get_slot_for_key() - Program a key into a keyslot.
214  * @ksm: The keyslot manager to program the key into.
215  * @key: Pointer to the key object to program, including the raw key, crypto
216  *       mode, and data unit size.
217  * @slot_ptr: A pointer to return the pointer of the allocated keyslot.
218  *
219  * Get a keyslot that's been programmed with the specified key.  If one already
220  * exists, return it with incremented refcount.  Otherwise, wait for a keyslot
221  * to become idle and program it.
222  *
223  * Context: Process context. Takes and releases ksm->lock.
224  * Return: BLK_STS_OK on success (and keyslot is set to the pointer of the
225  *         allocated keyslot), or some other blk_status_t otherwise (and
226  *         keyslot is set to NULL).
227  */
228 blk_status_t blk_ksm_get_slot_for_key(struct blk_keyslot_manager *ksm,
229                                       const struct blk_crypto_key *key,
230                                       struct blk_ksm_keyslot **slot_ptr)
231 {
232         struct blk_ksm_keyslot *slot;
233         int slot_idx;
234         int err;
235
236         *slot_ptr = NULL;
237         down_read(&ksm->lock);
238         slot = blk_ksm_find_and_grab_keyslot(ksm, key);
239         up_read(&ksm->lock);
240         if (slot)
241                 goto success;
242
243         for (;;) {
244                 blk_ksm_hw_enter(ksm);
245                 slot = blk_ksm_find_and_grab_keyslot(ksm, key);
246                 if (slot) {
247                         blk_ksm_hw_exit(ksm);
248                         goto success;
249                 }
250
251                 /*
252                  * If we're here, that means there wasn't a slot that was
253                  * already programmed with the key. So try to program it.
254                  */
255                 if (!list_empty(&ksm->idle_slots))
256                         break;
257
258                 blk_ksm_hw_exit(ksm);
259                 wait_event(ksm->idle_slots_wait_queue,
260                            !list_empty(&ksm->idle_slots));
261         }
262
263         slot = list_first_entry(&ksm->idle_slots, struct blk_ksm_keyslot,
264                                 idle_slot_node);
265         slot_idx = blk_ksm_get_slot_idx(slot);
266
267         err = ksm->ksm_ll_ops.keyslot_program(ksm, key, slot_idx);
268         if (err) {
269                 wake_up(&ksm->idle_slots_wait_queue);
270                 blk_ksm_hw_exit(ksm);
271                 return errno_to_blk_status(err);
272         }
273
274         /* Move this slot to the hash list for the new key. */
275         if (slot->key)
276                 hlist_del(&slot->hash_node);
277         slot->key = key;
278         hlist_add_head(&slot->hash_node, blk_ksm_hash_bucket_for_key(ksm, key));
279
280         atomic_set(&slot->slot_refs, 1);
281
282         blk_ksm_remove_slot_from_lru_list(slot);
283
284         blk_ksm_hw_exit(ksm);
285 success:
286         *slot_ptr = slot;
287         return BLK_STS_OK;
288 }
289
290 /**
291  * blk_ksm_put_slot() - Release a reference to a slot
292  * @slot: The keyslot to release the reference of.
293  *
294  * Context: Any context.
295  */
296 void blk_ksm_put_slot(struct blk_ksm_keyslot *slot)
297 {
298         struct blk_keyslot_manager *ksm;
299         unsigned long flags;
300
301         if (!slot)
302                 return;
303
304         ksm = slot->ksm;
305
306         if (atomic_dec_and_lock_irqsave(&slot->slot_refs,
307                                         &ksm->idle_slots_lock, flags)) {
308                 list_add_tail(&slot->idle_slot_node, &ksm->idle_slots);
309                 spin_unlock_irqrestore(&ksm->idle_slots_lock, flags);
310                 wake_up(&ksm->idle_slots_wait_queue);
311         }
312 }
313
314 /**
315  * blk_ksm_crypto_cfg_supported() - Find out if a crypto configuration is
316  *                                  supported by a ksm.
317  * @ksm: The keyslot manager to check
318  * @cfg: The crypto configuration to check for.
319  *
320  * Checks for crypto_mode/data unit size/dun bytes support.
321  *
322  * Return: Whether or not this ksm supports the specified crypto config.
323  */
324 bool blk_ksm_crypto_cfg_supported(struct blk_keyslot_manager *ksm,
325                                   const struct blk_crypto_config *cfg)
326 {
327         if (!ksm)
328                 return false;
329         if (!(ksm->crypto_modes_supported[cfg->crypto_mode] &
330               cfg->data_unit_size))
331                 return false;
332         if (ksm->max_dun_bytes_supported < cfg->dun_bytes)
333                 return false;
334         return true;
335 }
336
337 /**
338  * blk_ksm_evict_key() - Evict a key from the lower layer device.
339  * @ksm: The keyslot manager to evict from
340  * @key: The key to evict
341  *
342  * Find the keyslot that the specified key was programmed into, and evict that
343  * slot from the lower layer device. The slot must not be in use by any
344  * in-flight IO when this function is called.
345  *
346  * Context: Process context. Takes and releases ksm->lock.
347  * Return: 0 on success or if there's no keyslot with the specified key, -EBUSY
348  *         if the keyslot is still in use, or another -errno value on other
349  *         error.
350  */
351 int blk_ksm_evict_key(struct blk_keyslot_manager *ksm,
352                       const struct blk_crypto_key *key)
353 {
354         struct blk_ksm_keyslot *slot;
355         int err = 0;
356
357         blk_ksm_hw_enter(ksm);
358         slot = blk_ksm_find_keyslot(ksm, key);
359         if (!slot)
360                 goto out_unlock;
361
362         if (WARN_ON_ONCE(atomic_read(&slot->slot_refs) != 0)) {
363                 err = -EBUSY;
364                 goto out_unlock;
365         }
366         err = ksm->ksm_ll_ops.keyslot_evict(ksm, key,
367                                             blk_ksm_get_slot_idx(slot));
368         if (err)
369                 goto out_unlock;
370
371         hlist_del(&slot->hash_node);
372         slot->key = NULL;
373         err = 0;
374 out_unlock:
375         blk_ksm_hw_exit(ksm);
376         return err;
377 }
378
379 /**
380  * blk_ksm_reprogram_all_keys() - Re-program all keyslots.
381  * @ksm: The keyslot manager
382  *
383  * Re-program all keyslots that are supposed to have a key programmed.  This is
384  * intended only for use by drivers for hardware that loses its keys on reset.
385  *
386  * Context: Process context. Takes and releases ksm->lock.
387  */
388 void blk_ksm_reprogram_all_keys(struct blk_keyslot_manager *ksm)
389 {
390         unsigned int slot;
391
392         /* This is for device initialization, so don't resume the device */
393         down_write(&ksm->lock);
394         for (slot = 0; slot < ksm->num_slots; slot++) {
395                 const struct blk_crypto_key *key = ksm->slots[slot].key;
396                 int err;
397
398                 if (!key)
399                         continue;
400
401                 err = ksm->ksm_ll_ops.keyslot_program(ksm, key, slot);
402                 WARN_ON(err);
403         }
404         up_write(&ksm->lock);
405 }
406 EXPORT_SYMBOL_GPL(blk_ksm_reprogram_all_keys);
407
408 void blk_ksm_destroy(struct blk_keyslot_manager *ksm)
409 {
410         if (!ksm)
411                 return;
412         kvfree(ksm->slot_hashtable);
413         kvfree_sensitive(ksm->slots, sizeof(ksm->slots[0]) * ksm->num_slots);
414         memzero_explicit(ksm, sizeof(*ksm));
415 }
416 EXPORT_SYMBOL_GPL(blk_ksm_destroy);
417
418 bool blk_ksm_register(struct blk_keyslot_manager *ksm, struct request_queue *q)
419 {
420         if (blk_integrity_queue_supports_integrity(q)) {
421                 pr_warn("Integrity and hardware inline encryption are not supported together. Disabling hardware inline encryption.\n");
422                 return false;
423         }
424         q->ksm = ksm;
425         return true;
426 }
427 EXPORT_SYMBOL_GPL(blk_ksm_register);
428
429 void blk_ksm_unregister(struct request_queue *q)
430 {
431         q->ksm = NULL;
432 }