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