2 * Copyright (c) 2002-2006 Sam Leffler. All rights reserved.
3 * Copyright (c) 2021 The FreeBSD Foundation
5 * Portions of this software were developed by Ararat River
6 * Consulting, LLC under sponsorship of the FreeBSD Foundation.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
33 * Cryptographic Subsystem.
35 * This code is derived from the Openbsd Cryptographic Framework (OCF)
36 * that has the copyright shown below. Very little of the original
41 * The author of this code is Angelos D. Keromytis (angelos@cis.upenn.edu)
43 * This code was written by Angelos D. Keromytis in Athens, Greece, in
44 * February 2000. Network Security Technologies Inc. (NSTI) kindly
45 * supported the development of this code.
47 * Copyright (c) 2000, 2001 Angelos D. Keromytis
49 * Permission to use, copy, and modify this software with or without fee
50 * is hereby granted, provided that this entire notice is included in
51 * all source code copies of any software which is or includes a copy or
52 * modification of this software.
54 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
55 * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
56 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
57 * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
61 #include "opt_compat.h"
64 #include <sys/param.h>
65 #include <sys/systm.h>
66 #include <sys/counter.h>
67 #include <sys/kernel.h>
68 #include <sys/kthread.h>
69 #include <sys/linker.h>
71 #include <sys/module.h>
72 #include <sys/mutex.h>
73 #include <sys/malloc.h>
76 #include <sys/refcount.h>
79 #include <sys/sysctl.h>
80 #include <sys/taskqueue.h>
85 #include <machine/vmparam.h>
88 #include <crypto/intake.h>
89 #include <opencrypto/cryptodev.h>
90 #include <opencrypto/xform_auth.h>
91 #include <opencrypto/xform_enc.h>
95 #include "cryptodev_if.h"
97 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
98 #include <machine/pcb.h>
101 SDT_PROVIDER_DEFINE(opencrypto);
104 * Crypto drivers register themselves by allocating a slot in the
105 * crypto_drivers table with crypto_get_driverid().
107 static struct mtx crypto_drivers_mtx; /* lock on driver table */
108 #define CRYPTO_DRIVER_LOCK() mtx_lock(&crypto_drivers_mtx)
109 #define CRYPTO_DRIVER_UNLOCK() mtx_unlock(&crypto_drivers_mtx)
110 #define CRYPTO_DRIVER_ASSERT() mtx_assert(&crypto_drivers_mtx, MA_OWNED)
113 * Crypto device/driver capabilities structure.
116 * (d) - protected by CRYPTO_DRIVER_LOCK()
117 * (q) - protected by CRYPTO_Q_LOCK()
118 * Not tagged fields are read-only.
123 uint32_t cc_sessions; /* (d) # of sessions */
125 int cc_flags; /* (d) flags */
126 #define CRYPTOCAP_F_CLEANUP 0x80000000 /* needs resource cleanup */
127 int cc_qblocked; /* (q) symmetric 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;
137 struct crypto_session_params csp;
139 /* Driver softc follows. */
142 static int crp_sleep = 0;
143 static TAILQ_HEAD(cryptop_q ,cryptop) crp_q; /* request queues */
144 static struct mtx crypto_q_mtx;
145 #define CRYPTO_Q_LOCK() mtx_lock(&crypto_q_mtx)
146 #define CRYPTO_Q_UNLOCK() mtx_unlock(&crypto_q_mtx)
148 SYSCTL_NODE(_kern, OID_AUTO, crypto, CTLFLAG_RW, 0,
149 "In-kernel cryptography");
152 * Taskqueue used to dispatch the crypto requests
153 * that have the CRYPTO_F_ASYNC flag
155 static struct taskqueue *crypto_tq;
158 * Crypto seq numbers are operated on with modular arithmetic
160 #define CRYPTO_SEQ_GT(a,b) ((int)((a)-(b)) > 0)
162 struct crypto_ret_worker {
163 struct mtx crypto_ret_mtx;
165 TAILQ_HEAD(,cryptop) crp_ordered_ret_q; /* ordered callback queue for symetric jobs */
166 TAILQ_HEAD(,cryptop) crp_ret_q; /* callback queue for symetric jobs */
168 uint32_t reorder_ops; /* total ordered sym jobs received */
169 uint32_t reorder_cur_seq; /* current sym job dispatched */
173 static struct crypto_ret_worker *crypto_ret_workers = NULL;
175 #define CRYPTO_RETW(i) (&crypto_ret_workers[i])
176 #define CRYPTO_RETW_ID(w) ((w) - crypto_ret_workers)
177 #define FOREACH_CRYPTO_RETW(w) \
178 for (w = crypto_ret_workers; w < crypto_ret_workers + crypto_workers_num; ++w)
180 #define CRYPTO_RETW_LOCK(w) mtx_lock(&w->crypto_ret_mtx)
181 #define CRYPTO_RETW_UNLOCK(w) mtx_unlock(&w->crypto_ret_mtx)
183 static int crypto_workers_num = 0;
184 SYSCTL_INT(_kern_crypto, OID_AUTO, num_workers, CTLFLAG_RDTUN,
185 &crypto_workers_num, 0,
186 "Number of crypto workers used to dispatch crypto jobs");
187 #ifdef COMPAT_FREEBSD12
188 SYSCTL_INT(_kern, OID_AUTO, crypto_workers_num, CTLFLAG_RDTUN,
189 &crypto_workers_num, 0,
190 "Number of crypto workers used to dispatch crypto jobs");
193 static uma_zone_t cryptop_zone;
195 int crypto_devallowsoft = 0;
196 SYSCTL_INT(_kern_crypto, OID_AUTO, allow_soft, CTLFLAG_RWTUN,
197 &crypto_devallowsoft, 0,
198 "Enable use of software crypto by /dev/crypto");
199 #ifdef COMPAT_FREEBSD12
200 SYSCTL_INT(_kern, OID_AUTO, cryptodevallowsoft, CTLFLAG_RWTUN,
201 &crypto_devallowsoft, 0,
202 "Enable/disable use of software crypto by /dev/crypto");
205 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
207 static void crypto_dispatch_thread(void *arg);
208 static struct thread *cryptotd;
209 static void crypto_ret_thread(void *arg);
210 static void crypto_destroy(void);
211 static int crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint);
212 static void crypto_task_invoke(void *ctx, int pending);
213 static void crypto_batch_enqueue(struct cryptop *crp);
215 static counter_u64_t cryptostats[sizeof(struct cryptostats) / sizeof(uint64_t)];
216 SYSCTL_COUNTER_U64_ARRAY(_kern_crypto, OID_AUTO, stats, CTLFLAG_RW,
217 cryptostats, nitems(cryptostats),
218 "Crypto system statistics");
220 #define CRYPTOSTAT_INC(stat) do { \
222 cryptostats[offsetof(struct cryptostats, stat) / sizeof(uint64_t)],\
227 cryptostats_init(void *arg __unused)
229 COUNTER_ARRAY_ALLOC(cryptostats, nitems(cryptostats), M_WAITOK);
231 SYSINIT(cryptostats_init, SI_SUB_COUNTER, SI_ORDER_ANY, cryptostats_init, NULL);
234 cryptostats_fini(void *arg __unused)
236 COUNTER_ARRAY_FREE(cryptostats, nitems(cryptostats));
238 SYSUNINIT(cryptostats_fini, SI_SUB_COUNTER, SI_ORDER_ANY, cryptostats_fini,
241 /* Try to avoid directly exposing the key buffer as a symbol */
242 static struct keybuf *keybuf;
244 static struct keybuf empty_keybuf = {
248 /* Obtain the key buffer from boot metadata */
254 kmdp = preload_search_by_type("elf kernel");
257 kmdp = preload_search_by_type("elf64 kernel");
259 keybuf = (struct keybuf *)preload_search_info(kmdp,
260 MODINFO_METADATA | MODINFOMD_KEYBUF);
263 keybuf = &empty_keybuf;
266 /* It'd be nice if we could store these in some kind of secure memory... */
274 static struct cryptocap *
275 cap_ref(struct cryptocap *cap)
278 refcount_acquire(&cap->cc_refs);
283 cap_rele(struct cryptocap *cap)
286 if (refcount_release(&cap->cc_refs) == 0)
289 KASSERT(cap->cc_sessions == 0,
290 ("freeing crypto driver with active sessions"));
292 free(cap, M_CRYPTO_DATA);
298 struct crypto_ret_worker *ret_worker;
302 mtx_init(&crypto_drivers_mtx, "crypto driver table", NULL, MTX_DEF);
305 mtx_init(&crypto_q_mtx, "crypto op queues", NULL, MTX_DEF);
307 cryptop_zone = uma_zcreate("cryptop",
308 sizeof(struct cryptop), NULL, NULL, NULL, NULL,
309 UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
311 crypto_drivers_size = CRYPTO_DRIVERS_INITIAL;
312 crypto_drivers = malloc(crypto_drivers_size *
313 sizeof(struct cryptocap), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
315 if (crypto_workers_num < 1 || crypto_workers_num > mp_ncpus)
316 crypto_workers_num = mp_ncpus;
318 crypto_tq = taskqueue_create("crypto", M_WAITOK | M_ZERO,
319 taskqueue_thread_enqueue, &crypto_tq);
321 taskqueue_start_threads(&crypto_tq, crypto_workers_num, PRI_MIN_KERN,
325 error = kproc_kthread_add(crypto_dispatch_thread, NULL, &p, &cryptotd,
326 0, 0, "crypto", "crypto");
328 printf("crypto_init: cannot start crypto thread; error %d",
333 crypto_ret_workers = mallocarray(crypto_workers_num,
334 sizeof(struct crypto_ret_worker), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
336 FOREACH_CRYPTO_RETW(ret_worker) {
337 TAILQ_INIT(&ret_worker->crp_ordered_ret_q);
338 TAILQ_INIT(&ret_worker->crp_ret_q);
340 ret_worker->reorder_ops = 0;
341 ret_worker->reorder_cur_seq = 0;
343 mtx_init(&ret_worker->crypto_ret_mtx, "crypto return queues",
346 error = kthread_add(crypto_ret_thread, ret_worker, p,
347 &ret_worker->td, 0, 0, "crypto returns %td",
348 CRYPTO_RETW_ID(ret_worker));
350 printf("crypto_init: cannot start cryptoret thread; error %d",
365 * Signal a crypto thread to terminate. We use the driver
366 * table lock to synchronize the sleep/wakeups so that we
367 * are sure the threads have terminated before we release
368 * the data structures they use. See crypto_finis below
369 * for the other half of this song-and-dance.
372 crypto_terminate(struct thread **tdp, void *q)
376 mtx_assert(&crypto_drivers_mtx, MA_OWNED);
381 mtx_sleep(td, &crypto_drivers_mtx, PWAIT, "crypto_destroy", 0);
386 hmac_init_pad(const struct auth_hash *axf, const char *key, int klen,
387 void *auth_ctx, uint8_t padval)
389 uint8_t hmac_key[HMAC_MAX_BLOCK_LEN];
392 KASSERT(axf->blocksize <= sizeof(hmac_key),
393 ("Invalid HMAC block size %d", axf->blocksize));
396 * If the key is larger than the block size, use the digest of
397 * the key as the key instead.
399 memset(hmac_key, 0, sizeof(hmac_key));
400 if (klen > axf->blocksize) {
402 axf->Update(auth_ctx, key, klen);
403 axf->Final(hmac_key, auth_ctx);
404 klen = axf->hashsize;
406 memcpy(hmac_key, key, klen);
408 for (i = 0; i < axf->blocksize; i++)
409 hmac_key[i] ^= padval;
412 axf->Update(auth_ctx, hmac_key, axf->blocksize);
413 explicit_bzero(hmac_key, sizeof(hmac_key));
417 hmac_init_ipad(const struct auth_hash *axf, const char *key, int klen,
421 hmac_init_pad(axf, key, klen, auth_ctx, HMAC_IPAD_VAL);
425 hmac_init_opad(const struct auth_hash *axf, const char *key, int klen,
429 hmac_init_pad(axf, key, klen, auth_ctx, HMAC_OPAD_VAL);
435 struct crypto_ret_worker *ret_worker;
439 * Terminate any crypto threads.
441 if (crypto_tq != NULL)
442 taskqueue_drain_all(crypto_tq);
443 CRYPTO_DRIVER_LOCK();
444 crypto_terminate(&cryptotd, &crp_q);
445 FOREACH_CRYPTO_RETW(ret_worker)
446 crypto_terminate(&ret_worker->td, &ret_worker->crp_ret_q);
447 CRYPTO_DRIVER_UNLOCK();
449 /* XXX flush queues??? */
452 * Reclaim dynamically allocated resources.
454 for (i = 0; i < crypto_drivers_size; i++) {
455 if (crypto_drivers[i] != NULL)
456 cap_rele(crypto_drivers[i]);
458 free(crypto_drivers, M_CRYPTO_DATA);
460 if (cryptop_zone != NULL)
461 uma_zdestroy(cryptop_zone);
462 mtx_destroy(&crypto_q_mtx);
463 FOREACH_CRYPTO_RETW(ret_worker)
464 mtx_destroy(&ret_worker->crypto_ret_mtx);
465 free(crypto_ret_workers, M_CRYPTO_DATA);
466 if (crypto_tq != NULL)
467 taskqueue_free(crypto_tq);
468 mtx_destroy(&crypto_drivers_mtx);
472 crypto_ses2hid(crypto_session_t crypto_session)
474 return (crypto_session->cap->cc_hid);
478 crypto_ses2caps(crypto_session_t crypto_session)
480 return (crypto_session->cap->cc_flags & 0xff000000);
484 crypto_get_driver_session(crypto_session_t crypto_session)
486 return (crypto_session + 1);
489 const struct crypto_session_params *
490 crypto_get_params(crypto_session_t crypto_session)
492 return (&crypto_session->csp);
495 const struct auth_hash *
496 crypto_auth_hash(const struct crypto_session_params *csp)
499 switch (csp->csp_auth_alg) {
500 case CRYPTO_SHA1_HMAC:
501 return (&auth_hash_hmac_sha1);
502 case CRYPTO_SHA2_224_HMAC:
503 return (&auth_hash_hmac_sha2_224);
504 case CRYPTO_SHA2_256_HMAC:
505 return (&auth_hash_hmac_sha2_256);
506 case CRYPTO_SHA2_384_HMAC:
507 return (&auth_hash_hmac_sha2_384);
508 case CRYPTO_SHA2_512_HMAC:
509 return (&auth_hash_hmac_sha2_512);
510 case CRYPTO_NULL_HMAC:
511 return (&auth_hash_null);
512 case CRYPTO_RIPEMD160_HMAC:
513 return (&auth_hash_hmac_ripemd_160);
514 case CRYPTO_RIPEMD160:
515 return (&auth_hash_ripemd_160);
517 return (&auth_hash_sha1);
518 case CRYPTO_SHA2_224:
519 return (&auth_hash_sha2_224);
520 case CRYPTO_SHA2_256:
521 return (&auth_hash_sha2_256);
522 case CRYPTO_SHA2_384:
523 return (&auth_hash_sha2_384);
524 case CRYPTO_SHA2_512:
525 return (&auth_hash_sha2_512);
526 case CRYPTO_AES_NIST_GMAC:
527 switch (csp->csp_auth_klen) {
529 return (&auth_hash_nist_gmac_aes_128);
531 return (&auth_hash_nist_gmac_aes_192);
533 return (&auth_hash_nist_gmac_aes_256);
538 return (&auth_hash_blake2b);
540 return (&auth_hash_blake2s);
541 case CRYPTO_POLY1305:
542 return (&auth_hash_poly1305);
543 case CRYPTO_AES_CCM_CBC_MAC:
544 switch (csp->csp_auth_klen) {
546 return (&auth_hash_ccm_cbc_mac_128);
548 return (&auth_hash_ccm_cbc_mac_192);
550 return (&auth_hash_ccm_cbc_mac_256);
559 const struct enc_xform *
560 crypto_cipher(const struct crypto_session_params *csp)
563 switch (csp->csp_cipher_alg) {
565 return (&enc_xform_aes_cbc);
567 return (&enc_xform_aes_xts);
569 return (&enc_xform_aes_icm);
570 case CRYPTO_AES_NIST_GCM_16:
571 return (&enc_xform_aes_nist_gcm);
572 case CRYPTO_CAMELLIA_CBC:
573 return (&enc_xform_camellia);
574 case CRYPTO_NULL_CBC:
575 return (&enc_xform_null);
576 case CRYPTO_CHACHA20:
577 return (&enc_xform_chacha20);
578 case CRYPTO_AES_CCM_16:
579 return (&enc_xform_ccm);
580 case CRYPTO_CHACHA20_POLY1305:
581 return (&enc_xform_chacha20_poly1305);
587 static struct cryptocap *
588 crypto_checkdriver(uint32_t hid)
591 return (hid >= crypto_drivers_size ? NULL : crypto_drivers[hid]);
595 * Select a driver for a new session that supports the specified
596 * algorithms and, optionally, is constrained according to the flags.
598 static struct cryptocap *
599 crypto_select_driver(const struct crypto_session_params *csp, int flags)
601 struct cryptocap *cap, *best;
602 int best_match, error, hid;
604 CRYPTO_DRIVER_ASSERT();
607 for (hid = 0; hid < crypto_drivers_size; hid++) {
609 * If there is no driver for this slot, or the driver
610 * is not appropriate (hardware or software based on
613 cap = crypto_drivers[hid];
615 (cap->cc_flags & flags) == 0)
618 error = CRYPTODEV_PROBESESSION(cap->cc_dev, csp);
623 * Use the driver with the highest probe value.
624 * Hardware drivers use a higher probe value than
625 * software. In case of a tie, prefer the driver with
626 * the fewest active sessions.
628 if (best == NULL || error > best_match ||
629 (error == best_match &&
630 cap->cc_sessions < best->cc_sessions)) {
638 static enum alg_type {
646 [CRYPTO_SHA1_HMAC] = ALG_KEYED_DIGEST,
647 [CRYPTO_RIPEMD160_HMAC] = ALG_KEYED_DIGEST,
648 [CRYPTO_AES_CBC] = ALG_CIPHER,
649 [CRYPTO_SHA1] = ALG_DIGEST,
650 [CRYPTO_NULL_HMAC] = ALG_DIGEST,
651 [CRYPTO_NULL_CBC] = ALG_CIPHER,
652 [CRYPTO_DEFLATE_COMP] = ALG_COMPRESSION,
653 [CRYPTO_SHA2_256_HMAC] = ALG_KEYED_DIGEST,
654 [CRYPTO_SHA2_384_HMAC] = ALG_KEYED_DIGEST,
655 [CRYPTO_SHA2_512_HMAC] = ALG_KEYED_DIGEST,
656 [CRYPTO_CAMELLIA_CBC] = ALG_CIPHER,
657 [CRYPTO_AES_XTS] = ALG_CIPHER,
658 [CRYPTO_AES_ICM] = ALG_CIPHER,
659 [CRYPTO_AES_NIST_GMAC] = ALG_KEYED_DIGEST,
660 [CRYPTO_AES_NIST_GCM_16] = ALG_AEAD,
661 [CRYPTO_BLAKE2B] = ALG_KEYED_DIGEST,
662 [CRYPTO_BLAKE2S] = ALG_KEYED_DIGEST,
663 [CRYPTO_CHACHA20] = ALG_CIPHER,
664 [CRYPTO_SHA2_224_HMAC] = ALG_KEYED_DIGEST,
665 [CRYPTO_RIPEMD160] = ALG_DIGEST,
666 [CRYPTO_SHA2_224] = ALG_DIGEST,
667 [CRYPTO_SHA2_256] = ALG_DIGEST,
668 [CRYPTO_SHA2_384] = ALG_DIGEST,
669 [CRYPTO_SHA2_512] = ALG_DIGEST,
670 [CRYPTO_POLY1305] = ALG_KEYED_DIGEST,
671 [CRYPTO_AES_CCM_CBC_MAC] = ALG_KEYED_DIGEST,
672 [CRYPTO_AES_CCM_16] = ALG_AEAD,
673 [CRYPTO_CHACHA20_POLY1305] = ALG_AEAD,
680 if (alg < nitems(alg_types))
681 return (alg_types[alg]);
686 alg_is_compression(int alg)
689 return (alg_type(alg) == ALG_COMPRESSION);
693 alg_is_cipher(int alg)
696 return (alg_type(alg) == ALG_CIPHER);
700 alg_is_digest(int alg)
703 return (alg_type(alg) == ALG_DIGEST ||
704 alg_type(alg) == ALG_KEYED_DIGEST);
708 alg_is_keyed_digest(int alg)
711 return (alg_type(alg) == ALG_KEYED_DIGEST);
718 return (alg_type(alg) == ALG_AEAD);
722 ccm_tag_length_valid(int len)
739 #define SUPPORTED_SES (CSP_F_SEPARATE_OUTPUT | CSP_F_SEPARATE_AAD | CSP_F_ESN)
741 /* Various sanity checks on crypto session parameters. */
743 check_csp(const struct crypto_session_params *csp)
745 const struct auth_hash *axf;
747 /* Mode-independent checks. */
748 if ((csp->csp_flags & ~(SUPPORTED_SES)) != 0)
750 if (csp->csp_ivlen < 0 || csp->csp_cipher_klen < 0 ||
751 csp->csp_auth_klen < 0 || csp->csp_auth_mlen < 0)
753 if (csp->csp_auth_key != NULL && csp->csp_auth_klen == 0)
755 if (csp->csp_cipher_key != NULL && csp->csp_cipher_klen == 0)
758 switch (csp->csp_mode) {
759 case CSP_MODE_COMPRESS:
760 if (!alg_is_compression(csp->csp_cipher_alg))
762 if (csp->csp_flags & CSP_F_SEPARATE_OUTPUT)
764 if (csp->csp_flags & CSP_F_SEPARATE_AAD)
766 if (csp->csp_cipher_klen != 0 || csp->csp_ivlen != 0 ||
767 csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0 ||
768 csp->csp_auth_mlen != 0)
771 case CSP_MODE_CIPHER:
772 if (!alg_is_cipher(csp->csp_cipher_alg))
774 if (csp->csp_flags & CSP_F_SEPARATE_AAD)
776 if (csp->csp_cipher_alg != CRYPTO_NULL_CBC) {
777 if (csp->csp_cipher_klen == 0)
779 if (csp->csp_ivlen == 0)
782 if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
784 if (csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0 ||
785 csp->csp_auth_mlen != 0)
788 case CSP_MODE_DIGEST:
789 if (csp->csp_cipher_alg != 0 || csp->csp_cipher_klen != 0)
792 if (csp->csp_flags & CSP_F_SEPARATE_AAD)
795 /* IV is optional for digests (e.g. GMAC). */
796 switch (csp->csp_auth_alg) {
797 case CRYPTO_AES_CCM_CBC_MAC:
798 if (csp->csp_ivlen < 7 || csp->csp_ivlen > 13)
801 case CRYPTO_AES_NIST_GMAC:
802 if (csp->csp_ivlen != AES_GCM_IV_LEN)
806 if (csp->csp_ivlen != 0)
811 if (!alg_is_digest(csp->csp_auth_alg))
814 /* Key is optional for BLAKE2 digests. */
815 if (csp->csp_auth_alg == CRYPTO_BLAKE2B ||
816 csp->csp_auth_alg == CRYPTO_BLAKE2S)
818 else if (alg_is_keyed_digest(csp->csp_auth_alg)) {
819 if (csp->csp_auth_klen == 0)
822 if (csp->csp_auth_klen != 0)
825 if (csp->csp_auth_mlen != 0) {
826 axf = crypto_auth_hash(csp);
827 if (axf == NULL || csp->csp_auth_mlen > axf->hashsize)
830 if (csp->csp_auth_alg == CRYPTO_AES_CCM_CBC_MAC &&
831 !ccm_tag_length_valid(csp->csp_auth_mlen))
836 if (!alg_is_aead(csp->csp_cipher_alg))
838 if (csp->csp_cipher_klen == 0)
840 if (csp->csp_ivlen == 0 ||
841 csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
843 if (csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0)
846 switch (csp->csp_cipher_alg) {
847 case CRYPTO_AES_CCM_16:
848 if (csp->csp_auth_mlen != 0 &&
849 !ccm_tag_length_valid(csp->csp_auth_mlen))
852 if (csp->csp_ivlen < 7 || csp->csp_ivlen > 13)
855 case CRYPTO_AES_NIST_GCM_16:
856 if (csp->csp_auth_mlen > AES_GMAC_HASH_LEN)
859 if (csp->csp_ivlen != AES_GCM_IV_LEN)
862 case CRYPTO_CHACHA20_POLY1305:
863 if (csp->csp_ivlen != 8 && csp->csp_ivlen != 12)
865 if (csp->csp_auth_mlen > POLY1305_HASH_LEN)
871 if (!alg_is_cipher(csp->csp_cipher_alg))
873 if (csp->csp_cipher_alg != CRYPTO_NULL_CBC) {
874 if (csp->csp_cipher_klen == 0)
876 if (csp->csp_ivlen == 0)
879 if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
881 if (!alg_is_digest(csp->csp_auth_alg))
884 /* Key is optional for BLAKE2 digests. */
885 if (csp->csp_auth_alg == CRYPTO_BLAKE2B ||
886 csp->csp_auth_alg == CRYPTO_BLAKE2S)
888 else if (alg_is_keyed_digest(csp->csp_auth_alg)) {
889 if (csp->csp_auth_klen == 0)
892 if (csp->csp_auth_klen != 0)
895 if (csp->csp_auth_mlen != 0) {
896 axf = crypto_auth_hash(csp);
897 if (axf == NULL || csp->csp_auth_mlen > axf->hashsize)
909 * Delete a session after it has been detached from its driver.
912 crypto_deletesession(crypto_session_t cses)
914 struct cryptocap *cap;
918 zfree(cses, M_CRYPTO_DATA);
920 CRYPTO_DRIVER_LOCK();
922 if (cap->cc_sessions == 0 && cap->cc_flags & CRYPTOCAP_F_CLEANUP)
924 CRYPTO_DRIVER_UNLOCK();
929 * Create a new session. The crid argument specifies a crypto
930 * driver to use or constraints on a driver to select (hardware
931 * only, software only, either). Whatever driver is selected
932 * must be capable of the requested crypto algorithms.
935 crypto_newsession(crypto_session_t *cses,
936 const struct crypto_session_params *csp, int crid)
938 static uint64_t sessid = 0;
939 crypto_session_t res;
940 struct cryptocap *cap;
948 CRYPTO_DRIVER_LOCK();
949 if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
951 * Use specified driver; verify it is capable.
953 cap = crypto_checkdriver(crid);
954 if (cap != NULL && CRYPTODEV_PROBESESSION(cap->cc_dev, csp) > 0)
958 * No requested driver; select based on crid flags.
960 cap = crypto_select_driver(csp, crid);
963 CRYPTO_DRIVER_UNLOCK();
964 CRYPTDEB("no driver");
969 CRYPTO_DRIVER_UNLOCK();
971 /* Allocate a single block for the generic session and driver softc. */
972 res = malloc(sizeof(*res) + cap->cc_session_size, M_CRYPTO_DATA,
976 res->id = atomic_fetchadd_64(&sessid, 1);
978 /* Call the driver initialization routine. */
979 err = CRYPTODEV_NEWSESSION(cap->cc_dev, res, csp);
981 CRYPTDEB("dev newsession failed: %d", err);
982 crypto_deletesession(res);
991 * Delete an existing session (or a reserved session on an unregistered
995 crypto_freesession(crypto_session_t cses)
997 struct cryptocap *cap;
1004 /* Call the driver cleanup routine, if available. */
1005 CRYPTODEV_FREESESSION(cap->cc_dev, cses);
1007 crypto_deletesession(cses);
1011 * Return a new driver id. Registers a driver with the system so that
1012 * it can be probed by subsequent sessions.
1015 crypto_get_driverid(device_t dev, size_t sessionsize, int flags)
1017 struct cryptocap *cap, **newdrv;
1020 if ((flags & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
1022 "no flags specified when registering driver\n");
1026 cap = malloc(sizeof(*cap), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
1028 cap->cc_session_size = sessionsize;
1029 cap->cc_flags = flags;
1030 refcount_init(&cap->cc_refs, 1);
1032 CRYPTO_DRIVER_LOCK();
1034 for (i = 0; i < crypto_drivers_size; i++) {
1035 if (crypto_drivers[i] == NULL)
1039 if (i < crypto_drivers_size)
1042 /* Out of entries, allocate some more. */
1044 if (2 * crypto_drivers_size <= crypto_drivers_size) {
1045 CRYPTO_DRIVER_UNLOCK();
1046 printf("crypto: driver count wraparound!\n");
1050 CRYPTO_DRIVER_UNLOCK();
1052 newdrv = malloc(2 * crypto_drivers_size *
1053 sizeof(*crypto_drivers), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
1055 CRYPTO_DRIVER_LOCK();
1056 memcpy(newdrv, crypto_drivers,
1057 crypto_drivers_size * sizeof(*crypto_drivers));
1059 crypto_drivers_size *= 2;
1061 free(crypto_drivers, M_CRYPTO_DATA);
1062 crypto_drivers = newdrv;
1066 crypto_drivers[i] = cap;
1067 CRYPTO_DRIVER_UNLOCK();
1070 printf("crypto: assign %s driver id %u, flags 0x%x\n",
1071 device_get_nameunit(dev), i, flags);
1077 * Lookup a driver by name. We match against the full device
1078 * name and unit, and against just the name. The latter gives
1079 * us a simple widlcarding by device name. On success return the
1080 * driver/hardware identifier; otherwise return -1.
1083 crypto_find_driver(const char *match)
1085 struct cryptocap *cap;
1086 int i, len = strlen(match);
1088 CRYPTO_DRIVER_LOCK();
1089 for (i = 0; i < crypto_drivers_size; i++) {
1090 if (crypto_drivers[i] == NULL)
1092 cap = crypto_drivers[i];
1093 if (strncmp(match, device_get_nameunit(cap->cc_dev), len) == 0 ||
1094 strncmp(match, device_get_name(cap->cc_dev), len) == 0) {
1095 CRYPTO_DRIVER_UNLOCK();
1099 CRYPTO_DRIVER_UNLOCK();
1104 * Return the device_t for the specified driver or NULL
1105 * if the driver identifier is invalid.
1108 crypto_find_device_byhid(int hid)
1110 struct cryptocap *cap;
1114 CRYPTO_DRIVER_LOCK();
1115 cap = crypto_checkdriver(hid);
1118 CRYPTO_DRIVER_UNLOCK();
1123 * Return the device/driver capabilities.
1126 crypto_getcaps(int hid)
1128 struct cryptocap *cap;
1132 CRYPTO_DRIVER_LOCK();
1133 cap = crypto_checkdriver(hid);
1135 flags = cap->cc_flags;
1136 CRYPTO_DRIVER_UNLOCK();
1141 * Unregister all algorithms associated with a crypto driver.
1142 * If there are pending sessions using it, leave enough information
1143 * around so that subsequent calls using those sessions will
1144 * correctly detect the driver has been unregistered and reroute
1148 crypto_unregister_all(uint32_t driverid)
1150 struct cryptocap *cap;
1152 CRYPTO_DRIVER_LOCK();
1153 cap = crypto_checkdriver(driverid);
1155 CRYPTO_DRIVER_UNLOCK();
1159 cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
1160 crypto_drivers[driverid] = NULL;
1163 * XXX: This doesn't do anything to kick sessions that
1164 * have no pending operations.
1166 while (cap->cc_sessions != 0)
1167 mtx_sleep(cap, &crypto_drivers_mtx, 0, "cryunreg", 0);
1168 CRYPTO_DRIVER_UNLOCK();
1175 * Clear blockage on a driver. The what parameter indicates whether
1176 * the driver is now ready for cryptop's and/or cryptokop's.
1179 crypto_unblock(uint32_t driverid, int what)
1181 struct cryptocap *cap;
1185 cap = crypto_checkdriver(driverid);
1187 if (what & CRYPTO_SYMQ)
1188 cap->cc_qblocked = 0;
1200 crypto_buffer_len(struct crypto_buffer *cb)
1202 switch (cb->cb_type) {
1203 case CRYPTO_BUF_CONTIG:
1204 return (cb->cb_buf_len);
1205 case CRYPTO_BUF_MBUF:
1206 if (cb->cb_mbuf->m_flags & M_PKTHDR)
1207 return (cb->cb_mbuf->m_pkthdr.len);
1208 return (m_length(cb->cb_mbuf, NULL));
1209 case CRYPTO_BUF_SINGLE_MBUF:
1210 return (cb->cb_mbuf->m_len);
1211 case CRYPTO_BUF_VMPAGE:
1212 return (cb->cb_vm_page_len);
1213 case CRYPTO_BUF_UIO:
1214 return (cb->cb_uio->uio_resid);
1221 /* Various sanity checks on crypto requests. */
1223 cb_sanity(struct crypto_buffer *cb, const char *name)
1225 KASSERT(cb->cb_type > CRYPTO_BUF_NONE && cb->cb_type <= CRYPTO_BUF_LAST,
1226 ("incoming crp with invalid %s buffer type", name));
1227 switch (cb->cb_type) {
1228 case CRYPTO_BUF_CONTIG:
1229 KASSERT(cb->cb_buf_len >= 0,
1230 ("incoming crp with -ve %s buffer length", name));
1232 case CRYPTO_BUF_VMPAGE:
1233 KASSERT(CRYPTO_HAS_VMPAGE,
1234 ("incoming crp uses dmap on supported arch"));
1235 KASSERT(cb->cb_vm_page_len >= 0,
1236 ("incoming crp with -ve %s buffer length", name));
1237 KASSERT(cb->cb_vm_page_offset >= 0,
1238 ("incoming crp with -ve %s buffer offset", name));
1239 KASSERT(cb->cb_vm_page_offset < PAGE_SIZE,
1240 ("incoming crp with %s buffer offset greater than page size"
1249 crp_sanity(struct cryptop *crp)
1251 struct crypto_session_params *csp;
1252 struct crypto_buffer *out;
1253 size_t ilen, len, olen;
1255 KASSERT(crp->crp_session != NULL, ("incoming crp without a session"));
1256 KASSERT(crp->crp_obuf.cb_type >= CRYPTO_BUF_NONE &&
1257 crp->crp_obuf.cb_type <= CRYPTO_BUF_LAST,
1258 ("incoming crp with invalid output buffer type"));
1259 KASSERT(crp->crp_etype == 0, ("incoming crp with error"));
1260 KASSERT(!(crp->crp_flags & CRYPTO_F_DONE),
1261 ("incoming crp already done"));
1263 csp = &crp->crp_session->csp;
1264 cb_sanity(&crp->crp_buf, "input");
1265 ilen = crypto_buffer_len(&crp->crp_buf);
1268 if (csp->csp_flags & CSP_F_SEPARATE_OUTPUT) {
1269 if (crp->crp_obuf.cb_type != CRYPTO_BUF_NONE) {
1270 cb_sanity(&crp->crp_obuf, "output");
1271 out = &crp->crp_obuf;
1272 olen = crypto_buffer_len(out);
1275 KASSERT(crp->crp_obuf.cb_type == CRYPTO_BUF_NONE,
1276 ("incoming crp with separate output buffer "
1277 "but no session support"));
1279 switch (csp->csp_mode) {
1280 case CSP_MODE_COMPRESS:
1281 KASSERT(crp->crp_op == CRYPTO_OP_COMPRESS ||
1282 crp->crp_op == CRYPTO_OP_DECOMPRESS,
1283 ("invalid compression op %x", crp->crp_op));
1285 case CSP_MODE_CIPHER:
1286 KASSERT(crp->crp_op == CRYPTO_OP_ENCRYPT ||
1287 crp->crp_op == CRYPTO_OP_DECRYPT,
1288 ("invalid cipher op %x", crp->crp_op));
1290 case CSP_MODE_DIGEST:
1291 KASSERT(crp->crp_op == CRYPTO_OP_COMPUTE_DIGEST ||
1292 crp->crp_op == CRYPTO_OP_VERIFY_DIGEST,
1293 ("invalid digest op %x", crp->crp_op));
1296 KASSERT(crp->crp_op ==
1297 (CRYPTO_OP_ENCRYPT | CRYPTO_OP_COMPUTE_DIGEST) ||
1299 (CRYPTO_OP_DECRYPT | CRYPTO_OP_VERIFY_DIGEST),
1300 ("invalid AEAD op %x", crp->crp_op));
1301 KASSERT(crp->crp_flags & CRYPTO_F_IV_SEPARATE,
1302 ("AEAD without a separate IV"));
1305 KASSERT(crp->crp_op ==
1306 (CRYPTO_OP_ENCRYPT | CRYPTO_OP_COMPUTE_DIGEST) ||
1308 (CRYPTO_OP_DECRYPT | CRYPTO_OP_VERIFY_DIGEST),
1309 ("invalid ETA op %x", crp->crp_op));
1312 if (csp->csp_mode == CSP_MODE_AEAD || csp->csp_mode == CSP_MODE_ETA) {
1313 if (crp->crp_aad == NULL) {
1314 KASSERT(crp->crp_aad_start == 0 ||
1315 crp->crp_aad_start < ilen,
1316 ("invalid AAD start"));
1317 KASSERT(crp->crp_aad_length != 0 ||
1318 crp->crp_aad_start == 0,
1319 ("AAD with zero length and non-zero start"));
1320 KASSERT(crp->crp_aad_length == 0 ||
1321 crp->crp_aad_start + crp->crp_aad_length <= ilen,
1322 ("AAD outside input length"));
1324 KASSERT(csp->csp_flags & CSP_F_SEPARATE_AAD,
1325 ("session doesn't support separate AAD buffer"));
1326 KASSERT(crp->crp_aad_start == 0,
1327 ("separate AAD buffer with non-zero AAD start"));
1328 KASSERT(crp->crp_aad_length != 0,
1329 ("separate AAD buffer with zero length"));
1332 KASSERT(crp->crp_aad == NULL && crp->crp_aad_start == 0 &&
1333 crp->crp_aad_length == 0,
1334 ("AAD region in request not supporting AAD"));
1336 if (csp->csp_ivlen == 0) {
1337 KASSERT((crp->crp_flags & CRYPTO_F_IV_SEPARATE) == 0,
1338 ("IV_SEPARATE set when IV isn't used"));
1339 KASSERT(crp->crp_iv_start == 0,
1340 ("crp_iv_start set when IV isn't used"));
1341 } else if (crp->crp_flags & CRYPTO_F_IV_SEPARATE) {
1342 KASSERT(crp->crp_iv_start == 0,
1343 ("IV_SEPARATE used with non-zero IV start"));
1345 KASSERT(crp->crp_iv_start < ilen,
1346 ("invalid IV start"));
1347 KASSERT(crp->crp_iv_start + csp->csp_ivlen <= ilen,
1348 ("IV outside buffer length"));
1350 /* XXX: payload_start of 0 should always be < ilen? */
1351 KASSERT(crp->crp_payload_start == 0 ||
1352 crp->crp_payload_start < ilen,
1353 ("invalid payload start"));
1354 KASSERT(crp->crp_payload_start + crp->crp_payload_length <=
1355 ilen, ("payload outside input buffer"));
1357 KASSERT(crp->crp_payload_output_start == 0,
1358 ("payload output start non-zero without output buffer"));
1360 KASSERT(crp->crp_payload_output_start == 0 ||
1361 crp->crp_payload_output_start < olen,
1362 ("invalid payload output start"));
1363 KASSERT(crp->crp_payload_output_start +
1364 crp->crp_payload_length <= olen,
1365 ("payload outside output buffer"));
1367 if (csp->csp_mode == CSP_MODE_DIGEST ||
1368 csp->csp_mode == CSP_MODE_AEAD || csp->csp_mode == CSP_MODE_ETA) {
1369 if (crp->crp_op & CRYPTO_OP_VERIFY_DIGEST)
1373 KASSERT(crp->crp_digest_start == 0 ||
1374 crp->crp_digest_start < len,
1375 ("invalid digest start"));
1376 /* XXX: For the mlen == 0 case this check isn't perfect. */
1377 KASSERT(crp->crp_digest_start + csp->csp_auth_mlen <= len,
1378 ("digest outside buffer"));
1380 KASSERT(crp->crp_digest_start == 0,
1381 ("non-zero digest start for request without a digest"));
1383 if (csp->csp_cipher_klen != 0)
1384 KASSERT(csp->csp_cipher_key != NULL ||
1385 crp->crp_cipher_key != NULL,
1386 ("cipher request without a key"));
1387 if (csp->csp_auth_klen != 0)
1388 KASSERT(csp->csp_auth_key != NULL || crp->crp_auth_key != NULL,
1389 ("auth request without a key"));
1390 KASSERT(crp->crp_callback != NULL, ("incoming crp without callback"));
1395 crypto_dispatch_one(struct cryptop *crp, int hint)
1397 struct cryptocap *cap;
1403 CRYPTOSTAT_INC(cs_ops);
1405 crp->crp_retw_id = crp->crp_session->id % crypto_workers_num;
1408 * Caller marked the request to be processed immediately; dispatch it
1409 * directly to the driver unless the driver is currently blocked, in
1410 * which case it is queued for deferred dispatch.
1412 cap = crp->crp_session->cap;
1413 if (!atomic_load_int(&cap->cc_qblocked)) {
1414 result = crypto_invoke(cap, crp, hint);
1415 if (result != ERESTART)
1419 * The driver ran out of resources, put the request on the
1423 crypto_batch_enqueue(crp);
1428 crypto_dispatch(struct cryptop *crp)
1430 return (crypto_dispatch_one(crp, 0));
1434 crypto_dispatch_async(struct cryptop *crp, int flags)
1436 struct crypto_ret_worker *ret_worker;
1438 if (!CRYPTO_SESS_SYNC(crp->crp_session)) {
1440 * The driver issues completions asynchonously, don't bother
1441 * deferring dispatch to a worker thread.
1443 return (crypto_dispatch(crp));
1449 CRYPTOSTAT_INC(cs_ops);
1451 crp->crp_retw_id = crp->crp_session->id % crypto_workers_num;
1452 if ((flags & CRYPTO_ASYNC_ORDERED) != 0) {
1453 crp->crp_flags |= CRYPTO_F_ASYNC_ORDERED;
1454 ret_worker = CRYPTO_RETW(crp->crp_retw_id);
1455 CRYPTO_RETW_LOCK(ret_worker);
1456 crp->crp_seq = ret_worker->reorder_ops++;
1457 CRYPTO_RETW_UNLOCK(ret_worker);
1459 TASK_INIT(&crp->crp_task, 0, crypto_task_invoke, crp);
1460 taskqueue_enqueue(crypto_tq, &crp->crp_task);
1465 crypto_dispatch_batch(struct cryptopq *crpq, int flags)
1467 struct cryptop *crp;
1470 while ((crp = TAILQ_FIRST(crpq)) != NULL) {
1471 hint = TAILQ_NEXT(crp, crp_next) != NULL ? CRYPTO_HINT_MORE : 0;
1472 TAILQ_REMOVE(crpq, crp, crp_next);
1473 if (crypto_dispatch_one(crp, hint) != 0)
1474 crypto_batch_enqueue(crp);
1479 crypto_batch_enqueue(struct cryptop *crp)
1483 TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
1490 crypto_task_invoke(void *ctx, int pending)
1492 struct cryptocap *cap;
1493 struct cryptop *crp;
1496 crp = (struct cryptop *)ctx;
1497 cap = crp->crp_session->cap;
1498 result = crypto_invoke(cap, crp, 0);
1499 if (result == ERESTART)
1500 crypto_batch_enqueue(crp);
1504 * Dispatch a crypto request to the appropriate crypto devices.
1507 crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint)
1510 KASSERT(crp != NULL, ("%s: crp == NULL", __func__));
1511 KASSERT(crp->crp_callback != NULL,
1512 ("%s: crp->crp_callback == NULL", __func__));
1513 KASSERT(crp->crp_session != NULL,
1514 ("%s: crp->crp_session == NULL", __func__));
1516 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1517 struct crypto_session_params csp;
1518 crypto_session_t nses;
1521 * Driver has unregistered; migrate the session and return
1522 * an error to the caller so they'll resubmit the op.
1524 * XXX: What if there are more already queued requests for this
1527 * XXX: Real solution is to make sessions refcounted
1528 * and force callers to hold a reference when
1529 * assigning to crp_session. Could maybe change
1530 * crypto_getreq to accept a session pointer to make
1531 * that work. Alternatively, we could abandon the
1532 * notion of rewriting crp_session in requests forcing
1533 * the caller to deal with allocating a new session.
1534 * Perhaps provide a method to allow a crp's session to
1535 * be swapped that callers could use.
1537 csp = crp->crp_session->csp;
1538 crypto_freesession(crp->crp_session);
1541 * XXX: Key pointers may no longer be valid. If we
1542 * really want to support this we need to define the
1543 * KPI such that 'csp' is required to be valid for the
1544 * duration of a session by the caller perhaps.
1546 * XXX: If the keys have been changed this will reuse
1547 * the old keys. This probably suggests making
1548 * rekeying more explicit and updating the key
1549 * pointers in 'csp' when the keys change.
1551 if (crypto_newsession(&nses, &csp,
1552 CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE) == 0)
1553 crp->crp_session = nses;
1555 crp->crp_etype = EAGAIN;
1560 * Invoke the driver to process the request.
1562 return CRYPTODEV_PROCESS(cap->cc_dev, crp, hint);
1567 crypto_destroyreq(struct cryptop *crp)
1571 struct cryptop *crp2;
1572 struct crypto_ret_worker *ret_worker;
1575 TAILQ_FOREACH(crp2, &crp_q, crp_next) {
1576 KASSERT(crp2 != crp,
1577 ("Freeing cryptop from the crypto queue (%p).",
1582 FOREACH_CRYPTO_RETW(ret_worker) {
1583 CRYPTO_RETW_LOCK(ret_worker);
1584 TAILQ_FOREACH(crp2, &ret_worker->crp_ret_q, crp_next) {
1585 KASSERT(crp2 != crp,
1586 ("Freeing cryptop from the return queue (%p).",
1589 CRYPTO_RETW_UNLOCK(ret_worker);
1596 crypto_freereq(struct cryptop *crp)
1601 crypto_destroyreq(crp);
1602 uma_zfree(cryptop_zone, crp);
1606 _crypto_initreq(struct cryptop *crp, crypto_session_t cses)
1608 crp->crp_session = cses;
1612 crypto_initreq(struct cryptop *crp, crypto_session_t cses)
1614 memset(crp, 0, sizeof(*crp));
1615 _crypto_initreq(crp, cses);
1619 crypto_getreq(crypto_session_t cses, int how)
1621 struct cryptop *crp;
1623 MPASS(how == M_WAITOK || how == M_NOWAIT);
1624 crp = uma_zalloc(cryptop_zone, how | M_ZERO);
1626 _crypto_initreq(crp, cses);
1631 * Invoke the callback on behalf of the driver.
1634 crypto_done(struct cryptop *crp)
1636 KASSERT((crp->crp_flags & CRYPTO_F_DONE) == 0,
1637 ("crypto_done: op already done, flags 0x%x", crp->crp_flags));
1638 crp->crp_flags |= CRYPTO_F_DONE;
1639 if (crp->crp_etype != 0)
1640 CRYPTOSTAT_INC(cs_errs);
1643 * CBIMM means unconditionally do the callback immediately;
1644 * CBIFSYNC means do the callback immediately only if the
1645 * operation was done synchronously. Both are used to avoid
1646 * doing extraneous context switches; the latter is mostly
1647 * used with the software crypto driver.
1649 if ((crp->crp_flags & CRYPTO_F_ASYNC_ORDERED) == 0 &&
1650 ((crp->crp_flags & CRYPTO_F_CBIMM) != 0 ||
1651 ((crp->crp_flags & CRYPTO_F_CBIFSYNC) != 0 &&
1652 CRYPTO_SESS_SYNC(crp->crp_session)))) {
1654 * Do the callback directly. This is ok when the
1655 * callback routine does very little (e.g. the
1656 * /dev/crypto callback method just does a wakeup).
1658 crp->crp_callback(crp);
1660 struct crypto_ret_worker *ret_worker;
1663 ret_worker = CRYPTO_RETW(crp->crp_retw_id);
1666 * Normal case; queue the callback for the thread.
1668 CRYPTO_RETW_LOCK(ret_worker);
1669 if ((crp->crp_flags & CRYPTO_F_ASYNC_ORDERED) != 0) {
1670 struct cryptop *tmp;
1672 TAILQ_FOREACH_REVERSE(tmp,
1673 &ret_worker->crp_ordered_ret_q, cryptop_q,
1675 if (CRYPTO_SEQ_GT(crp->crp_seq, tmp->crp_seq)) {
1677 &ret_worker->crp_ordered_ret_q, tmp,
1684 &ret_worker->crp_ordered_ret_q, crp,
1688 wake = crp->crp_seq == ret_worker->reorder_cur_seq;
1690 wake = TAILQ_EMPTY(&ret_worker->crp_ret_q);
1691 TAILQ_INSERT_TAIL(&ret_worker->crp_ret_q, crp,
1696 wakeup_one(&ret_worker->crp_ret_q); /* shared wait channel */
1697 CRYPTO_RETW_UNLOCK(ret_worker);
1702 * Terminate a thread at module unload. The process that
1703 * initiated this is waiting for us to signal that we're gone;
1704 * wake it up and exit. We use the driver table lock to insure
1705 * we don't do the wakeup before they're waiting. There is no
1706 * race here because the waiter sleeps on the proc lock for the
1707 * thread so it gets notified at the right time because of an
1708 * extra wakeup that's done in exit1().
1711 crypto_finis(void *chan)
1713 CRYPTO_DRIVER_LOCK();
1715 CRYPTO_DRIVER_UNLOCK();
1720 * Crypto thread, dispatches crypto requests.
1723 crypto_dispatch_thread(void *arg __unused)
1725 struct cryptop *crp, *submit;
1726 struct cryptocap *cap;
1729 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
1730 fpu_kern_thread(FPU_KERN_NORMAL);
1736 * Find the first element in the queue that can be
1737 * processed and look-ahead to see if multiple ops
1738 * are ready for the same driver.
1742 TAILQ_FOREACH(crp, &crp_q, crp_next) {
1743 cap = crp->crp_session->cap;
1745 * Driver cannot disappeared when there is an active
1748 KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1749 __func__, __LINE__));
1750 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1751 /* Op needs to be migrated, process it. */
1756 if (!cap->cc_qblocked) {
1757 if (submit != NULL) {
1759 * We stop on finding another op,
1760 * regardless whether its for the same
1761 * driver or not. We could keep
1762 * searching the queue but it might be
1763 * better to just use a per-driver
1766 if (submit->crp_session->cap == cap)
1767 hint = CRYPTO_HINT_MORE;
1774 if (submit != NULL) {
1775 TAILQ_REMOVE(&crp_q, submit, crp_next);
1776 cap = submit->crp_session->cap;
1777 KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1778 __func__, __LINE__));
1780 result = crypto_invoke(cap, submit, hint);
1782 if (result == ERESTART) {
1784 * The driver ran out of resources, mark the
1785 * driver ``blocked'' for cryptop's and put
1786 * the request back in the queue. It would
1787 * best to put the request back where we got
1788 * it but that's hard so for now we put it
1789 * at the front. This should be ok; putting
1790 * it at the end does not work.
1792 cap->cc_qblocked = 1;
1793 TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
1794 CRYPTOSTAT_INC(cs_blocks);
1798 * Nothing more to be processed. Sleep until we're
1799 * woken because there are more ops to process.
1800 * This happens either by submission or by a driver
1801 * becoming unblocked and notifying us through
1802 * crypto_unblock. Note that when we wakeup we
1803 * start processing each queue again from the
1804 * front. It's not clear that it's important to
1805 * preserve this ordering since ops may finish
1806 * out of order if dispatched to different devices
1807 * and some become blocked while others do not.
1810 msleep(&crp_q, &crypto_q_mtx, PWAIT, "crypto_wait", 0);
1812 if (cryptotd == NULL)
1814 CRYPTOSTAT_INC(cs_intrs);
1819 crypto_finis(&crp_q);
1823 * Crypto returns thread, does callbacks for processed crypto requests.
1824 * Callbacks are done here, rather than in the crypto drivers, because
1825 * callbacks typically are expensive and would slow interrupt handling.
1828 crypto_ret_thread(void *arg)
1830 struct crypto_ret_worker *ret_worker = arg;
1831 struct cryptop *crpt;
1833 CRYPTO_RETW_LOCK(ret_worker);
1835 /* Harvest return q's for completed ops */
1836 crpt = TAILQ_FIRST(&ret_worker->crp_ordered_ret_q);
1838 if (crpt->crp_seq == ret_worker->reorder_cur_seq) {
1839 TAILQ_REMOVE(&ret_worker->crp_ordered_ret_q, crpt, crp_next);
1840 ret_worker->reorder_cur_seq++;
1847 crpt = TAILQ_FIRST(&ret_worker->crp_ret_q);
1849 TAILQ_REMOVE(&ret_worker->crp_ret_q, crpt, crp_next);
1853 CRYPTO_RETW_UNLOCK(ret_worker);
1855 * Run callbacks unlocked.
1858 crpt->crp_callback(crpt);
1859 CRYPTO_RETW_LOCK(ret_worker);
1862 * Nothing more to be processed. Sleep until we're
1863 * woken because there are more returns to process.
1865 msleep(&ret_worker->crp_ret_q, &ret_worker->crypto_ret_mtx, PWAIT,
1866 "crypto_ret_wait", 0);
1867 if (ret_worker->td == NULL)
1869 CRYPTOSTAT_INC(cs_rets);
1872 CRYPTO_RETW_UNLOCK(ret_worker);
1874 crypto_finis(&ret_worker->crp_ret_q);
1879 db_show_drivers(void)
1883 db_printf("%12s %4s %8s %2s\n"
1889 for (hid = 0; hid < crypto_drivers_size; hid++) {
1890 const struct cryptocap *cap = crypto_drivers[hid];
1893 db_printf("%-12s %4u %08x %2u\n"
1894 , device_get_nameunit(cap->cc_dev)
1902 DB_SHOW_COMMAND(crypto, db_show_crypto)
1904 struct cryptop *crp;
1905 struct crypto_ret_worker *ret_worker;
1910 db_printf("%4s %8s %4s %4s %4s %4s %8s %8s\n",
1911 "HID", "Caps", "Ilen", "Olen", "Etype", "Flags",
1912 "Device", "Callback");
1913 TAILQ_FOREACH(crp, &crp_q, crp_next) {
1914 db_printf("%4u %08x %4u %4u %04x %8p %8p\n"
1915 , crp->crp_session->cap->cc_hid
1916 , (int) crypto_ses2caps(crp->crp_session)
1920 , device_get_nameunit(crp->crp_session->cap->cc_dev)
1924 FOREACH_CRYPTO_RETW(ret_worker) {
1925 db_printf("\n%8s %4s %4s %4s %8s\n",
1926 "ret_worker", "HID", "Etype", "Flags", "Callback");
1927 if (!TAILQ_EMPTY(&ret_worker->crp_ret_q)) {
1928 TAILQ_FOREACH(crp, &ret_worker->crp_ret_q, crp_next) {
1929 db_printf("%8td %4u %4u %04x %8p\n"
1930 , CRYPTO_RETW_ID(ret_worker)
1931 , crp->crp_session->cap->cc_hid
1942 int crypto_modevent(module_t mod, int type, void *unused);
1945 * Initialization code, both for static and dynamic loading.
1946 * Note this is not invoked with the usual MODULE_DECLARE
1947 * mechanism but instead is listed as a dependency by the
1948 * cryptosoft driver. This guarantees proper ordering of
1949 * calls on module load/unload.
1952 crypto_modevent(module_t mod, int type, void *unused)
1958 error = crypto_init();
1959 if (error == 0 && bootverbose)
1960 printf("crypto: <crypto core>\n");
1963 /*XXX disallow if active sessions */
1970 MODULE_VERSION(crypto, 1);
1971 MODULE_DEPEND(crypto, zlib, 1, 1, 1);