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>
31 * Cryptographic Subsystem.
33 * This code is derived from the Openbsd Cryptographic Framework (OCF)
34 * that has the copyright shown below. Very little of the original
39 * The author of this code is Angelos D. Keromytis (angelos@cis.upenn.edu)
41 * This code was written by Angelos D. Keromytis in Athens, Greece, in
42 * February 2000. Network Security Technologies Inc. (NSTI) kindly
43 * supported the development of this code.
45 * Copyright (c) 2000, 2001 Angelos D. Keromytis
47 * Permission to use, copy, and modify this software with or without fee
48 * is hereby granted, provided that this entire notice is included in
49 * all source code copies of any software which is or includes a copy or
50 * modification of this software.
52 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
53 * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
54 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
55 * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
61 #include <sys/param.h>
62 #include <sys/systm.h>
63 #include <sys/counter.h>
64 #include <sys/kernel.h>
65 #include <sys/kthread.h>
66 #include <sys/linker.h>
68 #include <sys/module.h>
69 #include <sys/mutex.h>
70 #include <sys/malloc.h>
73 #include <sys/refcount.h>
76 #include <sys/sysctl.h>
77 #include <sys/taskqueue.h>
82 #include <machine/vmparam.h>
85 #include <crypto/intake.h>
86 #include <opencrypto/cryptodev.h>
87 #include <opencrypto/xform_auth.h>
88 #include <opencrypto/xform_enc.h>
92 #include "cryptodev_if.h"
94 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
95 #include <machine/pcb.h>
98 SDT_PROVIDER_DEFINE(opencrypto);
101 * Crypto drivers register themselves by allocating a slot in the
102 * crypto_drivers table with crypto_get_driverid().
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 */
122 int cc_flags; /* (d) flags */
123 #define CRYPTOCAP_F_CLEANUP 0x80000000 /* needs resource cleanup */
124 int cc_qblocked; /* (q) symmetric q blocked */
125 size_t cc_session_size;
126 volatile int cc_refs;
129 static struct cryptocap **crypto_drivers = NULL;
130 static int crypto_drivers_size = 0;
132 struct crypto_session {
133 struct cryptocap *cap;
134 struct crypto_session_params csp;
136 /* Driver softc follows. */
139 static int crp_sleep = 0;
140 static TAILQ_HEAD(cryptop_q ,cryptop) crp_q; /* request queues */
141 static struct mtx crypto_q_mtx;
142 #define CRYPTO_Q_LOCK() mtx_lock(&crypto_q_mtx)
143 #define CRYPTO_Q_UNLOCK() mtx_unlock(&crypto_q_mtx)
145 SYSCTL_NODE(_kern, OID_AUTO, crypto, CTLFLAG_RW, 0,
146 "In-kernel cryptography");
149 * Taskqueue used to dispatch the crypto requests submitted with
150 * crypto_dispatch_async .
152 static struct taskqueue *crypto_tq;
155 * Crypto seq numbers are operated on with modular arithmetic
157 #define CRYPTO_SEQ_GT(a,b) ((int)((a)-(b)) > 0)
159 struct crypto_ret_worker {
160 struct mtx crypto_ret_mtx;
162 TAILQ_HEAD(,cryptop) crp_ordered_ret_q; /* ordered callback queue for symetric jobs */
163 TAILQ_HEAD(,cryptop) crp_ret_q; /* callback queue for symetric jobs */
165 uint32_t reorder_ops; /* total ordered sym jobs received */
166 uint32_t reorder_cur_seq; /* current sym job dispatched */
170 static struct crypto_ret_worker *crypto_ret_workers = NULL;
172 #define CRYPTO_RETW(i) (&crypto_ret_workers[i])
173 #define CRYPTO_RETW_ID(w) ((w) - crypto_ret_workers)
174 #define FOREACH_CRYPTO_RETW(w) \
175 for (w = crypto_ret_workers; w < crypto_ret_workers + crypto_workers_num; ++w)
177 #define CRYPTO_RETW_LOCK(w) mtx_lock(&w->crypto_ret_mtx)
178 #define CRYPTO_RETW_UNLOCK(w) mtx_unlock(&w->crypto_ret_mtx)
180 static int crypto_workers_num = 0;
181 SYSCTL_INT(_kern_crypto, OID_AUTO, num_workers, CTLFLAG_RDTUN,
182 &crypto_workers_num, 0,
183 "Number of crypto workers used to dispatch crypto jobs");
184 #ifdef COMPAT_FREEBSD12
185 SYSCTL_INT(_kern, OID_AUTO, crypto_workers_num, CTLFLAG_RDTUN,
186 &crypto_workers_num, 0,
187 "Number of crypto workers used to dispatch crypto jobs");
190 static uma_zone_t cryptop_zone;
192 int crypto_devallowsoft = 0;
193 SYSCTL_INT(_kern_crypto, OID_AUTO, allow_soft, CTLFLAG_RWTUN,
194 &crypto_devallowsoft, 0,
195 "Enable use of software crypto by /dev/crypto");
196 #ifdef COMPAT_FREEBSD12
197 SYSCTL_INT(_kern, OID_AUTO, cryptodevallowsoft, CTLFLAG_RWTUN,
198 &crypto_devallowsoft, 0,
199 "Enable/disable use of software crypto by /dev/crypto");
203 bool crypto_destroyreq_check;
204 SYSCTL_BOOL(_kern_crypto, OID_AUTO, destroyreq_check, CTLFLAG_RWTUN,
205 &crypto_destroyreq_check, 0,
206 "Enable checks when destroying a request");
209 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
211 static void crypto_dispatch_thread(void *arg);
212 static struct thread *cryptotd;
213 static void crypto_ret_thread(void *arg);
214 static void crypto_destroy(void);
215 static int crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint);
216 static void crypto_task_invoke(void *ctx, int pending);
217 static void crypto_batch_enqueue(struct cryptop *crp);
219 static counter_u64_t cryptostats[sizeof(struct cryptostats) / sizeof(uint64_t)];
220 SYSCTL_COUNTER_U64_ARRAY(_kern_crypto, OID_AUTO, stats, CTLFLAG_RW,
221 cryptostats, nitems(cryptostats),
222 "Crypto system statistics");
224 #define CRYPTOSTAT_INC(stat) do { \
226 cryptostats[offsetof(struct cryptostats, stat) / sizeof(uint64_t)],\
231 cryptostats_init(void *arg __unused)
233 COUNTER_ARRAY_ALLOC(cryptostats, nitems(cryptostats), M_WAITOK);
235 SYSINIT(cryptostats_init, SI_SUB_COUNTER, SI_ORDER_ANY, cryptostats_init, NULL);
238 cryptostats_fini(void *arg __unused)
240 COUNTER_ARRAY_FREE(cryptostats, nitems(cryptostats));
242 SYSUNINIT(cryptostats_fini, SI_SUB_COUNTER, SI_ORDER_ANY, cryptostats_fini,
245 /* Try to avoid directly exposing the key buffer as a symbol */
246 static struct keybuf *keybuf;
248 static struct keybuf empty_keybuf = {
252 /* Obtain the key buffer from boot metadata */
258 kmdp = preload_search_by_type("elf kernel");
261 kmdp = preload_search_by_type("elf64 kernel");
263 keybuf = (struct keybuf *)preload_search_info(kmdp,
264 MODINFO_METADATA | MODINFOMD_KEYBUF);
267 keybuf = &empty_keybuf;
270 /* It'd be nice if we could store these in some kind of secure memory... */
278 static struct cryptocap *
279 cap_ref(struct cryptocap *cap)
282 refcount_acquire(&cap->cc_refs);
287 cap_rele(struct cryptocap *cap)
290 if (refcount_release(&cap->cc_refs) == 0)
293 KASSERT(cap->cc_sessions == 0,
294 ("freeing crypto driver with active sessions"));
296 free(cap, M_CRYPTO_DATA);
302 struct crypto_ret_worker *ret_worker;
306 mtx_init(&crypto_drivers_mtx, "crypto driver table", NULL, MTX_DEF);
309 mtx_init(&crypto_q_mtx, "crypto op queues", NULL, MTX_DEF);
311 cryptop_zone = uma_zcreate("cryptop",
312 sizeof(struct cryptop), NULL, NULL, NULL, NULL,
313 UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
315 crypto_drivers_size = CRYPTO_DRIVERS_INITIAL;
316 crypto_drivers = malloc(crypto_drivers_size *
317 sizeof(struct cryptocap), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
319 if (crypto_workers_num < 1 || crypto_workers_num > mp_ncpus)
320 crypto_workers_num = mp_ncpus;
322 crypto_tq = taskqueue_create("crypto", M_WAITOK | M_ZERO,
323 taskqueue_thread_enqueue, &crypto_tq);
325 taskqueue_start_threads(&crypto_tq, crypto_workers_num, PRI_MIN_KERN,
329 error = kproc_kthread_add(crypto_dispatch_thread, NULL, &p, &cryptotd,
330 0, 0, "crypto", "crypto");
332 printf("crypto_init: cannot start crypto thread; error %d",
337 crypto_ret_workers = mallocarray(crypto_workers_num,
338 sizeof(struct crypto_ret_worker), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
340 FOREACH_CRYPTO_RETW(ret_worker) {
341 TAILQ_INIT(&ret_worker->crp_ordered_ret_q);
342 TAILQ_INIT(&ret_worker->crp_ret_q);
344 ret_worker->reorder_ops = 0;
345 ret_worker->reorder_cur_seq = 0;
347 mtx_init(&ret_worker->crypto_ret_mtx, "crypto return queues",
350 error = kthread_add(crypto_ret_thread, ret_worker, p,
351 &ret_worker->td, 0, 0, "crypto returns %td",
352 CRYPTO_RETW_ID(ret_worker));
354 printf("crypto_init: cannot start cryptoret thread; error %d",
369 * Signal a crypto thread to terminate. We use the driver
370 * table lock to synchronize the sleep/wakeups so that we
371 * are sure the threads have terminated before we release
372 * the data structures they use. See crypto_finis below
373 * for the other half of this song-and-dance.
376 crypto_terminate(struct thread **tdp, void *q)
380 mtx_assert(&crypto_drivers_mtx, MA_OWNED);
385 mtx_sleep(td, &crypto_drivers_mtx, PWAIT, "crypto_destroy", 0);
390 hmac_init_pad(const struct auth_hash *axf, const char *key, int klen,
391 void *auth_ctx, uint8_t padval)
393 uint8_t hmac_key[HMAC_MAX_BLOCK_LEN];
396 KASSERT(axf->blocksize <= sizeof(hmac_key),
397 ("Invalid HMAC block size %d", axf->blocksize));
400 * If the key is larger than the block size, use the digest of
401 * the key as the key instead.
403 memset(hmac_key, 0, sizeof(hmac_key));
404 if (klen > axf->blocksize) {
406 axf->Update(auth_ctx, key, klen);
407 axf->Final(hmac_key, auth_ctx);
408 klen = axf->hashsize;
410 memcpy(hmac_key, key, klen);
412 for (i = 0; i < axf->blocksize; i++)
413 hmac_key[i] ^= padval;
416 axf->Update(auth_ctx, hmac_key, axf->blocksize);
417 explicit_bzero(hmac_key, sizeof(hmac_key));
421 hmac_init_ipad(const struct auth_hash *axf, const char *key, int klen,
425 hmac_init_pad(axf, key, klen, auth_ctx, HMAC_IPAD_VAL);
429 hmac_init_opad(const struct auth_hash *axf, const char *key, int klen,
433 hmac_init_pad(axf, key, klen, auth_ctx, HMAC_OPAD_VAL);
439 struct crypto_ret_worker *ret_worker;
443 * Terminate any crypto threads.
445 if (crypto_tq != NULL)
446 taskqueue_drain_all(crypto_tq);
447 CRYPTO_DRIVER_LOCK();
448 crypto_terminate(&cryptotd, &crp_q);
449 FOREACH_CRYPTO_RETW(ret_worker)
450 crypto_terminate(&ret_worker->td, &ret_worker->crp_ret_q);
451 CRYPTO_DRIVER_UNLOCK();
453 /* XXX flush queues??? */
456 * Reclaim dynamically allocated resources.
458 for (i = 0; i < crypto_drivers_size; i++) {
459 if (crypto_drivers[i] != NULL)
460 cap_rele(crypto_drivers[i]);
462 free(crypto_drivers, M_CRYPTO_DATA);
464 if (cryptop_zone != NULL)
465 uma_zdestroy(cryptop_zone);
466 mtx_destroy(&crypto_q_mtx);
467 FOREACH_CRYPTO_RETW(ret_worker)
468 mtx_destroy(&ret_worker->crypto_ret_mtx);
469 free(crypto_ret_workers, M_CRYPTO_DATA);
470 if (crypto_tq != NULL)
471 taskqueue_free(crypto_tq);
472 mtx_destroy(&crypto_drivers_mtx);
476 crypto_ses2hid(crypto_session_t crypto_session)
478 return (crypto_session->cap->cc_hid);
482 crypto_ses2caps(crypto_session_t crypto_session)
484 return (crypto_session->cap->cc_flags & 0xff000000);
488 crypto_get_driver_session(crypto_session_t crypto_session)
490 return (crypto_session + 1);
493 const struct crypto_session_params *
494 crypto_get_params(crypto_session_t crypto_session)
496 return (&crypto_session->csp);
499 const struct auth_hash *
500 crypto_auth_hash(const struct crypto_session_params *csp)
503 switch (csp->csp_auth_alg) {
504 case CRYPTO_SHA1_HMAC:
505 return (&auth_hash_hmac_sha1);
506 case CRYPTO_SHA2_224_HMAC:
507 return (&auth_hash_hmac_sha2_224);
508 case CRYPTO_SHA2_256_HMAC:
509 return (&auth_hash_hmac_sha2_256);
510 case CRYPTO_SHA2_384_HMAC:
511 return (&auth_hash_hmac_sha2_384);
512 case CRYPTO_SHA2_512_HMAC:
513 return (&auth_hash_hmac_sha2_512);
514 case CRYPTO_NULL_HMAC:
515 return (&auth_hash_null);
516 case CRYPTO_RIPEMD160_HMAC:
517 return (&auth_hash_hmac_ripemd_160);
518 case CRYPTO_RIPEMD160:
519 return (&auth_hash_ripemd_160);
521 return (&auth_hash_sha1);
522 case CRYPTO_SHA2_224:
523 return (&auth_hash_sha2_224);
524 case CRYPTO_SHA2_256:
525 return (&auth_hash_sha2_256);
526 case CRYPTO_SHA2_384:
527 return (&auth_hash_sha2_384);
528 case CRYPTO_SHA2_512:
529 return (&auth_hash_sha2_512);
530 case CRYPTO_AES_NIST_GMAC:
531 switch (csp->csp_auth_klen) {
533 return (&auth_hash_nist_gmac_aes_128);
535 return (&auth_hash_nist_gmac_aes_192);
537 return (&auth_hash_nist_gmac_aes_256);
542 return (&auth_hash_blake2b);
544 return (&auth_hash_blake2s);
545 case CRYPTO_POLY1305:
546 return (&auth_hash_poly1305);
547 case CRYPTO_AES_CCM_CBC_MAC:
548 switch (csp->csp_auth_klen) {
550 return (&auth_hash_ccm_cbc_mac_128);
552 return (&auth_hash_ccm_cbc_mac_192);
554 return (&auth_hash_ccm_cbc_mac_256);
563 const struct enc_xform *
564 crypto_cipher(const struct crypto_session_params *csp)
567 switch (csp->csp_cipher_alg) {
569 return (&enc_xform_aes_cbc);
571 return (&enc_xform_aes_xts);
573 return (&enc_xform_aes_icm);
574 case CRYPTO_AES_NIST_GCM_16:
575 return (&enc_xform_aes_nist_gcm);
576 case CRYPTO_CAMELLIA_CBC:
577 return (&enc_xform_camellia);
578 case CRYPTO_NULL_CBC:
579 return (&enc_xform_null);
580 case CRYPTO_CHACHA20:
581 return (&enc_xform_chacha20);
582 case CRYPTO_AES_CCM_16:
583 return (&enc_xform_ccm);
584 case CRYPTO_CHACHA20_POLY1305:
585 return (&enc_xform_chacha20_poly1305);
586 case CRYPTO_XCHACHA20_POLY1305:
587 return (&enc_xform_xchacha20_poly1305);
593 static struct cryptocap *
594 crypto_checkdriver(uint32_t hid)
597 return (hid >= crypto_drivers_size ? NULL : crypto_drivers[hid]);
601 * Select a driver for a new session that supports the specified
602 * algorithms and, optionally, is constrained according to the flags.
604 static struct cryptocap *
605 crypto_select_driver(const struct crypto_session_params *csp, int flags)
607 struct cryptocap *cap, *best;
608 int best_match, error, hid;
610 CRYPTO_DRIVER_ASSERT();
613 for (hid = 0; hid < crypto_drivers_size; hid++) {
615 * If there is no driver for this slot, or the driver
616 * is not appropriate (hardware or software based on
619 cap = crypto_drivers[hid];
621 (cap->cc_flags & flags) == 0)
624 error = CRYPTODEV_PROBESESSION(cap->cc_dev, csp);
629 * Use the driver with the highest probe value.
630 * Hardware drivers use a higher probe value than
631 * software. In case of a tie, prefer the driver with
632 * the fewest active sessions.
634 if (best == NULL || error > best_match ||
635 (error == best_match &&
636 cap->cc_sessions < best->cc_sessions)) {
644 static enum alg_type {
652 [CRYPTO_SHA1_HMAC] = ALG_KEYED_DIGEST,
653 [CRYPTO_RIPEMD160_HMAC] = ALG_KEYED_DIGEST,
654 [CRYPTO_AES_CBC] = ALG_CIPHER,
655 [CRYPTO_SHA1] = ALG_DIGEST,
656 [CRYPTO_NULL_HMAC] = ALG_DIGEST,
657 [CRYPTO_NULL_CBC] = ALG_CIPHER,
658 [CRYPTO_DEFLATE_COMP] = ALG_COMPRESSION,
659 [CRYPTO_SHA2_256_HMAC] = ALG_KEYED_DIGEST,
660 [CRYPTO_SHA2_384_HMAC] = ALG_KEYED_DIGEST,
661 [CRYPTO_SHA2_512_HMAC] = ALG_KEYED_DIGEST,
662 [CRYPTO_CAMELLIA_CBC] = ALG_CIPHER,
663 [CRYPTO_AES_XTS] = ALG_CIPHER,
664 [CRYPTO_AES_ICM] = ALG_CIPHER,
665 [CRYPTO_AES_NIST_GMAC] = ALG_KEYED_DIGEST,
666 [CRYPTO_AES_NIST_GCM_16] = ALG_AEAD,
667 [CRYPTO_BLAKE2B] = ALG_KEYED_DIGEST,
668 [CRYPTO_BLAKE2S] = ALG_KEYED_DIGEST,
669 [CRYPTO_CHACHA20] = ALG_CIPHER,
670 [CRYPTO_SHA2_224_HMAC] = ALG_KEYED_DIGEST,
671 [CRYPTO_RIPEMD160] = ALG_DIGEST,
672 [CRYPTO_SHA2_224] = ALG_DIGEST,
673 [CRYPTO_SHA2_256] = ALG_DIGEST,
674 [CRYPTO_SHA2_384] = ALG_DIGEST,
675 [CRYPTO_SHA2_512] = ALG_DIGEST,
676 [CRYPTO_POLY1305] = ALG_KEYED_DIGEST,
677 [CRYPTO_AES_CCM_CBC_MAC] = ALG_KEYED_DIGEST,
678 [CRYPTO_AES_CCM_16] = ALG_AEAD,
679 [CRYPTO_CHACHA20_POLY1305] = ALG_AEAD,
680 [CRYPTO_XCHACHA20_POLY1305] = ALG_AEAD,
687 if (alg < nitems(alg_types))
688 return (alg_types[alg]);
693 alg_is_compression(int alg)
696 return (alg_type(alg) == ALG_COMPRESSION);
700 alg_is_cipher(int alg)
703 return (alg_type(alg) == ALG_CIPHER);
707 alg_is_digest(int alg)
710 return (alg_type(alg) == ALG_DIGEST ||
711 alg_type(alg) == ALG_KEYED_DIGEST);
715 alg_is_keyed_digest(int alg)
718 return (alg_type(alg) == ALG_KEYED_DIGEST);
725 return (alg_type(alg) == ALG_AEAD);
729 ccm_tag_length_valid(int len)
746 #define SUPPORTED_SES (CSP_F_SEPARATE_OUTPUT | CSP_F_SEPARATE_AAD | CSP_F_ESN)
748 /* Various sanity checks on crypto session parameters. */
750 check_csp(const struct crypto_session_params *csp)
752 const struct auth_hash *axf;
754 /* Mode-independent checks. */
755 if ((csp->csp_flags & ~(SUPPORTED_SES)) != 0)
757 if (csp->csp_ivlen < 0 || csp->csp_cipher_klen < 0 ||
758 csp->csp_auth_klen < 0 || csp->csp_auth_mlen < 0)
760 if (csp->csp_auth_key != NULL && csp->csp_auth_klen == 0)
762 if (csp->csp_cipher_key != NULL && csp->csp_cipher_klen == 0)
765 switch (csp->csp_mode) {
766 case CSP_MODE_COMPRESS:
767 if (!alg_is_compression(csp->csp_cipher_alg))
769 if (csp->csp_flags & CSP_F_SEPARATE_OUTPUT)
771 if (csp->csp_flags & CSP_F_SEPARATE_AAD)
773 if (csp->csp_cipher_klen != 0 || csp->csp_ivlen != 0 ||
774 csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0 ||
775 csp->csp_auth_mlen != 0)
778 case CSP_MODE_CIPHER:
779 if (!alg_is_cipher(csp->csp_cipher_alg))
781 if (csp->csp_flags & CSP_F_SEPARATE_AAD)
783 if (csp->csp_cipher_alg != CRYPTO_NULL_CBC) {
784 if (csp->csp_cipher_klen == 0)
786 if (csp->csp_ivlen == 0)
789 if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
791 if (csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0 ||
792 csp->csp_auth_mlen != 0)
795 case CSP_MODE_DIGEST:
796 if (csp->csp_cipher_alg != 0 || csp->csp_cipher_klen != 0)
799 if (csp->csp_flags & CSP_F_SEPARATE_AAD)
802 /* IV is optional for digests (e.g. GMAC). */
803 switch (csp->csp_auth_alg) {
804 case CRYPTO_AES_CCM_CBC_MAC:
805 if (csp->csp_ivlen < 7 || csp->csp_ivlen > 13)
808 case CRYPTO_AES_NIST_GMAC:
809 if (csp->csp_ivlen != AES_GCM_IV_LEN)
813 if (csp->csp_ivlen != 0)
818 if (!alg_is_digest(csp->csp_auth_alg))
821 /* Key is optional for BLAKE2 digests. */
822 if (csp->csp_auth_alg == CRYPTO_BLAKE2B ||
823 csp->csp_auth_alg == CRYPTO_BLAKE2S)
825 else if (alg_is_keyed_digest(csp->csp_auth_alg)) {
826 if (csp->csp_auth_klen == 0)
829 if (csp->csp_auth_klen != 0)
832 if (csp->csp_auth_mlen != 0) {
833 axf = crypto_auth_hash(csp);
834 if (axf == NULL || csp->csp_auth_mlen > axf->hashsize)
837 if (csp->csp_auth_alg == CRYPTO_AES_CCM_CBC_MAC &&
838 !ccm_tag_length_valid(csp->csp_auth_mlen))
843 if (!alg_is_aead(csp->csp_cipher_alg))
845 if (csp->csp_cipher_klen == 0)
847 if (csp->csp_ivlen == 0 ||
848 csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
850 if (csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0)
853 switch (csp->csp_cipher_alg) {
854 case CRYPTO_AES_CCM_16:
855 if (csp->csp_auth_mlen != 0 &&
856 !ccm_tag_length_valid(csp->csp_auth_mlen))
859 if (csp->csp_ivlen < 7 || csp->csp_ivlen > 13)
862 case CRYPTO_AES_NIST_GCM_16:
863 if (csp->csp_auth_mlen > AES_GMAC_HASH_LEN)
866 if (csp->csp_ivlen != AES_GCM_IV_LEN)
869 case CRYPTO_CHACHA20_POLY1305:
870 if (csp->csp_ivlen != 8 && csp->csp_ivlen != 12)
872 if (csp->csp_auth_mlen > POLY1305_HASH_LEN)
875 case CRYPTO_XCHACHA20_POLY1305:
876 if (csp->csp_ivlen != XCHACHA20_POLY1305_IV_LEN)
878 if (csp->csp_auth_mlen > POLY1305_HASH_LEN)
884 if (!alg_is_cipher(csp->csp_cipher_alg))
886 if (csp->csp_cipher_alg != CRYPTO_NULL_CBC) {
887 if (csp->csp_cipher_klen == 0)
889 if (csp->csp_ivlen == 0)
892 if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
894 if (!alg_is_digest(csp->csp_auth_alg))
897 /* Key is optional for BLAKE2 digests. */
898 if (csp->csp_auth_alg == CRYPTO_BLAKE2B ||
899 csp->csp_auth_alg == CRYPTO_BLAKE2S)
901 else if (alg_is_keyed_digest(csp->csp_auth_alg)) {
902 if (csp->csp_auth_klen == 0)
905 if (csp->csp_auth_klen != 0)
908 if (csp->csp_auth_mlen != 0) {
909 axf = crypto_auth_hash(csp);
910 if (axf == NULL || csp->csp_auth_mlen > axf->hashsize)
922 * Delete a session after it has been detached from its driver.
925 crypto_deletesession(crypto_session_t cses)
927 struct cryptocap *cap;
931 zfree(cses, M_CRYPTO_DATA);
933 CRYPTO_DRIVER_LOCK();
935 if (cap->cc_sessions == 0 && cap->cc_flags & CRYPTOCAP_F_CLEANUP)
937 CRYPTO_DRIVER_UNLOCK();
942 * Create a new session. The crid argument specifies a crypto
943 * driver to use or constraints on a driver to select (hardware
944 * only, software only, either). Whatever driver is selected
945 * must be capable of the requested crypto algorithms.
948 crypto_newsession(crypto_session_t *cses,
949 const struct crypto_session_params *csp, int crid)
951 static uint64_t sessid = 0;
952 crypto_session_t res;
953 struct cryptocap *cap;
961 CRYPTO_DRIVER_LOCK();
962 if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
964 * Use specified driver; verify it is capable.
966 cap = crypto_checkdriver(crid);
967 if (cap != NULL && CRYPTODEV_PROBESESSION(cap->cc_dev, csp) > 0)
971 * No requested driver; select based on crid flags.
973 cap = crypto_select_driver(csp, crid);
976 CRYPTO_DRIVER_UNLOCK();
977 CRYPTDEB("no driver");
982 CRYPTO_DRIVER_UNLOCK();
984 /* Allocate a single block for the generic session and driver softc. */
985 res = malloc(sizeof(*res) + cap->cc_session_size, M_CRYPTO_DATA,
989 res->id = atomic_fetchadd_64(&sessid, 1);
991 /* Call the driver initialization routine. */
992 err = CRYPTODEV_NEWSESSION(cap->cc_dev, res, csp);
994 CRYPTDEB("dev newsession failed: %d", err);
995 crypto_deletesession(res);
1004 * Delete an existing session (or a reserved session on an unregistered
1008 crypto_freesession(crypto_session_t cses)
1010 struct cryptocap *cap;
1017 /* Call the driver cleanup routine, if available. */
1018 CRYPTODEV_FREESESSION(cap->cc_dev, cses);
1020 crypto_deletesession(cses);
1024 * Return a new driver id. Registers a driver with the system so that
1025 * it can be probed by subsequent sessions.
1028 crypto_get_driverid(device_t dev, size_t sessionsize, int flags)
1030 struct cryptocap *cap, **newdrv;
1033 if ((flags & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
1035 "no flags specified when registering driver\n");
1039 cap = malloc(sizeof(*cap), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
1041 cap->cc_session_size = sessionsize;
1042 cap->cc_flags = flags;
1043 refcount_init(&cap->cc_refs, 1);
1045 CRYPTO_DRIVER_LOCK();
1047 for (i = 0; i < crypto_drivers_size; i++) {
1048 if (crypto_drivers[i] == NULL)
1052 if (i < crypto_drivers_size)
1055 /* Out of entries, allocate some more. */
1057 if (2 * crypto_drivers_size <= crypto_drivers_size) {
1058 CRYPTO_DRIVER_UNLOCK();
1059 printf("crypto: driver count wraparound!\n");
1063 CRYPTO_DRIVER_UNLOCK();
1065 newdrv = malloc(2 * crypto_drivers_size *
1066 sizeof(*crypto_drivers), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
1068 CRYPTO_DRIVER_LOCK();
1069 memcpy(newdrv, crypto_drivers,
1070 crypto_drivers_size * sizeof(*crypto_drivers));
1072 crypto_drivers_size *= 2;
1074 free(crypto_drivers, M_CRYPTO_DATA);
1075 crypto_drivers = newdrv;
1079 crypto_drivers[i] = cap;
1080 CRYPTO_DRIVER_UNLOCK();
1083 printf("crypto: assign %s driver id %u, flags 0x%x\n",
1084 device_get_nameunit(dev), i, flags);
1090 * Lookup a driver by name. We match against the full device
1091 * name and unit, and against just the name. The latter gives
1092 * us a simple widlcarding by device name. On success return the
1093 * driver/hardware identifier; otherwise return -1.
1096 crypto_find_driver(const char *match)
1098 struct cryptocap *cap;
1099 int i, len = strlen(match);
1101 CRYPTO_DRIVER_LOCK();
1102 for (i = 0; i < crypto_drivers_size; i++) {
1103 if (crypto_drivers[i] == NULL)
1105 cap = crypto_drivers[i];
1106 if (strncmp(match, device_get_nameunit(cap->cc_dev), len) == 0 ||
1107 strncmp(match, device_get_name(cap->cc_dev), len) == 0) {
1108 CRYPTO_DRIVER_UNLOCK();
1112 CRYPTO_DRIVER_UNLOCK();
1117 * Return the device_t for the specified driver or NULL
1118 * if the driver identifier is invalid.
1121 crypto_find_device_byhid(int hid)
1123 struct cryptocap *cap;
1127 CRYPTO_DRIVER_LOCK();
1128 cap = crypto_checkdriver(hid);
1131 CRYPTO_DRIVER_UNLOCK();
1136 * Return the device/driver capabilities.
1139 crypto_getcaps(int hid)
1141 struct cryptocap *cap;
1145 CRYPTO_DRIVER_LOCK();
1146 cap = crypto_checkdriver(hid);
1148 flags = cap->cc_flags;
1149 CRYPTO_DRIVER_UNLOCK();
1154 * Unregister all algorithms associated with a crypto driver.
1155 * If there are pending sessions using it, leave enough information
1156 * around so that subsequent calls using those sessions will
1157 * correctly detect the driver has been unregistered and reroute
1161 crypto_unregister_all(uint32_t driverid)
1163 struct cryptocap *cap;
1165 CRYPTO_DRIVER_LOCK();
1166 cap = crypto_checkdriver(driverid);
1168 CRYPTO_DRIVER_UNLOCK();
1172 cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
1173 crypto_drivers[driverid] = NULL;
1176 * XXX: This doesn't do anything to kick sessions that
1177 * have no pending operations.
1179 while (cap->cc_sessions != 0)
1180 mtx_sleep(cap, &crypto_drivers_mtx, 0, "cryunreg", 0);
1181 CRYPTO_DRIVER_UNLOCK();
1188 * Clear blockage on a driver. The what parameter indicates whether
1189 * the driver is now ready for cryptop's and/or cryptokop's.
1192 crypto_unblock(uint32_t driverid, int what)
1194 struct cryptocap *cap;
1198 cap = crypto_checkdriver(driverid);
1200 if (what & CRYPTO_SYMQ)
1201 cap->cc_qblocked = 0;
1213 crypto_buffer_len(struct crypto_buffer *cb)
1215 switch (cb->cb_type) {
1216 case CRYPTO_BUF_CONTIG:
1217 return (cb->cb_buf_len);
1218 case CRYPTO_BUF_MBUF:
1219 if (cb->cb_mbuf->m_flags & M_PKTHDR)
1220 return (cb->cb_mbuf->m_pkthdr.len);
1221 return (m_length(cb->cb_mbuf, NULL));
1222 case CRYPTO_BUF_SINGLE_MBUF:
1223 return (cb->cb_mbuf->m_len);
1224 case CRYPTO_BUF_VMPAGE:
1225 return (cb->cb_vm_page_len);
1226 case CRYPTO_BUF_UIO:
1227 return (cb->cb_uio->uio_resid);
1234 /* Various sanity checks on crypto requests. */
1236 cb_sanity(struct crypto_buffer *cb, const char *name)
1238 KASSERT(cb->cb_type > CRYPTO_BUF_NONE && cb->cb_type <= CRYPTO_BUF_LAST,
1239 ("incoming crp with invalid %s buffer type", name));
1240 switch (cb->cb_type) {
1241 case CRYPTO_BUF_CONTIG:
1242 KASSERT(cb->cb_buf_len >= 0,
1243 ("incoming crp with -ve %s buffer length", name));
1245 case CRYPTO_BUF_VMPAGE:
1246 KASSERT(CRYPTO_HAS_VMPAGE,
1247 ("incoming crp uses dmap on supported arch"));
1248 KASSERT(cb->cb_vm_page_len >= 0,
1249 ("incoming crp with -ve %s buffer length", name));
1250 KASSERT(cb->cb_vm_page_offset >= 0,
1251 ("incoming crp with -ve %s buffer offset", name));
1252 KASSERT(cb->cb_vm_page_offset < PAGE_SIZE,
1253 ("incoming crp with %s buffer offset greater than page size"
1262 crp_sanity(struct cryptop *crp)
1264 struct crypto_session_params *csp;
1265 struct crypto_buffer *out;
1266 size_t ilen, len, olen;
1268 KASSERT(crp->crp_session != NULL, ("incoming crp without a session"));
1269 KASSERT(crp->crp_obuf.cb_type >= CRYPTO_BUF_NONE &&
1270 crp->crp_obuf.cb_type <= CRYPTO_BUF_LAST,
1271 ("incoming crp with invalid output buffer type"));
1272 KASSERT(crp->crp_etype == 0, ("incoming crp with error"));
1273 KASSERT(!(crp->crp_flags & CRYPTO_F_DONE),
1274 ("incoming crp already done"));
1276 csp = &crp->crp_session->csp;
1277 cb_sanity(&crp->crp_buf, "input");
1278 ilen = crypto_buffer_len(&crp->crp_buf);
1281 if (csp->csp_flags & CSP_F_SEPARATE_OUTPUT) {
1282 if (crp->crp_obuf.cb_type != CRYPTO_BUF_NONE) {
1283 cb_sanity(&crp->crp_obuf, "output");
1284 out = &crp->crp_obuf;
1285 olen = crypto_buffer_len(out);
1288 KASSERT(crp->crp_obuf.cb_type == CRYPTO_BUF_NONE,
1289 ("incoming crp with separate output buffer "
1290 "but no session support"));
1292 switch (csp->csp_mode) {
1293 case CSP_MODE_COMPRESS:
1294 KASSERT(crp->crp_op == CRYPTO_OP_COMPRESS ||
1295 crp->crp_op == CRYPTO_OP_DECOMPRESS,
1296 ("invalid compression op %x", crp->crp_op));
1298 case CSP_MODE_CIPHER:
1299 KASSERT(crp->crp_op == CRYPTO_OP_ENCRYPT ||
1300 crp->crp_op == CRYPTO_OP_DECRYPT,
1301 ("invalid cipher op %x", crp->crp_op));
1303 case CSP_MODE_DIGEST:
1304 KASSERT(crp->crp_op == CRYPTO_OP_COMPUTE_DIGEST ||
1305 crp->crp_op == CRYPTO_OP_VERIFY_DIGEST,
1306 ("invalid digest op %x", crp->crp_op));
1309 KASSERT(crp->crp_op ==
1310 (CRYPTO_OP_ENCRYPT | CRYPTO_OP_COMPUTE_DIGEST) ||
1312 (CRYPTO_OP_DECRYPT | CRYPTO_OP_VERIFY_DIGEST),
1313 ("invalid AEAD op %x", crp->crp_op));
1314 KASSERT(crp->crp_flags & CRYPTO_F_IV_SEPARATE,
1315 ("AEAD without a separate IV"));
1318 KASSERT(crp->crp_op ==
1319 (CRYPTO_OP_ENCRYPT | CRYPTO_OP_COMPUTE_DIGEST) ||
1321 (CRYPTO_OP_DECRYPT | CRYPTO_OP_VERIFY_DIGEST),
1322 ("invalid ETA op %x", crp->crp_op));
1325 if (csp->csp_mode == CSP_MODE_AEAD || csp->csp_mode == CSP_MODE_ETA) {
1326 if (crp->crp_aad == NULL) {
1327 KASSERT(crp->crp_aad_start == 0 ||
1328 crp->crp_aad_start < ilen,
1329 ("invalid AAD start"));
1330 KASSERT(crp->crp_aad_length != 0 ||
1331 crp->crp_aad_start == 0,
1332 ("AAD with zero length and non-zero start"));
1333 KASSERT(crp->crp_aad_length == 0 ||
1334 crp->crp_aad_start + crp->crp_aad_length <= ilen,
1335 ("AAD outside input length"));
1337 KASSERT(csp->csp_flags & CSP_F_SEPARATE_AAD,
1338 ("session doesn't support separate AAD buffer"));
1339 KASSERT(crp->crp_aad_start == 0,
1340 ("separate AAD buffer with non-zero AAD start"));
1341 KASSERT(crp->crp_aad_length != 0,
1342 ("separate AAD buffer with zero length"));
1345 KASSERT(crp->crp_aad == NULL && crp->crp_aad_start == 0 &&
1346 crp->crp_aad_length == 0,
1347 ("AAD region in request not supporting AAD"));
1349 if (csp->csp_ivlen == 0) {
1350 KASSERT((crp->crp_flags & CRYPTO_F_IV_SEPARATE) == 0,
1351 ("IV_SEPARATE set when IV isn't used"));
1352 KASSERT(crp->crp_iv_start == 0,
1353 ("crp_iv_start set when IV isn't used"));
1354 } else if (crp->crp_flags & CRYPTO_F_IV_SEPARATE) {
1355 KASSERT(crp->crp_iv_start == 0,
1356 ("IV_SEPARATE used with non-zero IV start"));
1358 KASSERT(crp->crp_iv_start < ilen,
1359 ("invalid IV start"));
1360 KASSERT(crp->crp_iv_start + csp->csp_ivlen <= ilen,
1361 ("IV outside buffer length"));
1363 /* XXX: payload_start of 0 should always be < ilen? */
1364 KASSERT(crp->crp_payload_start == 0 ||
1365 crp->crp_payload_start < ilen,
1366 ("invalid payload start"));
1367 KASSERT(crp->crp_payload_start + crp->crp_payload_length <=
1368 ilen, ("payload outside input buffer"));
1370 KASSERT(crp->crp_payload_output_start == 0,
1371 ("payload output start non-zero without output buffer"));
1372 } else if (csp->csp_mode == CSP_MODE_DIGEST) {
1373 KASSERT(!(crp->crp_op & CRYPTO_OP_VERIFY_DIGEST),
1374 ("digest verify with separate output buffer"));
1375 KASSERT(crp->crp_payload_output_start == 0,
1376 ("digest operation with non-zero payload output start"));
1378 KASSERT(crp->crp_payload_output_start == 0 ||
1379 crp->crp_payload_output_start < olen,
1380 ("invalid payload output start"));
1381 KASSERT(crp->crp_payload_output_start +
1382 crp->crp_payload_length <= olen,
1383 ("payload outside output buffer"));
1385 if (csp->csp_mode == CSP_MODE_DIGEST ||
1386 csp->csp_mode == CSP_MODE_AEAD || csp->csp_mode == CSP_MODE_ETA) {
1387 if (crp->crp_op & CRYPTO_OP_VERIFY_DIGEST)
1391 KASSERT(crp->crp_digest_start == 0 ||
1392 crp->crp_digest_start < len,
1393 ("invalid digest start"));
1394 /* XXX: For the mlen == 0 case this check isn't perfect. */
1395 KASSERT(crp->crp_digest_start + csp->csp_auth_mlen <= len,
1396 ("digest outside buffer"));
1398 KASSERT(crp->crp_digest_start == 0,
1399 ("non-zero digest start for request without a digest"));
1401 if (csp->csp_cipher_klen != 0)
1402 KASSERT(csp->csp_cipher_key != NULL ||
1403 crp->crp_cipher_key != NULL,
1404 ("cipher request without a key"));
1405 if (csp->csp_auth_klen != 0)
1406 KASSERT(csp->csp_auth_key != NULL || crp->crp_auth_key != NULL,
1407 ("auth request without a key"));
1408 KASSERT(crp->crp_callback != NULL, ("incoming crp without callback"));
1413 crypto_dispatch_one(struct cryptop *crp, int hint)
1415 struct cryptocap *cap;
1421 CRYPTOSTAT_INC(cs_ops);
1423 crp->crp_retw_id = crp->crp_session->id % crypto_workers_num;
1426 * Caller marked the request to be processed immediately; dispatch it
1427 * directly to the driver unless the driver is currently blocked, in
1428 * which case it is queued for deferred dispatch.
1430 cap = crp->crp_session->cap;
1431 if (!atomic_load_int(&cap->cc_qblocked)) {
1432 result = crypto_invoke(cap, crp, hint);
1433 if (result != ERESTART)
1437 * The driver ran out of resources, put the request on the
1441 crypto_batch_enqueue(crp);
1446 crypto_dispatch(struct cryptop *crp)
1448 return (crypto_dispatch_one(crp, 0));
1452 crypto_dispatch_async(struct cryptop *crp, int flags)
1454 struct crypto_ret_worker *ret_worker;
1456 if (!CRYPTO_SESS_SYNC(crp->crp_session)) {
1458 * The driver issues completions asynchonously, don't bother
1459 * deferring dispatch to a worker thread.
1461 return (crypto_dispatch(crp));
1467 CRYPTOSTAT_INC(cs_ops);
1469 crp->crp_retw_id = crp->crp_session->id % crypto_workers_num;
1470 if ((flags & CRYPTO_ASYNC_ORDERED) != 0) {
1471 crp->crp_flags |= CRYPTO_F_ASYNC_ORDERED;
1472 ret_worker = CRYPTO_RETW(crp->crp_retw_id);
1473 CRYPTO_RETW_LOCK(ret_worker);
1474 crp->crp_seq = ret_worker->reorder_ops++;
1475 CRYPTO_RETW_UNLOCK(ret_worker);
1477 TASK_INIT(&crp->crp_task, 0, crypto_task_invoke, crp);
1478 taskqueue_enqueue(crypto_tq, &crp->crp_task);
1483 crypto_dispatch_batch(struct cryptopq *crpq, int flags)
1485 struct cryptop *crp;
1488 while ((crp = TAILQ_FIRST(crpq)) != NULL) {
1489 hint = TAILQ_NEXT(crp, crp_next) != NULL ? CRYPTO_HINT_MORE : 0;
1490 TAILQ_REMOVE(crpq, crp, crp_next);
1491 if (crypto_dispatch_one(crp, hint) != 0)
1492 crypto_batch_enqueue(crp);
1497 crypto_batch_enqueue(struct cryptop *crp)
1501 TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
1508 crypto_task_invoke(void *ctx, int pending)
1510 struct cryptocap *cap;
1511 struct cryptop *crp;
1514 crp = (struct cryptop *)ctx;
1515 cap = crp->crp_session->cap;
1516 result = crypto_invoke(cap, crp, 0);
1517 if (result == ERESTART)
1518 crypto_batch_enqueue(crp);
1522 * Dispatch a crypto request to the appropriate crypto devices.
1525 crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint)
1529 KASSERT(crp != NULL, ("%s: crp == NULL", __func__));
1530 KASSERT(crp->crp_callback != NULL,
1531 ("%s: crp->crp_callback == NULL", __func__));
1532 KASSERT(crp->crp_session != NULL,
1533 ("%s: crp->crp_session == NULL", __func__));
1535 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1536 struct crypto_session_params csp;
1537 crypto_session_t nses;
1540 * Driver has unregistered; migrate the session and return
1541 * an error to the caller so they'll resubmit the op.
1543 * XXX: What if there are more already queued requests for this
1546 * XXX: Real solution is to make sessions refcounted
1547 * and force callers to hold a reference when
1548 * assigning to crp_session. Could maybe change
1549 * crypto_getreq to accept a session pointer to make
1550 * that work. Alternatively, we could abandon the
1551 * notion of rewriting crp_session in requests forcing
1552 * the caller to deal with allocating a new session.
1553 * Perhaps provide a method to allow a crp's session to
1554 * be swapped that callers could use.
1556 csp = crp->crp_session->csp;
1557 crypto_freesession(crp->crp_session);
1560 * XXX: Key pointers may no longer be valid. If we
1561 * really want to support this we need to define the
1562 * KPI such that 'csp' is required to be valid for the
1563 * duration of a session by the caller perhaps.
1565 * XXX: If the keys have been changed this will reuse
1566 * the old keys. This probably suggests making
1567 * rekeying more explicit and updating the key
1568 * pointers in 'csp' when the keys change.
1570 if (crypto_newsession(&nses, &csp,
1571 CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE) == 0)
1572 crp->crp_session = nses;
1574 crp->crp_etype = EAGAIN;
1579 * Invoke the driver to process the request. Errors are
1580 * signaled by setting crp_etype before invoking the completion
1583 error = CRYPTODEV_PROCESS(cap->cc_dev, crp, hint);
1584 KASSERT(error == 0 || error == ERESTART,
1585 ("%s: invalid error %d from CRYPTODEV_PROCESS",
1592 crypto_destroyreq(struct cryptop *crp)
1596 struct cryptop *crp2;
1597 struct crypto_ret_worker *ret_worker;
1599 if (!crypto_destroyreq_check)
1603 TAILQ_FOREACH(crp2, &crp_q, crp_next) {
1604 KASSERT(crp2 != crp,
1605 ("Freeing cryptop from the crypto queue (%p).",
1610 FOREACH_CRYPTO_RETW(ret_worker) {
1611 CRYPTO_RETW_LOCK(ret_worker);
1612 TAILQ_FOREACH(crp2, &ret_worker->crp_ret_q, crp_next) {
1613 KASSERT(crp2 != crp,
1614 ("Freeing cryptop from the return queue (%p).",
1617 CRYPTO_RETW_UNLOCK(ret_worker);
1624 crypto_freereq(struct cryptop *crp)
1629 crypto_destroyreq(crp);
1630 uma_zfree(cryptop_zone, crp);
1634 crypto_initreq(struct cryptop *crp, crypto_session_t cses)
1636 memset(crp, 0, sizeof(*crp));
1637 crp->crp_session = cses;
1641 crypto_getreq(crypto_session_t cses, int how)
1643 struct cryptop *crp;
1645 MPASS(how == M_WAITOK || how == M_NOWAIT);
1646 crp = uma_zalloc(cryptop_zone, how);
1648 crypto_initreq(crp, cses);
1653 * Clone a crypto request, but associate it with the specified session
1654 * rather than inheriting the session from the original request. The
1655 * fields describing the request buffers are copied, but not the
1656 * opaque field or callback function.
1659 crypto_clonereq(struct cryptop *crp, crypto_session_t cses, int how)
1661 struct cryptop *new;
1663 MPASS((crp->crp_flags & CRYPTO_F_DONE) == 0);
1664 new = crypto_getreq(cses, how);
1668 memcpy(&new->crp_startcopy, &crp->crp_startcopy,
1669 __rangeof(struct cryptop, crp_startcopy, crp_endcopy));
1674 * Invoke the callback on behalf of the driver.
1677 crypto_done(struct cryptop *crp)
1679 KASSERT((crp->crp_flags & CRYPTO_F_DONE) == 0,
1680 ("crypto_done: op already done, flags 0x%x", crp->crp_flags));
1681 crp->crp_flags |= CRYPTO_F_DONE;
1682 if (crp->crp_etype != 0)
1683 CRYPTOSTAT_INC(cs_errs);
1686 * CBIMM means unconditionally do the callback immediately;
1687 * CBIFSYNC means do the callback immediately only if the
1688 * operation was done synchronously. Both are used to avoid
1689 * doing extraneous context switches; the latter is mostly
1690 * used with the software crypto driver.
1692 if ((crp->crp_flags & CRYPTO_F_ASYNC_ORDERED) == 0 &&
1693 ((crp->crp_flags & CRYPTO_F_CBIMM) != 0 ||
1694 ((crp->crp_flags & CRYPTO_F_CBIFSYNC) != 0 &&
1695 CRYPTO_SESS_SYNC(crp->crp_session)))) {
1697 * Do the callback directly. This is ok when the
1698 * callback routine does very little (e.g. the
1699 * /dev/crypto callback method just does a wakeup).
1701 crp->crp_callback(crp);
1703 struct crypto_ret_worker *ret_worker;
1706 ret_worker = CRYPTO_RETW(crp->crp_retw_id);
1709 * Normal case; queue the callback for the thread.
1711 CRYPTO_RETW_LOCK(ret_worker);
1712 if ((crp->crp_flags & CRYPTO_F_ASYNC_ORDERED) != 0) {
1713 struct cryptop *tmp;
1715 TAILQ_FOREACH_REVERSE(tmp,
1716 &ret_worker->crp_ordered_ret_q, cryptop_q,
1718 if (CRYPTO_SEQ_GT(crp->crp_seq, tmp->crp_seq)) {
1720 &ret_worker->crp_ordered_ret_q, tmp,
1727 &ret_worker->crp_ordered_ret_q, crp,
1731 wake = crp->crp_seq == ret_worker->reorder_cur_seq;
1733 wake = TAILQ_EMPTY(&ret_worker->crp_ret_q);
1734 TAILQ_INSERT_TAIL(&ret_worker->crp_ret_q, crp,
1739 wakeup_one(&ret_worker->crp_ret_q); /* shared wait channel */
1740 CRYPTO_RETW_UNLOCK(ret_worker);
1745 * Terminate a thread at module unload. The process that
1746 * initiated this is waiting for us to signal that we're gone;
1747 * wake it up and exit. We use the driver table lock to insure
1748 * we don't do the wakeup before they're waiting. There is no
1749 * race here because the waiter sleeps on the proc lock for the
1750 * thread so it gets notified at the right time because of an
1751 * extra wakeup that's done in exit1().
1754 crypto_finis(void *chan)
1756 CRYPTO_DRIVER_LOCK();
1758 CRYPTO_DRIVER_UNLOCK();
1763 * Crypto thread, dispatches crypto requests.
1766 crypto_dispatch_thread(void *arg __unused)
1768 struct cryptop *crp, *submit;
1769 struct cryptocap *cap;
1772 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
1773 fpu_kern_thread(FPU_KERN_NORMAL);
1779 * Find the first element in the queue that can be
1780 * processed and look-ahead to see if multiple ops
1781 * are ready for the same driver.
1785 TAILQ_FOREACH(crp, &crp_q, crp_next) {
1786 cap = crp->crp_session->cap;
1788 * Driver cannot disappeared when there is an active
1791 KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1792 __func__, __LINE__));
1793 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1794 /* Op needs to be migrated, process it. */
1799 if (!cap->cc_qblocked) {
1800 if (submit != NULL) {
1802 * We stop on finding another op,
1803 * regardless whether its for the same
1804 * driver or not. We could keep
1805 * searching the queue but it might be
1806 * better to just use a per-driver
1809 if (submit->crp_session->cap == cap)
1810 hint = CRYPTO_HINT_MORE;
1817 if (submit != NULL) {
1818 TAILQ_REMOVE(&crp_q, submit, crp_next);
1819 cap = submit->crp_session->cap;
1820 KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1821 __func__, __LINE__));
1823 result = crypto_invoke(cap, submit, hint);
1825 if (result == ERESTART) {
1827 * The driver ran out of resources, mark the
1828 * driver ``blocked'' for cryptop's and put
1829 * the request back in the queue. It would
1830 * best to put the request back where we got
1831 * it but that's hard so for now we put it
1832 * at the front. This should be ok; putting
1833 * it at the end does not work.
1835 cap->cc_qblocked = 1;
1836 TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
1837 CRYPTOSTAT_INC(cs_blocks);
1841 * Nothing more to be processed. Sleep until we're
1842 * woken because there are more ops to process.
1843 * This happens either by submission or by a driver
1844 * becoming unblocked and notifying us through
1845 * crypto_unblock. Note that when we wakeup we
1846 * start processing each queue again from the
1847 * front. It's not clear that it's important to
1848 * preserve this ordering since ops may finish
1849 * out of order if dispatched to different devices
1850 * and some become blocked while others do not.
1853 msleep(&crp_q, &crypto_q_mtx, PWAIT, "crypto_wait", 0);
1855 if (cryptotd == NULL)
1857 CRYPTOSTAT_INC(cs_intrs);
1862 crypto_finis(&crp_q);
1866 * Crypto returns thread, does callbacks for processed crypto requests.
1867 * Callbacks are done here, rather than in the crypto drivers, because
1868 * callbacks typically are expensive and would slow interrupt handling.
1871 crypto_ret_thread(void *arg)
1873 struct crypto_ret_worker *ret_worker = arg;
1874 struct cryptop *crpt;
1876 CRYPTO_RETW_LOCK(ret_worker);
1878 /* Harvest return q's for completed ops */
1879 crpt = TAILQ_FIRST(&ret_worker->crp_ordered_ret_q);
1881 if (crpt->crp_seq == ret_worker->reorder_cur_seq) {
1882 TAILQ_REMOVE(&ret_worker->crp_ordered_ret_q, crpt, crp_next);
1883 ret_worker->reorder_cur_seq++;
1890 crpt = TAILQ_FIRST(&ret_worker->crp_ret_q);
1892 TAILQ_REMOVE(&ret_worker->crp_ret_q, crpt, crp_next);
1896 CRYPTO_RETW_UNLOCK(ret_worker);
1898 * Run callbacks unlocked.
1901 crpt->crp_callback(crpt);
1902 CRYPTO_RETW_LOCK(ret_worker);
1905 * Nothing more to be processed. Sleep until we're
1906 * woken because there are more returns to process.
1908 msleep(&ret_worker->crp_ret_q, &ret_worker->crypto_ret_mtx, PWAIT,
1909 "crypto_ret_wait", 0);
1910 if (ret_worker->td == NULL)
1912 CRYPTOSTAT_INC(cs_rets);
1915 CRYPTO_RETW_UNLOCK(ret_worker);
1917 crypto_finis(&ret_worker->crp_ret_q);
1922 db_show_drivers(void)
1926 db_printf("%12s %4s %8s %2s\n"
1932 for (hid = 0; hid < crypto_drivers_size; hid++) {
1933 const struct cryptocap *cap = crypto_drivers[hid];
1936 db_printf("%-12s %4u %08x %2u\n"
1937 , device_get_nameunit(cap->cc_dev)
1945 DB_SHOW_COMMAND_FLAGS(crypto, db_show_crypto, DB_CMD_MEMSAFE)
1947 struct cryptop *crp;
1948 struct crypto_ret_worker *ret_worker;
1953 db_printf("%4s %8s %4s %4s %4s %4s %8s %8s\n",
1954 "HID", "Caps", "Ilen", "Olen", "Etype", "Flags",
1955 "Device", "Callback");
1956 TAILQ_FOREACH(crp, &crp_q, crp_next) {
1957 db_printf("%4u %08x %4u %4u %04x %8p %8p\n"
1958 , crp->crp_session->cap->cc_hid
1959 , (int) crypto_ses2caps(crp->crp_session)
1963 , device_get_nameunit(crp->crp_session->cap->cc_dev)
1967 FOREACH_CRYPTO_RETW(ret_worker) {
1968 db_printf("\n%8s %4s %4s %4s %8s\n",
1969 "ret_worker", "HID", "Etype", "Flags", "Callback");
1970 if (!TAILQ_EMPTY(&ret_worker->crp_ret_q)) {
1971 TAILQ_FOREACH(crp, &ret_worker->crp_ret_q, crp_next) {
1972 db_printf("%8td %4u %4u %04x %8p\n"
1973 , CRYPTO_RETW_ID(ret_worker)
1974 , crp->crp_session->cap->cc_hid
1985 int crypto_modevent(module_t mod, int type, void *unused);
1988 * Initialization code, both for static and dynamic loading.
1989 * Note this is not invoked with the usual MODULE_DECLARE
1990 * mechanism but instead is listed as a dependency by the
1991 * cryptosoft driver. This guarantees proper ordering of
1992 * calls on module load/unload.
1995 crypto_modevent(module_t mod, int type, void *unused)
2001 error = crypto_init();
2002 if (error == 0 && bootverbose)
2003 printf("crypto: <crypto core>\n");
2006 /*XXX disallow if active sessions */
2013 MODULE_VERSION(crypto, 1);
2014 MODULE_DEPEND(crypto, zlib, 1, 1, 1);