2 * Copyright (c) 2002-2006 Sam Leffler. All rights reserved.
3 * Copyright (c) 2021 The FreeBSD Foundation
5 * Portions of this software were developed by Ararat River
6 * Consulting, LLC under sponsorship of the FreeBSD Foundation.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
33 * Cryptographic Subsystem.
35 * This code is derived from the Openbsd Cryptographic Framework (OCF)
36 * that has the copyright shown below. Very little of the original
41 * The author of this code is Angelos D. Keromytis (angelos@cis.upenn.edu)
43 * This code was written by Angelos D. Keromytis in Athens, Greece, in
44 * February 2000. Network Security Technologies Inc. (NSTI) kindly
45 * supported the development of this code.
47 * Copyright (c) 2000, 2001 Angelos D. Keromytis
49 * Permission to use, copy, and modify this software with or without fee
50 * is hereby granted, provided that this entire notice is included in
51 * all source code copies of any software which is or includes a copy or
52 * modification of this software.
54 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
55 * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
56 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
57 * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
61 #include "opt_compat.h"
64 #include <sys/param.h>
65 #include <sys/systm.h>
66 #include <sys/counter.h>
67 #include <sys/kernel.h>
68 #include <sys/kthread.h>
69 #include <sys/linker.h>
71 #include <sys/module.h>
72 #include <sys/mutex.h>
73 #include <sys/malloc.h>
76 #include <sys/refcount.h>
79 #include <sys/sysctl.h>
80 #include <sys/taskqueue.h>
85 #include <machine/vmparam.h>
88 #include <crypto/intake.h>
89 #include <opencrypto/cryptodev.h>
90 #include <opencrypto/xform_auth.h>
91 #include <opencrypto/xform_enc.h>
95 #include "cryptodev_if.h"
97 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
98 #include <machine/pcb.h>
101 SDT_PROVIDER_DEFINE(opencrypto);
104 * Crypto drivers register themselves by allocating a slot in the
105 * crypto_drivers table with crypto_get_driverid() and then registering
106 * each asym algorithm they support with crypto_kregister().
108 static struct mtx crypto_drivers_mtx; /* lock on driver table */
109 #define CRYPTO_DRIVER_LOCK() mtx_lock(&crypto_drivers_mtx)
110 #define CRYPTO_DRIVER_UNLOCK() mtx_unlock(&crypto_drivers_mtx)
111 #define CRYPTO_DRIVER_ASSERT() mtx_assert(&crypto_drivers_mtx, MA_OWNED)
114 * Crypto device/driver capabilities structure.
117 * (d) - protected by CRYPTO_DRIVER_LOCK()
118 * (q) - protected by CRYPTO_Q_LOCK()
119 * Not tagged fields are read-only.
124 uint32_t cc_sessions; /* (d) # of sessions */
125 uint32_t cc_koperations; /* (d) # os asym operations */
126 uint8_t cc_kalg[CRK_ALGORITHM_MAX + 1];
128 int cc_flags; /* (d) flags */
129 #define CRYPTOCAP_F_CLEANUP 0x80000000 /* needs resource cleanup */
130 int cc_qblocked; /* (q) symmetric q blocked */
131 int cc_kqblocked; /* (q) asymmetric q blocked */
132 size_t cc_session_size;
133 volatile int cc_refs;
136 static struct cryptocap **crypto_drivers = NULL;
137 static int crypto_drivers_size = 0;
139 struct crypto_session {
140 struct cryptocap *cap;
141 struct crypto_session_params csp;
143 /* Driver softc follows. */
147 * There are two queues for crypto requests; one for symmetric (e.g.
148 * cipher) operations and one for asymmetric (e.g. MOD)operations.
149 * A single mutex is used to lock access to both queues. We could
150 * have one per-queue but having one simplifies handling of block/unblock
153 static int crp_sleep = 0;
154 static TAILQ_HEAD(cryptop_q ,cryptop) crp_q; /* request queues */
155 static TAILQ_HEAD(,cryptkop) crp_kq;
156 static struct mtx crypto_q_mtx;
157 #define CRYPTO_Q_LOCK() mtx_lock(&crypto_q_mtx)
158 #define CRYPTO_Q_UNLOCK() mtx_unlock(&crypto_q_mtx)
160 SYSCTL_NODE(_kern, OID_AUTO, crypto, CTLFLAG_RW, 0,
161 "In-kernel cryptography");
164 * Taskqueue used to dispatch the crypto requests
165 * that have the CRYPTO_F_ASYNC flag
167 static struct taskqueue *crypto_tq;
170 * Crypto seq numbers are operated on with modular arithmetic
172 #define CRYPTO_SEQ_GT(a,b) ((int)((a)-(b)) > 0)
174 struct crypto_ret_worker {
175 struct mtx crypto_ret_mtx;
177 TAILQ_HEAD(,cryptop) crp_ordered_ret_q; /* ordered callback queue for symetric jobs */
178 TAILQ_HEAD(,cryptop) crp_ret_q; /* callback queue for symetric jobs */
179 TAILQ_HEAD(,cryptkop) crp_ret_kq; /* callback queue for asym jobs */
181 uint32_t reorder_ops; /* total ordered sym jobs received */
182 uint32_t reorder_cur_seq; /* current sym job dispatched */
186 static struct crypto_ret_worker *crypto_ret_workers = NULL;
188 #define CRYPTO_RETW(i) (&crypto_ret_workers[i])
189 #define CRYPTO_RETW_ID(w) ((w) - crypto_ret_workers)
190 #define FOREACH_CRYPTO_RETW(w) \
191 for (w = crypto_ret_workers; w < crypto_ret_workers + crypto_workers_num; ++w)
193 #define CRYPTO_RETW_LOCK(w) mtx_lock(&w->crypto_ret_mtx)
194 #define CRYPTO_RETW_UNLOCK(w) mtx_unlock(&w->crypto_ret_mtx)
195 #define CRYPTO_RETW_EMPTY(w) \
196 (TAILQ_EMPTY(&w->crp_ret_q) && TAILQ_EMPTY(&w->crp_ret_kq) && TAILQ_EMPTY(&w->crp_ordered_ret_q))
198 static int crypto_workers_num = 0;
199 SYSCTL_INT(_kern_crypto, OID_AUTO, num_workers, CTLFLAG_RDTUN,
200 &crypto_workers_num, 0,
201 "Number of crypto workers used to dispatch crypto jobs");
202 #ifdef COMPAT_FREEBSD12
203 SYSCTL_INT(_kern, OID_AUTO, crypto_workers_num, CTLFLAG_RDTUN,
204 &crypto_workers_num, 0,
205 "Number of crypto workers used to dispatch crypto jobs");
208 static uma_zone_t cryptop_zone;
210 int crypto_userasymcrypto = 1;
211 SYSCTL_INT(_kern_crypto, OID_AUTO, asym_enable, CTLFLAG_RW,
212 &crypto_userasymcrypto, 0,
213 "Enable user-mode access to asymmetric crypto support");
214 #ifdef COMPAT_FREEBSD12
215 SYSCTL_INT(_kern, OID_AUTO, userasymcrypto, CTLFLAG_RW,
216 &crypto_userasymcrypto, 0,
217 "Enable/disable user-mode access to asymmetric crypto support");
220 int crypto_devallowsoft = 0;
221 SYSCTL_INT(_kern_crypto, OID_AUTO, allow_soft, CTLFLAG_RWTUN,
222 &crypto_devallowsoft, 0,
223 "Enable use of software crypto by /dev/crypto");
224 #ifdef COMPAT_FREEBSD12
225 SYSCTL_INT(_kern, OID_AUTO, cryptodevallowsoft, CTLFLAG_RWTUN,
226 &crypto_devallowsoft, 0,
227 "Enable/disable use of software crypto by /dev/crypto");
230 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
232 static void crypto_dispatch_thread(void *arg);
233 static struct thread *cryptotd;
234 static void crypto_ret_thread(void *arg);
235 static void crypto_destroy(void);
236 static int crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint);
237 static int crypto_kinvoke(struct cryptkop *krp);
238 static void crypto_task_invoke(void *ctx, int pending);
239 static void crypto_batch_enqueue(struct cryptop *crp);
241 static counter_u64_t cryptostats[sizeof(struct cryptostats) / sizeof(uint64_t)];
242 SYSCTL_COUNTER_U64_ARRAY(_kern_crypto, OID_AUTO, stats, CTLFLAG_RW,
243 cryptostats, nitems(cryptostats),
244 "Crypto system statistics");
246 #define CRYPTOSTAT_INC(stat) do { \
248 cryptostats[offsetof(struct cryptostats, stat) / sizeof(uint64_t)],\
253 cryptostats_init(void *arg __unused)
255 COUNTER_ARRAY_ALLOC(cryptostats, nitems(cryptostats), M_WAITOK);
257 SYSINIT(cryptostats_init, SI_SUB_COUNTER, SI_ORDER_ANY, cryptostats_init, NULL);
260 cryptostats_fini(void *arg __unused)
262 COUNTER_ARRAY_FREE(cryptostats, nitems(cryptostats));
264 SYSUNINIT(cryptostats_fini, SI_SUB_COUNTER, SI_ORDER_ANY, cryptostats_fini,
267 /* Try to avoid directly exposing the key buffer as a symbol */
268 static struct keybuf *keybuf;
270 static struct keybuf empty_keybuf = {
274 /* Obtain the key buffer from boot metadata */
280 kmdp = preload_search_by_type("elf kernel");
283 kmdp = preload_search_by_type("elf64 kernel");
285 keybuf = (struct keybuf *)preload_search_info(kmdp,
286 MODINFO_METADATA | MODINFOMD_KEYBUF);
289 keybuf = &empty_keybuf;
292 /* It'd be nice if we could store these in some kind of secure memory... */
300 static struct cryptocap *
301 cap_ref(struct cryptocap *cap)
304 refcount_acquire(&cap->cc_refs);
309 cap_rele(struct cryptocap *cap)
312 if (refcount_release(&cap->cc_refs) == 0)
315 KASSERT(cap->cc_sessions == 0,
316 ("freeing crypto driver with active sessions"));
317 KASSERT(cap->cc_koperations == 0,
318 ("freeing crypto driver with active key operations"));
320 free(cap, M_CRYPTO_DATA);
326 struct crypto_ret_worker *ret_worker;
330 mtx_init(&crypto_drivers_mtx, "crypto driver table", NULL, MTX_DEF);
334 mtx_init(&crypto_q_mtx, "crypto op queues", NULL, MTX_DEF);
336 cryptop_zone = uma_zcreate("cryptop",
337 sizeof(struct cryptop), NULL, NULL, NULL, NULL,
338 UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
340 crypto_drivers_size = CRYPTO_DRIVERS_INITIAL;
341 crypto_drivers = malloc(crypto_drivers_size *
342 sizeof(struct cryptocap), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
344 if (crypto_workers_num < 1 || crypto_workers_num > mp_ncpus)
345 crypto_workers_num = mp_ncpus;
347 crypto_tq = taskqueue_create("crypto", M_WAITOK | M_ZERO,
348 taskqueue_thread_enqueue, &crypto_tq);
350 taskqueue_start_threads(&crypto_tq, crypto_workers_num, PRI_MIN_KERN,
354 error = kproc_kthread_add(crypto_dispatch_thread, NULL, &p, &cryptotd,
355 0, 0, "crypto", "crypto");
357 printf("crypto_init: cannot start crypto thread; error %d",
362 crypto_ret_workers = mallocarray(crypto_workers_num,
363 sizeof(struct crypto_ret_worker), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
365 FOREACH_CRYPTO_RETW(ret_worker) {
366 TAILQ_INIT(&ret_worker->crp_ordered_ret_q);
367 TAILQ_INIT(&ret_worker->crp_ret_q);
368 TAILQ_INIT(&ret_worker->crp_ret_kq);
370 ret_worker->reorder_ops = 0;
371 ret_worker->reorder_cur_seq = 0;
373 mtx_init(&ret_worker->crypto_ret_mtx, "crypto return queues",
376 error = kthread_add(crypto_ret_thread, ret_worker, p,
377 &ret_worker->td, 0, 0, "crypto returns %td",
378 CRYPTO_RETW_ID(ret_worker));
380 printf("crypto_init: cannot start cryptoret thread; error %d",
395 * Signal a crypto thread to terminate. We use the driver
396 * table lock to synchronize the sleep/wakeups so that we
397 * are sure the threads have terminated before we release
398 * the data structures they use. See crypto_finis below
399 * for the other half of this song-and-dance.
402 crypto_terminate(struct thread **tdp, void *q)
406 mtx_assert(&crypto_drivers_mtx, MA_OWNED);
411 mtx_sleep(td, &crypto_drivers_mtx, PWAIT, "crypto_destroy", 0);
416 hmac_init_pad(const struct auth_hash *axf, const char *key, int klen,
417 void *auth_ctx, uint8_t padval)
419 uint8_t hmac_key[HMAC_MAX_BLOCK_LEN];
422 KASSERT(axf->blocksize <= sizeof(hmac_key),
423 ("Invalid HMAC block size %d", axf->blocksize));
426 * If the key is larger than the block size, use the digest of
427 * the key as the key instead.
429 memset(hmac_key, 0, sizeof(hmac_key));
430 if (klen > axf->blocksize) {
432 axf->Update(auth_ctx, key, klen);
433 axf->Final(hmac_key, auth_ctx);
434 klen = axf->hashsize;
436 memcpy(hmac_key, key, klen);
438 for (i = 0; i < axf->blocksize; i++)
439 hmac_key[i] ^= padval;
442 axf->Update(auth_ctx, hmac_key, axf->blocksize);
443 explicit_bzero(hmac_key, sizeof(hmac_key));
447 hmac_init_ipad(const struct auth_hash *axf, const char *key, int klen,
451 hmac_init_pad(axf, key, klen, auth_ctx, HMAC_IPAD_VAL);
455 hmac_init_opad(const struct auth_hash *axf, const char *key, int klen,
459 hmac_init_pad(axf, key, klen, auth_ctx, HMAC_OPAD_VAL);
465 struct crypto_ret_worker *ret_worker;
469 * Terminate any crypto threads.
471 if (crypto_tq != NULL)
472 taskqueue_drain_all(crypto_tq);
473 CRYPTO_DRIVER_LOCK();
474 crypto_terminate(&cryptotd, &crp_q);
475 FOREACH_CRYPTO_RETW(ret_worker)
476 crypto_terminate(&ret_worker->td, &ret_worker->crp_ret_q);
477 CRYPTO_DRIVER_UNLOCK();
479 /* XXX flush queues??? */
482 * Reclaim dynamically allocated resources.
484 for (i = 0; i < crypto_drivers_size; i++) {
485 if (crypto_drivers[i] != NULL)
486 cap_rele(crypto_drivers[i]);
488 free(crypto_drivers, M_CRYPTO_DATA);
490 if (cryptop_zone != NULL)
491 uma_zdestroy(cryptop_zone);
492 mtx_destroy(&crypto_q_mtx);
493 FOREACH_CRYPTO_RETW(ret_worker)
494 mtx_destroy(&ret_worker->crypto_ret_mtx);
495 free(crypto_ret_workers, M_CRYPTO_DATA);
496 if (crypto_tq != NULL)
497 taskqueue_free(crypto_tq);
498 mtx_destroy(&crypto_drivers_mtx);
502 crypto_ses2hid(crypto_session_t crypto_session)
504 return (crypto_session->cap->cc_hid);
508 crypto_ses2caps(crypto_session_t crypto_session)
510 return (crypto_session->cap->cc_flags & 0xff000000);
514 crypto_get_driver_session(crypto_session_t crypto_session)
516 return (crypto_session + 1);
519 const struct crypto_session_params *
520 crypto_get_params(crypto_session_t crypto_session)
522 return (&crypto_session->csp);
526 crypto_auth_hash(const struct crypto_session_params *csp)
529 switch (csp->csp_auth_alg) {
530 case CRYPTO_SHA1_HMAC:
531 return (&auth_hash_hmac_sha1);
532 case CRYPTO_SHA2_224_HMAC:
533 return (&auth_hash_hmac_sha2_224);
534 case CRYPTO_SHA2_256_HMAC:
535 return (&auth_hash_hmac_sha2_256);
536 case CRYPTO_SHA2_384_HMAC:
537 return (&auth_hash_hmac_sha2_384);
538 case CRYPTO_SHA2_512_HMAC:
539 return (&auth_hash_hmac_sha2_512);
540 case CRYPTO_NULL_HMAC:
541 return (&auth_hash_null);
542 case CRYPTO_RIPEMD160_HMAC:
543 return (&auth_hash_hmac_ripemd_160);
545 return (&auth_hash_sha1);
546 case CRYPTO_SHA2_224:
547 return (&auth_hash_sha2_224);
548 case CRYPTO_SHA2_256:
549 return (&auth_hash_sha2_256);
550 case CRYPTO_SHA2_384:
551 return (&auth_hash_sha2_384);
552 case CRYPTO_SHA2_512:
553 return (&auth_hash_sha2_512);
554 case CRYPTO_AES_NIST_GMAC:
555 switch (csp->csp_auth_klen) {
557 return (&auth_hash_nist_gmac_aes_128);
559 return (&auth_hash_nist_gmac_aes_192);
561 return (&auth_hash_nist_gmac_aes_256);
566 return (&auth_hash_blake2b);
568 return (&auth_hash_blake2s);
569 case CRYPTO_POLY1305:
570 return (&auth_hash_poly1305);
571 case CRYPTO_AES_CCM_CBC_MAC:
572 switch (csp->csp_auth_klen) {
574 return (&auth_hash_ccm_cbc_mac_128);
576 return (&auth_hash_ccm_cbc_mac_192);
578 return (&auth_hash_ccm_cbc_mac_256);
588 crypto_cipher(const struct crypto_session_params *csp)
591 switch (csp->csp_cipher_alg) {
592 case CRYPTO_RIJNDAEL128_CBC:
593 return (&enc_xform_rijndael128);
595 return (&enc_xform_aes_xts);
597 return (&enc_xform_aes_icm);
598 case CRYPTO_AES_NIST_GCM_16:
599 return (&enc_xform_aes_nist_gcm);
600 case CRYPTO_CAMELLIA_CBC:
601 return (&enc_xform_camellia);
602 case CRYPTO_NULL_CBC:
603 return (&enc_xform_null);
604 case CRYPTO_CHACHA20:
605 return (&enc_xform_chacha20);
606 case CRYPTO_AES_CCM_16:
607 return (&enc_xform_ccm);
608 case CRYPTO_CHACHA20_POLY1305:
609 return (&enc_xform_chacha20_poly1305);
615 static struct cryptocap *
616 crypto_checkdriver(uint32_t hid)
619 return (hid >= crypto_drivers_size ? NULL : crypto_drivers[hid]);
623 * Select a driver for a new session that supports the specified
624 * algorithms and, optionally, is constrained according to the flags.
626 static struct cryptocap *
627 crypto_select_driver(const struct crypto_session_params *csp, int flags)
629 struct cryptocap *cap, *best;
630 int best_match, error, hid;
632 CRYPTO_DRIVER_ASSERT();
635 for (hid = 0; hid < crypto_drivers_size; hid++) {
637 * If there is no driver for this slot, or the driver
638 * is not appropriate (hardware or software based on
641 cap = crypto_drivers[hid];
643 (cap->cc_flags & flags) == 0)
646 error = CRYPTODEV_PROBESESSION(cap->cc_dev, csp);
651 * Use the driver with the highest probe value.
652 * Hardware drivers use a higher probe value than
653 * software. In case of a tie, prefer the driver with
654 * the fewest active sessions.
656 if (best == NULL || error > best_match ||
657 (error == best_match &&
658 cap->cc_sessions < best->cc_sessions)) {
666 static enum alg_type {
674 [CRYPTO_SHA1_HMAC] = ALG_KEYED_DIGEST,
675 [CRYPTO_RIPEMD160_HMAC] = ALG_KEYED_DIGEST,
676 [CRYPTO_AES_CBC] = ALG_CIPHER,
677 [CRYPTO_SHA1] = ALG_DIGEST,
678 [CRYPTO_NULL_HMAC] = ALG_DIGEST,
679 [CRYPTO_NULL_CBC] = ALG_CIPHER,
680 [CRYPTO_DEFLATE_COMP] = ALG_COMPRESSION,
681 [CRYPTO_SHA2_256_HMAC] = ALG_KEYED_DIGEST,
682 [CRYPTO_SHA2_384_HMAC] = ALG_KEYED_DIGEST,
683 [CRYPTO_SHA2_512_HMAC] = ALG_KEYED_DIGEST,
684 [CRYPTO_CAMELLIA_CBC] = ALG_CIPHER,
685 [CRYPTO_AES_XTS] = ALG_CIPHER,
686 [CRYPTO_AES_ICM] = ALG_CIPHER,
687 [CRYPTO_AES_NIST_GMAC] = ALG_KEYED_DIGEST,
688 [CRYPTO_AES_NIST_GCM_16] = ALG_AEAD,
689 [CRYPTO_BLAKE2B] = ALG_KEYED_DIGEST,
690 [CRYPTO_BLAKE2S] = ALG_KEYED_DIGEST,
691 [CRYPTO_CHACHA20] = ALG_CIPHER,
692 [CRYPTO_SHA2_224_HMAC] = ALG_KEYED_DIGEST,
693 [CRYPTO_RIPEMD160] = ALG_DIGEST,
694 [CRYPTO_SHA2_224] = ALG_DIGEST,
695 [CRYPTO_SHA2_256] = ALG_DIGEST,
696 [CRYPTO_SHA2_384] = ALG_DIGEST,
697 [CRYPTO_SHA2_512] = ALG_DIGEST,
698 [CRYPTO_POLY1305] = ALG_KEYED_DIGEST,
699 [CRYPTO_AES_CCM_CBC_MAC] = ALG_KEYED_DIGEST,
700 [CRYPTO_AES_CCM_16] = ALG_AEAD,
701 [CRYPTO_CHACHA20_POLY1305] = ALG_AEAD,
708 if (alg < nitems(alg_types))
709 return (alg_types[alg]);
714 alg_is_compression(int alg)
717 return (alg_type(alg) == ALG_COMPRESSION);
721 alg_is_cipher(int alg)
724 return (alg_type(alg) == ALG_CIPHER);
728 alg_is_digest(int alg)
731 return (alg_type(alg) == ALG_DIGEST ||
732 alg_type(alg) == ALG_KEYED_DIGEST);
736 alg_is_keyed_digest(int alg)
739 return (alg_type(alg) == ALG_KEYED_DIGEST);
746 return (alg_type(alg) == ALG_AEAD);
750 ccm_tag_length_valid(int len)
767 #define SUPPORTED_SES (CSP_F_SEPARATE_OUTPUT | CSP_F_SEPARATE_AAD | CSP_F_ESN)
769 /* Various sanity checks on crypto session parameters. */
771 check_csp(const struct crypto_session_params *csp)
773 struct auth_hash *axf;
775 /* Mode-independent checks. */
776 if ((csp->csp_flags & ~(SUPPORTED_SES)) != 0)
778 if (csp->csp_ivlen < 0 || csp->csp_cipher_klen < 0 ||
779 csp->csp_auth_klen < 0 || csp->csp_auth_mlen < 0)
781 if (csp->csp_auth_key != NULL && csp->csp_auth_klen == 0)
783 if (csp->csp_cipher_key != NULL && csp->csp_cipher_klen == 0)
786 switch (csp->csp_mode) {
787 case CSP_MODE_COMPRESS:
788 if (!alg_is_compression(csp->csp_cipher_alg))
790 if (csp->csp_flags & CSP_F_SEPARATE_OUTPUT)
792 if (csp->csp_flags & CSP_F_SEPARATE_AAD)
794 if (csp->csp_cipher_klen != 0 || csp->csp_ivlen != 0 ||
795 csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0 ||
796 csp->csp_auth_mlen != 0)
799 case CSP_MODE_CIPHER:
800 if (!alg_is_cipher(csp->csp_cipher_alg))
802 if (csp->csp_flags & CSP_F_SEPARATE_AAD)
804 if (csp->csp_cipher_alg != CRYPTO_NULL_CBC) {
805 if (csp->csp_cipher_klen == 0)
807 if (csp->csp_ivlen == 0)
810 if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
812 if (csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0 ||
813 csp->csp_auth_mlen != 0)
816 case CSP_MODE_DIGEST:
817 if (csp->csp_cipher_alg != 0 || csp->csp_cipher_klen != 0)
820 if (csp->csp_flags & CSP_F_SEPARATE_AAD)
823 /* IV is optional for digests (e.g. GMAC). */
824 switch (csp->csp_auth_alg) {
825 case CRYPTO_AES_CCM_CBC_MAC:
826 if (csp->csp_ivlen < 7 || csp->csp_ivlen > 13)
829 case CRYPTO_AES_NIST_GMAC:
830 if (csp->csp_ivlen != AES_GCM_IV_LEN)
834 if (csp->csp_ivlen != 0)
839 if (!alg_is_digest(csp->csp_auth_alg))
842 /* Key is optional for BLAKE2 digests. */
843 if (csp->csp_auth_alg == CRYPTO_BLAKE2B ||
844 csp->csp_auth_alg == CRYPTO_BLAKE2S)
846 else if (alg_is_keyed_digest(csp->csp_auth_alg)) {
847 if (csp->csp_auth_klen == 0)
850 if (csp->csp_auth_klen != 0)
853 if (csp->csp_auth_mlen != 0) {
854 axf = crypto_auth_hash(csp);
855 if (axf == NULL || csp->csp_auth_mlen > axf->hashsize)
858 if (csp->csp_auth_alg == CRYPTO_AES_CCM_CBC_MAC &&
859 !ccm_tag_length_valid(csp->csp_auth_mlen))
864 if (!alg_is_aead(csp->csp_cipher_alg))
866 if (csp->csp_cipher_klen == 0)
868 if (csp->csp_ivlen == 0 ||
869 csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
871 if (csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0)
874 switch (csp->csp_cipher_alg) {
875 case CRYPTO_AES_CCM_16:
876 if (csp->csp_auth_mlen != 0 &&
877 !ccm_tag_length_valid(csp->csp_auth_mlen))
880 if (csp->csp_ivlen < 7 || csp->csp_ivlen > 13)
883 case CRYPTO_AES_NIST_GCM_16:
884 if (csp->csp_auth_mlen > AES_GMAC_HASH_LEN)
887 if (csp->csp_ivlen != AES_GCM_IV_LEN)
890 case CRYPTO_CHACHA20_POLY1305:
891 if (csp->csp_ivlen != 8 && csp->csp_ivlen != 12)
893 if (csp->csp_auth_mlen > POLY1305_HASH_LEN)
899 if (!alg_is_cipher(csp->csp_cipher_alg))
901 if (csp->csp_cipher_alg != CRYPTO_NULL_CBC) {
902 if (csp->csp_cipher_klen == 0)
904 if (csp->csp_ivlen == 0)
907 if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
909 if (!alg_is_digest(csp->csp_auth_alg))
912 /* Key is optional for BLAKE2 digests. */
913 if (csp->csp_auth_alg == CRYPTO_BLAKE2B ||
914 csp->csp_auth_alg == CRYPTO_BLAKE2S)
916 else if (alg_is_keyed_digest(csp->csp_auth_alg)) {
917 if (csp->csp_auth_klen == 0)
920 if (csp->csp_auth_klen != 0)
923 if (csp->csp_auth_mlen != 0) {
924 axf = crypto_auth_hash(csp);
925 if (axf == NULL || csp->csp_auth_mlen > axf->hashsize)
937 * Delete a session after it has been detached from its driver.
940 crypto_deletesession(crypto_session_t cses)
942 struct cryptocap *cap;
946 zfree(cses, M_CRYPTO_DATA);
948 CRYPTO_DRIVER_LOCK();
950 if (cap->cc_sessions == 0 && cap->cc_flags & CRYPTOCAP_F_CLEANUP)
952 CRYPTO_DRIVER_UNLOCK();
957 * Create a new session. The crid argument specifies a crypto
958 * driver to use or constraints on a driver to select (hardware
959 * only, software only, either). Whatever driver is selected
960 * must be capable of the requested crypto algorithms.
963 crypto_newsession(crypto_session_t *cses,
964 const struct crypto_session_params *csp, int crid)
966 static uint64_t sessid = 0;
967 crypto_session_t res;
968 struct cryptocap *cap;
976 CRYPTO_DRIVER_LOCK();
977 if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
979 * Use specified driver; verify it is capable.
981 cap = crypto_checkdriver(crid);
982 if (cap != NULL && CRYPTODEV_PROBESESSION(cap->cc_dev, csp) > 0)
986 * No requested driver; select based on crid flags.
988 cap = crypto_select_driver(csp, crid);
991 CRYPTO_DRIVER_UNLOCK();
992 CRYPTDEB("no driver");
997 CRYPTO_DRIVER_UNLOCK();
999 /* Allocate a single block for the generic session and driver softc. */
1000 res = malloc(sizeof(*res) + cap->cc_session_size, M_CRYPTO_DATA,
1004 res->id = atomic_fetchadd_64(&sessid, 1);
1006 /* Call the driver initialization routine. */
1007 err = CRYPTODEV_NEWSESSION(cap->cc_dev, res, csp);
1009 CRYPTDEB("dev newsession failed: %d", err);
1010 crypto_deletesession(res);
1019 * Delete an existing session (or a reserved session on an unregistered
1023 crypto_freesession(crypto_session_t cses)
1025 struct cryptocap *cap;
1032 /* Call the driver cleanup routine, if available. */
1033 CRYPTODEV_FREESESSION(cap->cc_dev, cses);
1035 crypto_deletesession(cses);
1039 * Return a new driver id. Registers a driver with the system so that
1040 * it can be probed by subsequent sessions.
1043 crypto_get_driverid(device_t dev, size_t sessionsize, int flags)
1045 struct cryptocap *cap, **newdrv;
1048 if ((flags & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
1050 "no flags specified when registering driver\n");
1054 cap = malloc(sizeof(*cap), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
1056 cap->cc_session_size = sessionsize;
1057 cap->cc_flags = flags;
1058 refcount_init(&cap->cc_refs, 1);
1060 CRYPTO_DRIVER_LOCK();
1062 for (i = 0; i < crypto_drivers_size; i++) {
1063 if (crypto_drivers[i] == NULL)
1067 if (i < crypto_drivers_size)
1070 /* Out of entries, allocate some more. */
1072 if (2 * crypto_drivers_size <= crypto_drivers_size) {
1073 CRYPTO_DRIVER_UNLOCK();
1074 printf("crypto: driver count wraparound!\n");
1078 CRYPTO_DRIVER_UNLOCK();
1080 newdrv = malloc(2 * crypto_drivers_size *
1081 sizeof(*crypto_drivers), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
1083 CRYPTO_DRIVER_LOCK();
1084 memcpy(newdrv, crypto_drivers,
1085 crypto_drivers_size * sizeof(*crypto_drivers));
1087 crypto_drivers_size *= 2;
1089 free(crypto_drivers, M_CRYPTO_DATA);
1090 crypto_drivers = newdrv;
1094 crypto_drivers[i] = cap;
1095 CRYPTO_DRIVER_UNLOCK();
1098 printf("crypto: assign %s driver id %u, flags 0x%x\n",
1099 device_get_nameunit(dev), i, flags);
1105 * Lookup a driver by name. We match against the full device
1106 * name and unit, and against just the name. The latter gives
1107 * us a simple widlcarding by device name. On success return the
1108 * driver/hardware identifier; otherwise return -1.
1111 crypto_find_driver(const char *match)
1113 struct cryptocap *cap;
1114 int i, len = strlen(match);
1116 CRYPTO_DRIVER_LOCK();
1117 for (i = 0; i < crypto_drivers_size; i++) {
1118 if (crypto_drivers[i] == NULL)
1120 cap = crypto_drivers[i];
1121 if (strncmp(match, device_get_nameunit(cap->cc_dev), len) == 0 ||
1122 strncmp(match, device_get_name(cap->cc_dev), len) == 0) {
1123 CRYPTO_DRIVER_UNLOCK();
1127 CRYPTO_DRIVER_UNLOCK();
1132 * Return the device_t for the specified driver or NULL
1133 * if the driver identifier is invalid.
1136 crypto_find_device_byhid(int hid)
1138 struct cryptocap *cap;
1142 CRYPTO_DRIVER_LOCK();
1143 cap = crypto_checkdriver(hid);
1146 CRYPTO_DRIVER_UNLOCK();
1151 * Return the device/driver capabilities.
1154 crypto_getcaps(int hid)
1156 struct cryptocap *cap;
1160 CRYPTO_DRIVER_LOCK();
1161 cap = crypto_checkdriver(hid);
1163 flags = cap->cc_flags;
1164 CRYPTO_DRIVER_UNLOCK();
1169 * Register support for a key-related algorithm. This routine
1170 * is called once for each algorithm supported a driver.
1173 crypto_kregister(uint32_t driverid, int kalg, uint32_t flags)
1175 struct cryptocap *cap;
1178 CRYPTO_DRIVER_LOCK();
1180 cap = crypto_checkdriver(driverid);
1182 (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
1184 * XXX Do some performance testing to determine placing.
1185 * XXX We probably need an auxiliary data structure that
1186 * XXX describes relative performances.
1189 cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
1191 printf("crypto: %s registers key alg %u flags %u\n"
1192 , device_get_nameunit(cap->cc_dev)
1196 gone_in_dev(cap->cc_dev, 14, "asymmetric crypto");
1201 CRYPTO_DRIVER_UNLOCK();
1206 * Unregister all algorithms associated with a crypto driver.
1207 * If there are pending sessions using it, leave enough information
1208 * around so that subsequent calls using those sessions will
1209 * correctly detect the driver has been unregistered and reroute
1213 crypto_unregister_all(uint32_t driverid)
1215 struct cryptocap *cap;
1217 CRYPTO_DRIVER_LOCK();
1218 cap = crypto_checkdriver(driverid);
1220 CRYPTO_DRIVER_UNLOCK();
1224 cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
1225 crypto_drivers[driverid] = NULL;
1228 * XXX: This doesn't do anything to kick sessions that
1229 * have no pending operations.
1231 while (cap->cc_sessions != 0 || cap->cc_koperations != 0)
1232 mtx_sleep(cap, &crypto_drivers_mtx, 0, "cryunreg", 0);
1233 CRYPTO_DRIVER_UNLOCK();
1240 * Clear blockage on a driver. The what parameter indicates whether
1241 * the driver is now ready for cryptop's and/or cryptokop's.
1244 crypto_unblock(uint32_t driverid, int what)
1246 struct cryptocap *cap;
1250 cap = crypto_checkdriver(driverid);
1252 if (what & CRYPTO_SYMQ)
1253 cap->cc_qblocked = 0;
1254 if (what & CRYPTO_ASYMQ)
1255 cap->cc_kqblocked = 0;
1267 crypto_buffer_len(struct crypto_buffer *cb)
1269 switch (cb->cb_type) {
1270 case CRYPTO_BUF_CONTIG:
1271 return (cb->cb_buf_len);
1272 case CRYPTO_BUF_MBUF:
1273 if (cb->cb_mbuf->m_flags & M_PKTHDR)
1274 return (cb->cb_mbuf->m_pkthdr.len);
1275 return (m_length(cb->cb_mbuf, NULL));
1276 case CRYPTO_BUF_SINGLE_MBUF:
1277 return (cb->cb_mbuf->m_len);
1278 case CRYPTO_BUF_VMPAGE:
1279 return (cb->cb_vm_page_len);
1280 case CRYPTO_BUF_UIO:
1281 return (cb->cb_uio->uio_resid);
1288 /* Various sanity checks on crypto requests. */
1290 cb_sanity(struct crypto_buffer *cb, const char *name)
1292 KASSERT(cb->cb_type > CRYPTO_BUF_NONE && cb->cb_type <= CRYPTO_BUF_LAST,
1293 ("incoming crp with invalid %s buffer type", name));
1294 switch (cb->cb_type) {
1295 case CRYPTO_BUF_CONTIG:
1296 KASSERT(cb->cb_buf_len >= 0,
1297 ("incoming crp with -ve %s buffer length", name));
1299 case CRYPTO_BUF_VMPAGE:
1300 KASSERT(CRYPTO_HAS_VMPAGE,
1301 ("incoming crp uses dmap on supported arch"));
1302 KASSERT(cb->cb_vm_page_len >= 0,
1303 ("incoming crp with -ve %s buffer length", name));
1304 KASSERT(cb->cb_vm_page_offset >= 0,
1305 ("incoming crp with -ve %s buffer offset", name));
1306 KASSERT(cb->cb_vm_page_offset < PAGE_SIZE,
1307 ("incoming crp with %s buffer offset greater than page size"
1316 crp_sanity(struct cryptop *crp)
1318 struct crypto_session_params *csp;
1319 struct crypto_buffer *out;
1320 size_t ilen, len, olen;
1322 KASSERT(crp->crp_session != NULL, ("incoming crp without a session"));
1323 KASSERT(crp->crp_obuf.cb_type >= CRYPTO_BUF_NONE &&
1324 crp->crp_obuf.cb_type <= CRYPTO_BUF_LAST,
1325 ("incoming crp with invalid output buffer type"));
1326 KASSERT(crp->crp_etype == 0, ("incoming crp with error"));
1327 KASSERT(!(crp->crp_flags & CRYPTO_F_DONE),
1328 ("incoming crp already done"));
1330 csp = &crp->crp_session->csp;
1331 cb_sanity(&crp->crp_buf, "input");
1332 ilen = crypto_buffer_len(&crp->crp_buf);
1335 if (csp->csp_flags & CSP_F_SEPARATE_OUTPUT) {
1336 if (crp->crp_obuf.cb_type != CRYPTO_BUF_NONE) {
1337 cb_sanity(&crp->crp_obuf, "output");
1338 out = &crp->crp_obuf;
1339 olen = crypto_buffer_len(out);
1342 KASSERT(crp->crp_obuf.cb_type == CRYPTO_BUF_NONE,
1343 ("incoming crp with separate output buffer "
1344 "but no session support"));
1346 switch (csp->csp_mode) {
1347 case CSP_MODE_COMPRESS:
1348 KASSERT(crp->crp_op == CRYPTO_OP_COMPRESS ||
1349 crp->crp_op == CRYPTO_OP_DECOMPRESS,
1350 ("invalid compression op %x", crp->crp_op));
1352 case CSP_MODE_CIPHER:
1353 KASSERT(crp->crp_op == CRYPTO_OP_ENCRYPT ||
1354 crp->crp_op == CRYPTO_OP_DECRYPT,
1355 ("invalid cipher op %x", crp->crp_op));
1357 case CSP_MODE_DIGEST:
1358 KASSERT(crp->crp_op == CRYPTO_OP_COMPUTE_DIGEST ||
1359 crp->crp_op == CRYPTO_OP_VERIFY_DIGEST,
1360 ("invalid digest op %x", crp->crp_op));
1363 KASSERT(crp->crp_op ==
1364 (CRYPTO_OP_ENCRYPT | CRYPTO_OP_COMPUTE_DIGEST) ||
1366 (CRYPTO_OP_DECRYPT | CRYPTO_OP_VERIFY_DIGEST),
1367 ("invalid AEAD op %x", crp->crp_op));
1368 KASSERT(crp->crp_flags & CRYPTO_F_IV_SEPARATE,
1369 ("AEAD without a separate IV"));
1372 KASSERT(crp->crp_op ==
1373 (CRYPTO_OP_ENCRYPT | CRYPTO_OP_COMPUTE_DIGEST) ||
1375 (CRYPTO_OP_DECRYPT | CRYPTO_OP_VERIFY_DIGEST),
1376 ("invalid ETA op %x", crp->crp_op));
1379 if (csp->csp_mode == CSP_MODE_AEAD || csp->csp_mode == CSP_MODE_ETA) {
1380 if (crp->crp_aad == NULL) {
1381 KASSERT(crp->crp_aad_start == 0 ||
1382 crp->crp_aad_start < ilen,
1383 ("invalid AAD start"));
1384 KASSERT(crp->crp_aad_length != 0 ||
1385 crp->crp_aad_start == 0,
1386 ("AAD with zero length and non-zero start"));
1387 KASSERT(crp->crp_aad_length == 0 ||
1388 crp->crp_aad_start + crp->crp_aad_length <= ilen,
1389 ("AAD outside input length"));
1391 KASSERT(csp->csp_flags & CSP_F_SEPARATE_AAD,
1392 ("session doesn't support separate AAD buffer"));
1393 KASSERT(crp->crp_aad_start == 0,
1394 ("separate AAD buffer with non-zero AAD start"));
1395 KASSERT(crp->crp_aad_length != 0,
1396 ("separate AAD buffer with zero length"));
1399 KASSERT(crp->crp_aad == NULL && crp->crp_aad_start == 0 &&
1400 crp->crp_aad_length == 0,
1401 ("AAD region in request not supporting AAD"));
1403 if (csp->csp_ivlen == 0) {
1404 KASSERT((crp->crp_flags & CRYPTO_F_IV_SEPARATE) == 0,
1405 ("IV_SEPARATE set when IV isn't used"));
1406 KASSERT(crp->crp_iv_start == 0,
1407 ("crp_iv_start set when IV isn't used"));
1408 } else if (crp->crp_flags & CRYPTO_F_IV_SEPARATE) {
1409 KASSERT(crp->crp_iv_start == 0,
1410 ("IV_SEPARATE used with non-zero IV start"));
1412 KASSERT(crp->crp_iv_start < ilen,
1413 ("invalid IV start"));
1414 KASSERT(crp->crp_iv_start + csp->csp_ivlen <= ilen,
1415 ("IV outside buffer length"));
1417 /* XXX: payload_start of 0 should always be < ilen? */
1418 KASSERT(crp->crp_payload_start == 0 ||
1419 crp->crp_payload_start < ilen,
1420 ("invalid payload start"));
1421 KASSERT(crp->crp_payload_start + crp->crp_payload_length <=
1422 ilen, ("payload outside input buffer"));
1424 KASSERT(crp->crp_payload_output_start == 0,
1425 ("payload output start non-zero without output buffer"));
1427 KASSERT(crp->crp_payload_output_start == 0 ||
1428 crp->crp_payload_output_start < olen,
1429 ("invalid payload output start"));
1430 KASSERT(crp->crp_payload_output_start +
1431 crp->crp_payload_length <= olen,
1432 ("payload outside output buffer"));
1434 if (csp->csp_mode == CSP_MODE_DIGEST ||
1435 csp->csp_mode == CSP_MODE_AEAD || csp->csp_mode == CSP_MODE_ETA) {
1436 if (crp->crp_op & CRYPTO_OP_VERIFY_DIGEST)
1440 KASSERT(crp->crp_digest_start == 0 ||
1441 crp->crp_digest_start < len,
1442 ("invalid digest start"));
1443 /* XXX: For the mlen == 0 case this check isn't perfect. */
1444 KASSERT(crp->crp_digest_start + csp->csp_auth_mlen <= len,
1445 ("digest outside buffer"));
1447 KASSERT(crp->crp_digest_start == 0,
1448 ("non-zero digest start for request without a digest"));
1450 if (csp->csp_cipher_klen != 0)
1451 KASSERT(csp->csp_cipher_key != NULL ||
1452 crp->crp_cipher_key != NULL,
1453 ("cipher request without a key"));
1454 if (csp->csp_auth_klen != 0)
1455 KASSERT(csp->csp_auth_key != NULL || crp->crp_auth_key != NULL,
1456 ("auth request without a key"));
1457 KASSERT(crp->crp_callback != NULL, ("incoming crp without callback"));
1462 * Add a crypto request to a queue, to be processed by the kernel thread.
1465 crypto_dispatch(struct cryptop *crp)
1467 struct cryptocap *cap;
1474 CRYPTOSTAT_INC(cs_ops);
1476 crp->crp_retw_id = crp->crp_session->id % crypto_workers_num;
1478 if (CRYPTOP_ASYNC(crp)) {
1479 if (crp->crp_flags & CRYPTO_F_ASYNC_KEEPORDER) {
1480 struct crypto_ret_worker *ret_worker;
1482 ret_worker = CRYPTO_RETW(crp->crp_retw_id);
1484 CRYPTO_RETW_LOCK(ret_worker);
1485 crp->crp_seq = ret_worker->reorder_ops++;
1486 CRYPTO_RETW_UNLOCK(ret_worker);
1489 TASK_INIT(&crp->crp_task, 0, crypto_task_invoke, crp);
1490 taskqueue_enqueue(crypto_tq, &crp->crp_task);
1494 if ((crp->crp_flags & CRYPTO_F_BATCH) == 0) {
1496 * Caller marked the request to be processed
1497 * immediately; dispatch it directly to the
1498 * driver unless the driver is currently blocked.
1500 cap = crp->crp_session->cap;
1501 if (!cap->cc_qblocked) {
1502 result = crypto_invoke(cap, crp, 0);
1503 if (result != ERESTART)
1506 * The driver ran out of resources, put the request on
1511 crypto_batch_enqueue(crp);
1516 crypto_batch_enqueue(struct cryptop *crp)
1520 TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
1527 * Add an asymetric crypto request to a queue,
1528 * to be processed by the kernel thread.
1531 crypto_kdispatch(struct cryptkop *krp)
1535 CRYPTOSTAT_INC(cs_kops);
1537 krp->krp_cap = NULL;
1538 error = crypto_kinvoke(krp);
1539 if (error == ERESTART) {
1541 TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
1551 * Verify a driver is suitable for the specified operation.
1554 kdriver_suitable(const struct cryptocap *cap, const struct cryptkop *krp)
1556 return (cap->cc_kalg[krp->krp_op] & CRYPTO_ALG_FLAG_SUPPORTED) != 0;
1560 * Select a driver for an asym operation. The driver must
1561 * support the necessary algorithm. The caller can constrain
1562 * which device is selected with the flags parameter. The
1563 * algorithm we use here is pretty stupid; just use the first
1564 * driver that supports the algorithms we need. If there are
1565 * multiple suitable drivers we choose the driver with the
1566 * fewest active operations. We prefer hardware-backed
1567 * drivers to software ones when either may be used.
1569 static struct cryptocap *
1570 crypto_select_kdriver(const struct cryptkop *krp, int flags)
1572 struct cryptocap *cap, *best;
1575 CRYPTO_DRIVER_ASSERT();
1578 * Look first for hardware crypto devices if permitted.
1580 if (flags & CRYPTOCAP_F_HARDWARE)
1581 match = CRYPTOCAP_F_HARDWARE;
1583 match = CRYPTOCAP_F_SOFTWARE;
1586 for (hid = 0; hid < crypto_drivers_size; hid++) {
1588 * If there is no driver for this slot, or the driver
1589 * is not appropriate (hardware or software based on
1590 * match), then skip.
1592 cap = crypto_drivers[hid];
1594 (cap->cc_flags & match) == 0)
1597 /* verify all the algorithms are supported. */
1598 if (kdriver_suitable(cap, krp)) {
1600 cap->cc_koperations < best->cc_koperations)
1606 if (match == CRYPTOCAP_F_HARDWARE && (flags & CRYPTOCAP_F_SOFTWARE)) {
1607 /* sort of an Algol 68-style for loop */
1608 match = CRYPTOCAP_F_SOFTWARE;
1615 * Choose a driver for an asymmetric crypto request.
1617 static struct cryptocap *
1618 crypto_lookup_kdriver(struct cryptkop *krp)
1620 struct cryptocap *cap;
1623 /* If this request is requeued, it might already have a driver. */
1628 /* Use krp_crid to choose a driver. */
1629 crid = krp->krp_crid;
1630 if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
1631 cap = crypto_checkdriver(crid);
1634 * Driver present, it must support the
1635 * necessary algorithm and, if s/w drivers are
1636 * excluded, it must be registered as
1639 if (!kdriver_suitable(cap, krp) ||
1640 (!crypto_devallowsoft &&
1641 (cap->cc_flags & CRYPTOCAP_F_HARDWARE) == 0))
1646 * No requested driver; select based on crid flags.
1648 if (!crypto_devallowsoft) /* NB: disallow s/w drivers */
1649 crid &= ~CRYPTOCAP_F_SOFTWARE;
1650 cap = crypto_select_kdriver(krp, crid);
1654 krp->krp_cap = cap_ref(cap);
1655 krp->krp_hid = cap->cc_hid;
1661 * Dispatch an asymmetric crypto request.
1664 crypto_kinvoke(struct cryptkop *krp)
1666 struct cryptocap *cap = NULL;
1669 KASSERT(krp != NULL, ("%s: krp == NULL", __func__));
1670 KASSERT(krp->krp_callback != NULL,
1671 ("%s: krp->crp_callback == NULL", __func__));
1673 CRYPTO_DRIVER_LOCK();
1674 cap = crypto_lookup_kdriver(krp);
1676 CRYPTO_DRIVER_UNLOCK();
1677 krp->krp_status = ENODEV;
1683 * If the device is blocked, return ERESTART to requeue it.
1685 if (cap->cc_kqblocked) {
1687 * XXX: Previously this set krp_status to ERESTART and
1688 * invoked crypto_kdone but the caller would still
1691 CRYPTO_DRIVER_UNLOCK();
1695 cap->cc_koperations++;
1696 CRYPTO_DRIVER_UNLOCK();
1697 error = CRYPTODEV_KPROCESS(cap->cc_dev, krp, 0);
1698 if (error == ERESTART) {
1699 CRYPTO_DRIVER_LOCK();
1700 cap->cc_koperations--;
1701 CRYPTO_DRIVER_UNLOCK();
1705 KASSERT(error == 0, ("error %d returned from crypto_kprocess", error));
1710 crypto_task_invoke(void *ctx, int pending)
1712 struct cryptocap *cap;
1713 struct cryptop *crp;
1716 crp = (struct cryptop *)ctx;
1717 cap = crp->crp_session->cap;
1718 result = crypto_invoke(cap, crp, 0);
1719 if (result == ERESTART)
1720 crypto_batch_enqueue(crp);
1724 * Dispatch a crypto request to the appropriate crypto devices.
1727 crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint)
1730 KASSERT(crp != NULL, ("%s: crp == NULL", __func__));
1731 KASSERT(crp->crp_callback != NULL,
1732 ("%s: crp->crp_callback == NULL", __func__));
1733 KASSERT(crp->crp_session != NULL,
1734 ("%s: crp->crp_session == NULL", __func__));
1736 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1737 struct crypto_session_params csp;
1738 crypto_session_t nses;
1741 * Driver has unregistered; migrate the session and return
1742 * an error to the caller so they'll resubmit the op.
1744 * XXX: What if there are more already queued requests for this
1747 * XXX: Real solution is to make sessions refcounted
1748 * and force callers to hold a reference when
1749 * assigning to crp_session. Could maybe change
1750 * crypto_getreq to accept a session pointer to make
1751 * that work. Alternatively, we could abandon the
1752 * notion of rewriting crp_session in requests forcing
1753 * the caller to deal with allocating a new session.
1754 * Perhaps provide a method to allow a crp's session to
1755 * be swapped that callers could use.
1757 csp = crp->crp_session->csp;
1758 crypto_freesession(crp->crp_session);
1761 * XXX: Key pointers may no longer be valid. If we
1762 * really want to support this we need to define the
1763 * KPI such that 'csp' is required to be valid for the
1764 * duration of a session by the caller perhaps.
1766 * XXX: If the keys have been changed this will reuse
1767 * the old keys. This probably suggests making
1768 * rekeying more explicit and updating the key
1769 * pointers in 'csp' when the keys change.
1771 if (crypto_newsession(&nses, &csp,
1772 CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE) == 0)
1773 crp->crp_session = nses;
1775 crp->crp_etype = EAGAIN;
1780 * Invoke the driver to process the request.
1782 return CRYPTODEV_PROCESS(cap->cc_dev, crp, hint);
1787 crypto_destroyreq(struct cryptop *crp)
1791 struct cryptop *crp2;
1792 struct crypto_ret_worker *ret_worker;
1795 TAILQ_FOREACH(crp2, &crp_q, crp_next) {
1796 KASSERT(crp2 != crp,
1797 ("Freeing cryptop from the crypto queue (%p).",
1802 FOREACH_CRYPTO_RETW(ret_worker) {
1803 CRYPTO_RETW_LOCK(ret_worker);
1804 TAILQ_FOREACH(crp2, &ret_worker->crp_ret_q, crp_next) {
1805 KASSERT(crp2 != crp,
1806 ("Freeing cryptop from the return queue (%p).",
1809 CRYPTO_RETW_UNLOCK(ret_worker);
1816 crypto_freereq(struct cryptop *crp)
1821 crypto_destroyreq(crp);
1822 uma_zfree(cryptop_zone, crp);
1826 _crypto_initreq(struct cryptop *crp, crypto_session_t cses)
1828 crp->crp_session = cses;
1832 crypto_initreq(struct cryptop *crp, crypto_session_t cses)
1834 memset(crp, 0, sizeof(*crp));
1835 _crypto_initreq(crp, cses);
1839 crypto_getreq(crypto_session_t cses, int how)
1841 struct cryptop *crp;
1843 MPASS(how == M_WAITOK || how == M_NOWAIT);
1844 crp = uma_zalloc(cryptop_zone, how | M_ZERO);
1846 _crypto_initreq(crp, cses);
1851 * Invoke the callback on behalf of the driver.
1854 crypto_done(struct cryptop *crp)
1856 KASSERT((crp->crp_flags & CRYPTO_F_DONE) == 0,
1857 ("crypto_done: op already done, flags 0x%x", crp->crp_flags));
1858 crp->crp_flags |= CRYPTO_F_DONE;
1859 if (crp->crp_etype != 0)
1860 CRYPTOSTAT_INC(cs_errs);
1863 * CBIMM means unconditionally do the callback immediately;
1864 * CBIFSYNC means do the callback immediately only if the
1865 * operation was done synchronously. Both are used to avoid
1866 * doing extraneous context switches; the latter is mostly
1867 * used with the software crypto driver.
1869 if (!CRYPTOP_ASYNC_KEEPORDER(crp) &&
1870 ((crp->crp_flags & CRYPTO_F_CBIMM) ||
1871 ((crp->crp_flags & CRYPTO_F_CBIFSYNC) &&
1872 (crypto_ses2caps(crp->crp_session) & CRYPTOCAP_F_SYNC)))) {
1874 * Do the callback directly. This is ok when the
1875 * callback routine does very little (e.g. the
1876 * /dev/crypto callback method just does a wakeup).
1878 crp->crp_callback(crp);
1880 struct crypto_ret_worker *ret_worker;
1883 ret_worker = CRYPTO_RETW(crp->crp_retw_id);
1887 * Normal case; queue the callback for the thread.
1889 CRYPTO_RETW_LOCK(ret_worker);
1890 if (CRYPTOP_ASYNC_KEEPORDER(crp)) {
1891 struct cryptop *tmp;
1893 TAILQ_FOREACH_REVERSE(tmp, &ret_worker->crp_ordered_ret_q,
1894 cryptop_q, crp_next) {
1895 if (CRYPTO_SEQ_GT(crp->crp_seq, tmp->crp_seq)) {
1896 TAILQ_INSERT_AFTER(&ret_worker->crp_ordered_ret_q,
1897 tmp, crp, crp_next);
1902 TAILQ_INSERT_HEAD(&ret_worker->crp_ordered_ret_q,
1906 if (crp->crp_seq == ret_worker->reorder_cur_seq)
1910 if (CRYPTO_RETW_EMPTY(ret_worker))
1913 TAILQ_INSERT_TAIL(&ret_worker->crp_ret_q, crp, crp_next);
1917 wakeup_one(&ret_worker->crp_ret_q); /* shared wait channel */
1918 CRYPTO_RETW_UNLOCK(ret_worker);
1923 * Invoke the callback on behalf of the driver.
1926 crypto_kdone(struct cryptkop *krp)
1928 struct crypto_ret_worker *ret_worker;
1929 struct cryptocap *cap;
1931 if (krp->krp_status != 0)
1932 CRYPTOSTAT_INC(cs_kerrs);
1935 CRYPTO_DRIVER_LOCK();
1936 KASSERT(cap->cc_koperations > 0, ("cc_koperations == 0"));
1937 cap->cc_koperations--;
1938 if (cap->cc_koperations == 0 &&
1939 cap->cc_flags & CRYPTOCAP_F_CLEANUP)
1941 CRYPTO_DRIVER_UNLOCK();
1942 krp->krp_cap = NULL;
1946 ret_worker = CRYPTO_RETW(0);
1948 CRYPTO_RETW_LOCK(ret_worker);
1949 if (CRYPTO_RETW_EMPTY(ret_worker))
1950 wakeup_one(&ret_worker->crp_ret_q); /* shared wait channel */
1951 TAILQ_INSERT_TAIL(&ret_worker->crp_ret_kq, krp, krp_next);
1952 CRYPTO_RETW_UNLOCK(ret_worker);
1956 crypto_getfeat(int *featp)
1958 int hid, kalg, feat = 0;
1960 CRYPTO_DRIVER_LOCK();
1961 for (hid = 0; hid < crypto_drivers_size; hid++) {
1962 const struct cryptocap *cap = crypto_drivers[hid];
1965 ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
1966 !crypto_devallowsoft)) {
1969 for (kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
1970 if (cap->cc_kalg[kalg] & CRYPTO_ALG_FLAG_SUPPORTED)
1973 CRYPTO_DRIVER_UNLOCK();
1979 * Terminate a thread at module unload. The process that
1980 * initiated this is waiting for us to signal that we're gone;
1981 * wake it up and exit. We use the driver table lock to insure
1982 * we don't do the wakeup before they're waiting. There is no
1983 * race here because the waiter sleeps on the proc lock for the
1984 * thread so it gets notified at the right time because of an
1985 * extra wakeup that's done in exit1().
1988 crypto_finis(void *chan)
1990 CRYPTO_DRIVER_LOCK();
1992 CRYPTO_DRIVER_UNLOCK();
1997 * Crypto thread, dispatches crypto requests.
2000 crypto_dispatch_thread(void *arg __unused)
2002 struct cryptop *crp, *submit;
2003 struct cryptkop *krp;
2004 struct cryptocap *cap;
2007 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
2008 fpu_kern_thread(FPU_KERN_NORMAL);
2014 * Find the first element in the queue that can be
2015 * processed and look-ahead to see if multiple ops
2016 * are ready for the same driver.
2020 TAILQ_FOREACH(crp, &crp_q, crp_next) {
2021 cap = crp->crp_session->cap;
2023 * Driver cannot disappeared when there is an active
2026 KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
2027 __func__, __LINE__));
2028 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
2029 /* Op needs to be migrated, process it. */
2034 if (!cap->cc_qblocked) {
2035 if (submit != NULL) {
2037 * We stop on finding another op,
2038 * regardless whether its for the same
2039 * driver or not. We could keep
2040 * searching the queue but it might be
2041 * better to just use a per-driver
2044 if (submit->crp_session->cap == cap)
2045 hint = CRYPTO_HINT_MORE;
2049 if ((submit->crp_flags & CRYPTO_F_BATCH) == 0)
2051 /* keep scanning for more are q'd */
2055 if (submit != NULL) {
2056 TAILQ_REMOVE(&crp_q, submit, crp_next);
2057 cap = submit->crp_session->cap;
2058 KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
2059 __func__, __LINE__));
2061 result = crypto_invoke(cap, submit, hint);
2063 if (result == ERESTART) {
2065 * The driver ran out of resources, mark the
2066 * driver ``blocked'' for cryptop's and put
2067 * the request back in the queue. It would
2068 * best to put the request back where we got
2069 * it but that's hard so for now we put it
2070 * at the front. This should be ok; putting
2071 * it at the end does not work.
2073 cap->cc_qblocked = 1;
2074 TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
2075 CRYPTOSTAT_INC(cs_blocks);
2079 /* As above, but for key ops */
2080 TAILQ_FOREACH(krp, &crp_kq, krp_next) {
2082 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
2084 * Operation needs to be migrated,
2085 * clear krp_cap so a new driver is
2088 krp->krp_cap = NULL;
2092 if (!cap->cc_kqblocked)
2096 TAILQ_REMOVE(&crp_kq, krp, krp_next);
2098 result = crypto_kinvoke(krp);
2100 if (result == ERESTART) {
2102 * The driver ran out of resources, mark the
2103 * driver ``blocked'' for cryptkop's and put
2104 * the request back in the queue. It would
2105 * best to put the request back where we got
2106 * it but that's hard so for now we put it
2107 * at the front. This should be ok; putting
2108 * it at the end does not work.
2110 krp->krp_cap->cc_kqblocked = 1;
2111 TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
2112 CRYPTOSTAT_INC(cs_kblocks);
2116 if (submit == NULL && krp == NULL) {
2118 * Nothing more to be processed. Sleep until we're
2119 * woken because there are more ops to process.
2120 * This happens either by submission or by a driver
2121 * becoming unblocked and notifying us through
2122 * crypto_unblock. Note that when we wakeup we
2123 * start processing each queue again from the
2124 * front. It's not clear that it's important to
2125 * preserve this ordering since ops may finish
2126 * out of order if dispatched to different devices
2127 * and some become blocked while others do not.
2130 msleep(&crp_q, &crypto_q_mtx, PWAIT, "crypto_wait", 0);
2132 if (cryptotd == NULL)
2134 CRYPTOSTAT_INC(cs_intrs);
2139 crypto_finis(&crp_q);
2143 * Crypto returns thread, does callbacks for processed crypto requests.
2144 * Callbacks are done here, rather than in the crypto drivers, because
2145 * callbacks typically are expensive and would slow interrupt handling.
2148 crypto_ret_thread(void *arg)
2150 struct crypto_ret_worker *ret_worker = arg;
2151 struct cryptop *crpt;
2152 struct cryptkop *krpt;
2154 CRYPTO_RETW_LOCK(ret_worker);
2156 /* Harvest return q's for completed ops */
2157 crpt = TAILQ_FIRST(&ret_worker->crp_ordered_ret_q);
2159 if (crpt->crp_seq == ret_worker->reorder_cur_seq) {
2160 TAILQ_REMOVE(&ret_worker->crp_ordered_ret_q, crpt, crp_next);
2161 ret_worker->reorder_cur_seq++;
2168 crpt = TAILQ_FIRST(&ret_worker->crp_ret_q);
2170 TAILQ_REMOVE(&ret_worker->crp_ret_q, crpt, crp_next);
2173 krpt = TAILQ_FIRST(&ret_worker->crp_ret_kq);
2175 TAILQ_REMOVE(&ret_worker->crp_ret_kq, krpt, krp_next);
2177 if (crpt != NULL || krpt != NULL) {
2178 CRYPTO_RETW_UNLOCK(ret_worker);
2180 * Run callbacks unlocked.
2183 crpt->crp_callback(crpt);
2185 krpt->krp_callback(krpt);
2186 CRYPTO_RETW_LOCK(ret_worker);
2189 * Nothing more to be processed. Sleep until we're
2190 * woken because there are more returns to process.
2192 msleep(&ret_worker->crp_ret_q, &ret_worker->crypto_ret_mtx, PWAIT,
2193 "crypto_ret_wait", 0);
2194 if (ret_worker->td == NULL)
2196 CRYPTOSTAT_INC(cs_rets);
2199 CRYPTO_RETW_UNLOCK(ret_worker);
2201 crypto_finis(&ret_worker->crp_ret_q);
2206 db_show_drivers(void)
2210 db_printf("%12s %4s %4s %8s %2s %2s\n"
2218 for (hid = 0; hid < crypto_drivers_size; hid++) {
2219 const struct cryptocap *cap = crypto_drivers[hid];
2222 db_printf("%-12s %4u %4u %08x %2u %2u\n"
2223 , device_get_nameunit(cap->cc_dev)
2225 , cap->cc_koperations
2233 DB_SHOW_COMMAND(crypto, db_show_crypto)
2235 struct cryptop *crp;
2236 struct crypto_ret_worker *ret_worker;
2241 db_printf("%4s %8s %4s %4s %4s %4s %8s %8s\n",
2242 "HID", "Caps", "Ilen", "Olen", "Etype", "Flags",
2243 "Device", "Callback");
2244 TAILQ_FOREACH(crp, &crp_q, crp_next) {
2245 db_printf("%4u %08x %4u %4u %04x %8p %8p\n"
2246 , crp->crp_session->cap->cc_hid
2247 , (int) crypto_ses2caps(crp->crp_session)
2251 , device_get_nameunit(crp->crp_session->cap->cc_dev)
2255 FOREACH_CRYPTO_RETW(ret_worker) {
2256 db_printf("\n%8s %4s %4s %4s %8s\n",
2257 "ret_worker", "HID", "Etype", "Flags", "Callback");
2258 if (!TAILQ_EMPTY(&ret_worker->crp_ret_q)) {
2259 TAILQ_FOREACH(crp, &ret_worker->crp_ret_q, crp_next) {
2260 db_printf("%8td %4u %4u %04x %8p\n"
2261 , CRYPTO_RETW_ID(ret_worker)
2262 , crp->crp_session->cap->cc_hid
2272 DB_SHOW_COMMAND(kcrypto, db_show_kcrypto)
2274 struct cryptkop *krp;
2275 struct crypto_ret_worker *ret_worker;
2280 db_printf("%4s %5s %4s %4s %8s %4s %8s\n",
2281 "Op", "Status", "#IP", "#OP", "CRID", "HID", "Callback");
2282 TAILQ_FOREACH(krp, &crp_kq, krp_next) {
2283 db_printf("%4u %5u %4u %4u %08x %4u %8p\n"
2286 , krp->krp_iparams, krp->krp_oparams
2287 , krp->krp_crid, krp->krp_hid
2292 ret_worker = CRYPTO_RETW(0);
2293 if (!TAILQ_EMPTY(&ret_worker->crp_ret_q)) {
2294 db_printf("%4s %5s %8s %4s %8s\n",
2295 "Op", "Status", "CRID", "HID", "Callback");
2296 TAILQ_FOREACH(krp, &ret_worker->crp_ret_kq, krp_next) {
2297 db_printf("%4u %5u %08x %4u %8p\n"
2300 , krp->krp_crid, krp->krp_hid
2308 int crypto_modevent(module_t mod, int type, void *unused);
2311 * Initialization code, both for static and dynamic loading.
2312 * Note this is not invoked with the usual MODULE_DECLARE
2313 * mechanism but instead is listed as a dependency by the
2314 * cryptosoft driver. This guarantees proper ordering of
2315 * calls on module load/unload.
2318 crypto_modevent(module_t mod, int type, void *unused)
2324 error = crypto_init();
2325 if (error == 0 && bootverbose)
2326 printf("crypto: <crypto core>\n");
2329 /*XXX disallow if active sessions */
2336 MODULE_VERSION(crypto, 1);
2337 MODULE_DEPEND(crypto, zlib, 1, 1, 1);