2 * Copyright (c) 2002-2006 Sam Leffler. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 #include <sys/cdefs.h>
26 __FBSDID("$FreeBSD$");
29 * Cryptographic Subsystem.
31 * This code is derived from the Openbsd Cryptographic Framework (OCF)
32 * that has the copyright shown below. Very little of the original
37 * The author of this code is Angelos D. Keromytis (angelos@cis.upenn.edu)
39 * This code was written by Angelos D. Keromytis in Athens, Greece, in
40 * February 2000. Network Security Technologies Inc. (NSTI) kindly
41 * supported the development of this code.
43 * Copyright (c) 2000, 2001 Angelos D. Keromytis
45 * Permission to use, copy, and modify this software with or without fee
46 * is hereby granted, provided that this entire notice is included in
47 * all source code copies of any software which is or includes a copy or
48 * modification of this software.
50 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
51 * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
52 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
53 * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
57 #define CRYPTO_TIMING /* enable timing support */
59 #include "opt_compat.h"
62 #include <sys/param.h>
63 #include <sys/systm.h>
64 #include <sys/eventhandler.h>
65 #include <sys/kernel.h>
66 #include <sys/kthread.h>
67 #include <sys/linker.h>
69 #include <sys/module.h>
70 #include <sys/mutex.h>
71 #include <sys/malloc.h>
73 #include <sys/refcount.h>
76 #include <sys/sysctl.h>
77 #include <sys/taskqueue.h>
82 #include <crypto/intake.h>
83 #include <opencrypto/cryptodev.h>
84 #include <opencrypto/xform_auth.h>
85 #include <opencrypto/xform_enc.h>
89 #include "cryptodev_if.h"
91 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
92 #include <machine/pcb.h>
95 SDT_PROVIDER_DEFINE(opencrypto);
98 * Crypto drivers register themselves by allocating a slot in the
99 * crypto_drivers table with crypto_get_driverid() and then registering
100 * each asym algorithm they support with crypto_kregister().
102 static struct mtx crypto_drivers_mtx; /* lock on driver table */
103 #define CRYPTO_DRIVER_LOCK() mtx_lock(&crypto_drivers_mtx)
104 #define CRYPTO_DRIVER_UNLOCK() mtx_unlock(&crypto_drivers_mtx)
105 #define CRYPTO_DRIVER_ASSERT() mtx_assert(&crypto_drivers_mtx, MA_OWNED)
108 * Crypto device/driver capabilities structure.
111 * (d) - protected by CRYPTO_DRIVER_LOCK()
112 * (q) - protected by CRYPTO_Q_LOCK()
113 * Not tagged fields are read-only.
118 u_int32_t cc_sessions; /* (d) # of sessions */
119 u_int32_t cc_koperations; /* (d) # os asym operations */
120 u_int8_t cc_kalg[CRK_ALGORITHM_MAX + 1];
122 int cc_flags; /* (d) flags */
123 #define CRYPTOCAP_F_CLEANUP 0x80000000 /* needs resource cleanup */
124 int cc_qblocked; /* (q) symmetric q blocked */
125 int cc_kqblocked; /* (q) asymmetric q blocked */
126 size_t cc_session_size;
127 volatile int cc_refs;
130 static struct cryptocap **crypto_drivers = NULL;
131 static int crypto_drivers_size = 0;
133 struct crypto_session {
134 struct cryptocap *cap;
136 struct crypto_session_params csp;
140 * There are two queues for crypto requests; one for symmetric (e.g.
141 * cipher) operations and one for asymmetric (e.g. MOD)operations.
142 * A single mutex is used to lock access to both queues. We could
143 * have one per-queue but having one simplifies handling of block/unblock
146 static int crp_sleep = 0;
147 static TAILQ_HEAD(cryptop_q ,cryptop) crp_q; /* request queues */
148 static TAILQ_HEAD(,cryptkop) crp_kq;
149 static struct mtx crypto_q_mtx;
150 #define CRYPTO_Q_LOCK() mtx_lock(&crypto_q_mtx)
151 #define CRYPTO_Q_UNLOCK() mtx_unlock(&crypto_q_mtx)
153 static SYSCTL_NODE(_kern, OID_AUTO, crypto, CTLFLAG_RW, 0,
154 "In-kernel cryptography");
157 * Taskqueue used to dispatch the crypto requests
158 * that have the CRYPTO_F_ASYNC flag
160 static struct taskqueue *crypto_tq;
163 * Crypto seq numbers are operated on with modular arithmetic
165 #define CRYPTO_SEQ_GT(a,b) ((int)((a)-(b)) > 0)
167 struct crypto_ret_worker {
168 struct mtx crypto_ret_mtx;
170 TAILQ_HEAD(,cryptop) crp_ordered_ret_q; /* ordered callback queue for symetric jobs */
171 TAILQ_HEAD(,cryptop) crp_ret_q; /* callback queue for symetric jobs */
172 TAILQ_HEAD(,cryptkop) crp_ret_kq; /* callback queue for asym jobs */
174 u_int32_t reorder_ops; /* total ordered sym jobs received */
175 u_int32_t reorder_cur_seq; /* current sym job dispatched */
177 struct proc *cryptoretproc;
179 static struct crypto_ret_worker *crypto_ret_workers = NULL;
181 #define CRYPTO_RETW(i) (&crypto_ret_workers[i])
182 #define CRYPTO_RETW_ID(w) ((w) - crypto_ret_workers)
183 #define FOREACH_CRYPTO_RETW(w) \
184 for (w = crypto_ret_workers; w < crypto_ret_workers + crypto_workers_num; ++w)
186 #define CRYPTO_RETW_LOCK(w) mtx_lock(&w->crypto_ret_mtx)
187 #define CRYPTO_RETW_UNLOCK(w) mtx_unlock(&w->crypto_ret_mtx)
188 #define CRYPTO_RETW_EMPTY(w) \
189 (TAILQ_EMPTY(&w->crp_ret_q) && TAILQ_EMPTY(&w->crp_ret_kq) && TAILQ_EMPTY(&w->crp_ordered_ret_q))
191 static int crypto_workers_num = 0;
192 SYSCTL_INT(_kern_crypto, OID_AUTO, num_workers, CTLFLAG_RDTUN,
193 &crypto_workers_num, 0,
194 "Number of crypto workers used to dispatch crypto jobs");
195 #ifdef COMPAT_FREEBSD12
196 SYSCTL_INT(_kern, OID_AUTO, crypto_workers_num, CTLFLAG_RDTUN,
197 &crypto_workers_num, 0,
198 "Number of crypto workers used to dispatch crypto jobs");
201 static uma_zone_t cryptop_zone;
202 static uma_zone_t cryptoses_zone;
204 int crypto_userasymcrypto = 1;
205 SYSCTL_INT(_kern_crypto, OID_AUTO, asym_enable, CTLFLAG_RW,
206 &crypto_userasymcrypto, 0,
207 "Enable user-mode access to asymmetric crypto support");
208 #ifdef COMPAT_FREEBSD12
209 SYSCTL_INT(_kern, OID_AUTO, userasymcrypto, CTLFLAG_RW,
210 &crypto_userasymcrypto, 0,
211 "Enable/disable user-mode access to asymmetric crypto support");
214 int crypto_devallowsoft = 0;
215 SYSCTL_INT(_kern_crypto, OID_AUTO, allow_soft, CTLFLAG_RW,
216 &crypto_devallowsoft, 0,
217 "Enable use of software crypto by /dev/crypto");
218 #ifdef COMPAT_FREEBSD12
219 SYSCTL_INT(_kern, OID_AUTO, cryptodevallowsoft, CTLFLAG_RW,
220 &crypto_devallowsoft, 0,
221 "Enable/disable use of software crypto by /dev/crypto");
224 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
226 static void crypto_proc(void);
227 static struct proc *cryptoproc;
228 static void crypto_ret_proc(struct crypto_ret_worker *ret_worker);
229 static void crypto_destroy(void);
230 static int crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint);
231 static int crypto_kinvoke(struct cryptkop *krp);
232 static void crypto_task_invoke(void *ctx, int pending);
233 static void crypto_batch_enqueue(struct cryptop *crp);
235 static struct cryptostats cryptostats;
236 SYSCTL_STRUCT(_kern_crypto, OID_AUTO, stats, CTLFLAG_RW, &cryptostats,
237 cryptostats, "Crypto system statistics");
240 static int crypto_timing = 0;
241 SYSCTL_INT(_debug, OID_AUTO, crypto_timing, CTLFLAG_RW,
242 &crypto_timing, 0, "Enable/disable crypto timing support");
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... */
271 struct keybuf * get_keybuf(void) {
276 static struct cryptocap *
277 cap_ref(struct cryptocap *cap)
280 refcount_acquire(&cap->cc_refs);
285 cap_rele(struct cryptocap *cap)
288 if (refcount_release(&cap->cc_refs) == 0)
291 KASSERT(cap->cc_sessions == 0,
292 ("freeing crypto driver with active sessions"));
293 KASSERT(cap->cc_koperations == 0,
294 ("freeing crypto driver with active key operations"));
296 free(cap, M_CRYPTO_DATA);
302 struct crypto_ret_worker *ret_worker;
305 mtx_init(&crypto_drivers_mtx, "crypto", "crypto driver table",
310 mtx_init(&crypto_q_mtx, "crypto", "crypto op queues", MTX_DEF);
312 cryptop_zone = uma_zcreate("cryptop", sizeof (struct cryptop),
314 UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
315 cryptoses_zone = uma_zcreate("crypto_session",
316 sizeof(struct crypto_session), NULL, NULL, NULL, NULL,
317 UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
319 if (cryptop_zone == NULL || cryptoses_zone == NULL) {
320 printf("crypto_init: cannot setup crypto zones\n");
325 crypto_drivers_size = CRYPTO_DRIVERS_INITIAL;
326 crypto_drivers = malloc(crypto_drivers_size *
327 sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT | M_ZERO);
328 if (crypto_drivers == NULL) {
329 printf("crypto_init: cannot setup crypto drivers\n");
334 if (crypto_workers_num < 1 || crypto_workers_num > mp_ncpus)
335 crypto_workers_num = mp_ncpus;
337 crypto_tq = taskqueue_create("crypto", M_WAITOK|M_ZERO,
338 taskqueue_thread_enqueue, &crypto_tq);
339 if (crypto_tq == NULL) {
340 printf("crypto init: cannot setup crypto taskqueue\n");
345 taskqueue_start_threads(&crypto_tq, crypto_workers_num, PRI_MIN_KERN,
348 error = kproc_create((void (*)(void *)) crypto_proc, NULL,
349 &cryptoproc, 0, 0, "crypto");
351 printf("crypto_init: cannot start crypto thread; error %d",
356 crypto_ret_workers = malloc(crypto_workers_num * sizeof(struct crypto_ret_worker),
357 M_CRYPTO_DATA, M_NOWAIT|M_ZERO);
358 if (crypto_ret_workers == NULL) {
360 printf("crypto_init: cannot allocate ret workers\n");
365 FOREACH_CRYPTO_RETW(ret_worker) {
366 TAILQ_INIT(&ret_worker->crp_ordered_ret_q);
367 TAILQ_INIT(&ret_worker->crp_ret_q);
368 TAILQ_INIT(&ret_worker->crp_ret_kq);
370 ret_worker->reorder_ops = 0;
371 ret_worker->reorder_cur_seq = 0;
373 mtx_init(&ret_worker->crypto_ret_mtx, "crypto", "crypto return queues", MTX_DEF);
375 error = kproc_create((void (*)(void *)) crypto_ret_proc, ret_worker,
376 &ret_worker->cryptoretproc, 0, 0, "crypto returns %td", CRYPTO_RETW_ID(ret_worker));
378 printf("crypto_init: cannot start cryptoret thread; error %d",
393 * Signal a crypto thread to terminate. We use the driver
394 * table lock to synchronize the sleep/wakeups so that we
395 * are sure the threads have terminated before we release
396 * the data structures they use. See crypto_finis below
397 * for the other half of this song-and-dance.
400 crypto_terminate(struct proc **pp, void *q)
404 mtx_assert(&crypto_drivers_mtx, MA_OWNED);
409 PROC_LOCK(p); /* NB: insure we don't miss wakeup */
410 CRYPTO_DRIVER_UNLOCK(); /* let crypto_finis progress */
411 msleep(p, &p->p_mtx, PWAIT, "crypto_destroy", 0);
413 CRYPTO_DRIVER_LOCK();
418 hmac_init_pad(struct auth_hash *axf, const char *key, int klen, void *auth_ctx,
421 uint8_t hmac_key[HMAC_MAX_BLOCK_LEN];
424 KASSERT(axf->blocksize <= sizeof(hmac_key),
425 ("Invalid HMAC block size %d", axf->blocksize));
428 * If the key is larger than the block size, use the digest of
429 * the key as the key instead.
431 memset(hmac_key, 0, sizeof(hmac_key));
432 if (klen > axf->blocksize) {
434 axf->Update(auth_ctx, key, klen);
435 axf->Final(hmac_key, auth_ctx);
436 klen = axf->hashsize;
438 memcpy(hmac_key, key, klen);
440 for (i = 0; i < axf->blocksize; i++)
441 hmac_key[i] ^= padval;
444 axf->Update(auth_ctx, hmac_key, axf->blocksize);
448 hmac_init_ipad(struct auth_hash *axf, const char *key, int klen,
452 hmac_init_pad(axf, key, klen, auth_ctx, HMAC_IPAD_VAL);
456 hmac_init_opad(struct auth_hash *axf, const char *key, int klen,
460 hmac_init_pad(axf, key, klen, auth_ctx, HMAC_OPAD_VAL);
466 struct crypto_ret_worker *ret_worker;
470 * Terminate any crypto threads.
472 if (crypto_tq != NULL)
473 taskqueue_drain_all(crypto_tq);
474 CRYPTO_DRIVER_LOCK();
475 crypto_terminate(&cryptoproc, &crp_q);
476 FOREACH_CRYPTO_RETW(ret_worker)
477 crypto_terminate(&ret_worker->cryptoretproc, &ret_worker->crp_ret_q);
478 CRYPTO_DRIVER_UNLOCK();
480 /* XXX flush queues??? */
483 * Reclaim dynamically allocated resources.
485 for (i = 0; i < crypto_drivers_size; i++) {
486 if (crypto_drivers[i] != NULL)
487 cap_rele(crypto_drivers[i]);
489 free(crypto_drivers, M_CRYPTO_DATA);
491 if (cryptoses_zone != NULL)
492 uma_zdestroy(cryptoses_zone);
493 if (cryptop_zone != NULL)
494 uma_zdestroy(cryptop_zone);
495 mtx_destroy(&crypto_q_mtx);
496 FOREACH_CRYPTO_RETW(ret_worker)
497 mtx_destroy(&ret_worker->crypto_ret_mtx);
498 free(crypto_ret_workers, M_CRYPTO_DATA);
499 if (crypto_tq != NULL)
500 taskqueue_free(crypto_tq);
501 mtx_destroy(&crypto_drivers_mtx);
505 crypto_ses2hid(crypto_session_t crypto_session)
507 return (crypto_session->cap->cc_hid);
511 crypto_ses2caps(crypto_session_t crypto_session)
513 return (crypto_session->cap->cc_flags & 0xff000000);
517 crypto_get_driver_session(crypto_session_t crypto_session)
519 return (crypto_session->softc);
522 const struct crypto_session_params *
523 crypto_get_params(crypto_session_t crypto_session)
525 return (&crypto_session->csp);
529 crypto_auth_hash(const struct crypto_session_params *csp)
532 switch (csp->csp_auth_alg) {
533 case CRYPTO_SHA1_HMAC:
534 return (&auth_hash_hmac_sha1);
535 case CRYPTO_SHA2_224_HMAC:
536 return (&auth_hash_hmac_sha2_224);
537 case CRYPTO_SHA2_256_HMAC:
538 return (&auth_hash_hmac_sha2_256);
539 case CRYPTO_SHA2_384_HMAC:
540 return (&auth_hash_hmac_sha2_384);
541 case CRYPTO_SHA2_512_HMAC:
542 return (&auth_hash_hmac_sha2_512);
543 case CRYPTO_NULL_HMAC:
544 return (&auth_hash_null);
545 case CRYPTO_RIPEMD160_HMAC:
546 return (&auth_hash_hmac_ripemd_160);
548 return (&auth_hash_sha1);
549 case CRYPTO_SHA2_224:
550 return (&auth_hash_sha2_224);
551 case CRYPTO_SHA2_256:
552 return (&auth_hash_sha2_256);
553 case CRYPTO_SHA2_384:
554 return (&auth_hash_sha2_384);
555 case CRYPTO_SHA2_512:
556 return (&auth_hash_sha2_512);
557 case CRYPTO_AES_NIST_GMAC:
558 switch (csp->csp_auth_klen) {
560 return (&auth_hash_nist_gmac_aes_128);
562 return (&auth_hash_nist_gmac_aes_192);
564 return (&auth_hash_nist_gmac_aes_256);
569 return (&auth_hash_blake2b);
571 return (&auth_hash_blake2s);
572 case CRYPTO_POLY1305:
573 return (&auth_hash_poly1305);
574 case CRYPTO_AES_CCM_CBC_MAC:
575 switch (csp->csp_auth_klen) {
577 return (&auth_hash_ccm_cbc_mac_128);
579 return (&auth_hash_ccm_cbc_mac_192);
581 return (&auth_hash_ccm_cbc_mac_256);
591 crypto_cipher(const struct crypto_session_params *csp)
594 switch (csp->csp_cipher_alg) {
595 case CRYPTO_RIJNDAEL128_CBC:
596 return (&enc_xform_rijndael128);
598 return (&enc_xform_aes_xts);
600 return (&enc_xform_aes_icm);
601 case CRYPTO_AES_NIST_GCM_16:
602 return (&enc_xform_aes_nist_gcm);
603 case CRYPTO_CAMELLIA_CBC:
604 return (&enc_xform_camellia);
605 case CRYPTO_NULL_CBC:
606 return (&enc_xform_null);
607 case CRYPTO_CHACHA20:
608 return (&enc_xform_chacha20);
609 case CRYPTO_AES_CCM_16:
610 return (&enc_xform_ccm);
616 static struct cryptocap *
617 crypto_checkdriver(u_int32_t hid)
620 return (hid >= crypto_drivers_size ? NULL : crypto_drivers[hid]);
624 * Select a driver for a new session that supports the specified
625 * algorithms and, optionally, is constrained according to the flags.
627 static struct cryptocap *
628 crypto_select_driver(const struct crypto_session_params *csp, int flags)
630 struct cryptocap *cap, *best;
631 int best_match, error, hid;
633 CRYPTO_DRIVER_ASSERT();
636 for (hid = 0; hid < crypto_drivers_size; hid++) {
638 * If there is no driver for this slot, or the driver
639 * is not appropriate (hardware or software based on
642 cap = crypto_drivers[hid];
644 (cap->cc_flags & flags) == 0)
647 error = CRYPTODEV_PROBESESSION(cap->cc_dev, csp);
652 * Use the driver with the highest probe value.
653 * Hardware drivers use a higher probe value than
654 * software. In case of a tie, prefer the driver with
655 * the fewest active sessions.
657 if (best == NULL || error > best_match ||
658 (error == best_match &&
659 cap->cc_sessions < best->cc_sessions)) {
667 static enum alg_type {
675 [CRYPTO_SHA1_HMAC] = ALG_KEYED_DIGEST,
676 [CRYPTO_RIPEMD160_HMAC] = ALG_KEYED_DIGEST,
677 [CRYPTO_AES_CBC] = ALG_CIPHER,
678 [CRYPTO_SHA1] = ALG_DIGEST,
679 [CRYPTO_NULL_HMAC] = ALG_DIGEST,
680 [CRYPTO_NULL_CBC] = ALG_CIPHER,
681 [CRYPTO_DEFLATE_COMP] = ALG_COMPRESSION,
682 [CRYPTO_SHA2_256_HMAC] = ALG_KEYED_DIGEST,
683 [CRYPTO_SHA2_384_HMAC] = ALG_KEYED_DIGEST,
684 [CRYPTO_SHA2_512_HMAC] = ALG_KEYED_DIGEST,
685 [CRYPTO_CAMELLIA_CBC] = ALG_CIPHER,
686 [CRYPTO_AES_XTS] = ALG_CIPHER,
687 [CRYPTO_AES_ICM] = ALG_CIPHER,
688 [CRYPTO_AES_NIST_GMAC] = ALG_KEYED_DIGEST,
689 [CRYPTO_AES_NIST_GCM_16] = ALG_AEAD,
690 [CRYPTO_BLAKE2B] = ALG_KEYED_DIGEST,
691 [CRYPTO_BLAKE2S] = ALG_KEYED_DIGEST,
692 [CRYPTO_CHACHA20] = ALG_CIPHER,
693 [CRYPTO_SHA2_224_HMAC] = ALG_KEYED_DIGEST,
694 [CRYPTO_RIPEMD160] = ALG_DIGEST,
695 [CRYPTO_SHA2_224] = ALG_DIGEST,
696 [CRYPTO_SHA2_256] = ALG_DIGEST,
697 [CRYPTO_SHA2_384] = ALG_DIGEST,
698 [CRYPTO_SHA2_512] = ALG_DIGEST,
699 [CRYPTO_POLY1305] = ALG_KEYED_DIGEST,
700 [CRYPTO_AES_CCM_CBC_MAC] = ALG_KEYED_DIGEST,
701 [CRYPTO_AES_CCM_16] = ALG_AEAD,
708 if (alg < nitems(alg_types))
709 return (alg_types[alg]);
714 alg_is_compression(int alg)
717 return (alg_type(alg) == ALG_COMPRESSION);
721 alg_is_cipher(int alg)
724 return (alg_type(alg) == ALG_CIPHER);
728 alg_is_digest(int alg)
731 return (alg_type(alg) == ALG_DIGEST ||
732 alg_type(alg) == ALG_KEYED_DIGEST);
736 alg_is_keyed_digest(int alg)
739 return (alg_type(alg) == ALG_KEYED_DIGEST);
746 return (alg_type(alg) == ALG_AEAD);
749 /* Various sanity checks on crypto session parameters. */
751 check_csp(const struct crypto_session_params *csp)
753 struct auth_hash *axf;
755 /* Mode-independent checks. */
756 if (csp->csp_flags != 0)
758 if (csp->csp_ivlen < 0 || csp->csp_cipher_klen < 0 ||
759 csp->csp_auth_klen < 0 || csp->csp_auth_mlen < 0)
761 if (csp->csp_auth_key != NULL && csp->csp_auth_klen == 0)
763 if (csp->csp_cipher_key != NULL && csp->csp_cipher_klen == 0)
766 switch (csp->csp_mode) {
767 case CSP_MODE_COMPRESS:
768 if (!alg_is_compression(csp->csp_cipher_alg))
770 if (csp->csp_flags != 0)
772 if (csp->csp_cipher_klen != 0 || csp->csp_ivlen != 0 ||
773 csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0 ||
774 csp->csp_auth_mlen != 0)
777 case CSP_MODE_CIPHER:
778 if (!alg_is_cipher(csp->csp_cipher_alg))
780 if (csp->csp_cipher_alg != CRYPTO_NULL_CBC) {
781 if (csp->csp_cipher_klen == 0)
783 if (csp->csp_ivlen == 0)
786 if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
788 if (csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0 ||
789 csp->csp_auth_mlen != 0)
792 case CSP_MODE_DIGEST:
793 if (csp->csp_cipher_alg != 0 || csp->csp_cipher_klen != 0)
796 /* IV is optional for digests (e.g. GMAC). */
797 if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
799 if (!alg_is_digest(csp->csp_auth_alg))
802 /* Key is optional for BLAKE2 digests. */
803 if (csp->csp_auth_alg == CRYPTO_BLAKE2B ||
804 csp->csp_auth_alg == CRYPTO_BLAKE2S)
806 else if (alg_is_keyed_digest(csp->csp_auth_alg)) {
807 if (csp->csp_auth_klen == 0)
810 if (csp->csp_auth_klen != 0)
813 if (csp->csp_auth_mlen != 0) {
814 axf = crypto_auth_hash(csp);
815 if (axf == NULL || csp->csp_auth_mlen > axf->hashsize)
820 if (!alg_is_aead(csp->csp_cipher_alg))
822 if (csp->csp_cipher_klen == 0)
824 if (csp->csp_ivlen == 0 ||
825 csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
827 if (csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0)
831 * XXX: Would be nice to have a better way to get this
834 switch (csp->csp_cipher_alg) {
835 case CRYPTO_AES_NIST_GCM_16:
836 case CRYPTO_AES_CCM_16:
837 if (csp->csp_auth_mlen > 16)
843 if (!alg_is_cipher(csp->csp_cipher_alg))
845 if (csp->csp_cipher_alg != CRYPTO_NULL_CBC) {
846 if (csp->csp_cipher_klen == 0)
848 if (csp->csp_ivlen == 0)
851 if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
853 if (!alg_is_digest(csp->csp_auth_alg))
856 /* Key is optional for BLAKE2 digests. */
857 if (csp->csp_auth_alg == CRYPTO_BLAKE2B ||
858 csp->csp_auth_alg == CRYPTO_BLAKE2S)
860 else if (alg_is_keyed_digest(csp->csp_auth_alg)) {
861 if (csp->csp_auth_klen == 0)
864 if (csp->csp_auth_klen != 0)
867 if (csp->csp_auth_mlen != 0) {
868 axf = crypto_auth_hash(csp);
869 if (axf == NULL || csp->csp_auth_mlen > axf->hashsize)
881 * Delete a session after it has been detached from its driver.
884 crypto_deletesession(crypto_session_t cses)
886 struct cryptocap *cap;
890 explicit_bzero(cses->softc, cap->cc_session_size);
891 free(cses->softc, M_CRYPTO_DATA);
892 uma_zfree(cryptoses_zone, cses);
894 CRYPTO_DRIVER_LOCK();
896 if (cap->cc_sessions == 0 && cap->cc_flags & CRYPTOCAP_F_CLEANUP)
898 CRYPTO_DRIVER_UNLOCK();
903 * Create a new session. The crid argument specifies a crypto
904 * driver to use or constraints on a driver to select (hardware
905 * only, software only, either). Whatever driver is selected
906 * must be capable of the requested crypto algorithms.
909 crypto_newsession(crypto_session_t *cses,
910 const struct crypto_session_params *csp, int crid)
912 crypto_session_t res;
913 struct cryptocap *cap;
921 CRYPTO_DRIVER_LOCK();
922 if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
924 * Use specified driver; verify it is capable.
926 cap = crypto_checkdriver(crid);
927 if (cap != NULL && CRYPTODEV_PROBESESSION(cap->cc_dev, csp) > 0)
931 * No requested driver; select based on crid flags.
933 cap = crypto_select_driver(csp, crid);
936 CRYPTO_DRIVER_UNLOCK();
937 CRYPTDEB("no driver");
942 CRYPTO_DRIVER_UNLOCK();
944 res = uma_zalloc(cryptoses_zone, M_WAITOK | M_ZERO);
946 res->softc = malloc(cap->cc_session_size, M_CRYPTO_DATA, M_WAITOK |
950 /* Call the driver initialization routine. */
951 err = CRYPTODEV_NEWSESSION(cap->cc_dev, res, csp);
953 CRYPTDEB("dev newsession failed: %d", err);
954 crypto_deletesession(res);
963 * Delete an existing session (or a reserved session on an unregistered
967 crypto_freesession(crypto_session_t cses)
969 struct cryptocap *cap;
976 /* Call the driver cleanup routine, if available. */
977 CRYPTODEV_FREESESSION(cap->cc_dev, cses);
979 crypto_deletesession(cses);
983 * Return a new driver id. Registers a driver with the system so that
984 * it can be probed by subsequent sessions.
987 crypto_get_driverid(device_t dev, size_t sessionsize, int flags)
989 struct cryptocap *cap, **newdrv;
992 if ((flags & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
994 "no flags specified when registering driver\n");
998 cap = malloc(sizeof(*cap), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
1000 cap->cc_session_size = sessionsize;
1001 cap->cc_flags = flags;
1002 refcount_init(&cap->cc_refs, 1);
1004 CRYPTO_DRIVER_LOCK();
1006 for (i = 0; i < crypto_drivers_size; i++) {
1007 if (crypto_drivers[i] == NULL)
1011 if (i < crypto_drivers_size)
1014 /* Out of entries, allocate some more. */
1016 if (2 * crypto_drivers_size <= crypto_drivers_size) {
1017 CRYPTO_DRIVER_UNLOCK();
1018 printf("crypto: driver count wraparound!\n");
1022 CRYPTO_DRIVER_UNLOCK();
1024 newdrv = malloc(2 * crypto_drivers_size *
1025 sizeof(*crypto_drivers), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
1027 CRYPTO_DRIVER_LOCK();
1028 memcpy(newdrv, crypto_drivers,
1029 crypto_drivers_size * sizeof(*crypto_drivers));
1031 crypto_drivers_size *= 2;
1033 free(crypto_drivers, M_CRYPTO_DATA);
1034 crypto_drivers = newdrv;
1038 crypto_drivers[i] = cap;
1039 CRYPTO_DRIVER_UNLOCK();
1042 printf("crypto: assign %s driver id %u, flags 0x%x\n",
1043 device_get_nameunit(dev), i, flags);
1049 * Lookup a driver by name. We match against the full device
1050 * name and unit, and against just the name. The latter gives
1051 * us a simple widlcarding by device name. On success return the
1052 * driver/hardware identifier; otherwise return -1.
1055 crypto_find_driver(const char *match)
1057 struct cryptocap *cap;
1058 int i, len = strlen(match);
1060 CRYPTO_DRIVER_LOCK();
1061 for (i = 0; i < crypto_drivers_size; i++) {
1062 if (crypto_drivers[i] == NULL)
1064 cap = crypto_drivers[i];
1065 if (strncmp(match, device_get_nameunit(cap->cc_dev), len) == 0 ||
1066 strncmp(match, device_get_name(cap->cc_dev), len) == 0) {
1067 CRYPTO_DRIVER_UNLOCK();
1071 CRYPTO_DRIVER_UNLOCK();
1076 * Return the device_t for the specified driver or NULL
1077 * if the driver identifier is invalid.
1080 crypto_find_device_byhid(int hid)
1082 struct cryptocap *cap;
1086 CRYPTO_DRIVER_LOCK();
1087 cap = crypto_checkdriver(hid);
1090 CRYPTO_DRIVER_UNLOCK();
1095 * Return the device/driver capabilities.
1098 crypto_getcaps(int hid)
1100 struct cryptocap *cap;
1104 CRYPTO_DRIVER_LOCK();
1105 cap = crypto_checkdriver(hid);
1107 flags = cap->cc_flags;
1108 CRYPTO_DRIVER_UNLOCK();
1113 * Register support for a key-related algorithm. This routine
1114 * is called once for each algorithm supported a driver.
1117 crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags)
1119 struct cryptocap *cap;
1122 CRYPTO_DRIVER_LOCK();
1124 cap = crypto_checkdriver(driverid);
1126 (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
1128 * XXX Do some performance testing to determine placing.
1129 * XXX We probably need an auxiliary data structure that
1130 * XXX describes relative performances.
1133 cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
1135 printf("crypto: %s registers key alg %u flags %u\n"
1136 , device_get_nameunit(cap->cc_dev)
1144 CRYPTO_DRIVER_UNLOCK();
1149 * Unregister all algorithms associated with a crypto driver.
1150 * If there are pending sessions using it, leave enough information
1151 * around so that subsequent calls using those sessions will
1152 * correctly detect the driver has been unregistered and reroute
1156 crypto_unregister_all(u_int32_t driverid)
1158 struct cryptocap *cap;
1160 CRYPTO_DRIVER_LOCK();
1161 cap = crypto_checkdriver(driverid);
1163 CRYPTO_DRIVER_UNLOCK();
1167 cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
1168 crypto_drivers[driverid] = NULL;
1171 * XXX: This doesn't do anything to kick sessions that
1172 * have no pending operations.
1174 while (cap->cc_sessions != 0 || cap->cc_koperations != 0)
1175 mtx_sleep(cap, &crypto_drivers_mtx, 0, "cryunreg", 0);
1176 CRYPTO_DRIVER_UNLOCK();
1183 * Clear blockage on a driver. The what parameter indicates whether
1184 * the driver is now ready for cryptop's and/or cryptokop's.
1187 crypto_unblock(u_int32_t driverid, int what)
1189 struct cryptocap *cap;
1193 cap = crypto_checkdriver(driverid);
1195 if (what & CRYPTO_SYMQ)
1196 cap->cc_qblocked = 0;
1197 if (what & CRYPTO_ASYMQ)
1198 cap->cc_kqblocked = 0;
1210 /* Various sanity checks on crypto requests. */
1212 crp_sanity(struct cryptop *crp)
1214 struct crypto_session_params *csp;
1216 KASSERT(crp->crp_session != NULL, ("incoming crp without a session"));
1217 KASSERT(crp->crp_ilen >= 0, ("incoming crp with -ve input length"));
1218 KASSERT(crp->crp_etype == 0, ("incoming crp with error"));
1219 KASSERT(!(crp->crp_flags & CRYPTO_F_DONE),
1220 ("incoming crp already done"));
1222 csp = &crp->crp_session->csp;
1223 switch (csp->csp_mode) {
1224 case CSP_MODE_COMPRESS:
1225 KASSERT(crp->crp_op == CRYPTO_OP_COMPRESS ||
1226 crp->crp_op == CRYPTO_OP_DECOMPRESS,
1227 ("invalid compression op %x", crp->crp_op));
1229 case CSP_MODE_CIPHER:
1230 KASSERT(crp->crp_op == CRYPTO_OP_ENCRYPT ||
1231 crp->crp_op == CRYPTO_OP_DECRYPT,
1232 ("invalid cipher op %x", crp->crp_op));
1234 case CSP_MODE_DIGEST:
1235 KASSERT(crp->crp_op == CRYPTO_OP_COMPUTE_DIGEST ||
1236 crp->crp_op == CRYPTO_OP_VERIFY_DIGEST,
1237 ("invalid digest op %x", crp->crp_op));
1240 KASSERT(crp->crp_op ==
1241 (CRYPTO_OP_ENCRYPT | CRYPTO_OP_COMPUTE_DIGEST) ||
1243 (CRYPTO_OP_DECRYPT | CRYPTO_OP_VERIFY_DIGEST),
1244 ("invalid AEAD op %x", crp->crp_op));
1245 if (csp->csp_cipher_alg == CRYPTO_AES_NIST_GCM_16)
1246 KASSERT(crp->crp_flags & CRYPTO_F_IV_SEPARATE,
1247 ("GCM without a separate IV"));
1248 if (csp->csp_cipher_alg == CRYPTO_AES_CCM_16)
1249 KASSERT(crp->crp_flags & CRYPTO_F_IV_SEPARATE,
1250 ("CCM without a separate IV"));
1253 KASSERT(crp->crp_op ==
1254 (CRYPTO_OP_ENCRYPT | CRYPTO_OP_COMPUTE_DIGEST) ||
1256 (CRYPTO_OP_DECRYPT | CRYPTO_OP_VERIFY_DIGEST),
1257 ("invalid ETA op %x", crp->crp_op));
1260 KASSERT(crp->crp_buf_type >= CRYPTO_BUF_CONTIG &&
1261 crp->crp_buf_type <= CRYPTO_BUF_MBUF,
1262 ("invalid crp buffer type %d", crp->crp_buf_type));
1263 if (csp->csp_mode == CSP_MODE_AEAD || csp->csp_mode == CSP_MODE_ETA) {
1264 KASSERT(crp->crp_aad_start == 0 ||
1265 crp->crp_aad_start < crp->crp_ilen,
1266 ("invalid AAD start"));
1267 KASSERT(crp->crp_aad_length != 0 || crp->crp_aad_start == 0,
1268 ("AAD with zero length and non-zero start"));
1269 KASSERT(crp->crp_aad_length == 0 ||
1270 crp->crp_aad_start + crp->crp_aad_length <= crp->crp_ilen,
1271 ("AAD outside input length"));
1273 KASSERT(crp->crp_aad_start == 0 && crp->crp_aad_length == 0,
1274 ("AAD region in request not supporting AAD"));
1276 if (csp->csp_ivlen == 0) {
1277 KASSERT((crp->crp_flags & CRYPTO_F_IV_SEPARATE) == 0,
1278 ("IV_SEPARATE set when IV isn't used"));
1279 KASSERT(crp->crp_iv_start == 0,
1280 ("crp_iv_start set when IV isn't used"));
1281 } else if (crp->crp_flags & CRYPTO_F_IV_SEPARATE) {
1282 KASSERT(crp->crp_iv_start == 0,
1283 ("IV_SEPARATE used with non-zero IV start"));
1285 KASSERT(crp->crp_iv_start < crp->crp_ilen,
1286 ("invalid IV start"));
1287 KASSERT(crp->crp_iv_start + csp->csp_ivlen <= crp->crp_ilen,
1288 ("IV outside input length"));
1290 KASSERT(crp->crp_payload_start == 0 ||
1291 crp->crp_payload_start < crp->crp_ilen,
1292 ("invalid payload start"));
1293 KASSERT(crp->crp_payload_start + crp->crp_payload_length <=
1294 crp->crp_ilen, ("payload outside input length"));
1295 if (csp->csp_mode == CSP_MODE_DIGEST ||
1296 csp->csp_mode == CSP_MODE_AEAD || csp->csp_mode == CSP_MODE_ETA) {
1297 KASSERT(crp->crp_digest_start == 0 ||
1298 crp->crp_digest_start < crp->crp_ilen,
1299 ("invalid digest start"));
1300 /* XXX: For the mlen == 0 case this check isn't perfect. */
1301 KASSERT(crp->crp_digest_start + csp->csp_auth_mlen <=
1303 ("digest outside input length"));
1305 KASSERT(crp->crp_digest_start == 0,
1306 ("non-zero digest start for request without a digest"));
1308 if (csp->csp_cipher_klen != 0)
1309 KASSERT(csp->csp_cipher_key != NULL ||
1310 crp->crp_cipher_key != NULL,
1311 ("cipher request without a key"));
1312 if (csp->csp_auth_klen != 0)
1313 KASSERT(csp->csp_auth_key != NULL || crp->crp_auth_key != NULL,
1314 ("auth request without a key"));
1315 KASSERT(crp->crp_callback != NULL, ("incoming crp without callback"));
1320 * Add a crypto request to a queue, to be processed by the kernel thread.
1323 crypto_dispatch(struct cryptop *crp)
1325 struct cryptocap *cap;
1332 cryptostats.cs_ops++;
1334 #ifdef CRYPTO_TIMING
1336 binuptime(&crp->crp_tstamp);
1339 crp->crp_retw_id = ((uintptr_t)crp->crp_session) % crypto_workers_num;
1341 if (CRYPTOP_ASYNC(crp)) {
1342 if (crp->crp_flags & CRYPTO_F_ASYNC_KEEPORDER) {
1343 struct crypto_ret_worker *ret_worker;
1345 ret_worker = CRYPTO_RETW(crp->crp_retw_id);
1347 CRYPTO_RETW_LOCK(ret_worker);
1348 crp->crp_seq = ret_worker->reorder_ops++;
1349 CRYPTO_RETW_UNLOCK(ret_worker);
1352 TASK_INIT(&crp->crp_task, 0, crypto_task_invoke, crp);
1353 taskqueue_enqueue(crypto_tq, &crp->crp_task);
1357 if ((crp->crp_flags & CRYPTO_F_BATCH) == 0) {
1359 * Caller marked the request to be processed
1360 * immediately; dispatch it directly to the
1361 * driver unless the driver is currently blocked.
1363 cap = crp->crp_session->cap;
1364 if (!cap->cc_qblocked) {
1365 result = crypto_invoke(cap, crp, 0);
1366 if (result != ERESTART)
1369 * The driver ran out of resources, put the request on
1374 crypto_batch_enqueue(crp);
1379 crypto_batch_enqueue(struct cryptop *crp)
1383 TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
1390 * Add an asymetric crypto request to a queue,
1391 * to be processed by the kernel thread.
1394 crypto_kdispatch(struct cryptkop *krp)
1398 cryptostats.cs_kops++;
1400 krp->krp_cap = NULL;
1401 error = crypto_kinvoke(krp);
1402 if (error == ERESTART) {
1404 TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
1414 * Verify a driver is suitable for the specified operation.
1417 kdriver_suitable(const struct cryptocap *cap, const struct cryptkop *krp)
1419 return (cap->cc_kalg[krp->krp_op] & CRYPTO_ALG_FLAG_SUPPORTED) != 0;
1423 * Select a driver for an asym operation. The driver must
1424 * support the necessary algorithm. The caller can constrain
1425 * which device is selected with the flags parameter. The
1426 * algorithm we use here is pretty stupid; just use the first
1427 * driver that supports the algorithms we need. If there are
1428 * multiple suitable drivers we choose the driver with the
1429 * fewest active operations. We prefer hardware-backed
1430 * drivers to software ones when either may be used.
1432 static struct cryptocap *
1433 crypto_select_kdriver(const struct cryptkop *krp, int flags)
1435 struct cryptocap *cap, *best;
1438 CRYPTO_DRIVER_ASSERT();
1441 * Look first for hardware crypto devices if permitted.
1443 if (flags & CRYPTOCAP_F_HARDWARE)
1444 match = CRYPTOCAP_F_HARDWARE;
1446 match = CRYPTOCAP_F_SOFTWARE;
1449 for (hid = 0; hid < crypto_drivers_size; hid++) {
1451 * If there is no driver for this slot, or the driver
1452 * is not appropriate (hardware or software based on
1453 * match), then skip.
1455 cap = crypto_drivers[hid];
1456 if (cap->cc_dev == NULL ||
1457 (cap->cc_flags & match) == 0)
1460 /* verify all the algorithms are supported. */
1461 if (kdriver_suitable(cap, krp)) {
1463 cap->cc_koperations < best->cc_koperations)
1469 if (match == CRYPTOCAP_F_HARDWARE && (flags & CRYPTOCAP_F_SOFTWARE)) {
1470 /* sort of an Algol 68-style for loop */
1471 match = CRYPTOCAP_F_SOFTWARE;
1478 * Choose a driver for an asymmetric crypto request.
1480 static struct cryptocap *
1481 crypto_lookup_kdriver(struct cryptkop *krp)
1483 struct cryptocap *cap;
1486 /* If this request is requeued, it might already have a driver. */
1491 /* Use krp_crid to choose a driver. */
1492 crid = krp->krp_crid;
1493 if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
1494 cap = crypto_checkdriver(crid);
1497 * Driver present, it must support the
1498 * necessary algorithm and, if s/w drivers are
1499 * excluded, it must be registered as
1502 if (!kdriver_suitable(cap, krp) ||
1503 (!crypto_devallowsoft &&
1504 (cap->cc_flags & CRYPTOCAP_F_HARDWARE) == 0))
1509 * No requested driver; select based on crid flags.
1511 if (!crypto_devallowsoft) /* NB: disallow s/w drivers */
1512 crid &= ~CRYPTOCAP_F_SOFTWARE;
1513 cap = crypto_select_kdriver(krp, crid);
1517 krp->krp_cap = cap_ref(cap);
1518 krp->krp_hid = cap->cc_hid;
1524 * Dispatch an asymmetric crypto request.
1527 crypto_kinvoke(struct cryptkop *krp)
1529 struct cryptocap *cap = NULL;
1532 KASSERT(krp != NULL, ("%s: krp == NULL", __func__));
1533 KASSERT(krp->krp_callback != NULL,
1534 ("%s: krp->crp_callback == NULL", __func__));
1536 CRYPTO_DRIVER_LOCK();
1537 cap = crypto_lookup_kdriver(krp);
1539 CRYPTO_DRIVER_UNLOCK();
1540 krp->krp_status = ENODEV;
1546 * If the device is blocked, return ERESTART to requeue it.
1548 if (cap->cc_kqblocked) {
1550 * XXX: Previously this set krp_status to ERESTART and
1551 * invoked crypto_kdone but the caller would still
1554 CRYPTO_DRIVER_UNLOCK();
1558 cap->cc_koperations++;
1559 CRYPTO_DRIVER_UNLOCK();
1560 error = CRYPTODEV_KPROCESS(cap->cc_dev, krp, 0);
1561 if (error == ERESTART) {
1562 CRYPTO_DRIVER_LOCK();
1563 cap->cc_koperations--;
1564 CRYPTO_DRIVER_UNLOCK();
1568 KASSERT(error == 0, ("error %d returned from crypto_kprocess", error));
1572 #ifdef CRYPTO_TIMING
1574 crypto_tstat(struct cryptotstat *ts, struct bintime *bt)
1576 struct bintime now, delta;
1582 delta.frac = now.frac - bt->frac;
1583 delta.sec = now.sec - bt->sec;
1586 bintime2timespec(&delta, &t);
1587 timespecadd(&ts->acc, &t, &ts->acc);
1588 if (timespeccmp(&t, &ts->min, <))
1590 if (timespeccmp(&t, &ts->max, >))
1599 crypto_task_invoke(void *ctx, int pending)
1601 struct cryptocap *cap;
1602 struct cryptop *crp;
1605 crp = (struct cryptop *)ctx;
1606 cap = crp->crp_session->cap;
1607 result = crypto_invoke(cap, crp, 0);
1608 if (result == ERESTART)
1609 crypto_batch_enqueue(crp);
1613 * Dispatch a crypto request to the appropriate crypto devices.
1616 crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint)
1619 KASSERT(crp != NULL, ("%s: crp == NULL", __func__));
1620 KASSERT(crp->crp_callback != NULL,
1621 ("%s: crp->crp_callback == NULL", __func__));
1622 KASSERT(crp->crp_session != NULL,
1623 ("%s: crp->crp_session == NULL", __func__));
1625 #ifdef CRYPTO_TIMING
1627 crypto_tstat(&cryptostats.cs_invoke, &crp->crp_tstamp);
1629 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1630 struct crypto_session_params csp;
1631 crypto_session_t nses;
1634 * Driver has unregistered; migrate the session and return
1635 * an error to the caller so they'll resubmit the op.
1637 * XXX: What if there are more already queued requests for this
1640 * XXX: Real solution is to make sessions refcounted
1641 * and force callers to hold a reference when
1642 * assigning to crp_session. Could maybe change
1643 * crypto_getreq to accept a session pointer to make
1644 * that work. Alternatively, we could abandon the
1645 * notion of rewriting crp_session in requests forcing
1646 * the caller to deal with allocating a new session.
1647 * Perhaps provide a method to allow a crp's session to
1648 * be swapped that callers could use.
1650 csp = crp->crp_session->csp;
1651 crypto_freesession(crp->crp_session);
1654 * XXX: Key pointers may no longer be valid. If we
1655 * really want to support this we need to define the
1656 * KPI such that 'csp' is required to be valid for the
1657 * duration of a session by the caller perhaps.
1659 * XXX: If the keys have been changed this will reuse
1660 * the old keys. This probably suggests making
1661 * rekeying more explicit and updating the key
1662 * pointers in 'csp' when the keys change.
1664 if (crypto_newsession(&nses, &csp,
1665 CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE) == 0)
1666 crp->crp_session = nses;
1668 crp->crp_etype = EAGAIN;
1673 * Invoke the driver to process the request.
1675 return CRYPTODEV_PROCESS(cap->cc_dev, crp, hint);
1680 crypto_freereq(struct cryptop *crp)
1688 struct cryptop *crp2;
1689 struct crypto_ret_worker *ret_worker;
1692 TAILQ_FOREACH(crp2, &crp_q, crp_next) {
1693 KASSERT(crp2 != crp,
1694 ("Freeing cryptop from the crypto queue (%p).",
1699 FOREACH_CRYPTO_RETW(ret_worker) {
1700 CRYPTO_RETW_LOCK(ret_worker);
1701 TAILQ_FOREACH(crp2, &ret_worker->crp_ret_q, crp_next) {
1702 KASSERT(crp2 != crp,
1703 ("Freeing cryptop from the return queue (%p).",
1706 CRYPTO_RETW_UNLOCK(ret_worker);
1711 uma_zfree(cryptop_zone, crp);
1715 crypto_getreq(crypto_session_t cses, int how)
1717 struct cryptop *crp;
1719 MPASS(how == M_WAITOK || how == M_NOWAIT);
1720 crp = uma_zalloc(cryptop_zone, how | M_ZERO);
1721 crp->crp_session = cses;
1726 * Invoke the callback on behalf of the driver.
1729 crypto_done(struct cryptop *crp)
1731 KASSERT((crp->crp_flags & CRYPTO_F_DONE) == 0,
1732 ("crypto_done: op already done, flags 0x%x", crp->crp_flags));
1733 crp->crp_flags |= CRYPTO_F_DONE;
1734 if (crp->crp_etype != 0)
1735 cryptostats.cs_errs++;
1736 #ifdef CRYPTO_TIMING
1738 crypto_tstat(&cryptostats.cs_done, &crp->crp_tstamp);
1741 * CBIMM means unconditionally do the callback immediately;
1742 * CBIFSYNC means do the callback immediately only if the
1743 * operation was done synchronously. Both are used to avoid
1744 * doing extraneous context switches; the latter is mostly
1745 * used with the software crypto driver.
1747 if (!CRYPTOP_ASYNC_KEEPORDER(crp) &&
1748 ((crp->crp_flags & CRYPTO_F_CBIMM) ||
1749 ((crp->crp_flags & CRYPTO_F_CBIFSYNC) &&
1750 (crypto_ses2caps(crp->crp_session) & CRYPTOCAP_F_SYNC)))) {
1752 * Do the callback directly. This is ok when the
1753 * callback routine does very little (e.g. the
1754 * /dev/crypto callback method just does a wakeup).
1756 #ifdef CRYPTO_TIMING
1757 if (crypto_timing) {
1759 * NB: We must copy the timestamp before
1760 * doing the callback as the cryptop is
1761 * likely to be reclaimed.
1763 struct bintime t = crp->crp_tstamp;
1764 crypto_tstat(&cryptostats.cs_cb, &t);
1765 crp->crp_callback(crp);
1766 crypto_tstat(&cryptostats.cs_finis, &t);
1769 crp->crp_callback(crp);
1771 struct crypto_ret_worker *ret_worker;
1774 ret_worker = CRYPTO_RETW(crp->crp_retw_id);
1778 * Normal case; queue the callback for the thread.
1780 CRYPTO_RETW_LOCK(ret_worker);
1781 if (CRYPTOP_ASYNC_KEEPORDER(crp)) {
1782 struct cryptop *tmp;
1784 TAILQ_FOREACH_REVERSE(tmp, &ret_worker->crp_ordered_ret_q,
1785 cryptop_q, crp_next) {
1786 if (CRYPTO_SEQ_GT(crp->crp_seq, tmp->crp_seq)) {
1787 TAILQ_INSERT_AFTER(&ret_worker->crp_ordered_ret_q,
1788 tmp, crp, crp_next);
1793 TAILQ_INSERT_HEAD(&ret_worker->crp_ordered_ret_q,
1797 if (crp->crp_seq == ret_worker->reorder_cur_seq)
1801 if (CRYPTO_RETW_EMPTY(ret_worker))
1804 TAILQ_INSERT_TAIL(&ret_worker->crp_ret_q, crp, crp_next);
1808 wakeup_one(&ret_worker->crp_ret_q); /* shared wait channel */
1809 CRYPTO_RETW_UNLOCK(ret_worker);
1814 * Invoke the callback on behalf of the driver.
1817 crypto_kdone(struct cryptkop *krp)
1819 struct crypto_ret_worker *ret_worker;
1820 struct cryptocap *cap;
1822 if (krp->krp_status != 0)
1823 cryptostats.cs_kerrs++;
1824 CRYPTO_DRIVER_LOCK();
1826 KASSERT(cap->cc_koperations > 0, ("cc_koperations == 0"));
1827 cap->cc_koperations--;
1828 if (cap->cc_koperations == 0 && cap->cc_flags & CRYPTOCAP_F_CLEANUP)
1830 CRYPTO_DRIVER_UNLOCK();
1831 krp->krp_cap = NULL;
1834 ret_worker = CRYPTO_RETW(0);
1836 CRYPTO_RETW_LOCK(ret_worker);
1837 if (CRYPTO_RETW_EMPTY(ret_worker))
1838 wakeup_one(&ret_worker->crp_ret_q); /* shared wait channel */
1839 TAILQ_INSERT_TAIL(&ret_worker->crp_ret_kq, krp, krp_next);
1840 CRYPTO_RETW_UNLOCK(ret_worker);
1844 crypto_getfeat(int *featp)
1846 int hid, kalg, feat = 0;
1848 CRYPTO_DRIVER_LOCK();
1849 for (hid = 0; hid < crypto_drivers_size; hid++) {
1850 const struct cryptocap *cap = crypto_drivers[hid];
1853 ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
1854 !crypto_devallowsoft)) {
1857 for (kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
1858 if (cap->cc_kalg[kalg] & CRYPTO_ALG_FLAG_SUPPORTED)
1861 CRYPTO_DRIVER_UNLOCK();
1867 * Terminate a thread at module unload. The process that
1868 * initiated this is waiting for us to signal that we're gone;
1869 * wake it up and exit. We use the driver table lock to insure
1870 * we don't do the wakeup before they're waiting. There is no
1871 * race here because the waiter sleeps on the proc lock for the
1872 * thread so it gets notified at the right time because of an
1873 * extra wakeup that's done in exit1().
1876 crypto_finis(void *chan)
1878 CRYPTO_DRIVER_LOCK();
1880 CRYPTO_DRIVER_UNLOCK();
1885 * Crypto thread, dispatches crypto requests.
1890 struct cryptop *crp, *submit;
1891 struct cryptkop *krp;
1892 struct cryptocap *cap;
1895 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
1896 fpu_kern_thread(FPU_KERN_NORMAL);
1902 * Find the first element in the queue that can be
1903 * processed and look-ahead to see if multiple ops
1904 * are ready for the same driver.
1908 TAILQ_FOREACH(crp, &crp_q, crp_next) {
1909 cap = crp->crp_session->cap;
1911 * Driver cannot disappeared when there is an active
1914 KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1915 __func__, __LINE__));
1916 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1917 /* Op needs to be migrated, process it. */
1922 if (!cap->cc_qblocked) {
1923 if (submit != NULL) {
1925 * We stop on finding another op,
1926 * regardless whether its for the same
1927 * driver or not. We could keep
1928 * searching the queue but it might be
1929 * better to just use a per-driver
1932 if (submit->crp_session->cap == cap)
1933 hint = CRYPTO_HINT_MORE;
1937 if ((submit->crp_flags & CRYPTO_F_BATCH) == 0)
1939 /* keep scanning for more are q'd */
1943 if (submit != NULL) {
1944 TAILQ_REMOVE(&crp_q, submit, crp_next);
1945 cap = submit->crp_session->cap;
1946 KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1947 __func__, __LINE__));
1949 result = crypto_invoke(cap, submit, hint);
1951 if (result == ERESTART) {
1953 * The driver ran out of resources, mark the
1954 * driver ``blocked'' for cryptop's and put
1955 * the request back in the queue. It would
1956 * best to put the request back where we got
1957 * it but that's hard so for now we put it
1958 * at the front. This should be ok; putting
1959 * it at the end does not work.
1961 cap->cc_qblocked = 1;
1962 TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
1963 cryptostats.cs_blocks++;
1967 /* As above, but for key ops */
1968 TAILQ_FOREACH(krp, &crp_kq, krp_next) {
1970 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1972 * Operation needs to be migrated,
1973 * clear krp_cap so a new driver is
1976 krp->krp_cap = NULL;
1980 if (!cap->cc_kqblocked)
1984 TAILQ_REMOVE(&crp_kq, krp, krp_next);
1986 result = crypto_kinvoke(krp);
1988 if (result == ERESTART) {
1990 * The driver ran out of resources, mark the
1991 * driver ``blocked'' for cryptkop's and put
1992 * the request back in the queue. It would
1993 * best to put the request back where we got
1994 * it but that's hard so for now we put it
1995 * at the front. This should be ok; putting
1996 * it at the end does not work.
1998 krp->krp_cap->cc_kqblocked = 1;
1999 TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
2000 cryptostats.cs_kblocks++;
2004 if (submit == NULL && krp == NULL) {
2006 * Nothing more to be processed. Sleep until we're
2007 * woken because there are more ops to process.
2008 * This happens either by submission or by a driver
2009 * becoming unblocked and notifying us through
2010 * crypto_unblock. Note that when we wakeup we
2011 * start processing each queue again from the
2012 * front. It's not clear that it's important to
2013 * preserve this ordering since ops may finish
2014 * out of order if dispatched to different devices
2015 * and some become blocked while others do not.
2018 msleep(&crp_q, &crypto_q_mtx, PWAIT, "crypto_wait", 0);
2020 if (cryptoproc == NULL)
2022 cryptostats.cs_intrs++;
2027 crypto_finis(&crp_q);
2031 * Crypto returns thread, does callbacks for processed crypto requests.
2032 * Callbacks are done here, rather than in the crypto drivers, because
2033 * callbacks typically are expensive and would slow interrupt handling.
2036 crypto_ret_proc(struct crypto_ret_worker *ret_worker)
2038 struct cryptop *crpt;
2039 struct cryptkop *krpt;
2041 CRYPTO_RETW_LOCK(ret_worker);
2043 /* Harvest return q's for completed ops */
2044 crpt = TAILQ_FIRST(&ret_worker->crp_ordered_ret_q);
2046 if (crpt->crp_seq == ret_worker->reorder_cur_seq) {
2047 TAILQ_REMOVE(&ret_worker->crp_ordered_ret_q, crpt, crp_next);
2048 ret_worker->reorder_cur_seq++;
2055 crpt = TAILQ_FIRST(&ret_worker->crp_ret_q);
2057 TAILQ_REMOVE(&ret_worker->crp_ret_q, crpt, crp_next);
2060 krpt = TAILQ_FIRST(&ret_worker->crp_ret_kq);
2062 TAILQ_REMOVE(&ret_worker->crp_ret_kq, krpt, krp_next);
2064 if (crpt != NULL || krpt != NULL) {
2065 CRYPTO_RETW_UNLOCK(ret_worker);
2067 * Run callbacks unlocked.
2070 #ifdef CRYPTO_TIMING
2071 if (crypto_timing) {
2073 * NB: We must copy the timestamp before
2074 * doing the callback as the cryptop is
2075 * likely to be reclaimed.
2077 struct bintime t = crpt->crp_tstamp;
2078 crypto_tstat(&cryptostats.cs_cb, &t);
2079 crpt->crp_callback(crpt);
2080 crypto_tstat(&cryptostats.cs_finis, &t);
2083 crpt->crp_callback(crpt);
2086 krpt->krp_callback(krpt);
2087 CRYPTO_RETW_LOCK(ret_worker);
2090 * Nothing more to be processed. Sleep until we're
2091 * woken because there are more returns to process.
2093 msleep(&ret_worker->crp_ret_q, &ret_worker->crypto_ret_mtx, PWAIT,
2094 "crypto_ret_wait", 0);
2095 if (ret_worker->cryptoretproc == NULL)
2097 cryptostats.cs_rets++;
2100 CRYPTO_RETW_UNLOCK(ret_worker);
2102 crypto_finis(&ret_worker->crp_ret_q);
2107 db_show_drivers(void)
2111 db_printf("%12s %4s %4s %8s %2s %2s\n"
2119 for (hid = 0; hid < crypto_drivers_size; hid++) {
2120 const struct cryptocap *cap = crypto_drivers[hid];
2123 db_printf("%-12s %4u %4u %08x %2u %2u\n"
2124 , device_get_nameunit(cap->cc_dev)
2126 , cap->cc_koperations
2134 DB_SHOW_COMMAND(crypto, db_show_crypto)
2136 struct cryptop *crp;
2137 struct crypto_ret_worker *ret_worker;
2142 db_printf("%4s %8s %4s %4s %4s %4s %8s %8s\n",
2143 "HID", "Caps", "Ilen", "Olen", "Etype", "Flags",
2144 "Device", "Callback");
2145 TAILQ_FOREACH(crp, &crp_q, crp_next) {
2146 db_printf("%4u %08x %4u %4u %4u %04x %8p %8p\n"
2147 , crp->crp_session->cap->cc_hid
2148 , (int) crypto_ses2caps(crp->crp_session)
2149 , crp->crp_ilen, crp->crp_olen
2152 , device_get_nameunit(crp->crp_session->cap->cc_dev)
2156 FOREACH_CRYPTO_RETW(ret_worker) {
2157 db_printf("\n%8s %4s %4s %4s %8s\n",
2158 "ret_worker", "HID", "Etype", "Flags", "Callback");
2159 if (!TAILQ_EMPTY(&ret_worker->crp_ret_q)) {
2160 TAILQ_FOREACH(crp, &ret_worker->crp_ret_q, crp_next) {
2161 db_printf("%8td %4u %4u %04x %8p\n"
2162 , CRYPTO_RETW_ID(ret_worker)
2163 , crp->crp_session->cap->cc_hid
2173 DB_SHOW_COMMAND(kcrypto, db_show_kcrypto)
2175 struct cryptkop *krp;
2176 struct crypto_ret_worker *ret_worker;
2181 db_printf("%4s %5s %4s %4s %8s %4s %8s\n",
2182 "Op", "Status", "#IP", "#OP", "CRID", "HID", "Callback");
2183 TAILQ_FOREACH(krp, &crp_kq, krp_next) {
2184 db_printf("%4u %5u %4u %4u %08x %4u %8p\n"
2187 , krp->krp_iparams, krp->krp_oparams
2188 , krp->krp_crid, krp->krp_hid
2193 ret_worker = CRYPTO_RETW(0);
2194 if (!TAILQ_EMPTY(&ret_worker->crp_ret_q)) {
2195 db_printf("%4s %5s %8s %4s %8s\n",
2196 "Op", "Status", "CRID", "HID", "Callback");
2197 TAILQ_FOREACH(krp, &ret_worker->crp_ret_kq, krp_next) {
2198 db_printf("%4u %5u %08x %4u %8p\n"
2201 , krp->krp_crid, krp->krp_hid
2209 int crypto_modevent(module_t mod, int type, void *unused);
2212 * Initialization code, both for static and dynamic loading.
2213 * Note this is not invoked with the usual MODULE_DECLARE
2214 * mechanism but instead is listed as a dependency by the
2215 * cryptosoft driver. This guarantees proper ordering of
2216 * calls on module load/unload.
2219 crypto_modevent(module_t mod, int type, void *unused)
2225 error = crypto_init();
2226 if (error == 0 && bootverbose)
2227 printf("crypto: <crypto core>\n");
2230 /*XXX disallow if active sessions */
2237 MODULE_VERSION(crypto, 1);
2238 MODULE_DEPEND(crypto, zlib, 1, 1, 1);