2 * Copyright (c) 2002-2006 Sam Leffler. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 #include <sys/cdefs.h>
26 __FBSDID("$FreeBSD$");
29 * Cryptographic Subsystem.
31 * This code is derived from the Openbsd Cryptographic Framework (OCF)
32 * that has the copyright shown below. Very little of the original
37 * The author of this code is Angelos D. Keromytis (angelos@cis.upenn.edu)
39 * This code was written by Angelos D. Keromytis in Athens, Greece, in
40 * February 2000. Network Security Technologies Inc. (NSTI) kindly
41 * supported the development of this code.
43 * Copyright (c) 2000, 2001 Angelos D. Keromytis
45 * Permission to use, copy, and modify this software with or without fee
46 * is hereby granted, provided that this entire notice is included in
47 * all source code copies of any software which is or includes a copy or
48 * modification of this software.
50 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
51 * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
52 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
53 * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
57 #include "opt_compat.h"
60 #include <sys/param.h>
61 #include <sys/systm.h>
62 #include <sys/counter.h>
63 #include <sys/kernel.h>
64 #include <sys/kthread.h>
65 #include <sys/linker.h>
67 #include <sys/module.h>
68 #include <sys/mutex.h>
69 #include <sys/malloc.h>
72 #include <sys/refcount.h>
75 #include <sys/sysctl.h>
76 #include <sys/taskqueue.h>
81 #include <machine/vmparam.h>
84 #include <crypto/intake.h>
85 #include <opencrypto/cryptodev.h>
86 #include <opencrypto/xform_auth.h>
87 #include <opencrypto/xform_enc.h>
91 #include "cryptodev_if.h"
93 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
94 #include <machine/pcb.h>
97 SDT_PROVIDER_DEFINE(opencrypto);
100 * Crypto drivers register themselves by allocating a slot in the
101 * crypto_drivers table with crypto_get_driverid() and then registering
102 * each asym algorithm they support with crypto_kregister().
104 static struct mtx crypto_drivers_mtx; /* lock on driver table */
105 #define CRYPTO_DRIVER_LOCK() mtx_lock(&crypto_drivers_mtx)
106 #define CRYPTO_DRIVER_UNLOCK() mtx_unlock(&crypto_drivers_mtx)
107 #define CRYPTO_DRIVER_ASSERT() mtx_assert(&crypto_drivers_mtx, MA_OWNED)
110 * Crypto device/driver capabilities structure.
113 * (d) - protected by CRYPTO_DRIVER_LOCK()
114 * (q) - protected by CRYPTO_Q_LOCK()
115 * Not tagged fields are read-only.
120 uint32_t cc_sessions; /* (d) # of sessions */
121 uint32_t cc_koperations; /* (d) # os asym operations */
122 uint8_t cc_kalg[CRK_ALGORITHM_MAX + 1];
124 int cc_flags; /* (d) flags */
125 #define CRYPTOCAP_F_CLEANUP 0x80000000 /* needs resource cleanup */
126 int cc_qblocked; /* (q) symmetric q blocked */
127 int cc_kqblocked; /* (q) asymmetric q blocked */
128 size_t cc_session_size;
129 volatile int cc_refs;
132 static struct cryptocap **crypto_drivers = NULL;
133 static int crypto_drivers_size = 0;
135 struct crypto_session {
136 struct cryptocap *cap;
138 struct crypto_session_params csp;
142 * There are two queues for crypto requests; one for symmetric (e.g.
143 * cipher) operations and one for asymmetric (e.g. MOD)operations.
144 * A single mutex is used to lock access to both queues. We could
145 * have one per-queue but having one simplifies handling of block/unblock
148 static int crp_sleep = 0;
149 static TAILQ_HEAD(cryptop_q ,cryptop) crp_q; /* request queues */
150 static TAILQ_HEAD(,cryptkop) crp_kq;
151 static struct mtx crypto_q_mtx;
152 #define CRYPTO_Q_LOCK() mtx_lock(&crypto_q_mtx)
153 #define CRYPTO_Q_UNLOCK() mtx_unlock(&crypto_q_mtx)
155 SYSCTL_NODE(_kern, OID_AUTO, crypto, CTLFLAG_RW, 0,
156 "In-kernel cryptography");
159 * Taskqueue used to dispatch the crypto requests
160 * that have the CRYPTO_F_ASYNC flag
162 static struct taskqueue *crypto_tq;
165 * Crypto seq numbers are operated on with modular arithmetic
167 #define CRYPTO_SEQ_GT(a,b) ((int)((a)-(b)) > 0)
169 struct crypto_ret_worker {
170 struct mtx crypto_ret_mtx;
172 TAILQ_HEAD(,cryptop) crp_ordered_ret_q; /* ordered callback queue for symetric jobs */
173 TAILQ_HEAD(,cryptop) crp_ret_q; /* callback queue for symetric jobs */
174 TAILQ_HEAD(,cryptkop) crp_ret_kq; /* callback queue for asym jobs */
176 uint32_t reorder_ops; /* total ordered sym jobs received */
177 uint32_t reorder_cur_seq; /* current sym job dispatched */
179 struct proc *cryptoretproc;
181 static struct crypto_ret_worker *crypto_ret_workers = NULL;
183 #define CRYPTO_RETW(i) (&crypto_ret_workers[i])
184 #define CRYPTO_RETW_ID(w) ((w) - crypto_ret_workers)
185 #define FOREACH_CRYPTO_RETW(w) \
186 for (w = crypto_ret_workers; w < crypto_ret_workers + crypto_workers_num; ++w)
188 #define CRYPTO_RETW_LOCK(w) mtx_lock(&w->crypto_ret_mtx)
189 #define CRYPTO_RETW_UNLOCK(w) mtx_unlock(&w->crypto_ret_mtx)
190 #define CRYPTO_RETW_EMPTY(w) \
191 (TAILQ_EMPTY(&w->crp_ret_q) && TAILQ_EMPTY(&w->crp_ret_kq) && TAILQ_EMPTY(&w->crp_ordered_ret_q))
193 static int crypto_workers_num = 0;
194 SYSCTL_INT(_kern_crypto, OID_AUTO, num_workers, CTLFLAG_RDTUN,
195 &crypto_workers_num, 0,
196 "Number of crypto workers used to dispatch crypto jobs");
197 #ifdef COMPAT_FREEBSD12
198 SYSCTL_INT(_kern, OID_AUTO, crypto_workers_num, CTLFLAG_RDTUN,
199 &crypto_workers_num, 0,
200 "Number of crypto workers used to dispatch crypto jobs");
203 static uma_zone_t cryptop_zone;
204 static uma_zone_t cryptoses_zone;
206 int crypto_userasymcrypto = 1;
207 SYSCTL_INT(_kern_crypto, OID_AUTO, asym_enable, CTLFLAG_RW,
208 &crypto_userasymcrypto, 0,
209 "Enable user-mode access to asymmetric crypto support");
210 #ifdef COMPAT_FREEBSD12
211 SYSCTL_INT(_kern, OID_AUTO, userasymcrypto, CTLFLAG_RW,
212 &crypto_userasymcrypto, 0,
213 "Enable/disable user-mode access to asymmetric crypto support");
216 int crypto_devallowsoft = 0;
217 SYSCTL_INT(_kern_crypto, OID_AUTO, allow_soft, CTLFLAG_RW,
218 &crypto_devallowsoft, 0,
219 "Enable use of software crypto by /dev/crypto");
220 #ifdef COMPAT_FREEBSD12
221 SYSCTL_INT(_kern, OID_AUTO, cryptodevallowsoft, CTLFLAG_RW,
222 &crypto_devallowsoft, 0,
223 "Enable/disable use of software crypto by /dev/crypto");
226 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
228 static void crypto_proc(void);
229 static struct proc *cryptoproc;
230 static void crypto_ret_proc(struct crypto_ret_worker *ret_worker);
231 static void crypto_destroy(void);
232 static int crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint);
233 static int crypto_kinvoke(struct cryptkop *krp);
234 static void crypto_task_invoke(void *ctx, int pending);
235 static void crypto_batch_enqueue(struct cryptop *crp);
237 static counter_u64_t cryptostats[sizeof(struct cryptostats) / sizeof(uint64_t)];
238 SYSCTL_COUNTER_U64_ARRAY(_kern_crypto, OID_AUTO, stats, CTLFLAG_RW,
239 cryptostats, nitems(cryptostats),
240 "Crypto system statistics");
242 #define CRYPTOSTAT_INC(stat) do { \
244 cryptostats[offsetof(struct cryptostats, stat) / sizeof(uint64_t)],\
249 cryptostats_init(void *arg __unused)
251 COUNTER_ARRAY_ALLOC(cryptostats, nitems(cryptostats), M_WAITOK);
253 SYSINIT(cryptostats_init, SI_SUB_COUNTER, SI_ORDER_ANY, cryptostats_init, NULL);
256 cryptostats_fini(void *arg __unused)
258 COUNTER_ARRAY_FREE(cryptostats, nitems(cryptostats));
260 SYSUNINIT(cryptostats_fini, SI_SUB_COUNTER, SI_ORDER_ANY, cryptostats_fini,
263 /* Try to avoid directly exposing the key buffer as a symbol */
264 static struct keybuf *keybuf;
266 static struct keybuf empty_keybuf = {
270 /* Obtain the key buffer from boot metadata */
276 kmdp = preload_search_by_type("elf kernel");
279 kmdp = preload_search_by_type("elf64 kernel");
281 keybuf = (struct keybuf *)preload_search_info(kmdp,
282 MODINFO_METADATA | MODINFOMD_KEYBUF);
285 keybuf = &empty_keybuf;
288 /* It'd be nice if we could store these in some kind of secure memory... */
296 static struct cryptocap *
297 cap_ref(struct cryptocap *cap)
300 refcount_acquire(&cap->cc_refs);
305 cap_rele(struct cryptocap *cap)
308 if (refcount_release(&cap->cc_refs) == 0)
311 KASSERT(cap->cc_sessions == 0,
312 ("freeing crypto driver with active sessions"));
313 KASSERT(cap->cc_koperations == 0,
314 ("freeing crypto driver with active key operations"));
316 free(cap, M_CRYPTO_DATA);
322 struct crypto_ret_worker *ret_worker;
325 mtx_init(&crypto_drivers_mtx, "crypto", "crypto driver table",
330 mtx_init(&crypto_q_mtx, "crypto", "crypto op queues", MTX_DEF);
332 cryptop_zone = uma_zcreate("cryptop",
333 sizeof(struct cryptop), NULL, NULL, NULL, NULL,
334 UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
335 cryptoses_zone = uma_zcreate("crypto_session",
336 sizeof(struct crypto_session), NULL, NULL, NULL, NULL,
337 UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
339 crypto_drivers_size = CRYPTO_DRIVERS_INITIAL;
340 crypto_drivers = malloc(crypto_drivers_size *
341 sizeof(struct cryptocap), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
343 if (crypto_workers_num < 1 || crypto_workers_num > mp_ncpus)
344 crypto_workers_num = mp_ncpus;
346 crypto_tq = taskqueue_create("crypto", M_WAITOK | M_ZERO,
347 taskqueue_thread_enqueue, &crypto_tq);
349 taskqueue_start_threads(&crypto_tq, crypto_workers_num, PRI_MIN_KERN,
352 error = kproc_create((void (*)(void *)) crypto_proc, NULL,
353 &cryptoproc, 0, 0, "crypto");
355 printf("crypto_init: cannot start crypto thread; error %d",
360 crypto_ret_workers = mallocarray(crypto_workers_num,
361 sizeof(struct crypto_ret_worker), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
363 FOREACH_CRYPTO_RETW(ret_worker) {
364 TAILQ_INIT(&ret_worker->crp_ordered_ret_q);
365 TAILQ_INIT(&ret_worker->crp_ret_q);
366 TAILQ_INIT(&ret_worker->crp_ret_kq);
368 ret_worker->reorder_ops = 0;
369 ret_worker->reorder_cur_seq = 0;
371 mtx_init(&ret_worker->crypto_ret_mtx, "crypto", "crypto return queues", MTX_DEF);
373 error = kproc_create((void (*)(void *)) crypto_ret_proc, ret_worker,
374 &ret_worker->cryptoretproc, 0, 0, "crypto returns %td", CRYPTO_RETW_ID(ret_worker));
376 printf("crypto_init: cannot start cryptoret thread; error %d",
391 * Signal a crypto thread to terminate. We use the driver
392 * table lock to synchronize the sleep/wakeups so that we
393 * are sure the threads have terminated before we release
394 * the data structures they use. See crypto_finis below
395 * for the other half of this song-and-dance.
398 crypto_terminate(struct proc **pp, void *q)
402 mtx_assert(&crypto_drivers_mtx, MA_OWNED);
407 PROC_LOCK(p); /* NB: insure we don't miss wakeup */
408 CRYPTO_DRIVER_UNLOCK(); /* let crypto_finis progress */
409 msleep(p, &p->p_mtx, PWAIT, "crypto_destroy", 0);
411 CRYPTO_DRIVER_LOCK();
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(&cryptoproc, &crp_q);
475 FOREACH_CRYPTO_RETW(ret_worker)
476 crypto_terminate(&ret_worker->cryptoretproc, &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 (cryptoses_zone != NULL)
491 uma_zdestroy(cryptoses_zone);
492 if (cryptop_zone != NULL)
493 uma_zdestroy(cryptop_zone);
494 mtx_destroy(&crypto_q_mtx);
495 FOREACH_CRYPTO_RETW(ret_worker)
496 mtx_destroy(&ret_worker->crypto_ret_mtx);
497 free(crypto_ret_workers, M_CRYPTO_DATA);
498 if (crypto_tq != NULL)
499 taskqueue_free(crypto_tq);
500 mtx_destroy(&crypto_drivers_mtx);
504 crypto_ses2hid(crypto_session_t crypto_session)
506 return (crypto_session->cap->cc_hid);
510 crypto_ses2caps(crypto_session_t crypto_session)
512 return (crypto_session->cap->cc_flags & 0xff000000);
516 crypto_get_driver_session(crypto_session_t crypto_session)
518 return (crypto_session->softc);
521 const struct crypto_session_params *
522 crypto_get_params(crypto_session_t crypto_session)
524 return (&crypto_session->csp);
528 crypto_auth_hash(const struct crypto_session_params *csp)
531 switch (csp->csp_auth_alg) {
532 case CRYPTO_SHA1_HMAC:
533 return (&auth_hash_hmac_sha1);
534 case CRYPTO_SHA2_224_HMAC:
535 return (&auth_hash_hmac_sha2_224);
536 case CRYPTO_SHA2_256_HMAC:
537 return (&auth_hash_hmac_sha2_256);
538 case CRYPTO_SHA2_384_HMAC:
539 return (&auth_hash_hmac_sha2_384);
540 case CRYPTO_SHA2_512_HMAC:
541 return (&auth_hash_hmac_sha2_512);
542 case CRYPTO_NULL_HMAC:
543 return (&auth_hash_null);
544 case CRYPTO_RIPEMD160_HMAC:
545 return (&auth_hash_hmac_ripemd_160);
547 return (&auth_hash_sha1);
548 case CRYPTO_SHA2_224:
549 return (&auth_hash_sha2_224);
550 case CRYPTO_SHA2_256:
551 return (&auth_hash_sha2_256);
552 case CRYPTO_SHA2_384:
553 return (&auth_hash_sha2_384);
554 case CRYPTO_SHA2_512:
555 return (&auth_hash_sha2_512);
556 case CRYPTO_AES_NIST_GMAC:
557 switch (csp->csp_auth_klen) {
559 return (&auth_hash_nist_gmac_aes_128);
561 return (&auth_hash_nist_gmac_aes_192);
563 return (&auth_hash_nist_gmac_aes_256);
568 return (&auth_hash_blake2b);
570 return (&auth_hash_blake2s);
571 case CRYPTO_POLY1305:
572 return (&auth_hash_poly1305);
573 case CRYPTO_AES_CCM_CBC_MAC:
574 switch (csp->csp_auth_klen) {
576 return (&auth_hash_ccm_cbc_mac_128);
578 return (&auth_hash_ccm_cbc_mac_192);
580 return (&auth_hash_ccm_cbc_mac_256);
590 crypto_cipher(const struct crypto_session_params *csp)
593 switch (csp->csp_cipher_alg) {
594 case CRYPTO_RIJNDAEL128_CBC:
595 return (&enc_xform_rijndael128);
597 return (&enc_xform_aes_xts);
599 return (&enc_xform_aes_icm);
600 case CRYPTO_AES_NIST_GCM_16:
601 return (&enc_xform_aes_nist_gcm);
602 case CRYPTO_CAMELLIA_CBC:
603 return (&enc_xform_camellia);
604 case CRYPTO_NULL_CBC:
605 return (&enc_xform_null);
606 case CRYPTO_CHACHA20:
607 return (&enc_xform_chacha20);
608 case CRYPTO_AES_CCM_16:
609 return (&enc_xform_ccm);
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,
707 if (alg < nitems(alg_types))
708 return (alg_types[alg]);
713 alg_is_compression(int alg)
716 return (alg_type(alg) == ALG_COMPRESSION);
720 alg_is_cipher(int alg)
723 return (alg_type(alg) == ALG_CIPHER);
727 alg_is_digest(int alg)
730 return (alg_type(alg) == ALG_DIGEST ||
731 alg_type(alg) == ALG_KEYED_DIGEST);
735 alg_is_keyed_digest(int alg)
738 return (alg_type(alg) == ALG_KEYED_DIGEST);
745 return (alg_type(alg) == ALG_AEAD);
748 #define SUPPORTED_SES (CSP_F_SEPARATE_OUTPUT | CSP_F_SEPARATE_AAD | CSP_F_ESN)
750 /* Various sanity checks on crypto session parameters. */
752 check_csp(const struct crypto_session_params *csp)
754 struct auth_hash *axf;
756 /* Mode-independent checks. */
757 if ((csp->csp_flags & ~(SUPPORTED_SES)) != 0)
759 if (csp->csp_ivlen < 0 || csp->csp_cipher_klen < 0 ||
760 csp->csp_auth_klen < 0 || csp->csp_auth_mlen < 0)
762 if (csp->csp_auth_key != NULL && csp->csp_auth_klen == 0)
764 if (csp->csp_cipher_key != NULL && csp->csp_cipher_klen == 0)
767 switch (csp->csp_mode) {
768 case CSP_MODE_COMPRESS:
769 if (!alg_is_compression(csp->csp_cipher_alg))
771 if (csp->csp_flags & CSP_F_SEPARATE_OUTPUT)
773 if (csp->csp_flags & CSP_F_SEPARATE_AAD)
775 if (csp->csp_cipher_klen != 0 || csp->csp_ivlen != 0 ||
776 csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0 ||
777 csp->csp_auth_mlen != 0)
780 case CSP_MODE_CIPHER:
781 if (!alg_is_cipher(csp->csp_cipher_alg))
783 if (csp->csp_flags & CSP_F_SEPARATE_AAD)
785 if (csp->csp_cipher_alg != CRYPTO_NULL_CBC) {
786 if (csp->csp_cipher_klen == 0)
788 if (csp->csp_ivlen == 0)
791 if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
793 if (csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0 ||
794 csp->csp_auth_mlen != 0)
797 case CSP_MODE_DIGEST:
798 if (csp->csp_cipher_alg != 0 || csp->csp_cipher_klen != 0)
801 if (csp->csp_flags & CSP_F_SEPARATE_AAD)
804 /* IV is optional for digests (e.g. GMAC). */
805 if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
807 if (!alg_is_digest(csp->csp_auth_alg))
810 /* Key is optional for BLAKE2 digests. */
811 if (csp->csp_auth_alg == CRYPTO_BLAKE2B ||
812 csp->csp_auth_alg == CRYPTO_BLAKE2S)
814 else if (alg_is_keyed_digest(csp->csp_auth_alg)) {
815 if (csp->csp_auth_klen == 0)
818 if (csp->csp_auth_klen != 0)
821 if (csp->csp_auth_mlen != 0) {
822 axf = crypto_auth_hash(csp);
823 if (axf == NULL || csp->csp_auth_mlen > axf->hashsize)
828 if (!alg_is_aead(csp->csp_cipher_alg))
830 if (csp->csp_cipher_klen == 0)
832 if (csp->csp_ivlen == 0 ||
833 csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
835 if (csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0)
839 * XXX: Would be nice to have a better way to get this
842 switch (csp->csp_cipher_alg) {
843 case CRYPTO_AES_NIST_GCM_16:
844 case CRYPTO_AES_CCM_16:
845 if (csp->csp_auth_mlen > 16)
851 if (!alg_is_cipher(csp->csp_cipher_alg))
853 if (csp->csp_cipher_alg != CRYPTO_NULL_CBC) {
854 if (csp->csp_cipher_klen == 0)
856 if (csp->csp_ivlen == 0)
859 if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
861 if (!alg_is_digest(csp->csp_auth_alg))
864 /* Key is optional for BLAKE2 digests. */
865 if (csp->csp_auth_alg == CRYPTO_BLAKE2B ||
866 csp->csp_auth_alg == CRYPTO_BLAKE2S)
868 else if (alg_is_keyed_digest(csp->csp_auth_alg)) {
869 if (csp->csp_auth_klen == 0)
872 if (csp->csp_auth_klen != 0)
875 if (csp->csp_auth_mlen != 0) {
876 axf = crypto_auth_hash(csp);
877 if (axf == NULL || csp->csp_auth_mlen > axf->hashsize)
889 * Delete a session after it has been detached from its driver.
892 crypto_deletesession(crypto_session_t cses)
894 struct cryptocap *cap;
898 zfree(cses->softc, M_CRYPTO_DATA);
899 uma_zfree(cryptoses_zone, cses);
901 CRYPTO_DRIVER_LOCK();
903 if (cap->cc_sessions == 0 && cap->cc_flags & CRYPTOCAP_F_CLEANUP)
905 CRYPTO_DRIVER_UNLOCK();
910 * Create a new session. The crid argument specifies a crypto
911 * driver to use or constraints on a driver to select (hardware
912 * only, software only, either). Whatever driver is selected
913 * must be capable of the requested crypto algorithms.
916 crypto_newsession(crypto_session_t *cses,
917 const struct crypto_session_params *csp, int crid)
919 crypto_session_t res;
920 struct cryptocap *cap;
928 CRYPTO_DRIVER_LOCK();
929 if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
931 * Use specified driver; verify it is capable.
933 cap = crypto_checkdriver(crid);
934 if (cap != NULL && CRYPTODEV_PROBESESSION(cap->cc_dev, csp) > 0)
938 * No requested driver; select based on crid flags.
940 cap = crypto_select_driver(csp, crid);
943 CRYPTO_DRIVER_UNLOCK();
944 CRYPTDEB("no driver");
949 CRYPTO_DRIVER_UNLOCK();
951 res = uma_zalloc(cryptoses_zone, M_WAITOK | M_ZERO);
953 res->softc = malloc(cap->cc_session_size, M_CRYPTO_DATA, M_WAITOK |
957 /* Call the driver initialization routine. */
958 err = CRYPTODEV_NEWSESSION(cap->cc_dev, res, csp);
960 CRYPTDEB("dev newsession failed: %d", err);
961 crypto_deletesession(res);
970 * Delete an existing session (or a reserved session on an unregistered
974 crypto_freesession(crypto_session_t cses)
976 struct cryptocap *cap;
983 /* Call the driver cleanup routine, if available. */
984 CRYPTODEV_FREESESSION(cap->cc_dev, cses);
986 crypto_deletesession(cses);
990 * Return a new driver id. Registers a driver with the system so that
991 * it can be probed by subsequent sessions.
994 crypto_get_driverid(device_t dev, size_t sessionsize, int flags)
996 struct cryptocap *cap, **newdrv;
999 if ((flags & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
1001 "no flags specified when registering driver\n");
1005 cap = malloc(sizeof(*cap), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
1007 cap->cc_session_size = sessionsize;
1008 cap->cc_flags = flags;
1009 refcount_init(&cap->cc_refs, 1);
1011 CRYPTO_DRIVER_LOCK();
1013 for (i = 0; i < crypto_drivers_size; i++) {
1014 if (crypto_drivers[i] == NULL)
1018 if (i < crypto_drivers_size)
1021 /* Out of entries, allocate some more. */
1023 if (2 * crypto_drivers_size <= crypto_drivers_size) {
1024 CRYPTO_DRIVER_UNLOCK();
1025 printf("crypto: driver count wraparound!\n");
1029 CRYPTO_DRIVER_UNLOCK();
1031 newdrv = malloc(2 * crypto_drivers_size *
1032 sizeof(*crypto_drivers), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
1034 CRYPTO_DRIVER_LOCK();
1035 memcpy(newdrv, crypto_drivers,
1036 crypto_drivers_size * sizeof(*crypto_drivers));
1038 crypto_drivers_size *= 2;
1040 free(crypto_drivers, M_CRYPTO_DATA);
1041 crypto_drivers = newdrv;
1045 crypto_drivers[i] = cap;
1046 CRYPTO_DRIVER_UNLOCK();
1049 printf("crypto: assign %s driver id %u, flags 0x%x\n",
1050 device_get_nameunit(dev), i, flags);
1056 * Lookup a driver by name. We match against the full device
1057 * name and unit, and against just the name. The latter gives
1058 * us a simple widlcarding by device name. On success return the
1059 * driver/hardware identifier; otherwise return -1.
1062 crypto_find_driver(const char *match)
1064 struct cryptocap *cap;
1065 int i, len = strlen(match);
1067 CRYPTO_DRIVER_LOCK();
1068 for (i = 0; i < crypto_drivers_size; i++) {
1069 if (crypto_drivers[i] == NULL)
1071 cap = crypto_drivers[i];
1072 if (strncmp(match, device_get_nameunit(cap->cc_dev), len) == 0 ||
1073 strncmp(match, device_get_name(cap->cc_dev), len) == 0) {
1074 CRYPTO_DRIVER_UNLOCK();
1078 CRYPTO_DRIVER_UNLOCK();
1083 * Return the device_t for the specified driver or NULL
1084 * if the driver identifier is invalid.
1087 crypto_find_device_byhid(int hid)
1089 struct cryptocap *cap;
1093 CRYPTO_DRIVER_LOCK();
1094 cap = crypto_checkdriver(hid);
1097 CRYPTO_DRIVER_UNLOCK();
1102 * Return the device/driver capabilities.
1105 crypto_getcaps(int hid)
1107 struct cryptocap *cap;
1111 CRYPTO_DRIVER_LOCK();
1112 cap = crypto_checkdriver(hid);
1114 flags = cap->cc_flags;
1115 CRYPTO_DRIVER_UNLOCK();
1120 * Register support for a key-related algorithm. This routine
1121 * is called once for each algorithm supported a driver.
1124 crypto_kregister(uint32_t driverid, int kalg, uint32_t flags)
1126 struct cryptocap *cap;
1129 CRYPTO_DRIVER_LOCK();
1131 cap = crypto_checkdriver(driverid);
1133 (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
1135 * XXX Do some performance testing to determine placing.
1136 * XXX We probably need an auxiliary data structure that
1137 * XXX describes relative performances.
1140 cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
1142 printf("crypto: %s registers key alg %u flags %u\n"
1143 , device_get_nameunit(cap->cc_dev)
1147 gone_in_dev(cap->cc_dev, 14, "asymmetric crypto");
1152 CRYPTO_DRIVER_UNLOCK();
1157 * Unregister all algorithms associated with a crypto driver.
1158 * If there are pending sessions using it, leave enough information
1159 * around so that subsequent calls using those sessions will
1160 * correctly detect the driver has been unregistered and reroute
1164 crypto_unregister_all(uint32_t driverid)
1166 struct cryptocap *cap;
1168 CRYPTO_DRIVER_LOCK();
1169 cap = crypto_checkdriver(driverid);
1171 CRYPTO_DRIVER_UNLOCK();
1175 cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
1176 crypto_drivers[driverid] = NULL;
1179 * XXX: This doesn't do anything to kick sessions that
1180 * have no pending operations.
1182 while (cap->cc_sessions != 0 || cap->cc_koperations != 0)
1183 mtx_sleep(cap, &crypto_drivers_mtx, 0, "cryunreg", 0);
1184 CRYPTO_DRIVER_UNLOCK();
1191 * Clear blockage on a driver. The what parameter indicates whether
1192 * the driver is now ready for cryptop's and/or cryptokop's.
1195 crypto_unblock(uint32_t driverid, int what)
1197 struct cryptocap *cap;
1201 cap = crypto_checkdriver(driverid);
1203 if (what & CRYPTO_SYMQ)
1204 cap->cc_qblocked = 0;
1205 if (what & CRYPTO_ASYMQ)
1206 cap->cc_kqblocked = 0;
1218 crypto_buffer_len(struct crypto_buffer *cb)
1220 switch (cb->cb_type) {
1221 case CRYPTO_BUF_CONTIG:
1222 return (cb->cb_buf_len);
1223 case CRYPTO_BUF_MBUF:
1224 if (cb->cb_mbuf->m_flags & M_PKTHDR)
1225 return (cb->cb_mbuf->m_pkthdr.len);
1226 return (m_length(cb->cb_mbuf, NULL));
1227 case CRYPTO_BUF_VMPAGE:
1228 return (cb->cb_vm_page_len);
1229 case CRYPTO_BUF_UIO:
1230 return (cb->cb_uio->uio_resid);
1237 /* Various sanity checks on crypto requests. */
1239 cb_sanity(struct crypto_buffer *cb, const char *name)
1241 KASSERT(cb->cb_type > CRYPTO_BUF_NONE && cb->cb_type <= CRYPTO_BUF_LAST,
1242 ("incoming crp with invalid %s buffer type", name));
1243 switch (cb->cb_type) {
1244 case CRYPTO_BUF_CONTIG:
1245 KASSERT(cb->cb_buf_len >= 0,
1246 ("incoming crp with -ve %s buffer length", name));
1248 case CRYPTO_BUF_VMPAGE:
1249 KASSERT(CRYPTO_HAS_VMPAGE,
1250 ("incoming crp uses dmap on supported arch"));
1251 KASSERT(cb->cb_vm_page_len >= 0,
1252 ("incoming crp with -ve %s buffer length", name));
1253 KASSERT(cb->cb_vm_page_offset >= 0,
1254 ("incoming crp with -ve %s buffer offset", name));
1255 KASSERT(cb->cb_vm_page_offset < PAGE_SIZE,
1256 ("incoming crp with %s buffer offset greater than page size"
1265 crp_sanity(struct cryptop *crp)
1267 struct crypto_session_params *csp;
1268 struct crypto_buffer *out;
1269 size_t ilen, len, olen;
1271 KASSERT(crp->crp_session != NULL, ("incoming crp without a session"));
1272 KASSERT(crp->crp_obuf.cb_type >= CRYPTO_BUF_NONE &&
1273 crp->crp_obuf.cb_type <= CRYPTO_BUF_LAST,
1274 ("incoming crp with invalid output buffer type"));
1275 KASSERT(crp->crp_etype == 0, ("incoming crp with error"));
1276 KASSERT(!(crp->crp_flags & CRYPTO_F_DONE),
1277 ("incoming crp already done"));
1279 csp = &crp->crp_session->csp;
1280 cb_sanity(&crp->crp_buf, "input");
1281 ilen = crypto_buffer_len(&crp->crp_buf);
1284 if (csp->csp_flags & CSP_F_SEPARATE_OUTPUT) {
1285 if (crp->crp_obuf.cb_type != CRYPTO_BUF_NONE) {
1286 cb_sanity(&crp->crp_obuf, "output");
1287 out = &crp->crp_obuf;
1288 olen = crypto_buffer_len(out);
1291 KASSERT(crp->crp_obuf.cb_type == CRYPTO_BUF_NONE,
1292 ("incoming crp with separate output buffer "
1293 "but no session support"));
1295 switch (csp->csp_mode) {
1296 case CSP_MODE_COMPRESS:
1297 KASSERT(crp->crp_op == CRYPTO_OP_COMPRESS ||
1298 crp->crp_op == CRYPTO_OP_DECOMPRESS,
1299 ("invalid compression op %x", crp->crp_op));
1301 case CSP_MODE_CIPHER:
1302 KASSERT(crp->crp_op == CRYPTO_OP_ENCRYPT ||
1303 crp->crp_op == CRYPTO_OP_DECRYPT,
1304 ("invalid cipher op %x", crp->crp_op));
1306 case CSP_MODE_DIGEST:
1307 KASSERT(crp->crp_op == CRYPTO_OP_COMPUTE_DIGEST ||
1308 crp->crp_op == CRYPTO_OP_VERIFY_DIGEST,
1309 ("invalid digest op %x", crp->crp_op));
1312 KASSERT(crp->crp_op ==
1313 (CRYPTO_OP_ENCRYPT | CRYPTO_OP_COMPUTE_DIGEST) ||
1315 (CRYPTO_OP_DECRYPT | CRYPTO_OP_VERIFY_DIGEST),
1316 ("invalid AEAD op %x", crp->crp_op));
1317 if (csp->csp_cipher_alg == CRYPTO_AES_NIST_GCM_16)
1318 KASSERT(crp->crp_flags & CRYPTO_F_IV_SEPARATE,
1319 ("GCM without a separate IV"));
1320 if (csp->csp_cipher_alg == CRYPTO_AES_CCM_16)
1321 KASSERT(crp->crp_flags & CRYPTO_F_IV_SEPARATE,
1322 ("CCM without a separate IV"));
1325 KASSERT(crp->crp_op ==
1326 (CRYPTO_OP_ENCRYPT | CRYPTO_OP_COMPUTE_DIGEST) ||
1328 (CRYPTO_OP_DECRYPT | CRYPTO_OP_VERIFY_DIGEST),
1329 ("invalid ETA op %x", crp->crp_op));
1332 if (csp->csp_mode == CSP_MODE_AEAD || csp->csp_mode == CSP_MODE_ETA) {
1333 if (crp->crp_aad == NULL) {
1334 KASSERT(crp->crp_aad_start == 0 ||
1335 crp->crp_aad_start < ilen,
1336 ("invalid AAD start"));
1337 KASSERT(crp->crp_aad_length != 0 ||
1338 crp->crp_aad_start == 0,
1339 ("AAD with zero length and non-zero start"));
1340 KASSERT(crp->crp_aad_length == 0 ||
1341 crp->crp_aad_start + crp->crp_aad_length <= ilen,
1342 ("AAD outside input length"));
1344 KASSERT(csp->csp_flags & CSP_F_SEPARATE_AAD,
1345 ("session doesn't support separate AAD buffer"));
1346 KASSERT(crp->crp_aad_start == 0,
1347 ("separate AAD buffer with non-zero AAD start"));
1348 KASSERT(crp->crp_aad_length != 0,
1349 ("separate AAD buffer with zero length"));
1352 KASSERT(crp->crp_aad == NULL && crp->crp_aad_start == 0 &&
1353 crp->crp_aad_length == 0,
1354 ("AAD region in request not supporting AAD"));
1356 if (csp->csp_ivlen == 0) {
1357 KASSERT((crp->crp_flags & CRYPTO_F_IV_SEPARATE) == 0,
1358 ("IV_SEPARATE set when IV isn't used"));
1359 KASSERT(crp->crp_iv_start == 0,
1360 ("crp_iv_start set when IV isn't used"));
1361 } else if (crp->crp_flags & CRYPTO_F_IV_SEPARATE) {
1362 KASSERT(crp->crp_iv_start == 0,
1363 ("IV_SEPARATE used with non-zero IV start"));
1365 KASSERT(crp->crp_iv_start < ilen,
1366 ("invalid IV start"));
1367 KASSERT(crp->crp_iv_start + csp->csp_ivlen <= ilen,
1368 ("IV outside buffer length"));
1370 /* XXX: payload_start of 0 should always be < ilen? */
1371 KASSERT(crp->crp_payload_start == 0 ||
1372 crp->crp_payload_start < ilen,
1373 ("invalid payload start"));
1374 KASSERT(crp->crp_payload_start + crp->crp_payload_length <=
1375 ilen, ("payload outside input buffer"));
1377 KASSERT(crp->crp_payload_output_start == 0,
1378 ("payload output start non-zero without output buffer"));
1380 KASSERT(crp->crp_payload_output_start < olen,
1381 ("invalid payload output start"));
1382 KASSERT(crp->crp_payload_output_start +
1383 crp->crp_payload_length <= olen,
1384 ("payload outside output buffer"));
1386 if (csp->csp_mode == CSP_MODE_DIGEST ||
1387 csp->csp_mode == CSP_MODE_AEAD || csp->csp_mode == CSP_MODE_ETA) {
1388 if (crp->crp_op & CRYPTO_OP_VERIFY_DIGEST)
1392 KASSERT(crp->crp_digest_start == 0 ||
1393 crp->crp_digest_start < len,
1394 ("invalid digest start"));
1395 /* XXX: For the mlen == 0 case this check isn't perfect. */
1396 KASSERT(crp->crp_digest_start + csp->csp_auth_mlen <= len,
1397 ("digest outside buffer"));
1399 KASSERT(crp->crp_digest_start == 0,
1400 ("non-zero digest start for request without a digest"));
1402 if (csp->csp_cipher_klen != 0)
1403 KASSERT(csp->csp_cipher_key != NULL ||
1404 crp->crp_cipher_key != NULL,
1405 ("cipher request without a key"));
1406 if (csp->csp_auth_klen != 0)
1407 KASSERT(csp->csp_auth_key != NULL || crp->crp_auth_key != NULL,
1408 ("auth request without a key"));
1409 KASSERT(crp->crp_callback != NULL, ("incoming crp without callback"));
1414 * Add a crypto request to a queue, to be processed by the kernel thread.
1417 crypto_dispatch(struct cryptop *crp)
1419 struct cryptocap *cap;
1426 CRYPTOSTAT_INC(cs_ops);
1428 crp->crp_retw_id = ((uintptr_t)crp->crp_session) % crypto_workers_num;
1430 if (CRYPTOP_ASYNC(crp)) {
1431 if (crp->crp_flags & CRYPTO_F_ASYNC_KEEPORDER) {
1432 struct crypto_ret_worker *ret_worker;
1434 ret_worker = CRYPTO_RETW(crp->crp_retw_id);
1436 CRYPTO_RETW_LOCK(ret_worker);
1437 crp->crp_seq = ret_worker->reorder_ops++;
1438 CRYPTO_RETW_UNLOCK(ret_worker);
1441 TASK_INIT(&crp->crp_task, 0, crypto_task_invoke, crp);
1442 taskqueue_enqueue(crypto_tq, &crp->crp_task);
1446 if ((crp->crp_flags & CRYPTO_F_BATCH) == 0) {
1448 * Caller marked the request to be processed
1449 * immediately; dispatch it directly to the
1450 * driver unless the driver is currently blocked.
1452 cap = crp->crp_session->cap;
1453 if (!cap->cc_qblocked) {
1454 result = crypto_invoke(cap, crp, 0);
1455 if (result != ERESTART)
1458 * The driver ran out of resources, put the request on
1463 crypto_batch_enqueue(crp);
1468 crypto_batch_enqueue(struct cryptop *crp)
1472 TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
1479 * Add an asymetric crypto request to a queue,
1480 * to be processed by the kernel thread.
1483 crypto_kdispatch(struct cryptkop *krp)
1487 CRYPTOSTAT_INC(cs_kops);
1489 krp->krp_cap = NULL;
1490 error = crypto_kinvoke(krp);
1491 if (error == ERESTART) {
1493 TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
1503 * Verify a driver is suitable for the specified operation.
1506 kdriver_suitable(const struct cryptocap *cap, const struct cryptkop *krp)
1508 return (cap->cc_kalg[krp->krp_op] & CRYPTO_ALG_FLAG_SUPPORTED) != 0;
1512 * Select a driver for an asym operation. The driver must
1513 * support the necessary algorithm. The caller can constrain
1514 * which device is selected with the flags parameter. The
1515 * algorithm we use here is pretty stupid; just use the first
1516 * driver that supports the algorithms we need. If there are
1517 * multiple suitable drivers we choose the driver with the
1518 * fewest active operations. We prefer hardware-backed
1519 * drivers to software ones when either may be used.
1521 static struct cryptocap *
1522 crypto_select_kdriver(const struct cryptkop *krp, int flags)
1524 struct cryptocap *cap, *best;
1527 CRYPTO_DRIVER_ASSERT();
1530 * Look first for hardware crypto devices if permitted.
1532 if (flags & CRYPTOCAP_F_HARDWARE)
1533 match = CRYPTOCAP_F_HARDWARE;
1535 match = CRYPTOCAP_F_SOFTWARE;
1538 for (hid = 0; hid < crypto_drivers_size; hid++) {
1540 * If there is no driver for this slot, or the driver
1541 * is not appropriate (hardware or software based on
1542 * match), then skip.
1544 cap = crypto_drivers[hid];
1546 (cap->cc_flags & match) == 0)
1549 /* verify all the algorithms are supported. */
1550 if (kdriver_suitable(cap, krp)) {
1552 cap->cc_koperations < best->cc_koperations)
1558 if (match == CRYPTOCAP_F_HARDWARE && (flags & CRYPTOCAP_F_SOFTWARE)) {
1559 /* sort of an Algol 68-style for loop */
1560 match = CRYPTOCAP_F_SOFTWARE;
1567 * Choose a driver for an asymmetric crypto request.
1569 static struct cryptocap *
1570 crypto_lookup_kdriver(struct cryptkop *krp)
1572 struct cryptocap *cap;
1575 /* If this request is requeued, it might already have a driver. */
1580 /* Use krp_crid to choose a driver. */
1581 crid = krp->krp_crid;
1582 if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
1583 cap = crypto_checkdriver(crid);
1586 * Driver present, it must support the
1587 * necessary algorithm and, if s/w drivers are
1588 * excluded, it must be registered as
1591 if (!kdriver_suitable(cap, krp) ||
1592 (!crypto_devallowsoft &&
1593 (cap->cc_flags & CRYPTOCAP_F_HARDWARE) == 0))
1598 * No requested driver; select based on crid flags.
1600 if (!crypto_devallowsoft) /* NB: disallow s/w drivers */
1601 crid &= ~CRYPTOCAP_F_SOFTWARE;
1602 cap = crypto_select_kdriver(krp, crid);
1606 krp->krp_cap = cap_ref(cap);
1607 krp->krp_hid = cap->cc_hid;
1613 * Dispatch an asymmetric crypto request.
1616 crypto_kinvoke(struct cryptkop *krp)
1618 struct cryptocap *cap = NULL;
1621 KASSERT(krp != NULL, ("%s: krp == NULL", __func__));
1622 KASSERT(krp->krp_callback != NULL,
1623 ("%s: krp->crp_callback == NULL", __func__));
1625 CRYPTO_DRIVER_LOCK();
1626 cap = crypto_lookup_kdriver(krp);
1628 CRYPTO_DRIVER_UNLOCK();
1629 krp->krp_status = ENODEV;
1635 * If the device is blocked, return ERESTART to requeue it.
1637 if (cap->cc_kqblocked) {
1639 * XXX: Previously this set krp_status to ERESTART and
1640 * invoked crypto_kdone but the caller would still
1643 CRYPTO_DRIVER_UNLOCK();
1647 cap->cc_koperations++;
1648 CRYPTO_DRIVER_UNLOCK();
1649 error = CRYPTODEV_KPROCESS(cap->cc_dev, krp, 0);
1650 if (error == ERESTART) {
1651 CRYPTO_DRIVER_LOCK();
1652 cap->cc_koperations--;
1653 CRYPTO_DRIVER_UNLOCK();
1657 KASSERT(error == 0, ("error %d returned from crypto_kprocess", error));
1662 crypto_task_invoke(void *ctx, int pending)
1664 struct cryptocap *cap;
1665 struct cryptop *crp;
1668 crp = (struct cryptop *)ctx;
1669 cap = crp->crp_session->cap;
1670 result = crypto_invoke(cap, crp, 0);
1671 if (result == ERESTART)
1672 crypto_batch_enqueue(crp);
1676 * Dispatch a crypto request to the appropriate crypto devices.
1679 crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint)
1682 KASSERT(crp != NULL, ("%s: crp == NULL", __func__));
1683 KASSERT(crp->crp_callback != NULL,
1684 ("%s: crp->crp_callback == NULL", __func__));
1685 KASSERT(crp->crp_session != NULL,
1686 ("%s: crp->crp_session == NULL", __func__));
1688 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1689 struct crypto_session_params csp;
1690 crypto_session_t nses;
1693 * Driver has unregistered; migrate the session and return
1694 * an error to the caller so they'll resubmit the op.
1696 * XXX: What if there are more already queued requests for this
1699 * XXX: Real solution is to make sessions refcounted
1700 * and force callers to hold a reference when
1701 * assigning to crp_session. Could maybe change
1702 * crypto_getreq to accept a session pointer to make
1703 * that work. Alternatively, we could abandon the
1704 * notion of rewriting crp_session in requests forcing
1705 * the caller to deal with allocating a new session.
1706 * Perhaps provide a method to allow a crp's session to
1707 * be swapped that callers could use.
1709 csp = crp->crp_session->csp;
1710 crypto_freesession(crp->crp_session);
1713 * XXX: Key pointers may no longer be valid. If we
1714 * really want to support this we need to define the
1715 * KPI such that 'csp' is required to be valid for the
1716 * duration of a session by the caller perhaps.
1718 * XXX: If the keys have been changed this will reuse
1719 * the old keys. This probably suggests making
1720 * rekeying more explicit and updating the key
1721 * pointers in 'csp' when the keys change.
1723 if (crypto_newsession(&nses, &csp,
1724 CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE) == 0)
1725 crp->crp_session = nses;
1727 crp->crp_etype = EAGAIN;
1732 * Invoke the driver to process the request.
1734 return CRYPTODEV_PROCESS(cap->cc_dev, crp, hint);
1739 crypto_destroyreq(struct cryptop *crp)
1743 struct cryptop *crp2;
1744 struct crypto_ret_worker *ret_worker;
1747 TAILQ_FOREACH(crp2, &crp_q, crp_next) {
1748 KASSERT(crp2 != crp,
1749 ("Freeing cryptop from the crypto queue (%p).",
1754 FOREACH_CRYPTO_RETW(ret_worker) {
1755 CRYPTO_RETW_LOCK(ret_worker);
1756 TAILQ_FOREACH(crp2, &ret_worker->crp_ret_q, crp_next) {
1757 KASSERT(crp2 != crp,
1758 ("Freeing cryptop from the return queue (%p).",
1761 CRYPTO_RETW_UNLOCK(ret_worker);
1768 crypto_freereq(struct cryptop *crp)
1773 crypto_destroyreq(crp);
1774 uma_zfree(cryptop_zone, crp);
1778 _crypto_initreq(struct cryptop *crp, crypto_session_t cses)
1780 crp->crp_session = cses;
1784 crypto_initreq(struct cryptop *crp, crypto_session_t cses)
1786 memset(crp, 0, sizeof(*crp));
1787 _crypto_initreq(crp, cses);
1791 crypto_getreq(crypto_session_t cses, int how)
1793 struct cryptop *crp;
1795 MPASS(how == M_WAITOK || how == M_NOWAIT);
1796 crp = uma_zalloc(cryptop_zone, how | M_ZERO);
1798 _crypto_initreq(crp, cses);
1803 * Invoke the callback on behalf of the driver.
1806 crypto_done(struct cryptop *crp)
1808 KASSERT((crp->crp_flags & CRYPTO_F_DONE) == 0,
1809 ("crypto_done: op already done, flags 0x%x", crp->crp_flags));
1810 crp->crp_flags |= CRYPTO_F_DONE;
1811 if (crp->crp_etype != 0)
1812 CRYPTOSTAT_INC(cs_errs);
1815 * CBIMM means unconditionally do the callback immediately;
1816 * CBIFSYNC means do the callback immediately only if the
1817 * operation was done synchronously. Both are used to avoid
1818 * doing extraneous context switches; the latter is mostly
1819 * used with the software crypto driver.
1821 if (!CRYPTOP_ASYNC_KEEPORDER(crp) &&
1822 ((crp->crp_flags & CRYPTO_F_CBIMM) ||
1823 ((crp->crp_flags & CRYPTO_F_CBIFSYNC) &&
1824 (crypto_ses2caps(crp->crp_session) & CRYPTOCAP_F_SYNC)))) {
1826 * Do the callback directly. This is ok when the
1827 * callback routine does very little (e.g. the
1828 * /dev/crypto callback method just does a wakeup).
1830 crp->crp_callback(crp);
1832 struct crypto_ret_worker *ret_worker;
1835 ret_worker = CRYPTO_RETW(crp->crp_retw_id);
1839 * Normal case; queue the callback for the thread.
1841 CRYPTO_RETW_LOCK(ret_worker);
1842 if (CRYPTOP_ASYNC_KEEPORDER(crp)) {
1843 struct cryptop *tmp;
1845 TAILQ_FOREACH_REVERSE(tmp, &ret_worker->crp_ordered_ret_q,
1846 cryptop_q, crp_next) {
1847 if (CRYPTO_SEQ_GT(crp->crp_seq, tmp->crp_seq)) {
1848 TAILQ_INSERT_AFTER(&ret_worker->crp_ordered_ret_q,
1849 tmp, crp, crp_next);
1854 TAILQ_INSERT_HEAD(&ret_worker->crp_ordered_ret_q,
1858 if (crp->crp_seq == ret_worker->reorder_cur_seq)
1862 if (CRYPTO_RETW_EMPTY(ret_worker))
1865 TAILQ_INSERT_TAIL(&ret_worker->crp_ret_q, crp, crp_next);
1869 wakeup_one(&ret_worker->crp_ret_q); /* shared wait channel */
1870 CRYPTO_RETW_UNLOCK(ret_worker);
1875 * Invoke the callback on behalf of the driver.
1878 crypto_kdone(struct cryptkop *krp)
1880 struct crypto_ret_worker *ret_worker;
1881 struct cryptocap *cap;
1883 if (krp->krp_status != 0)
1884 CRYPTOSTAT_INC(cs_kerrs);
1887 CRYPTO_DRIVER_LOCK();
1888 KASSERT(cap->cc_koperations > 0, ("cc_koperations == 0"));
1889 cap->cc_koperations--;
1890 if (cap->cc_koperations == 0 &&
1891 cap->cc_flags & CRYPTOCAP_F_CLEANUP)
1893 CRYPTO_DRIVER_UNLOCK();
1894 krp->krp_cap = NULL;
1898 ret_worker = CRYPTO_RETW(0);
1900 CRYPTO_RETW_LOCK(ret_worker);
1901 if (CRYPTO_RETW_EMPTY(ret_worker))
1902 wakeup_one(&ret_worker->crp_ret_q); /* shared wait channel */
1903 TAILQ_INSERT_TAIL(&ret_worker->crp_ret_kq, krp, krp_next);
1904 CRYPTO_RETW_UNLOCK(ret_worker);
1908 crypto_getfeat(int *featp)
1910 int hid, kalg, feat = 0;
1912 CRYPTO_DRIVER_LOCK();
1913 for (hid = 0; hid < crypto_drivers_size; hid++) {
1914 const struct cryptocap *cap = crypto_drivers[hid];
1917 ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
1918 !crypto_devallowsoft)) {
1921 for (kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
1922 if (cap->cc_kalg[kalg] & CRYPTO_ALG_FLAG_SUPPORTED)
1925 CRYPTO_DRIVER_UNLOCK();
1931 * Terminate a thread at module unload. The process that
1932 * initiated this is waiting for us to signal that we're gone;
1933 * wake it up and exit. We use the driver table lock to insure
1934 * we don't do the wakeup before they're waiting. There is no
1935 * race here because the waiter sleeps on the proc lock for the
1936 * thread so it gets notified at the right time because of an
1937 * extra wakeup that's done in exit1().
1940 crypto_finis(void *chan)
1942 CRYPTO_DRIVER_LOCK();
1944 CRYPTO_DRIVER_UNLOCK();
1949 * Crypto thread, dispatches crypto requests.
1954 struct cryptop *crp, *submit;
1955 struct cryptkop *krp;
1956 struct cryptocap *cap;
1959 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
1960 fpu_kern_thread(FPU_KERN_NORMAL);
1966 * Find the first element in the queue that can be
1967 * processed and look-ahead to see if multiple ops
1968 * are ready for the same driver.
1972 TAILQ_FOREACH(crp, &crp_q, crp_next) {
1973 cap = crp->crp_session->cap;
1975 * Driver cannot disappeared when there is an active
1978 KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1979 __func__, __LINE__));
1980 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1981 /* Op needs to be migrated, process it. */
1986 if (!cap->cc_qblocked) {
1987 if (submit != NULL) {
1989 * We stop on finding another op,
1990 * regardless whether its for the same
1991 * driver or not. We could keep
1992 * searching the queue but it might be
1993 * better to just use a per-driver
1996 if (submit->crp_session->cap == cap)
1997 hint = CRYPTO_HINT_MORE;
2001 if ((submit->crp_flags & CRYPTO_F_BATCH) == 0)
2003 /* keep scanning for more are q'd */
2007 if (submit != NULL) {
2008 TAILQ_REMOVE(&crp_q, submit, crp_next);
2009 cap = submit->crp_session->cap;
2010 KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
2011 __func__, __LINE__));
2013 result = crypto_invoke(cap, submit, hint);
2015 if (result == ERESTART) {
2017 * The driver ran out of resources, mark the
2018 * driver ``blocked'' for cryptop's and put
2019 * the request back in the queue. It would
2020 * best to put the request back where we got
2021 * it but that's hard so for now we put it
2022 * at the front. This should be ok; putting
2023 * it at the end does not work.
2025 cap->cc_qblocked = 1;
2026 TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
2027 CRYPTOSTAT_INC(cs_blocks);
2031 /* As above, but for key ops */
2032 TAILQ_FOREACH(krp, &crp_kq, krp_next) {
2034 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
2036 * Operation needs to be migrated,
2037 * clear krp_cap so a new driver is
2040 krp->krp_cap = NULL;
2044 if (!cap->cc_kqblocked)
2048 TAILQ_REMOVE(&crp_kq, krp, krp_next);
2050 result = crypto_kinvoke(krp);
2052 if (result == ERESTART) {
2054 * The driver ran out of resources, mark the
2055 * driver ``blocked'' for cryptkop's and put
2056 * the request back in the queue. It would
2057 * best to put the request back where we got
2058 * it but that's hard so for now we put it
2059 * at the front. This should be ok; putting
2060 * it at the end does not work.
2062 krp->krp_cap->cc_kqblocked = 1;
2063 TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
2064 CRYPTOSTAT_INC(cs_kblocks);
2068 if (submit == NULL && krp == NULL) {
2070 * Nothing more to be processed. Sleep until we're
2071 * woken because there are more ops to process.
2072 * This happens either by submission or by a driver
2073 * becoming unblocked and notifying us through
2074 * crypto_unblock. Note that when we wakeup we
2075 * start processing each queue again from the
2076 * front. It's not clear that it's important to
2077 * preserve this ordering since ops may finish
2078 * out of order if dispatched to different devices
2079 * and some become blocked while others do not.
2082 msleep(&crp_q, &crypto_q_mtx, PWAIT, "crypto_wait", 0);
2084 if (cryptoproc == NULL)
2086 CRYPTOSTAT_INC(cs_intrs);
2091 crypto_finis(&crp_q);
2095 * Crypto returns thread, does callbacks for processed crypto requests.
2096 * Callbacks are done here, rather than in the crypto drivers, because
2097 * callbacks typically are expensive and would slow interrupt handling.
2100 crypto_ret_proc(struct crypto_ret_worker *ret_worker)
2102 struct cryptop *crpt;
2103 struct cryptkop *krpt;
2105 CRYPTO_RETW_LOCK(ret_worker);
2107 /* Harvest return q's for completed ops */
2108 crpt = TAILQ_FIRST(&ret_worker->crp_ordered_ret_q);
2110 if (crpt->crp_seq == ret_worker->reorder_cur_seq) {
2111 TAILQ_REMOVE(&ret_worker->crp_ordered_ret_q, crpt, crp_next);
2112 ret_worker->reorder_cur_seq++;
2119 crpt = TAILQ_FIRST(&ret_worker->crp_ret_q);
2121 TAILQ_REMOVE(&ret_worker->crp_ret_q, crpt, crp_next);
2124 krpt = TAILQ_FIRST(&ret_worker->crp_ret_kq);
2126 TAILQ_REMOVE(&ret_worker->crp_ret_kq, krpt, krp_next);
2128 if (crpt != NULL || krpt != NULL) {
2129 CRYPTO_RETW_UNLOCK(ret_worker);
2131 * Run callbacks unlocked.
2134 crpt->crp_callback(crpt);
2136 krpt->krp_callback(krpt);
2137 CRYPTO_RETW_LOCK(ret_worker);
2140 * Nothing more to be processed. Sleep until we're
2141 * woken because there are more returns to process.
2143 msleep(&ret_worker->crp_ret_q, &ret_worker->crypto_ret_mtx, PWAIT,
2144 "crypto_ret_wait", 0);
2145 if (ret_worker->cryptoretproc == NULL)
2147 CRYPTOSTAT_INC(cs_rets);
2150 CRYPTO_RETW_UNLOCK(ret_worker);
2152 crypto_finis(&ret_worker->crp_ret_q);
2157 db_show_drivers(void)
2161 db_printf("%12s %4s %4s %8s %2s %2s\n"
2169 for (hid = 0; hid < crypto_drivers_size; hid++) {
2170 const struct cryptocap *cap = crypto_drivers[hid];
2173 db_printf("%-12s %4u %4u %08x %2u %2u\n"
2174 , device_get_nameunit(cap->cc_dev)
2176 , cap->cc_koperations
2184 DB_SHOW_COMMAND(crypto, db_show_crypto)
2186 struct cryptop *crp;
2187 struct crypto_ret_worker *ret_worker;
2192 db_printf("%4s %8s %4s %4s %4s %4s %8s %8s\n",
2193 "HID", "Caps", "Ilen", "Olen", "Etype", "Flags",
2194 "Device", "Callback");
2195 TAILQ_FOREACH(crp, &crp_q, crp_next) {
2196 db_printf("%4u %08x %4u %4u %04x %8p %8p\n"
2197 , crp->crp_session->cap->cc_hid
2198 , (int) crypto_ses2caps(crp->crp_session)
2202 , device_get_nameunit(crp->crp_session->cap->cc_dev)
2206 FOREACH_CRYPTO_RETW(ret_worker) {
2207 db_printf("\n%8s %4s %4s %4s %8s\n",
2208 "ret_worker", "HID", "Etype", "Flags", "Callback");
2209 if (!TAILQ_EMPTY(&ret_worker->crp_ret_q)) {
2210 TAILQ_FOREACH(crp, &ret_worker->crp_ret_q, crp_next) {
2211 db_printf("%8td %4u %4u %04x %8p\n"
2212 , CRYPTO_RETW_ID(ret_worker)
2213 , crp->crp_session->cap->cc_hid
2223 DB_SHOW_COMMAND(kcrypto, db_show_kcrypto)
2225 struct cryptkop *krp;
2226 struct crypto_ret_worker *ret_worker;
2231 db_printf("%4s %5s %4s %4s %8s %4s %8s\n",
2232 "Op", "Status", "#IP", "#OP", "CRID", "HID", "Callback");
2233 TAILQ_FOREACH(krp, &crp_kq, krp_next) {
2234 db_printf("%4u %5u %4u %4u %08x %4u %8p\n"
2237 , krp->krp_iparams, krp->krp_oparams
2238 , krp->krp_crid, krp->krp_hid
2243 ret_worker = CRYPTO_RETW(0);
2244 if (!TAILQ_EMPTY(&ret_worker->crp_ret_q)) {
2245 db_printf("%4s %5s %8s %4s %8s\n",
2246 "Op", "Status", "CRID", "HID", "Callback");
2247 TAILQ_FOREACH(krp, &ret_worker->crp_ret_kq, krp_next) {
2248 db_printf("%4u %5u %08x %4u %8p\n"
2251 , krp->krp_crid, krp->krp_hid
2259 int crypto_modevent(module_t mod, int type, void *unused);
2262 * Initialization code, both for static and dynamic loading.
2263 * Note this is not invoked with the usual MODULE_DECLARE
2264 * mechanism but instead is listed as a dependency by the
2265 * cryptosoft driver. This guarantees proper ordering of
2266 * calls on module load/unload.
2269 crypto_modevent(module_t mod, int type, void *unused)
2275 error = crypto_init();
2276 if (error == 0 && bootverbose)
2277 printf("crypto: <crypto core>\n");
2280 /*XXX disallow if active sessions */
2287 MODULE_VERSION(crypto, 1);
2288 MODULE_DEPEND(crypto, zlib, 1, 1, 1);