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>
74 #include <sys/refcount.h>
77 #include <sys/sysctl.h>
78 #include <sys/taskqueue.h>
84 #include <crypto/intake.h>
85 #include <opencrypto/cryptodev.h>
86 #include <opencrypto/xform_auth.h>
87 #include <opencrypto/xform_enc.h>
91 #include "cryptodev_if.h"
93 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
94 #include <machine/pcb.h>
97 SDT_PROVIDER_DEFINE(opencrypto);
100 * Crypto drivers register themselves by allocating a slot in the
101 * crypto_drivers table with crypto_get_driverid() and then registering
102 * each asym algorithm they support with crypto_kregister().
104 static struct mtx crypto_drivers_mtx; /* lock on driver table */
105 #define CRYPTO_DRIVER_LOCK() mtx_lock(&crypto_drivers_mtx)
106 #define CRYPTO_DRIVER_UNLOCK() mtx_unlock(&crypto_drivers_mtx)
107 #define CRYPTO_DRIVER_ASSERT() mtx_assert(&crypto_drivers_mtx, MA_OWNED)
110 * Crypto device/driver capabilities structure.
113 * (d) - protected by CRYPTO_DRIVER_LOCK()
114 * (q) - protected by CRYPTO_Q_LOCK()
115 * Not tagged fields are read-only.
120 u_int32_t cc_sessions; /* (d) # of sessions */
121 u_int32_t cc_koperations; /* (d) # os asym operations */
122 u_int8_t cc_kalg[CRK_ALGORITHM_MAX + 1];
124 int cc_flags; /* (d) flags */
125 #define CRYPTOCAP_F_CLEANUP 0x80000000 /* needs resource cleanup */
126 int cc_qblocked; /* (q) symmetric q blocked */
127 int cc_kqblocked; /* (q) asymmetric q blocked */
128 size_t cc_session_size;
129 volatile int cc_refs;
132 static struct cryptocap **crypto_drivers = NULL;
133 static int crypto_drivers_size = 0;
135 struct crypto_session {
136 struct cryptocap *cap;
138 struct crypto_session_params csp;
142 * There are two queues for crypto requests; one for symmetric (e.g.
143 * cipher) operations and one for asymmetric (e.g. MOD)operations.
144 * A single mutex is used to lock access to both queues. We could
145 * have one per-queue but having one simplifies handling of block/unblock
148 static int crp_sleep = 0;
149 static TAILQ_HEAD(cryptop_q ,cryptop) crp_q; /* request queues */
150 static TAILQ_HEAD(,cryptkop) crp_kq;
151 static struct mtx crypto_q_mtx;
152 #define CRYPTO_Q_LOCK() mtx_lock(&crypto_q_mtx)
153 #define CRYPTO_Q_UNLOCK() mtx_unlock(&crypto_q_mtx)
155 SYSCTL_NODE(_kern, OID_AUTO, crypto, CTLFLAG_RW, 0,
156 "In-kernel cryptography");
159 * Taskqueue used to dispatch the crypto requests
160 * that have the CRYPTO_F_ASYNC flag
162 static struct taskqueue *crypto_tq;
165 * Crypto seq numbers are operated on with modular arithmetic
167 #define CRYPTO_SEQ_GT(a,b) ((int)((a)-(b)) > 0)
169 struct crypto_ret_worker {
170 struct mtx crypto_ret_mtx;
172 TAILQ_HEAD(,cryptop) crp_ordered_ret_q; /* ordered callback queue for symetric jobs */
173 TAILQ_HEAD(,cryptop) crp_ret_q; /* callback queue for symetric jobs */
174 TAILQ_HEAD(,cryptkop) crp_ret_kq; /* callback queue for asym jobs */
176 u_int32_t reorder_ops; /* total ordered sym jobs received */
177 u_int32_t reorder_cur_seq; /* current sym job dispatched */
179 struct proc *cryptoretproc;
181 static struct crypto_ret_worker *crypto_ret_workers = NULL;
183 #define CRYPTO_RETW(i) (&crypto_ret_workers[i])
184 #define CRYPTO_RETW_ID(w) ((w) - crypto_ret_workers)
185 #define FOREACH_CRYPTO_RETW(w) \
186 for (w = crypto_ret_workers; w < crypto_ret_workers + crypto_workers_num; ++w)
188 #define CRYPTO_RETW_LOCK(w) mtx_lock(&w->crypto_ret_mtx)
189 #define CRYPTO_RETW_UNLOCK(w) mtx_unlock(&w->crypto_ret_mtx)
190 #define CRYPTO_RETW_EMPTY(w) \
191 (TAILQ_EMPTY(&w->crp_ret_q) && TAILQ_EMPTY(&w->crp_ret_kq) && TAILQ_EMPTY(&w->crp_ordered_ret_q))
193 static int crypto_workers_num = 0;
194 SYSCTL_INT(_kern_crypto, OID_AUTO, num_workers, CTLFLAG_RDTUN,
195 &crypto_workers_num, 0,
196 "Number of crypto workers used to dispatch crypto jobs");
197 #ifdef COMPAT_FREEBSD12
198 SYSCTL_INT(_kern, OID_AUTO, crypto_workers_num, CTLFLAG_RDTUN,
199 &crypto_workers_num, 0,
200 "Number of crypto workers used to dispatch crypto jobs");
203 static uma_zone_t cryptop_zone;
204 static uma_zone_t cryptoses_zone;
206 int crypto_userasymcrypto = 1;
207 SYSCTL_INT(_kern_crypto, OID_AUTO, asym_enable, CTLFLAG_RW,
208 &crypto_userasymcrypto, 0,
209 "Enable user-mode access to asymmetric crypto support");
210 #ifdef COMPAT_FREEBSD12
211 SYSCTL_INT(_kern, OID_AUTO, userasymcrypto, CTLFLAG_RW,
212 &crypto_userasymcrypto, 0,
213 "Enable/disable user-mode access to asymmetric crypto support");
216 int crypto_devallowsoft = 0;
217 SYSCTL_INT(_kern_crypto, OID_AUTO, allow_soft, CTLFLAG_RW,
218 &crypto_devallowsoft, 0,
219 "Enable use of software crypto by /dev/crypto");
220 #ifdef COMPAT_FREEBSD12
221 SYSCTL_INT(_kern, OID_AUTO, cryptodevallowsoft, CTLFLAG_RW,
222 &crypto_devallowsoft, 0,
223 "Enable/disable use of software crypto by /dev/crypto");
226 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
228 static void crypto_proc(void);
229 static struct proc *cryptoproc;
230 static void crypto_ret_proc(struct crypto_ret_worker *ret_worker);
231 static void crypto_destroy(void);
232 static int crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint);
233 static int crypto_kinvoke(struct cryptkop *krp);
234 static void crypto_task_invoke(void *ctx, int pending);
235 static void crypto_batch_enqueue(struct cryptop *crp);
237 static struct cryptostats cryptostats;
238 SYSCTL_STRUCT(_kern_crypto, OID_AUTO, stats, CTLFLAG_RW, &cryptostats,
239 cryptostats, "Crypto system statistics");
242 static int crypto_timing = 0;
243 SYSCTL_INT(_debug, OID_AUTO, crypto_timing, CTLFLAG_RW,
244 &crypto_timing, 0, "Enable/disable crypto timing support");
247 /* Try to avoid directly exposing the key buffer as a symbol */
248 static struct keybuf *keybuf;
250 static struct keybuf empty_keybuf = {
254 /* Obtain the key buffer from boot metadata */
260 kmdp = preload_search_by_type("elf kernel");
263 kmdp = preload_search_by_type("elf64 kernel");
265 keybuf = (struct keybuf *)preload_search_info(kmdp,
266 MODINFO_METADATA | MODINFOMD_KEYBUF);
269 keybuf = &empty_keybuf;
272 /* It'd be nice if we could store these in some kind of secure memory... */
273 struct keybuf * get_keybuf(void) {
278 static struct cryptocap *
279 cap_ref(struct cryptocap *cap)
282 refcount_acquire(&cap->cc_refs);
287 cap_rele(struct cryptocap *cap)
290 if (refcount_release(&cap->cc_refs) == 0)
293 KASSERT(cap->cc_sessions == 0,
294 ("freeing crypto driver with active sessions"));
295 KASSERT(cap->cc_koperations == 0,
296 ("freeing crypto driver with active key operations"));
298 free(cap, M_CRYPTO_DATA);
304 struct crypto_ret_worker *ret_worker;
307 mtx_init(&crypto_drivers_mtx, "crypto", "crypto driver table",
312 mtx_init(&crypto_q_mtx, "crypto", "crypto op queues", MTX_DEF);
314 cryptop_zone = uma_zcreate("cryptop", sizeof (struct cryptop),
316 UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
317 cryptoses_zone = uma_zcreate("crypto_session",
318 sizeof(struct crypto_session), NULL, NULL, NULL, NULL,
319 UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
321 if (cryptop_zone == NULL || cryptoses_zone == NULL) {
322 printf("crypto_init: cannot setup crypto zones\n");
327 crypto_drivers_size = CRYPTO_DRIVERS_INITIAL;
328 crypto_drivers = malloc(crypto_drivers_size *
329 sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT | M_ZERO);
330 if (crypto_drivers == NULL) {
331 printf("crypto_init: cannot setup crypto drivers\n");
336 if (crypto_workers_num < 1 || crypto_workers_num > mp_ncpus)
337 crypto_workers_num = mp_ncpus;
339 crypto_tq = taskqueue_create("crypto", M_WAITOK|M_ZERO,
340 taskqueue_thread_enqueue, &crypto_tq);
341 if (crypto_tq == NULL) {
342 printf("crypto init: cannot setup crypto taskqueue\n");
347 taskqueue_start_threads(&crypto_tq, crypto_workers_num, PRI_MIN_KERN,
350 error = kproc_create((void (*)(void *)) crypto_proc, NULL,
351 &cryptoproc, 0, 0, "crypto");
353 printf("crypto_init: cannot start crypto thread; error %d",
358 crypto_ret_workers = malloc(crypto_workers_num * sizeof(struct crypto_ret_worker),
359 M_CRYPTO_DATA, M_NOWAIT|M_ZERO);
360 if (crypto_ret_workers == NULL) {
362 printf("crypto_init: cannot allocate ret workers\n");
367 FOREACH_CRYPTO_RETW(ret_worker) {
368 TAILQ_INIT(&ret_worker->crp_ordered_ret_q);
369 TAILQ_INIT(&ret_worker->crp_ret_q);
370 TAILQ_INIT(&ret_worker->crp_ret_kq);
372 ret_worker->reorder_ops = 0;
373 ret_worker->reorder_cur_seq = 0;
375 mtx_init(&ret_worker->crypto_ret_mtx, "crypto", "crypto return queues", MTX_DEF);
377 error = kproc_create((void (*)(void *)) crypto_ret_proc, ret_worker,
378 &ret_worker->cryptoretproc, 0, 0, "crypto returns %td", CRYPTO_RETW_ID(ret_worker));
380 printf("crypto_init: cannot start cryptoret thread; error %d",
395 * Signal a crypto thread to terminate. We use the driver
396 * table lock to synchronize the sleep/wakeups so that we
397 * are sure the threads have terminated before we release
398 * the data structures they use. See crypto_finis below
399 * for the other half of this song-and-dance.
402 crypto_terminate(struct proc **pp, void *q)
406 mtx_assert(&crypto_drivers_mtx, MA_OWNED);
411 PROC_LOCK(p); /* NB: insure we don't miss wakeup */
412 CRYPTO_DRIVER_UNLOCK(); /* let crypto_finis progress */
413 msleep(p, &p->p_mtx, PWAIT, "crypto_destroy", 0);
415 CRYPTO_DRIVER_LOCK();
420 hmac_init_pad(struct auth_hash *axf, const char *key, int klen, void *auth_ctx,
423 uint8_t hmac_key[HMAC_MAX_BLOCK_LEN];
426 KASSERT(axf->blocksize <= sizeof(hmac_key),
427 ("Invalid HMAC block size %d", axf->blocksize));
430 * If the key is larger than the block size, use the digest of
431 * the key as the key instead.
433 memset(hmac_key, 0, sizeof(hmac_key));
434 if (klen > axf->blocksize) {
436 axf->Update(auth_ctx, key, klen);
437 axf->Final(hmac_key, auth_ctx);
438 klen = axf->hashsize;
440 memcpy(hmac_key, key, klen);
442 for (i = 0; i < axf->blocksize; i++)
443 hmac_key[i] ^= padval;
446 axf->Update(auth_ctx, hmac_key, axf->blocksize);
447 explicit_bzero(hmac_key, sizeof(hmac_key));
451 hmac_init_ipad(struct auth_hash *axf, const char *key, int klen,
455 hmac_init_pad(axf, key, klen, auth_ctx, HMAC_IPAD_VAL);
459 hmac_init_opad(struct auth_hash *axf, const char *key, int klen,
463 hmac_init_pad(axf, key, klen, auth_ctx, HMAC_OPAD_VAL);
469 struct crypto_ret_worker *ret_worker;
473 * Terminate any crypto threads.
475 if (crypto_tq != NULL)
476 taskqueue_drain_all(crypto_tq);
477 CRYPTO_DRIVER_LOCK();
478 crypto_terminate(&cryptoproc, &crp_q);
479 FOREACH_CRYPTO_RETW(ret_worker)
480 crypto_terminate(&ret_worker->cryptoretproc, &ret_worker->crp_ret_q);
481 CRYPTO_DRIVER_UNLOCK();
483 /* XXX flush queues??? */
486 * Reclaim dynamically allocated resources.
488 for (i = 0; i < crypto_drivers_size; i++) {
489 if (crypto_drivers[i] != NULL)
490 cap_rele(crypto_drivers[i]);
492 free(crypto_drivers, M_CRYPTO_DATA);
494 if (cryptoses_zone != NULL)
495 uma_zdestroy(cryptoses_zone);
496 if (cryptop_zone != NULL)
497 uma_zdestroy(cryptop_zone);
498 mtx_destroy(&crypto_q_mtx);
499 FOREACH_CRYPTO_RETW(ret_worker)
500 mtx_destroy(&ret_worker->crypto_ret_mtx);
501 free(crypto_ret_workers, M_CRYPTO_DATA);
502 if (crypto_tq != NULL)
503 taskqueue_free(crypto_tq);
504 mtx_destroy(&crypto_drivers_mtx);
508 crypto_ses2hid(crypto_session_t crypto_session)
510 return (crypto_session->cap->cc_hid);
514 crypto_ses2caps(crypto_session_t crypto_session)
516 return (crypto_session->cap->cc_flags & 0xff000000);
520 crypto_get_driver_session(crypto_session_t crypto_session)
522 return (crypto_session->softc);
525 const struct crypto_session_params *
526 crypto_get_params(crypto_session_t crypto_session)
528 return (&crypto_session->csp);
532 crypto_auth_hash(const struct crypto_session_params *csp)
535 switch (csp->csp_auth_alg) {
536 case CRYPTO_SHA1_HMAC:
537 return (&auth_hash_hmac_sha1);
538 case CRYPTO_SHA2_224_HMAC:
539 return (&auth_hash_hmac_sha2_224);
540 case CRYPTO_SHA2_256_HMAC:
541 return (&auth_hash_hmac_sha2_256);
542 case CRYPTO_SHA2_384_HMAC:
543 return (&auth_hash_hmac_sha2_384);
544 case CRYPTO_SHA2_512_HMAC:
545 return (&auth_hash_hmac_sha2_512);
546 case CRYPTO_NULL_HMAC:
547 return (&auth_hash_null);
548 case CRYPTO_RIPEMD160_HMAC:
549 return (&auth_hash_hmac_ripemd_160);
551 return (&auth_hash_sha1);
552 case CRYPTO_SHA2_224:
553 return (&auth_hash_sha2_224);
554 case CRYPTO_SHA2_256:
555 return (&auth_hash_sha2_256);
556 case CRYPTO_SHA2_384:
557 return (&auth_hash_sha2_384);
558 case CRYPTO_SHA2_512:
559 return (&auth_hash_sha2_512);
560 case CRYPTO_AES_NIST_GMAC:
561 switch (csp->csp_auth_klen) {
563 return (&auth_hash_nist_gmac_aes_128);
565 return (&auth_hash_nist_gmac_aes_192);
567 return (&auth_hash_nist_gmac_aes_256);
572 return (&auth_hash_blake2b);
574 return (&auth_hash_blake2s);
575 case CRYPTO_POLY1305:
576 return (&auth_hash_poly1305);
577 case CRYPTO_AES_CCM_CBC_MAC:
578 switch (csp->csp_auth_klen) {
580 return (&auth_hash_ccm_cbc_mac_128);
582 return (&auth_hash_ccm_cbc_mac_192);
584 return (&auth_hash_ccm_cbc_mac_256);
594 crypto_cipher(const struct crypto_session_params *csp)
597 switch (csp->csp_cipher_alg) {
598 case CRYPTO_RIJNDAEL128_CBC:
599 return (&enc_xform_rijndael128);
601 return (&enc_xform_aes_xts);
603 return (&enc_xform_aes_icm);
604 case CRYPTO_AES_NIST_GCM_16:
605 return (&enc_xform_aes_nist_gcm);
606 case CRYPTO_CAMELLIA_CBC:
607 return (&enc_xform_camellia);
608 case CRYPTO_NULL_CBC:
609 return (&enc_xform_null);
610 case CRYPTO_CHACHA20:
611 return (&enc_xform_chacha20);
612 case CRYPTO_AES_CCM_16:
613 return (&enc_xform_ccm);
619 static struct cryptocap *
620 crypto_checkdriver(u_int32_t hid)
623 return (hid >= crypto_drivers_size ? NULL : crypto_drivers[hid]);
627 * Select a driver for a new session that supports the specified
628 * algorithms and, optionally, is constrained according to the flags.
630 static struct cryptocap *
631 crypto_select_driver(const struct crypto_session_params *csp, int flags)
633 struct cryptocap *cap, *best;
634 int best_match, error, hid;
636 CRYPTO_DRIVER_ASSERT();
639 for (hid = 0; hid < crypto_drivers_size; hid++) {
641 * If there is no driver for this slot, or the driver
642 * is not appropriate (hardware or software based on
645 cap = crypto_drivers[hid];
647 (cap->cc_flags & flags) == 0)
650 error = CRYPTODEV_PROBESESSION(cap->cc_dev, csp);
655 * Use the driver with the highest probe value.
656 * Hardware drivers use a higher probe value than
657 * software. In case of a tie, prefer the driver with
658 * the fewest active sessions.
660 if (best == NULL || error > best_match ||
661 (error == best_match &&
662 cap->cc_sessions < best->cc_sessions)) {
670 static enum alg_type {
678 [CRYPTO_SHA1_HMAC] = ALG_KEYED_DIGEST,
679 [CRYPTO_RIPEMD160_HMAC] = ALG_KEYED_DIGEST,
680 [CRYPTO_AES_CBC] = ALG_CIPHER,
681 [CRYPTO_SHA1] = ALG_DIGEST,
682 [CRYPTO_NULL_HMAC] = ALG_DIGEST,
683 [CRYPTO_NULL_CBC] = ALG_CIPHER,
684 [CRYPTO_DEFLATE_COMP] = ALG_COMPRESSION,
685 [CRYPTO_SHA2_256_HMAC] = ALG_KEYED_DIGEST,
686 [CRYPTO_SHA2_384_HMAC] = ALG_KEYED_DIGEST,
687 [CRYPTO_SHA2_512_HMAC] = ALG_KEYED_DIGEST,
688 [CRYPTO_CAMELLIA_CBC] = ALG_CIPHER,
689 [CRYPTO_AES_XTS] = ALG_CIPHER,
690 [CRYPTO_AES_ICM] = ALG_CIPHER,
691 [CRYPTO_AES_NIST_GMAC] = ALG_KEYED_DIGEST,
692 [CRYPTO_AES_NIST_GCM_16] = ALG_AEAD,
693 [CRYPTO_BLAKE2B] = ALG_KEYED_DIGEST,
694 [CRYPTO_BLAKE2S] = ALG_KEYED_DIGEST,
695 [CRYPTO_CHACHA20] = ALG_CIPHER,
696 [CRYPTO_SHA2_224_HMAC] = ALG_KEYED_DIGEST,
697 [CRYPTO_RIPEMD160] = ALG_DIGEST,
698 [CRYPTO_SHA2_224] = ALG_DIGEST,
699 [CRYPTO_SHA2_256] = ALG_DIGEST,
700 [CRYPTO_SHA2_384] = ALG_DIGEST,
701 [CRYPTO_SHA2_512] = ALG_DIGEST,
702 [CRYPTO_POLY1305] = ALG_KEYED_DIGEST,
703 [CRYPTO_AES_CCM_CBC_MAC] = ALG_KEYED_DIGEST,
704 [CRYPTO_AES_CCM_16] = ALG_AEAD,
711 if (alg < nitems(alg_types))
712 return (alg_types[alg]);
717 alg_is_compression(int alg)
720 return (alg_type(alg) == ALG_COMPRESSION);
724 alg_is_cipher(int alg)
727 return (alg_type(alg) == ALG_CIPHER);
731 alg_is_digest(int alg)
734 return (alg_type(alg) == ALG_DIGEST ||
735 alg_type(alg) == ALG_KEYED_DIGEST);
739 alg_is_keyed_digest(int alg)
742 return (alg_type(alg) == ALG_KEYED_DIGEST);
749 return (alg_type(alg) == ALG_AEAD);
752 /* Various sanity checks on crypto session parameters. */
754 check_csp(const struct crypto_session_params *csp)
756 struct auth_hash *axf;
758 /* Mode-independent checks. */
759 if ((csp->csp_flags & ~(CSP_F_SEPARATE_OUTPUT | CSP_F_SEPARATE_AAD)) !=
762 if (csp->csp_ivlen < 0 || csp->csp_cipher_klen < 0 ||
763 csp->csp_auth_klen < 0 || csp->csp_auth_mlen < 0)
765 if (csp->csp_auth_key != NULL && csp->csp_auth_klen == 0)
767 if (csp->csp_cipher_key != NULL && csp->csp_cipher_klen == 0)
770 switch (csp->csp_mode) {
771 case CSP_MODE_COMPRESS:
772 if (!alg_is_compression(csp->csp_cipher_alg))
774 if (csp->csp_flags & CSP_F_SEPARATE_OUTPUT)
776 if (csp->csp_flags & CSP_F_SEPARATE_AAD)
778 if (csp->csp_cipher_klen != 0 || csp->csp_ivlen != 0 ||
779 csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0 ||
780 csp->csp_auth_mlen != 0)
783 case CSP_MODE_CIPHER:
784 if (!alg_is_cipher(csp->csp_cipher_alg))
786 if (csp->csp_flags & CSP_F_SEPARATE_AAD)
788 if (csp->csp_cipher_alg != CRYPTO_NULL_CBC) {
789 if (csp->csp_cipher_klen == 0)
791 if (csp->csp_ivlen == 0)
794 if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
796 if (csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0 ||
797 csp->csp_auth_mlen != 0)
800 case CSP_MODE_DIGEST:
801 if (csp->csp_cipher_alg != 0 || csp->csp_cipher_klen != 0)
804 if (csp->csp_flags & CSP_F_SEPARATE_AAD)
807 /* IV is optional for digests (e.g. GMAC). */
808 if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
810 if (!alg_is_digest(csp->csp_auth_alg))
813 /* Key is optional for BLAKE2 digests. */
814 if (csp->csp_auth_alg == CRYPTO_BLAKE2B ||
815 csp->csp_auth_alg == CRYPTO_BLAKE2S)
817 else if (alg_is_keyed_digest(csp->csp_auth_alg)) {
818 if (csp->csp_auth_klen == 0)
821 if (csp->csp_auth_klen != 0)
824 if (csp->csp_auth_mlen != 0) {
825 axf = crypto_auth_hash(csp);
826 if (axf == NULL || csp->csp_auth_mlen > axf->hashsize)
831 if (!alg_is_aead(csp->csp_cipher_alg))
833 if (csp->csp_cipher_klen == 0)
835 if (csp->csp_ivlen == 0 ||
836 csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
838 if (csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0)
842 * XXX: Would be nice to have a better way to get this
845 switch (csp->csp_cipher_alg) {
846 case CRYPTO_AES_NIST_GCM_16:
847 case CRYPTO_AES_CCM_16:
848 if (csp->csp_auth_mlen > 16)
854 if (!alg_is_cipher(csp->csp_cipher_alg))
856 if (csp->csp_cipher_alg != CRYPTO_NULL_CBC) {
857 if (csp->csp_cipher_klen == 0)
859 if (csp->csp_ivlen == 0)
862 if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
864 if (!alg_is_digest(csp->csp_auth_alg))
867 /* Key is optional for BLAKE2 digests. */
868 if (csp->csp_auth_alg == CRYPTO_BLAKE2B ||
869 csp->csp_auth_alg == CRYPTO_BLAKE2S)
871 else if (alg_is_keyed_digest(csp->csp_auth_alg)) {
872 if (csp->csp_auth_klen == 0)
875 if (csp->csp_auth_klen != 0)
878 if (csp->csp_auth_mlen != 0) {
879 axf = crypto_auth_hash(csp);
880 if (axf == NULL || csp->csp_auth_mlen > axf->hashsize)
892 * Delete a session after it has been detached from its driver.
895 crypto_deletesession(crypto_session_t cses)
897 struct cryptocap *cap;
901 zfree(cses->softc, M_CRYPTO_DATA);
902 uma_zfree(cryptoses_zone, cses);
904 CRYPTO_DRIVER_LOCK();
906 if (cap->cc_sessions == 0 && cap->cc_flags & CRYPTOCAP_F_CLEANUP)
908 CRYPTO_DRIVER_UNLOCK();
913 * Create a new session. The crid argument specifies a crypto
914 * driver to use or constraints on a driver to select (hardware
915 * only, software only, either). Whatever driver is selected
916 * must be capable of the requested crypto algorithms.
919 crypto_newsession(crypto_session_t *cses,
920 const struct crypto_session_params *csp, int crid)
922 crypto_session_t res;
923 struct cryptocap *cap;
931 CRYPTO_DRIVER_LOCK();
932 if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
934 * Use specified driver; verify it is capable.
936 cap = crypto_checkdriver(crid);
937 if (cap != NULL && CRYPTODEV_PROBESESSION(cap->cc_dev, csp) > 0)
941 * No requested driver; select based on crid flags.
943 cap = crypto_select_driver(csp, crid);
946 CRYPTO_DRIVER_UNLOCK();
947 CRYPTDEB("no driver");
952 CRYPTO_DRIVER_UNLOCK();
954 res = uma_zalloc(cryptoses_zone, M_WAITOK | M_ZERO);
956 res->softc = malloc(cap->cc_session_size, M_CRYPTO_DATA, M_WAITOK |
960 /* Call the driver initialization routine. */
961 err = CRYPTODEV_NEWSESSION(cap->cc_dev, res, csp);
963 CRYPTDEB("dev newsession failed: %d", err);
964 crypto_deletesession(res);
973 * Delete an existing session (or a reserved session on an unregistered
977 crypto_freesession(crypto_session_t cses)
979 struct cryptocap *cap;
986 /* Call the driver cleanup routine, if available. */
987 CRYPTODEV_FREESESSION(cap->cc_dev, cses);
989 crypto_deletesession(cses);
993 * Return a new driver id. Registers a driver with the system so that
994 * it can be probed by subsequent sessions.
997 crypto_get_driverid(device_t dev, size_t sessionsize, int flags)
999 struct cryptocap *cap, **newdrv;
1002 if ((flags & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
1004 "no flags specified when registering driver\n");
1008 cap = malloc(sizeof(*cap), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
1010 cap->cc_session_size = sessionsize;
1011 cap->cc_flags = flags;
1012 refcount_init(&cap->cc_refs, 1);
1014 CRYPTO_DRIVER_LOCK();
1016 for (i = 0; i < crypto_drivers_size; i++) {
1017 if (crypto_drivers[i] == NULL)
1021 if (i < crypto_drivers_size)
1024 /* Out of entries, allocate some more. */
1026 if (2 * crypto_drivers_size <= crypto_drivers_size) {
1027 CRYPTO_DRIVER_UNLOCK();
1028 printf("crypto: driver count wraparound!\n");
1032 CRYPTO_DRIVER_UNLOCK();
1034 newdrv = malloc(2 * crypto_drivers_size *
1035 sizeof(*crypto_drivers), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
1037 CRYPTO_DRIVER_LOCK();
1038 memcpy(newdrv, crypto_drivers,
1039 crypto_drivers_size * sizeof(*crypto_drivers));
1041 crypto_drivers_size *= 2;
1043 free(crypto_drivers, M_CRYPTO_DATA);
1044 crypto_drivers = newdrv;
1048 crypto_drivers[i] = cap;
1049 CRYPTO_DRIVER_UNLOCK();
1052 printf("crypto: assign %s driver id %u, flags 0x%x\n",
1053 device_get_nameunit(dev), i, flags);
1059 * Lookup a driver by name. We match against the full device
1060 * name and unit, and against just the name. The latter gives
1061 * us a simple widlcarding by device name. On success return the
1062 * driver/hardware identifier; otherwise return -1.
1065 crypto_find_driver(const char *match)
1067 struct cryptocap *cap;
1068 int i, len = strlen(match);
1070 CRYPTO_DRIVER_LOCK();
1071 for (i = 0; i < crypto_drivers_size; i++) {
1072 if (crypto_drivers[i] == NULL)
1074 cap = crypto_drivers[i];
1075 if (strncmp(match, device_get_nameunit(cap->cc_dev), len) == 0 ||
1076 strncmp(match, device_get_name(cap->cc_dev), len) == 0) {
1077 CRYPTO_DRIVER_UNLOCK();
1081 CRYPTO_DRIVER_UNLOCK();
1086 * Return the device_t for the specified driver or NULL
1087 * if the driver identifier is invalid.
1090 crypto_find_device_byhid(int hid)
1092 struct cryptocap *cap;
1096 CRYPTO_DRIVER_LOCK();
1097 cap = crypto_checkdriver(hid);
1100 CRYPTO_DRIVER_UNLOCK();
1105 * Return the device/driver capabilities.
1108 crypto_getcaps(int hid)
1110 struct cryptocap *cap;
1114 CRYPTO_DRIVER_LOCK();
1115 cap = crypto_checkdriver(hid);
1117 flags = cap->cc_flags;
1118 CRYPTO_DRIVER_UNLOCK();
1123 * Register support for a key-related algorithm. This routine
1124 * is called once for each algorithm supported a driver.
1127 crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags)
1129 struct cryptocap *cap;
1132 CRYPTO_DRIVER_LOCK();
1134 cap = crypto_checkdriver(driverid);
1136 (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
1138 * XXX Do some performance testing to determine placing.
1139 * XXX We probably need an auxiliary data structure that
1140 * XXX describes relative performances.
1143 cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
1145 printf("crypto: %s registers key alg %u flags %u\n"
1146 , device_get_nameunit(cap->cc_dev)
1154 CRYPTO_DRIVER_UNLOCK();
1159 * Unregister all algorithms associated with a crypto driver.
1160 * If there are pending sessions using it, leave enough information
1161 * around so that subsequent calls using those sessions will
1162 * correctly detect the driver has been unregistered and reroute
1166 crypto_unregister_all(u_int32_t driverid)
1168 struct cryptocap *cap;
1170 CRYPTO_DRIVER_LOCK();
1171 cap = crypto_checkdriver(driverid);
1173 CRYPTO_DRIVER_UNLOCK();
1177 cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
1178 crypto_drivers[driverid] = NULL;
1181 * XXX: This doesn't do anything to kick sessions that
1182 * have no pending operations.
1184 while (cap->cc_sessions != 0 || cap->cc_koperations != 0)
1185 mtx_sleep(cap, &crypto_drivers_mtx, 0, "cryunreg", 0);
1186 CRYPTO_DRIVER_UNLOCK();
1193 * Clear blockage on a driver. The what parameter indicates whether
1194 * the driver is now ready for cryptop's and/or cryptokop's.
1197 crypto_unblock(u_int32_t driverid, int what)
1199 struct cryptocap *cap;
1203 cap = crypto_checkdriver(driverid);
1205 if (what & CRYPTO_SYMQ)
1206 cap->cc_qblocked = 0;
1207 if (what & CRYPTO_ASYMQ)
1208 cap->cc_kqblocked = 0;
1220 crypto_buffer_len(struct crypto_buffer *cb)
1222 switch (cb->cb_type) {
1223 case CRYPTO_BUF_CONTIG:
1224 return (cb->cb_buf_len);
1225 case CRYPTO_BUF_MBUF:
1226 if (cb->cb_mbuf->m_flags & M_PKTHDR)
1227 return (cb->cb_mbuf->m_pkthdr.len);
1228 return (m_length(cb->cb_mbuf, NULL));
1229 case CRYPTO_BUF_UIO:
1230 return (cb->cb_uio->uio_resid);
1237 /* Various sanity checks on crypto requests. */
1239 cb_sanity(struct crypto_buffer *cb, const char *name)
1241 KASSERT(cb->cb_type > CRYPTO_BUF_NONE && cb->cb_type <= CRYPTO_BUF_LAST,
1242 ("incoming crp with invalid %s buffer type", name));
1243 if (cb->cb_type == CRYPTO_BUF_CONTIG)
1244 KASSERT(cb->cb_buf_len >= 0,
1245 ("incoming crp with -ve %s buffer length", name));
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 if (csp->csp_cipher_alg == CRYPTO_AES_NIST_GCM_16)
1302 KASSERT(crp->crp_flags & CRYPTO_F_IV_SEPARATE,
1303 ("GCM without a separate IV"));
1304 if (csp->csp_cipher_alg == CRYPTO_AES_CCM_16)
1305 KASSERT(crp->crp_flags & CRYPTO_F_IV_SEPARATE,
1306 ("CCM without a separate IV"));
1309 KASSERT(crp->crp_op ==
1310 (CRYPTO_OP_ENCRYPT | CRYPTO_OP_COMPUTE_DIGEST) ||
1312 (CRYPTO_OP_DECRYPT | CRYPTO_OP_VERIFY_DIGEST),
1313 ("invalid ETA op %x", crp->crp_op));
1316 if (csp->csp_mode == CSP_MODE_AEAD || csp->csp_mode == CSP_MODE_ETA) {
1317 if (crp->crp_aad == NULL) {
1318 KASSERT(crp->crp_aad_start == 0 ||
1319 crp->crp_aad_start < ilen,
1320 ("invalid AAD start"));
1321 KASSERT(crp->crp_aad_length != 0 ||
1322 crp->crp_aad_start == 0,
1323 ("AAD with zero length and non-zero start"));
1324 KASSERT(crp->crp_aad_length == 0 ||
1325 crp->crp_aad_start + crp->crp_aad_length <= ilen,
1326 ("AAD outside input length"));
1328 KASSERT(csp->csp_flags & CSP_F_SEPARATE_AAD,
1329 ("session doesn't support separate AAD buffer"));
1330 KASSERT(crp->crp_aad_start == 0,
1331 ("separate AAD buffer with non-zero AAD start"));
1332 KASSERT(crp->crp_aad_length != 0,
1333 ("separate AAD buffer with zero length"));
1336 KASSERT(crp->crp_aad == NULL && crp->crp_aad_start == 0 &&
1337 crp->crp_aad_length == 0,
1338 ("AAD region in request not supporting AAD"));
1340 if (csp->csp_ivlen == 0) {
1341 KASSERT((crp->crp_flags & CRYPTO_F_IV_SEPARATE) == 0,
1342 ("IV_SEPARATE set when IV isn't used"));
1343 KASSERT(crp->crp_iv_start == 0,
1344 ("crp_iv_start set when IV isn't used"));
1345 } else if (crp->crp_flags & CRYPTO_F_IV_SEPARATE) {
1346 KASSERT(crp->crp_iv_start == 0,
1347 ("IV_SEPARATE used with non-zero IV start"));
1349 KASSERT(crp->crp_iv_start < ilen,
1350 ("invalid IV start"));
1351 KASSERT(crp->crp_iv_start + csp->csp_ivlen <= ilen,
1352 ("IV outside buffer length"));
1354 /* XXX: payload_start of 0 should always be < ilen? */
1355 KASSERT(crp->crp_payload_start == 0 ||
1356 crp->crp_payload_start < ilen,
1357 ("invalid payload start"));
1358 KASSERT(crp->crp_payload_start + crp->crp_payload_length <=
1359 ilen, ("payload outside input buffer"));
1361 KASSERT(crp->crp_payload_output_start == 0,
1362 ("payload output start non-zero without output buffer"));
1364 KASSERT(crp->crp_payload_output_start < olen,
1365 ("invalid payload output start"));
1366 KASSERT(crp->crp_payload_output_start +
1367 crp->crp_payload_length <= olen,
1368 ("payload outside output buffer"));
1370 if (csp->csp_mode == CSP_MODE_DIGEST ||
1371 csp->csp_mode == CSP_MODE_AEAD || csp->csp_mode == CSP_MODE_ETA) {
1372 if (crp->crp_op & CRYPTO_OP_VERIFY_DIGEST)
1376 KASSERT(crp->crp_digest_start == 0 ||
1377 crp->crp_digest_start < len,
1378 ("invalid digest start"));
1379 /* XXX: For the mlen == 0 case this check isn't perfect. */
1380 KASSERT(crp->crp_digest_start + csp->csp_auth_mlen <= len,
1381 ("digest outside buffer"));
1383 KASSERT(crp->crp_digest_start == 0,
1384 ("non-zero digest start for request without a digest"));
1386 if (csp->csp_cipher_klen != 0)
1387 KASSERT(csp->csp_cipher_key != NULL ||
1388 crp->crp_cipher_key != NULL,
1389 ("cipher request without a key"));
1390 if (csp->csp_auth_klen != 0)
1391 KASSERT(csp->csp_auth_key != NULL || crp->crp_auth_key != NULL,
1392 ("auth request without a key"));
1393 KASSERT(crp->crp_callback != NULL, ("incoming crp without callback"));
1398 * Add a crypto request to a queue, to be processed by the kernel thread.
1401 crypto_dispatch(struct cryptop *crp)
1403 struct cryptocap *cap;
1410 cryptostats.cs_ops++;
1412 #ifdef CRYPTO_TIMING
1414 binuptime(&crp->crp_tstamp);
1417 crp->crp_retw_id = ((uintptr_t)crp->crp_session) % crypto_workers_num;
1419 if (CRYPTOP_ASYNC(crp)) {
1420 if (crp->crp_flags & CRYPTO_F_ASYNC_KEEPORDER) {
1421 struct crypto_ret_worker *ret_worker;
1423 ret_worker = CRYPTO_RETW(crp->crp_retw_id);
1425 CRYPTO_RETW_LOCK(ret_worker);
1426 crp->crp_seq = ret_worker->reorder_ops++;
1427 CRYPTO_RETW_UNLOCK(ret_worker);
1430 TASK_INIT(&crp->crp_task, 0, crypto_task_invoke, crp);
1431 taskqueue_enqueue(crypto_tq, &crp->crp_task);
1435 if ((crp->crp_flags & CRYPTO_F_BATCH) == 0) {
1437 * Caller marked the request to be processed
1438 * immediately; dispatch it directly to the
1439 * driver unless the driver is currently blocked.
1441 cap = crp->crp_session->cap;
1442 if (!cap->cc_qblocked) {
1443 result = crypto_invoke(cap, crp, 0);
1444 if (result != ERESTART)
1447 * The driver ran out of resources, put the request on
1452 crypto_batch_enqueue(crp);
1457 crypto_batch_enqueue(struct cryptop *crp)
1461 TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
1468 * Add an asymetric crypto request to a queue,
1469 * to be processed by the kernel thread.
1472 crypto_kdispatch(struct cryptkop *krp)
1476 cryptostats.cs_kops++;
1478 krp->krp_cap = NULL;
1479 error = crypto_kinvoke(krp);
1480 if (error == ERESTART) {
1482 TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
1492 * Verify a driver is suitable for the specified operation.
1495 kdriver_suitable(const struct cryptocap *cap, const struct cryptkop *krp)
1497 return (cap->cc_kalg[krp->krp_op] & CRYPTO_ALG_FLAG_SUPPORTED) != 0;
1501 * Select a driver for an asym operation. The driver must
1502 * support the necessary algorithm. The caller can constrain
1503 * which device is selected with the flags parameter. The
1504 * algorithm we use here is pretty stupid; just use the first
1505 * driver that supports the algorithms we need. If there are
1506 * multiple suitable drivers we choose the driver with the
1507 * fewest active operations. We prefer hardware-backed
1508 * drivers to software ones when either may be used.
1510 static struct cryptocap *
1511 crypto_select_kdriver(const struct cryptkop *krp, int flags)
1513 struct cryptocap *cap, *best;
1516 CRYPTO_DRIVER_ASSERT();
1519 * Look first for hardware crypto devices if permitted.
1521 if (flags & CRYPTOCAP_F_HARDWARE)
1522 match = CRYPTOCAP_F_HARDWARE;
1524 match = CRYPTOCAP_F_SOFTWARE;
1527 for (hid = 0; hid < crypto_drivers_size; hid++) {
1529 * If there is no driver for this slot, or the driver
1530 * is not appropriate (hardware or software based on
1531 * match), then skip.
1533 cap = crypto_drivers[hid];
1534 if (cap->cc_dev == NULL ||
1535 (cap->cc_flags & match) == 0)
1538 /* verify all the algorithms are supported. */
1539 if (kdriver_suitable(cap, krp)) {
1541 cap->cc_koperations < best->cc_koperations)
1547 if (match == CRYPTOCAP_F_HARDWARE && (flags & CRYPTOCAP_F_SOFTWARE)) {
1548 /* sort of an Algol 68-style for loop */
1549 match = CRYPTOCAP_F_SOFTWARE;
1556 * Choose a driver for an asymmetric crypto request.
1558 static struct cryptocap *
1559 crypto_lookup_kdriver(struct cryptkop *krp)
1561 struct cryptocap *cap;
1564 /* If this request is requeued, it might already have a driver. */
1569 /* Use krp_crid to choose a driver. */
1570 crid = krp->krp_crid;
1571 if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
1572 cap = crypto_checkdriver(crid);
1575 * Driver present, it must support the
1576 * necessary algorithm and, if s/w drivers are
1577 * excluded, it must be registered as
1580 if (!kdriver_suitable(cap, krp) ||
1581 (!crypto_devallowsoft &&
1582 (cap->cc_flags & CRYPTOCAP_F_HARDWARE) == 0))
1587 * No requested driver; select based on crid flags.
1589 if (!crypto_devallowsoft) /* NB: disallow s/w drivers */
1590 crid &= ~CRYPTOCAP_F_SOFTWARE;
1591 cap = crypto_select_kdriver(krp, crid);
1595 krp->krp_cap = cap_ref(cap);
1596 krp->krp_hid = cap->cc_hid;
1602 * Dispatch an asymmetric crypto request.
1605 crypto_kinvoke(struct cryptkop *krp)
1607 struct cryptocap *cap = NULL;
1610 KASSERT(krp != NULL, ("%s: krp == NULL", __func__));
1611 KASSERT(krp->krp_callback != NULL,
1612 ("%s: krp->crp_callback == NULL", __func__));
1614 CRYPTO_DRIVER_LOCK();
1615 cap = crypto_lookup_kdriver(krp);
1617 CRYPTO_DRIVER_UNLOCK();
1618 krp->krp_status = ENODEV;
1624 * If the device is blocked, return ERESTART to requeue it.
1626 if (cap->cc_kqblocked) {
1628 * XXX: Previously this set krp_status to ERESTART and
1629 * invoked crypto_kdone but the caller would still
1632 CRYPTO_DRIVER_UNLOCK();
1636 cap->cc_koperations++;
1637 CRYPTO_DRIVER_UNLOCK();
1638 error = CRYPTODEV_KPROCESS(cap->cc_dev, krp, 0);
1639 if (error == ERESTART) {
1640 CRYPTO_DRIVER_LOCK();
1641 cap->cc_koperations--;
1642 CRYPTO_DRIVER_UNLOCK();
1646 KASSERT(error == 0, ("error %d returned from crypto_kprocess", error));
1650 #ifdef CRYPTO_TIMING
1652 crypto_tstat(struct cryptotstat *ts, struct bintime *bt)
1654 struct bintime now, delta;
1660 delta.frac = now.frac - bt->frac;
1661 delta.sec = now.sec - bt->sec;
1664 bintime2timespec(&delta, &t);
1665 timespecadd(&ts->acc, &t, &ts->acc);
1666 if (timespeccmp(&t, &ts->min, <))
1668 if (timespeccmp(&t, &ts->max, >))
1677 crypto_task_invoke(void *ctx, int pending)
1679 struct cryptocap *cap;
1680 struct cryptop *crp;
1683 crp = (struct cryptop *)ctx;
1684 cap = crp->crp_session->cap;
1685 result = crypto_invoke(cap, crp, 0);
1686 if (result == ERESTART)
1687 crypto_batch_enqueue(crp);
1691 * Dispatch a crypto request to the appropriate crypto devices.
1694 crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint)
1697 KASSERT(crp != NULL, ("%s: crp == NULL", __func__));
1698 KASSERT(crp->crp_callback != NULL,
1699 ("%s: crp->crp_callback == NULL", __func__));
1700 KASSERT(crp->crp_session != NULL,
1701 ("%s: crp->crp_session == NULL", __func__));
1703 #ifdef CRYPTO_TIMING
1705 crypto_tstat(&cryptostats.cs_invoke, &crp->crp_tstamp);
1707 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1708 struct crypto_session_params csp;
1709 crypto_session_t nses;
1712 * Driver has unregistered; migrate the session and return
1713 * an error to the caller so they'll resubmit the op.
1715 * XXX: What if there are more already queued requests for this
1718 * XXX: Real solution is to make sessions refcounted
1719 * and force callers to hold a reference when
1720 * assigning to crp_session. Could maybe change
1721 * crypto_getreq to accept a session pointer to make
1722 * that work. Alternatively, we could abandon the
1723 * notion of rewriting crp_session in requests forcing
1724 * the caller to deal with allocating a new session.
1725 * Perhaps provide a method to allow a crp's session to
1726 * be swapped that callers could use.
1728 csp = crp->crp_session->csp;
1729 crypto_freesession(crp->crp_session);
1732 * XXX: Key pointers may no longer be valid. If we
1733 * really want to support this we need to define the
1734 * KPI such that 'csp' is required to be valid for the
1735 * duration of a session by the caller perhaps.
1737 * XXX: If the keys have been changed this will reuse
1738 * the old keys. This probably suggests making
1739 * rekeying more explicit and updating the key
1740 * pointers in 'csp' when the keys change.
1742 if (crypto_newsession(&nses, &csp,
1743 CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE) == 0)
1744 crp->crp_session = nses;
1746 crp->crp_etype = EAGAIN;
1751 * Invoke the driver to process the request.
1753 return CRYPTODEV_PROCESS(cap->cc_dev, crp, hint);
1758 crypto_freereq(struct cryptop *crp)
1766 struct cryptop *crp2;
1767 struct crypto_ret_worker *ret_worker;
1770 TAILQ_FOREACH(crp2, &crp_q, crp_next) {
1771 KASSERT(crp2 != crp,
1772 ("Freeing cryptop from the crypto queue (%p).",
1777 FOREACH_CRYPTO_RETW(ret_worker) {
1778 CRYPTO_RETW_LOCK(ret_worker);
1779 TAILQ_FOREACH(crp2, &ret_worker->crp_ret_q, crp_next) {
1780 KASSERT(crp2 != crp,
1781 ("Freeing cryptop from the return queue (%p).",
1784 CRYPTO_RETW_UNLOCK(ret_worker);
1789 uma_zfree(cryptop_zone, crp);
1793 crypto_getreq(crypto_session_t cses, int how)
1795 struct cryptop *crp;
1797 MPASS(how == M_WAITOK || how == M_NOWAIT);
1798 crp = uma_zalloc(cryptop_zone, how | M_ZERO);
1799 crp->crp_session = cses;
1804 * Invoke the callback on behalf of the driver.
1807 crypto_done(struct cryptop *crp)
1809 KASSERT((crp->crp_flags & CRYPTO_F_DONE) == 0,
1810 ("crypto_done: op already done, flags 0x%x", crp->crp_flags));
1811 crp->crp_flags |= CRYPTO_F_DONE;
1812 if (crp->crp_etype != 0)
1813 cryptostats.cs_errs++;
1814 #ifdef CRYPTO_TIMING
1816 crypto_tstat(&cryptostats.cs_done, &crp->crp_tstamp);
1819 * CBIMM means unconditionally do the callback immediately;
1820 * CBIFSYNC means do the callback immediately only if the
1821 * operation was done synchronously. Both are used to avoid
1822 * doing extraneous context switches; the latter is mostly
1823 * used with the software crypto driver.
1825 if (!CRYPTOP_ASYNC_KEEPORDER(crp) &&
1826 ((crp->crp_flags & CRYPTO_F_CBIMM) ||
1827 ((crp->crp_flags & CRYPTO_F_CBIFSYNC) &&
1828 (crypto_ses2caps(crp->crp_session) & CRYPTOCAP_F_SYNC)))) {
1830 * Do the callback directly. This is ok when the
1831 * callback routine does very little (e.g. the
1832 * /dev/crypto callback method just does a wakeup).
1834 #ifdef CRYPTO_TIMING
1835 if (crypto_timing) {
1837 * NB: We must copy the timestamp before
1838 * doing the callback as the cryptop is
1839 * likely to be reclaimed.
1841 struct bintime t = crp->crp_tstamp;
1842 crypto_tstat(&cryptostats.cs_cb, &t);
1843 crp->crp_callback(crp);
1844 crypto_tstat(&cryptostats.cs_finis, &t);
1847 crp->crp_callback(crp);
1849 struct crypto_ret_worker *ret_worker;
1852 ret_worker = CRYPTO_RETW(crp->crp_retw_id);
1856 * Normal case; queue the callback for the thread.
1858 CRYPTO_RETW_LOCK(ret_worker);
1859 if (CRYPTOP_ASYNC_KEEPORDER(crp)) {
1860 struct cryptop *tmp;
1862 TAILQ_FOREACH_REVERSE(tmp, &ret_worker->crp_ordered_ret_q,
1863 cryptop_q, crp_next) {
1864 if (CRYPTO_SEQ_GT(crp->crp_seq, tmp->crp_seq)) {
1865 TAILQ_INSERT_AFTER(&ret_worker->crp_ordered_ret_q,
1866 tmp, crp, crp_next);
1871 TAILQ_INSERT_HEAD(&ret_worker->crp_ordered_ret_q,
1875 if (crp->crp_seq == ret_worker->reorder_cur_seq)
1879 if (CRYPTO_RETW_EMPTY(ret_worker))
1882 TAILQ_INSERT_TAIL(&ret_worker->crp_ret_q, crp, crp_next);
1886 wakeup_one(&ret_worker->crp_ret_q); /* shared wait channel */
1887 CRYPTO_RETW_UNLOCK(ret_worker);
1892 * Invoke the callback on behalf of the driver.
1895 crypto_kdone(struct cryptkop *krp)
1897 struct crypto_ret_worker *ret_worker;
1898 struct cryptocap *cap;
1900 if (krp->krp_status != 0)
1901 cryptostats.cs_kerrs++;
1902 CRYPTO_DRIVER_LOCK();
1904 KASSERT(cap->cc_koperations > 0, ("cc_koperations == 0"));
1905 cap->cc_koperations--;
1906 if (cap->cc_koperations == 0 && cap->cc_flags & CRYPTOCAP_F_CLEANUP)
1908 CRYPTO_DRIVER_UNLOCK();
1909 krp->krp_cap = NULL;
1912 ret_worker = CRYPTO_RETW(0);
1914 CRYPTO_RETW_LOCK(ret_worker);
1915 if (CRYPTO_RETW_EMPTY(ret_worker))
1916 wakeup_one(&ret_worker->crp_ret_q); /* shared wait channel */
1917 TAILQ_INSERT_TAIL(&ret_worker->crp_ret_kq, krp, krp_next);
1918 CRYPTO_RETW_UNLOCK(ret_worker);
1922 crypto_getfeat(int *featp)
1924 int hid, kalg, feat = 0;
1926 CRYPTO_DRIVER_LOCK();
1927 for (hid = 0; hid < crypto_drivers_size; hid++) {
1928 const struct cryptocap *cap = crypto_drivers[hid];
1931 ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
1932 !crypto_devallowsoft)) {
1935 for (kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
1936 if (cap->cc_kalg[kalg] & CRYPTO_ALG_FLAG_SUPPORTED)
1939 CRYPTO_DRIVER_UNLOCK();
1945 * Terminate a thread at module unload. The process that
1946 * initiated this is waiting for us to signal that we're gone;
1947 * wake it up and exit. We use the driver table lock to insure
1948 * we don't do the wakeup before they're waiting. There is no
1949 * race here because the waiter sleeps on the proc lock for the
1950 * thread so it gets notified at the right time because of an
1951 * extra wakeup that's done in exit1().
1954 crypto_finis(void *chan)
1956 CRYPTO_DRIVER_LOCK();
1958 CRYPTO_DRIVER_UNLOCK();
1963 * Crypto thread, dispatches crypto requests.
1968 struct cryptop *crp, *submit;
1969 struct cryptkop *krp;
1970 struct cryptocap *cap;
1973 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
1974 fpu_kern_thread(FPU_KERN_NORMAL);
1980 * Find the first element in the queue that can be
1981 * processed and look-ahead to see if multiple ops
1982 * are ready for the same driver.
1986 TAILQ_FOREACH(crp, &crp_q, crp_next) {
1987 cap = crp->crp_session->cap;
1989 * Driver cannot disappeared when there is an active
1992 KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1993 __func__, __LINE__));
1994 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1995 /* Op needs to be migrated, process it. */
2000 if (!cap->cc_qblocked) {
2001 if (submit != NULL) {
2003 * We stop on finding another op,
2004 * regardless whether its for the same
2005 * driver or not. We could keep
2006 * searching the queue but it might be
2007 * better to just use a per-driver
2010 if (submit->crp_session->cap == cap)
2011 hint = CRYPTO_HINT_MORE;
2015 if ((submit->crp_flags & CRYPTO_F_BATCH) == 0)
2017 /* keep scanning for more are q'd */
2021 if (submit != NULL) {
2022 TAILQ_REMOVE(&crp_q, submit, crp_next);
2023 cap = submit->crp_session->cap;
2024 KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
2025 __func__, __LINE__));
2027 result = crypto_invoke(cap, submit, hint);
2029 if (result == ERESTART) {
2031 * The driver ran out of resources, mark the
2032 * driver ``blocked'' for cryptop's and put
2033 * the request back in the queue. It would
2034 * best to put the request back where we got
2035 * it but that's hard so for now we put it
2036 * at the front. This should be ok; putting
2037 * it at the end does not work.
2039 cap->cc_qblocked = 1;
2040 TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
2041 cryptostats.cs_blocks++;
2045 /* As above, but for key ops */
2046 TAILQ_FOREACH(krp, &crp_kq, krp_next) {
2048 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
2050 * Operation needs to be migrated,
2051 * clear krp_cap so a new driver is
2054 krp->krp_cap = NULL;
2058 if (!cap->cc_kqblocked)
2062 TAILQ_REMOVE(&crp_kq, krp, krp_next);
2064 result = crypto_kinvoke(krp);
2066 if (result == ERESTART) {
2068 * The driver ran out of resources, mark the
2069 * driver ``blocked'' for cryptkop's and put
2070 * the request back in the queue. It would
2071 * best to put the request back where we got
2072 * it but that's hard so for now we put it
2073 * at the front. This should be ok; putting
2074 * it at the end does not work.
2076 krp->krp_cap->cc_kqblocked = 1;
2077 TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
2078 cryptostats.cs_kblocks++;
2082 if (submit == NULL && krp == NULL) {
2084 * Nothing more to be processed. Sleep until we're
2085 * woken because there are more ops to process.
2086 * This happens either by submission or by a driver
2087 * becoming unblocked and notifying us through
2088 * crypto_unblock. Note that when we wakeup we
2089 * start processing each queue again from the
2090 * front. It's not clear that it's important to
2091 * preserve this ordering since ops may finish
2092 * out of order if dispatched to different devices
2093 * and some become blocked while others do not.
2096 msleep(&crp_q, &crypto_q_mtx, PWAIT, "crypto_wait", 0);
2098 if (cryptoproc == NULL)
2100 cryptostats.cs_intrs++;
2105 crypto_finis(&crp_q);
2109 * Crypto returns thread, does callbacks for processed crypto requests.
2110 * Callbacks are done here, rather than in the crypto drivers, because
2111 * callbacks typically are expensive and would slow interrupt handling.
2114 crypto_ret_proc(struct crypto_ret_worker *ret_worker)
2116 struct cryptop *crpt;
2117 struct cryptkop *krpt;
2119 CRYPTO_RETW_LOCK(ret_worker);
2121 /* Harvest return q's for completed ops */
2122 crpt = TAILQ_FIRST(&ret_worker->crp_ordered_ret_q);
2124 if (crpt->crp_seq == ret_worker->reorder_cur_seq) {
2125 TAILQ_REMOVE(&ret_worker->crp_ordered_ret_q, crpt, crp_next);
2126 ret_worker->reorder_cur_seq++;
2133 crpt = TAILQ_FIRST(&ret_worker->crp_ret_q);
2135 TAILQ_REMOVE(&ret_worker->crp_ret_q, crpt, crp_next);
2138 krpt = TAILQ_FIRST(&ret_worker->crp_ret_kq);
2140 TAILQ_REMOVE(&ret_worker->crp_ret_kq, krpt, krp_next);
2142 if (crpt != NULL || krpt != NULL) {
2143 CRYPTO_RETW_UNLOCK(ret_worker);
2145 * Run callbacks unlocked.
2148 #ifdef CRYPTO_TIMING
2149 if (crypto_timing) {
2151 * NB: We must copy the timestamp before
2152 * doing the callback as the cryptop is
2153 * likely to be reclaimed.
2155 struct bintime t = crpt->crp_tstamp;
2156 crypto_tstat(&cryptostats.cs_cb, &t);
2157 crpt->crp_callback(crpt);
2158 crypto_tstat(&cryptostats.cs_finis, &t);
2161 crpt->crp_callback(crpt);
2164 krpt->krp_callback(krpt);
2165 CRYPTO_RETW_LOCK(ret_worker);
2168 * Nothing more to be processed. Sleep until we're
2169 * woken because there are more returns to process.
2171 msleep(&ret_worker->crp_ret_q, &ret_worker->crypto_ret_mtx, PWAIT,
2172 "crypto_ret_wait", 0);
2173 if (ret_worker->cryptoretproc == NULL)
2175 cryptostats.cs_rets++;
2178 CRYPTO_RETW_UNLOCK(ret_worker);
2180 crypto_finis(&ret_worker->crp_ret_q);
2185 db_show_drivers(void)
2189 db_printf("%12s %4s %4s %8s %2s %2s\n"
2197 for (hid = 0; hid < crypto_drivers_size; hid++) {
2198 const struct cryptocap *cap = crypto_drivers[hid];
2201 db_printf("%-12s %4u %4u %08x %2u %2u\n"
2202 , device_get_nameunit(cap->cc_dev)
2204 , cap->cc_koperations
2212 DB_SHOW_COMMAND(crypto, db_show_crypto)
2214 struct cryptop *crp;
2215 struct crypto_ret_worker *ret_worker;
2220 db_printf("%4s %8s %4s %4s %4s %4s %8s %8s\n",
2221 "HID", "Caps", "Ilen", "Olen", "Etype", "Flags",
2222 "Device", "Callback");
2223 TAILQ_FOREACH(crp, &crp_q, crp_next) {
2224 db_printf("%4u %08x %4u %4u %04x %8p %8p\n"
2225 , crp->crp_session->cap->cc_hid
2226 , (int) crypto_ses2caps(crp->crp_session)
2230 , device_get_nameunit(crp->crp_session->cap->cc_dev)
2234 FOREACH_CRYPTO_RETW(ret_worker) {
2235 db_printf("\n%8s %4s %4s %4s %8s\n",
2236 "ret_worker", "HID", "Etype", "Flags", "Callback");
2237 if (!TAILQ_EMPTY(&ret_worker->crp_ret_q)) {
2238 TAILQ_FOREACH(crp, &ret_worker->crp_ret_q, crp_next) {
2239 db_printf("%8td %4u %4u %04x %8p\n"
2240 , CRYPTO_RETW_ID(ret_worker)
2241 , crp->crp_session->cap->cc_hid
2251 DB_SHOW_COMMAND(kcrypto, db_show_kcrypto)
2253 struct cryptkop *krp;
2254 struct crypto_ret_worker *ret_worker;
2259 db_printf("%4s %5s %4s %4s %8s %4s %8s\n",
2260 "Op", "Status", "#IP", "#OP", "CRID", "HID", "Callback");
2261 TAILQ_FOREACH(krp, &crp_kq, krp_next) {
2262 db_printf("%4u %5u %4u %4u %08x %4u %8p\n"
2265 , krp->krp_iparams, krp->krp_oparams
2266 , krp->krp_crid, krp->krp_hid
2271 ret_worker = CRYPTO_RETW(0);
2272 if (!TAILQ_EMPTY(&ret_worker->crp_ret_q)) {
2273 db_printf("%4s %5s %8s %4s %8s\n",
2274 "Op", "Status", "CRID", "HID", "Callback");
2275 TAILQ_FOREACH(krp, &ret_worker->crp_ret_kq, krp_next) {
2276 db_printf("%4u %5u %08x %4u %8p\n"
2279 , krp->krp_crid, krp->krp_hid
2287 int crypto_modevent(module_t mod, int type, void *unused);
2290 * Initialization code, both for static and dynamic loading.
2291 * Note this is not invoked with the usual MODULE_DECLARE
2292 * mechanism but instead is listed as a dependency by the
2293 * cryptosoft driver. This guarantees proper ordering of
2294 * calls on module load/unload.
2297 crypto_modevent(module_t mod, int type, void *unused)
2303 error = crypto_init();
2304 if (error == 0 && bootverbose)
2305 printf("crypto: <crypto core>\n");
2308 /*XXX disallow if active sessions */
2315 MODULE_VERSION(crypto, 1);
2316 MODULE_DEPEND(crypto, zlib, 1, 1, 1);