xref: /freebsd/sys/opencrypto/crypto.c (revision c1b2af731bbdd6f37d0f75386acab31b5ad86090)
1 /*-
2  * Copyright (c) 2002-2006 Sam Leffler.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
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.
12  *
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.
23  */
24 
25 #include <sys/cdefs.h>
26 __FBSDID("$FreeBSD$");
27 
28 /*
29  * Cryptographic Subsystem.
30  *
31  * This code is derived from the Openbsd Cryptographic Framework (OCF)
32  * that has the copyright shown below.  Very little of the original
33  * code remains.
34  */
35 
36 /*-
37  * The author of this code is Angelos D. Keromytis (angelos@cis.upenn.edu)
38  *
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.
42  *
43  * Copyright (c) 2000, 2001 Angelos D. Keromytis
44  *
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.
49  *
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
54  * PURPOSE.
55  */
56 
57 #define	CRYPTO_TIMING				/* enable timing support */
58 
59 #include "opt_compat.h"
60 #include "opt_ddb.h"
61 
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>
68 #include <sys/lock.h>
69 #include <sys/module.h>
70 #include <sys/mutex.h>
71 #include <sys/malloc.h>
72 #include <sys/proc.h>
73 #include <sys/refcount.h>
74 #include <sys/sdt.h>
75 #include <sys/smp.h>
76 #include <sys/sysctl.h>
77 #include <sys/taskqueue.h>
78 
79 #include <ddb/ddb.h>
80 
81 #include <vm/uma.h>
82 #include <crypto/intake.h>
83 #include <opencrypto/cryptodev.h>
84 #include <opencrypto/xform_auth.h>
85 #include <opencrypto/xform_enc.h>
86 
87 #include <sys/kobj.h>
88 #include <sys/bus.h>
89 #include "cryptodev_if.h"
90 
91 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
92 #include <machine/pcb.h>
93 #endif
94 
95 SDT_PROVIDER_DEFINE(opencrypto);
96 
97 /*
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().
101  */
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)
106 
107 /*
108  * Crypto device/driver capabilities structure.
109  *
110  * Synchronization:
111  * (d) - protected by CRYPTO_DRIVER_LOCK()
112  * (q) - protected by CRYPTO_Q_LOCK()
113  * Not tagged fields are read-only.
114  */
115 struct cryptocap {
116 	device_t	cc_dev;
117 	uint32_t	cc_hid;
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];
121 
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;
128 };
129 
130 static	struct cryptocap **crypto_drivers = NULL;
131 static	int crypto_drivers_size = 0;
132 
133 struct crypto_session {
134 	struct cryptocap *cap;
135 	void *softc;
136 	struct crypto_session_params csp;
137 };
138 
139 /*
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
144  * operations.
145  */
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)
152 
153 static SYSCTL_NODE(_kern, OID_AUTO, crypto, CTLFLAG_RW, 0,
154     "In-kernel cryptography");
155 
156 /*
157  * Taskqueue used to dispatch the crypto requests
158  * that have the CRYPTO_F_ASYNC flag
159  */
160 static struct taskqueue *crypto_tq;
161 
162 /*
163  * Crypto seq numbers are operated on with modular arithmetic
164  */
165 #define	CRYPTO_SEQ_GT(a,b)	((int)((a)-(b)) > 0)
166 
167 struct crypto_ret_worker {
168 	struct mtx crypto_ret_mtx;
169 
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 */
173 
174 	u_int32_t reorder_ops;		/* total ordered sym jobs received */
175 	u_int32_t reorder_cur_seq;	/* current sym job dispatched */
176 
177 	struct proc *cryptoretproc;
178 };
179 static struct crypto_ret_worker *crypto_ret_workers = NULL;
180 
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)
185 
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))
190 
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");
199 #endif
200 
201 static	uma_zone_t cryptop_zone;
202 static	uma_zone_t cryptoses_zone;
203 
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");
212 #endif
213 
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");
222 #endif
223 
224 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
225 
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);
234 
235 static	struct cryptostats cryptostats;
236 SYSCTL_STRUCT(_kern_crypto, OID_AUTO, stats, CTLFLAG_RW, &cryptostats,
237 	    cryptostats, "Crypto system statistics");
238 
239 #ifdef CRYPTO_TIMING
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");
243 #endif
244 
245 /* Try to avoid directly exposing the key buffer as a symbol */
246 static struct keybuf *keybuf;
247 
248 static struct keybuf empty_keybuf = {
249         .kb_nents = 0
250 };
251 
252 /* Obtain the key buffer from boot metadata */
253 static void
254 keybuf_init(void)
255 {
256 	caddr_t kmdp;
257 
258 	kmdp = preload_search_by_type("elf kernel");
259 
260 	if (kmdp == NULL)
261 		kmdp = preload_search_by_type("elf64 kernel");
262 
263 	keybuf = (struct keybuf *)preload_search_info(kmdp,
264 	    MODINFO_METADATA | MODINFOMD_KEYBUF);
265 
266         if (keybuf == NULL)
267                 keybuf = &empty_keybuf;
268 }
269 
270 /* It'd be nice if we could store these in some kind of secure memory... */
271 struct keybuf * get_keybuf(void) {
272 
273         return (keybuf);
274 }
275 
276 static struct cryptocap *
277 cap_ref(struct cryptocap *cap)
278 {
279 
280 	refcount_acquire(&cap->cc_refs);
281 	return (cap);
282 }
283 
284 static void
285 cap_rele(struct cryptocap *cap)
286 {
287 
288 	if (refcount_release(&cap->cc_refs) == 0)
289 		return;
290 
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"));
295 
296 	free(cap, M_CRYPTO_DATA);
297 }
298 
299 static int
300 crypto_init(void)
301 {
302 	struct crypto_ret_worker *ret_worker;
303 	int error;
304 
305 	mtx_init(&crypto_drivers_mtx, "crypto", "crypto driver table",
306 		MTX_DEF|MTX_QUIET);
307 
308 	TAILQ_INIT(&crp_q);
309 	TAILQ_INIT(&crp_kq);
310 	mtx_init(&crypto_q_mtx, "crypto", "crypto op queues", MTX_DEF);
311 
312 	cryptop_zone = uma_zcreate("cryptop", sizeof (struct cryptop),
313 				    0, 0, 0, 0,
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);
318 
319 	if (cryptop_zone == NULL || cryptoses_zone == NULL) {
320 		printf("crypto_init: cannot setup crypto zones\n");
321 		error = ENOMEM;
322 		goto bad;
323 	}
324 
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");
330 		error = ENOMEM;
331 		goto bad;
332 	}
333 
334 	if (crypto_workers_num < 1 || crypto_workers_num > mp_ncpus)
335 		crypto_workers_num = mp_ncpus;
336 
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");
341 		error = ENOMEM;
342 		goto bad;
343 	}
344 
345 	taskqueue_start_threads(&crypto_tq, crypto_workers_num, PRI_MIN_KERN,
346 		"crypto");
347 
348 	error = kproc_create((void (*)(void *)) crypto_proc, NULL,
349 		    &cryptoproc, 0, 0, "crypto");
350 	if (error) {
351 		printf("crypto_init: cannot start crypto thread; error %d",
352 			error);
353 		goto bad;
354 	}
355 
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) {
359 		error = ENOMEM;
360 		printf("crypto_init: cannot allocate ret workers\n");
361 		goto bad;
362 	}
363 
364 
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);
369 
370 		ret_worker->reorder_ops = 0;
371 		ret_worker->reorder_cur_seq = 0;
372 
373 		mtx_init(&ret_worker->crypto_ret_mtx, "crypto", "crypto return queues", MTX_DEF);
374 
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));
377 		if (error) {
378 			printf("crypto_init: cannot start cryptoret thread; error %d",
379 				error);
380 			goto bad;
381 		}
382 	}
383 
384 	keybuf_init();
385 
386 	return 0;
387 bad:
388 	crypto_destroy();
389 	return error;
390 }
391 
392 /*
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.
398  */
399 static void
400 crypto_terminate(struct proc **pp, void *q)
401 {
402 	struct proc *p;
403 
404 	mtx_assert(&crypto_drivers_mtx, MA_OWNED);
405 	p = *pp;
406 	*pp = NULL;
407 	if (p) {
408 		wakeup_one(q);
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);
412 		PROC_UNLOCK(p);
413 		CRYPTO_DRIVER_LOCK();
414 	}
415 }
416 
417 static void
418 hmac_init_pad(struct auth_hash *axf, const char *key, int klen, void *auth_ctx,
419     uint8_t padval)
420 {
421 	uint8_t hmac_key[HMAC_MAX_BLOCK_LEN];
422 	u_int i;
423 
424 	KASSERT(axf->blocksize <= sizeof(hmac_key),
425 	    ("Invalid HMAC block size %d", axf->blocksize));
426 
427 	/*
428 	 * If the key is larger than the block size, use the digest of
429 	 * the key as the key instead.
430 	 */
431 	memset(hmac_key, 0, sizeof(hmac_key));
432 	if (klen > axf->blocksize) {
433 		axf->Init(auth_ctx);
434 		axf->Update(auth_ctx, key, klen);
435 		axf->Final(hmac_key, auth_ctx);
436 		klen = axf->hashsize;
437 	} else
438 		memcpy(hmac_key, key, klen);
439 
440 	for (i = 0; i < axf->blocksize; i++)
441 		hmac_key[i] ^= padval;
442 
443 	axf->Init(auth_ctx);
444 	axf->Update(auth_ctx, hmac_key, axf->blocksize);
445 }
446 
447 void
448 hmac_init_ipad(struct auth_hash *axf, const char *key, int klen,
449     void *auth_ctx)
450 {
451 
452 	hmac_init_pad(axf, key, klen, auth_ctx, HMAC_IPAD_VAL);
453 }
454 
455 void
456 hmac_init_opad(struct auth_hash *axf, const char *key, int klen,
457     void *auth_ctx)
458 {
459 
460 	hmac_init_pad(axf, key, klen, auth_ctx, HMAC_OPAD_VAL);
461 }
462 
463 static void
464 crypto_destroy(void)
465 {
466 	struct crypto_ret_worker *ret_worker;
467 	int i;
468 
469 	/*
470 	 * Terminate any crypto threads.
471 	 */
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();
479 
480 	/* XXX flush queues??? */
481 
482 	/*
483 	 * Reclaim dynamically allocated resources.
484 	 */
485 	for (i = 0; i < crypto_drivers_size; i++) {
486 		if (crypto_drivers[i] != NULL)
487 			cap_rele(crypto_drivers[i]);
488 	}
489 	free(crypto_drivers, M_CRYPTO_DATA);
490 
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);
502 }
503 
504 uint32_t
505 crypto_ses2hid(crypto_session_t crypto_session)
506 {
507 	return (crypto_session->cap->cc_hid);
508 }
509 
510 uint32_t
511 crypto_ses2caps(crypto_session_t crypto_session)
512 {
513 	return (crypto_session->cap->cc_flags & 0xff000000);
514 }
515 
516 void *
517 crypto_get_driver_session(crypto_session_t crypto_session)
518 {
519 	return (crypto_session->softc);
520 }
521 
522 const struct crypto_session_params *
523 crypto_get_params(crypto_session_t crypto_session)
524 {
525 	return (&crypto_session->csp);
526 }
527 
528 struct auth_hash *
529 crypto_auth_hash(const struct crypto_session_params *csp)
530 {
531 
532 	switch (csp->csp_auth_alg) {
533 	case CRYPTO_MD5_HMAC:
534 		return (&auth_hash_hmac_md5);
535 	case CRYPTO_SHA1_HMAC:
536 		return (&auth_hash_hmac_sha1);
537 	case CRYPTO_SHA2_224_HMAC:
538 		return (&auth_hash_hmac_sha2_224);
539 	case CRYPTO_SHA2_256_HMAC:
540 		return (&auth_hash_hmac_sha2_256);
541 	case CRYPTO_SHA2_384_HMAC:
542 		return (&auth_hash_hmac_sha2_384);
543 	case CRYPTO_SHA2_512_HMAC:
544 		return (&auth_hash_hmac_sha2_512);
545 	case CRYPTO_NULL_HMAC:
546 		return (&auth_hash_null);
547 	case CRYPTO_RIPEMD160_HMAC:
548 		return (&auth_hash_hmac_ripemd_160);
549 	case CRYPTO_MD5_KPDK:
550 		return (&auth_hash_key_md5);
551 	case CRYPTO_SHA1_KPDK:
552 		return (&auth_hash_key_sha1);
553 #ifdef notyet
554 	case CRYPTO_MD5:
555 		return (&auth_hash_md5);
556 #endif
557 	case CRYPTO_SHA1:
558 		return (&auth_hash_sha1);
559 	case CRYPTO_SHA2_224:
560 		return (&auth_hash_sha2_224);
561 	case CRYPTO_SHA2_256:
562 		return (&auth_hash_sha2_256);
563 	case CRYPTO_SHA2_384:
564 		return (&auth_hash_sha2_384);
565 	case CRYPTO_SHA2_512:
566 		return (&auth_hash_sha2_512);
567 	case CRYPTO_AES_NIST_GMAC:
568 		switch (csp->csp_auth_klen) {
569 		case 128 / 8:
570 			return (&auth_hash_nist_gmac_aes_128);
571 		case 192 / 8:
572 			return (&auth_hash_nist_gmac_aes_192);
573 		case 256 / 8:
574 			return (&auth_hash_nist_gmac_aes_256);
575 		default:
576 			return (NULL);
577 		}
578 	case CRYPTO_BLAKE2B:
579 		return (&auth_hash_blake2b);
580 	case CRYPTO_BLAKE2S:
581 		return (&auth_hash_blake2s);
582 	case CRYPTO_POLY1305:
583 		return (&auth_hash_poly1305);
584 	case CRYPTO_AES_CCM_CBC_MAC:
585 		switch (csp->csp_auth_klen) {
586 		case 128 / 8:
587 			return (&auth_hash_ccm_cbc_mac_128);
588 		case 192 / 8:
589 			return (&auth_hash_ccm_cbc_mac_192);
590 		case 256 / 8:
591 			return (&auth_hash_ccm_cbc_mac_256);
592 		default:
593 			return (NULL);
594 		}
595 	default:
596 		return (NULL);
597 	}
598 }
599 
600 struct enc_xform *
601 crypto_cipher(const struct crypto_session_params *csp)
602 {
603 
604 	switch (csp->csp_cipher_alg) {
605 	case CRYPTO_DES_CBC:
606 		return (&enc_xform_des);
607 	case CRYPTO_3DES_CBC:
608 		return (&enc_xform_3des);
609 	case CRYPTO_BLF_CBC:
610 		return (&enc_xform_blf);
611 	case CRYPTO_CAST_CBC:
612 		return (&enc_xform_cast5);
613 	case CRYPTO_SKIPJACK_CBC:
614 		return (&enc_xform_skipjack);
615 	case CRYPTO_RIJNDAEL128_CBC:
616 		return (&enc_xform_rijndael128);
617 	case CRYPTO_AES_XTS:
618 		return (&enc_xform_aes_xts);
619 	case CRYPTO_AES_ICM:
620 		return (&enc_xform_aes_icm);
621 	case CRYPTO_AES_NIST_GCM_16:
622 		return (&enc_xform_aes_nist_gcm);
623 	case CRYPTO_CAMELLIA_CBC:
624 		return (&enc_xform_camellia);
625 	case CRYPTO_NULL_CBC:
626 		return (&enc_xform_null);
627 	case CRYPTO_CHACHA20:
628 		return (&enc_xform_chacha20);
629 	case CRYPTO_AES_CCM_16:
630 		return (&enc_xform_ccm);
631 	default:
632 		return (NULL);
633 	}
634 }
635 
636 static struct cryptocap *
637 crypto_checkdriver(u_int32_t hid)
638 {
639 
640 	return (hid >= crypto_drivers_size ? NULL : crypto_drivers[hid]);
641 }
642 
643 /*
644  * Select a driver for a new session that supports the specified
645  * algorithms and, optionally, is constrained according to the flags.
646  */
647 static struct cryptocap *
648 crypto_select_driver(const struct crypto_session_params *csp, int flags)
649 {
650 	struct cryptocap *cap, *best;
651 	int best_match, error, hid;
652 
653 	CRYPTO_DRIVER_ASSERT();
654 
655 	best = NULL;
656 	for (hid = 0; hid < crypto_drivers_size; hid++) {
657 		/*
658 		 * If there is no driver for this slot, or the driver
659 		 * is not appropriate (hardware or software based on
660 		 * match), then skip.
661 		 */
662 		cap = crypto_drivers[hid];
663 		if (cap == NULL ||
664 		    (cap->cc_flags & flags) == 0)
665 			continue;
666 
667 		error = CRYPTODEV_PROBESESSION(cap->cc_dev, csp);
668 		if (error >= 0)
669 			continue;
670 
671 		/*
672 		 * Use the driver with the highest probe value.
673 		 * Hardware drivers use a higher probe value than
674 		 * software.  In case of a tie, prefer the driver with
675 		 * the fewest active sessions.
676 		 */
677 		if (best == NULL || error > best_match ||
678 		    (error == best_match &&
679 		    cap->cc_sessions < best->cc_sessions)) {
680 			best = cap;
681 			best_match = error;
682 		}
683 	}
684 	return best;
685 }
686 
687 static bool
688 alg_is_compression(int alg)
689 {
690 
691 	if (alg == CRYPTO_DEFLATE_COMP)
692 		return (true);
693 	return (false);
694 }
695 
696 static bool
697 alg_is_cipher(int alg)
698 {
699 
700 	if (alg >= CRYPTO_DES_CBC && alg <= CRYPTO_SKIPJACK_CBC)
701 		return (true);
702 	if (alg >= CRYPTO_AES_CBC && alg <= CRYPTO_ARC4)
703 		return (true);
704 	if (alg == CRYPTO_NULL_CBC)
705 		return (true);
706 	if (alg >= CRYPTO_CAMELLIA_CBC && alg <= CRYPTO_AES_ICM)
707 		return (true);
708 	if (alg == CRYPTO_CHACHA20)
709 		return (true);
710 	return (false);
711 }
712 
713 static bool
714 alg_is_digest(int alg)
715 {
716 
717 	if (alg >= CRYPTO_MD5_HMAC && alg <= CRYPTO_SHA1_KPDK)
718 		return (true);
719 	if (alg >= CRYPTO_MD5 && alg <= CRYPTO_SHA1)
720 		return (true);
721 	if (alg == CRYPTO_NULL_HMAC)
722 		return (true);
723 	if (alg >= CRYPTO_SHA2_256_HMAC && alg <= CRYPTO_SHA2_512_HMAC)
724 		return (true);
725 	if (alg >= CRYPTO_SHA2_256_HMAC && alg <= CRYPTO_SHA2_512_HMAC)
726 		return (true);
727 	if (alg == CRYPTO_AES_NIST_GMAC)
728 		return (true);
729 	if (alg >= CRYPTO_BLAKE2B && alg <= CRYPTO_BLAKE2S)
730 		return (true);
731 	if (alg >= CRYPTO_SHA2_224_HMAC && alg <= CRYPTO_POLY1305)
732 		return (true);
733 	if (alg == CRYPTO_AES_CCM_CBC_MAC)
734 		return (true);
735 	return (false);
736 }
737 
738 static bool
739 alg_is_keyed_digest(int alg)
740 {
741 
742 	if (alg >= CRYPTO_MD5_HMAC && alg <= CRYPTO_SHA1_KPDK)
743 		return (true);
744 	if (alg >= CRYPTO_SHA2_256_HMAC && alg <= CRYPTO_SHA2_512_HMAC)
745 		return (true);
746 	if (alg == CRYPTO_AES_NIST_GMAC)
747 		return (true);
748 	if (alg >= CRYPTO_BLAKE2B && alg <= CRYPTO_BLAKE2S)
749 		return (true);
750 	if (alg == CRYPTO_SHA2_224_HMAC)
751 		return (true);
752 	if (alg == CRYPTO_POLY1305)
753 		return (true);
754 	if (alg == CRYPTO_AES_CCM_CBC_MAC)
755 		return (true);
756 	return (false);
757 }
758 
759 static bool
760 alg_is_aead(int alg)
761 {
762 
763 	if (alg == CRYPTO_AES_NIST_GCM_16)
764 		return (true);
765 	if (alg == CRYPTO_AES_CCM_16)
766 		return (true);
767 	return (false);
768 }
769 
770 /* Various sanity checks on crypto session parameters. */
771 static bool
772 check_csp(const struct crypto_session_params *csp)
773 {
774 	struct auth_hash *axf;
775 
776 	/* Mode-independent checks. */
777 	if (csp->csp_flags != 0)
778 		return (false);
779 	if (csp->csp_ivlen < 0 || csp->csp_cipher_klen < 0 ||
780 	    csp->csp_auth_klen < 0 || csp->csp_auth_mlen < 0)
781 		return (false);
782 	if (csp->csp_auth_key != NULL && csp->csp_auth_klen == 0)
783 		return (false);
784 	if (csp->csp_cipher_key != NULL && csp->csp_cipher_klen == 0)
785 		return (false);
786 
787 	switch (csp->csp_mode) {
788 	case CSP_MODE_COMPRESS:
789 		if (!alg_is_compression(csp->csp_cipher_alg))
790 			return (false);
791 		if (csp->csp_flags != 0)
792 			return (false);
793 		if (csp->csp_cipher_klen != 0 || csp->csp_ivlen != 0 ||
794 		    csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0 ||
795 		    csp->csp_auth_mlen != 0)
796 			return (false);
797 		break;
798 	case CSP_MODE_CIPHER:
799 		if (!alg_is_cipher(csp->csp_cipher_alg))
800 			return (false);
801 		if (csp->csp_cipher_alg != CRYPTO_NULL_CBC) {
802 			if (csp->csp_cipher_klen == 0)
803 				return (false);
804 			if (csp->csp_cipher_alg != CRYPTO_ARC4) {
805 				if (csp->csp_ivlen == 0)
806 					return (false);
807 			}
808 		}
809 		if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
810 			return (false);
811 		if (csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0 ||
812 		    csp->csp_auth_mlen != 0)
813 			return (false);
814 		break;
815 	case CSP_MODE_DIGEST:
816 		if (csp->csp_cipher_alg != 0 || csp->csp_cipher_klen != 0)
817 			return (false);
818 
819 		/* IV is optional for digests (e.g. GMAC). */
820 		if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
821 			return (false);
822 		if (!alg_is_digest(csp->csp_auth_alg))
823 			return (false);
824 
825 		/* Key is optional for BLAKE2 digests. */
826 		if (csp->csp_auth_alg == CRYPTO_BLAKE2B ||
827 		    csp->csp_auth_alg == CRYPTO_BLAKE2S)
828 			;
829 		else if (alg_is_keyed_digest(csp->csp_auth_alg)) {
830 			if (csp->csp_auth_klen == 0)
831 				return (false);
832 		} else {
833 			if (csp->csp_auth_klen != 0)
834 				return (false);
835 		}
836 		if (csp->csp_auth_mlen != 0) {
837 			axf = crypto_auth_hash(csp);
838 			if (axf == NULL || csp->csp_auth_mlen > axf->hashsize)
839 				return (false);
840 		}
841 		break;
842 	case CSP_MODE_AEAD:
843 		if (!alg_is_aead(csp->csp_cipher_alg))
844 			return (false);
845 		if (csp->csp_cipher_klen == 0)
846 			return (false);
847 		if (csp->csp_ivlen == 0 ||
848 		    csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
849 			return (false);
850 		if (csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0)
851 			return (false);
852 
853 		/*
854 		 * XXX: Would be nice to have a better way to get this
855 		 * value.
856 		 */
857 		switch (csp->csp_cipher_alg) {
858 		case CRYPTO_AES_NIST_GCM_16:
859 		case CRYPTO_AES_CCM_16:
860 			if (csp->csp_auth_mlen > 16)
861 				return (false);
862 			break;
863 		}
864 		break;
865 	case CSP_MODE_ETA:
866 		if (!alg_is_cipher(csp->csp_cipher_alg))
867 			return (false);
868 		if (csp->csp_cipher_alg != CRYPTO_NULL_CBC) {
869 			if (csp->csp_cipher_klen == 0)
870 				return (false);
871 			if (csp->csp_cipher_alg != CRYPTO_ARC4) {
872 				if (csp->csp_ivlen == 0)
873 					return (false);
874 			}
875 		}
876 		if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
877 			return (false);
878 		if (!alg_is_digest(csp->csp_auth_alg))
879 			return (false);
880 
881 		/* Key is optional for BLAKE2 digests. */
882 		if (csp->csp_auth_alg == CRYPTO_BLAKE2B ||
883 		    csp->csp_auth_alg == CRYPTO_BLAKE2S)
884 			;
885 		else if (alg_is_keyed_digest(csp->csp_auth_alg)) {
886 			if (csp->csp_auth_klen == 0)
887 				return (false);
888 		} else {
889 			if (csp->csp_auth_klen != 0)
890 				return (false);
891 		}
892 		if (csp->csp_auth_mlen != 0) {
893 			axf = crypto_auth_hash(csp);
894 			if (axf == NULL || csp->csp_auth_mlen > axf->hashsize)
895 				return (false);
896 		}
897 		break;
898 	default:
899 		return (false);
900 	}
901 
902 	return (true);
903 }
904 
905 /*
906  * Delete a session after it has been detached from its driver.
907  */
908 static void
909 crypto_deletesession(crypto_session_t cses)
910 {
911 	struct cryptocap *cap;
912 
913 	cap = cses->cap;
914 
915 	explicit_bzero(cses->softc, cap->cc_session_size);
916 	free(cses->softc, M_CRYPTO_DATA);
917 	uma_zfree(cryptoses_zone, cses);
918 
919 	CRYPTO_DRIVER_LOCK();
920 	cap->cc_sessions--;
921 	if (cap->cc_sessions == 0 && cap->cc_flags & CRYPTOCAP_F_CLEANUP)
922 		wakeup(cap);
923 	CRYPTO_DRIVER_UNLOCK();
924 	cap_rele(cap);
925 }
926 
927 /*
928  * Create a new session.  The crid argument specifies a crypto
929  * driver to use or constraints on a driver to select (hardware
930  * only, software only, either).  Whatever driver is selected
931  * must be capable of the requested crypto algorithms.
932  */
933 int
934 crypto_newsession(crypto_session_t *cses,
935     const struct crypto_session_params *csp, int crid)
936 {
937 	crypto_session_t res;
938 	struct cryptocap *cap;
939 	int err;
940 
941 	if (!check_csp(csp))
942 		return (EINVAL);
943 
944 	res = NULL;
945 
946 	CRYPTO_DRIVER_LOCK();
947 	if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
948 		/*
949 		 * Use specified driver; verify it is capable.
950 		 */
951 		cap = crypto_checkdriver(crid);
952 		if (cap != NULL && CRYPTODEV_PROBESESSION(cap->cc_dev, csp) > 0)
953 			cap = NULL;
954 	} else {
955 		/*
956 		 * No requested driver; select based on crid flags.
957 		 */
958 		cap = crypto_select_driver(csp, crid);
959 	}
960 	if (cap == NULL) {
961 		CRYPTO_DRIVER_UNLOCK();
962 		CRYPTDEB("no driver");
963 		return (EOPNOTSUPP);
964 	}
965 	cap_ref(cap);
966 	cap->cc_sessions++;
967 	CRYPTO_DRIVER_UNLOCK();
968 
969 	res = uma_zalloc(cryptoses_zone, M_WAITOK | M_ZERO);
970 	res->cap = cap;
971 	res->softc = malloc(cap->cc_session_size, M_CRYPTO_DATA, M_WAITOK |
972 	    M_ZERO);
973 	res->csp = *csp;
974 
975 	/* Call the driver initialization routine. */
976 	err = CRYPTODEV_NEWSESSION(cap->cc_dev, res, csp);
977 	if (err != 0) {
978 		CRYPTDEB("dev newsession failed: %d", err);
979 		crypto_deletesession(res);
980 		return (err);
981 	}
982 
983 	*cses = res;
984 	return (0);
985 }
986 
987 /*
988  * Delete an existing session (or a reserved session on an unregistered
989  * driver).
990  */
991 void
992 crypto_freesession(crypto_session_t cses)
993 {
994 	struct cryptocap *cap;
995 
996 	if (cses == NULL)
997 		return;
998 
999 	cap = cses->cap;
1000 
1001 	/* Call the driver cleanup routine, if available. */
1002 	CRYPTODEV_FREESESSION(cap->cc_dev, cses);
1003 
1004 	crypto_deletesession(cses);
1005 }
1006 
1007 /*
1008  * Return a new driver id.  Registers a driver with the system so that
1009  * it can be probed by subsequent sessions.
1010  */
1011 int32_t
1012 crypto_get_driverid(device_t dev, size_t sessionsize, int flags)
1013 {
1014 	struct cryptocap *cap, **newdrv;
1015 	int i;
1016 
1017 	if ((flags & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
1018 		device_printf(dev,
1019 		    "no flags specified when registering driver\n");
1020 		return -1;
1021 	}
1022 
1023 	cap = malloc(sizeof(*cap), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
1024 	cap->cc_dev = dev;
1025 	cap->cc_session_size = sessionsize;
1026 	cap->cc_flags = flags;
1027 	refcount_init(&cap->cc_refs, 1);
1028 
1029 	CRYPTO_DRIVER_LOCK();
1030 	for (;;) {
1031 		for (i = 0; i < crypto_drivers_size; i++) {
1032 			if (crypto_drivers[i] == NULL)
1033 				break;
1034 		}
1035 
1036 		if (i < crypto_drivers_size)
1037 			break;
1038 
1039 		/* Out of entries, allocate some more. */
1040 
1041 		if (2 * crypto_drivers_size <= crypto_drivers_size) {
1042 			CRYPTO_DRIVER_UNLOCK();
1043 			printf("crypto: driver count wraparound!\n");
1044 			cap_rele(cap);
1045 			return (-1);
1046 		}
1047 		CRYPTO_DRIVER_UNLOCK();
1048 
1049 		newdrv = malloc(2 * crypto_drivers_size *
1050 		    sizeof(*crypto_drivers), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
1051 
1052 		CRYPTO_DRIVER_LOCK();
1053 		memcpy(newdrv, crypto_drivers,
1054 		    crypto_drivers_size * sizeof(*crypto_drivers));
1055 
1056 		crypto_drivers_size *= 2;
1057 
1058 		free(crypto_drivers, M_CRYPTO_DATA);
1059 		crypto_drivers = newdrv;
1060 	}
1061 
1062 	cap->cc_hid = i;
1063 	crypto_drivers[i] = cap;
1064 	CRYPTO_DRIVER_UNLOCK();
1065 
1066 	if (bootverbose)
1067 		printf("crypto: assign %s driver id %u, flags 0x%x\n",
1068 		    device_get_nameunit(dev), i, flags);
1069 
1070 	return i;
1071 }
1072 
1073 /*
1074  * Lookup a driver by name.  We match against the full device
1075  * name and unit, and against just the name.  The latter gives
1076  * us a simple widlcarding by device name.  On success return the
1077  * driver/hardware identifier; otherwise return -1.
1078  */
1079 int
1080 crypto_find_driver(const char *match)
1081 {
1082 	struct cryptocap *cap;
1083 	int i, len = strlen(match);
1084 
1085 	CRYPTO_DRIVER_LOCK();
1086 	for (i = 0; i < crypto_drivers_size; i++) {
1087 		if (crypto_drivers[i] == NULL)
1088 			continue;
1089 		cap = crypto_drivers[i];
1090 		if (strncmp(match, device_get_nameunit(cap->cc_dev), len) == 0 ||
1091 		    strncmp(match, device_get_name(cap->cc_dev), len) == 0) {
1092 			CRYPTO_DRIVER_UNLOCK();
1093 			return (i);
1094 		}
1095 	}
1096 	CRYPTO_DRIVER_UNLOCK();
1097 	return (-1);
1098 }
1099 
1100 /*
1101  * Return the device_t for the specified driver or NULL
1102  * if the driver identifier is invalid.
1103  */
1104 device_t
1105 crypto_find_device_byhid(int hid)
1106 {
1107 	struct cryptocap *cap;
1108 	device_t dev;
1109 
1110 	dev = NULL;
1111 	CRYPTO_DRIVER_LOCK();
1112 	cap = crypto_checkdriver(hid);
1113 	if (cap != NULL)
1114 		dev = cap->cc_dev;
1115 	CRYPTO_DRIVER_UNLOCK();
1116 	return (dev);
1117 }
1118 
1119 /*
1120  * Return the device/driver capabilities.
1121  */
1122 int
1123 crypto_getcaps(int hid)
1124 {
1125 	struct cryptocap *cap;
1126 	int flags;
1127 
1128 	flags = 0;
1129 	CRYPTO_DRIVER_LOCK();
1130 	cap = crypto_checkdriver(hid);
1131 	if (cap != NULL)
1132 		flags = cap->cc_flags;
1133 	CRYPTO_DRIVER_UNLOCK();
1134 	return (flags);
1135 }
1136 
1137 /*
1138  * Register support for a key-related algorithm.  This routine
1139  * is called once for each algorithm supported a driver.
1140  */
1141 int
1142 crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags)
1143 {
1144 	struct cryptocap *cap;
1145 	int err;
1146 
1147 	CRYPTO_DRIVER_LOCK();
1148 
1149 	cap = crypto_checkdriver(driverid);
1150 	if (cap != NULL &&
1151 	    (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
1152 		/*
1153 		 * XXX Do some performance testing to determine placing.
1154 		 * XXX We probably need an auxiliary data structure that
1155 		 * XXX describes relative performances.
1156 		 */
1157 
1158 		cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
1159 		if (bootverbose)
1160 			printf("crypto: %s registers key alg %u flags %u\n"
1161 				, device_get_nameunit(cap->cc_dev)
1162 				, kalg
1163 				, flags
1164 			);
1165 		err = 0;
1166 	} else
1167 		err = EINVAL;
1168 
1169 	CRYPTO_DRIVER_UNLOCK();
1170 	return err;
1171 }
1172 
1173 /*
1174  * Unregister all algorithms associated with a crypto driver.
1175  * If there are pending sessions using it, leave enough information
1176  * around so that subsequent calls using those sessions will
1177  * correctly detect the driver has been unregistered and reroute
1178  * requests.
1179  */
1180 int
1181 crypto_unregister_all(u_int32_t driverid)
1182 {
1183 	struct cryptocap *cap;
1184 
1185 	CRYPTO_DRIVER_LOCK();
1186 	cap = crypto_checkdriver(driverid);
1187 	if (cap == NULL) {
1188 		CRYPTO_DRIVER_UNLOCK();
1189 		return (EINVAL);
1190 	}
1191 
1192 	cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
1193 	crypto_drivers[driverid] = NULL;
1194 
1195 	/*
1196 	 * XXX: This doesn't do anything to kick sessions that
1197 	 * have no pending operations.
1198 	 */
1199 	while (cap->cc_sessions != 0 || cap->cc_koperations != 0)
1200 		mtx_sleep(cap, &crypto_drivers_mtx, 0, "cryunreg", 0);
1201 	CRYPTO_DRIVER_UNLOCK();
1202 	cap_rele(cap);
1203 
1204 	return (0);
1205 }
1206 
1207 /*
1208  * Clear blockage on a driver.  The what parameter indicates whether
1209  * the driver is now ready for cryptop's and/or cryptokop's.
1210  */
1211 int
1212 crypto_unblock(u_int32_t driverid, int what)
1213 {
1214 	struct cryptocap *cap;
1215 	int err;
1216 
1217 	CRYPTO_Q_LOCK();
1218 	cap = crypto_checkdriver(driverid);
1219 	if (cap != NULL) {
1220 		if (what & CRYPTO_SYMQ)
1221 			cap->cc_qblocked = 0;
1222 		if (what & CRYPTO_ASYMQ)
1223 			cap->cc_kqblocked = 0;
1224 		if (crp_sleep)
1225 			wakeup_one(&crp_q);
1226 		err = 0;
1227 	} else
1228 		err = EINVAL;
1229 	CRYPTO_Q_UNLOCK();
1230 
1231 	return err;
1232 }
1233 
1234 #ifdef INVARIANTS
1235 /* Various sanity checks on crypto requests. */
1236 static void
1237 crp_sanity(struct cryptop *crp)
1238 {
1239 	struct crypto_session_params *csp;
1240 
1241 	KASSERT(crp->crp_session != NULL, ("incoming crp without a session"));
1242 	KASSERT(crp->crp_ilen >= 0, ("incoming crp with -ve input length"));
1243 	KASSERT(crp->crp_etype == 0, ("incoming crp with error"));
1244 	KASSERT(!(crp->crp_flags & CRYPTO_F_DONE),
1245 	    ("incoming crp already done"));
1246 
1247 	csp = &crp->crp_session->csp;
1248 	switch (csp->csp_mode) {
1249 	case CSP_MODE_COMPRESS:
1250 		KASSERT(crp->crp_op == CRYPTO_OP_COMPRESS ||
1251 		    crp->crp_op == CRYPTO_OP_DECOMPRESS,
1252 		    ("invalid compression op %x", crp->crp_op));
1253 		break;
1254 	case CSP_MODE_CIPHER:
1255 		KASSERT(crp->crp_op == CRYPTO_OP_ENCRYPT ||
1256 		    crp->crp_op == CRYPTO_OP_DECRYPT,
1257 		    ("invalid cipher op %x", crp->crp_op));
1258 		break;
1259 	case CSP_MODE_DIGEST:
1260 		KASSERT(crp->crp_op == CRYPTO_OP_COMPUTE_DIGEST ||
1261 		    crp->crp_op == CRYPTO_OP_VERIFY_DIGEST,
1262 		    ("invalid digest op %x", crp->crp_op));
1263 		break;
1264 	case CSP_MODE_AEAD:
1265 		KASSERT(crp->crp_op ==
1266 		    (CRYPTO_OP_ENCRYPT | CRYPTO_OP_COMPUTE_DIGEST) ||
1267 		    crp->crp_op ==
1268 		    (CRYPTO_OP_DECRYPT | CRYPTO_OP_VERIFY_DIGEST),
1269 		    ("invalid AEAD op %x", crp->crp_op));
1270 		if (csp->csp_cipher_alg == CRYPTO_AES_NIST_GCM_16)
1271 			KASSERT(crp->crp_flags & CRYPTO_F_IV_SEPARATE,
1272 			    ("GCM without a separate IV"));
1273 		if (csp->csp_cipher_alg == CRYPTO_AES_CCM_16)
1274 			KASSERT(crp->crp_flags & CRYPTO_F_IV_SEPARATE,
1275 			    ("CCM without a separate IV"));
1276 		break;
1277 	case CSP_MODE_ETA:
1278 		KASSERT(crp->crp_op ==
1279 		    (CRYPTO_OP_ENCRYPT | CRYPTO_OP_COMPUTE_DIGEST) ||
1280 		    crp->crp_op ==
1281 		    (CRYPTO_OP_DECRYPT | CRYPTO_OP_VERIFY_DIGEST),
1282 		    ("invalid ETA op %x", crp->crp_op));
1283 		break;
1284 	}
1285 	KASSERT((crp->crp_flags & CRYPTO_F_IV_GENERATE) == 0 ||
1286 	    crp->crp_op == CRYPTO_OP_ENCRYPT ||
1287 	    crp->crp_op == (CRYPTO_OP_ENCRYPT | CRYPTO_OP_COMPUTE_DIGEST),
1288 	    ("IV_GENERATE set for non-encryption operation %x", crp->crp_op));
1289 	KASSERT((crp->crp_flags &
1290 	    (CRYPTO_F_IV_SEPARATE | CRYPTO_F_IV_GENERATE)) !=
1291 	    (CRYPTO_F_IV_SEPARATE | CRYPTO_F_IV_GENERATE),
1292 	    ("crp with both IV_SEPARATE and IV_GENERATE set"));
1293 	KASSERT(crp->crp_buf_type >= CRYPTO_BUF_CONTIG &&
1294 	    crp->crp_buf_type <= CRYPTO_BUF_MBUF,
1295 	    ("invalid crp buffer type %d", crp->crp_buf_type));
1296 	if (csp->csp_mode == CSP_MODE_AEAD || csp->csp_mode == CSP_MODE_ETA) {
1297 		KASSERT(crp->crp_aad_start == 0 ||
1298 		    crp->crp_aad_start < crp->crp_ilen,
1299 		    ("invalid AAD start"));
1300 		KASSERT(crp->crp_aad_length != 0 || crp->crp_aad_start == 0,
1301 		    ("AAD with zero length and non-zero start"));
1302 		KASSERT(crp->crp_aad_length == 0 ||
1303 		    crp->crp_aad_start + crp->crp_aad_length <= crp->crp_ilen,
1304 		    ("AAD outside input length"));
1305 	} else {
1306 		KASSERT(crp->crp_aad_start == 0 && crp->crp_aad_length == 0,
1307 		    ("AAD region in request not supporting AAD"));
1308 	}
1309 	if (csp->csp_ivlen == 0) {
1310 		KASSERT((crp->crp_flags &
1311 		    (CRYPTO_F_IV_SEPARATE | CRYPTO_F_IV_GENERATE)) == 0,
1312 		    ("IV_GENERATE or IV_SEPARATE set when IV isn't used"));
1313 		KASSERT(crp->crp_iv_start == 0,
1314 		    ("crp_iv_start set when IV isn't used"));
1315 	} else if (crp->crp_flags & CRYPTO_F_IV_SEPARATE) {
1316 		KASSERT(crp->crp_iv_start == 0,
1317 		    ("IV_SEPARATE used with non-zero IV start"));
1318 	} else {
1319 		KASSERT(crp->crp_iv_start < crp->crp_ilen,
1320 		    ("invalid IV start"));
1321 		KASSERT(crp->crp_iv_start + csp->csp_ivlen <= crp->crp_ilen,
1322 		    ("IV outside input length"));
1323 	}
1324 	KASSERT(crp->crp_payload_start == 0 ||
1325 	    crp->crp_payload_start < crp->crp_ilen,
1326 	    ("invalid payload start"));
1327 	KASSERT(crp->crp_payload_start + crp->crp_payload_length <=
1328 	    crp->crp_ilen, ("payload outside input length"));
1329 	if (csp->csp_mode == CSP_MODE_DIGEST ||
1330 	    csp->csp_mode == CSP_MODE_AEAD || csp->csp_mode == CSP_MODE_ETA) {
1331 		KASSERT(crp->crp_digest_start == 0 ||
1332 		    crp->crp_digest_start < crp->crp_ilen,
1333 		    ("invalid digest start"));
1334 		/* XXX: For the mlen == 0 case this check isn't perfect. */
1335 		KASSERT(crp->crp_digest_start + csp->csp_auth_mlen <=
1336 		    crp->crp_ilen,
1337 		    ("digest outside input length"));
1338 	} else {
1339 		KASSERT(crp->crp_digest_start == 0,
1340 		    ("non-zero digest start for request without a digest"));
1341 	}
1342 	if (csp->csp_cipher_klen != 0)
1343 		KASSERT(csp->csp_cipher_key != NULL ||
1344 		    crp->crp_cipher_key != NULL,
1345 		    ("cipher request without a key"));
1346 	if (csp->csp_auth_klen != 0)
1347 		KASSERT(csp->csp_auth_key != NULL || crp->crp_auth_key != NULL,
1348 		    ("auth request without a key"));
1349 	KASSERT(crp->crp_callback != NULL, ("incoming crp without callback"));
1350 }
1351 #endif
1352 
1353 /*
1354  * Add a crypto request to a queue, to be processed by the kernel thread.
1355  */
1356 int
1357 crypto_dispatch(struct cryptop *crp)
1358 {
1359 	struct cryptocap *cap;
1360 	int result;
1361 
1362 #ifdef INVARIANTS
1363 	crp_sanity(crp);
1364 #endif
1365 
1366 	/* TODO: Handle CRYPTO_F_IV_GENERATE so drivers don't have to. */
1367 
1368 	cryptostats.cs_ops++;
1369 
1370 #ifdef CRYPTO_TIMING
1371 	if (crypto_timing)
1372 		binuptime(&crp->crp_tstamp);
1373 #endif
1374 
1375 	crp->crp_retw_id = ((uintptr_t)crp->crp_session) % crypto_workers_num;
1376 
1377 	if (CRYPTOP_ASYNC(crp)) {
1378 		if (crp->crp_flags & CRYPTO_F_ASYNC_KEEPORDER) {
1379 			struct crypto_ret_worker *ret_worker;
1380 
1381 			ret_worker = CRYPTO_RETW(crp->crp_retw_id);
1382 
1383 			CRYPTO_RETW_LOCK(ret_worker);
1384 			crp->crp_seq = ret_worker->reorder_ops++;
1385 			CRYPTO_RETW_UNLOCK(ret_worker);
1386 		}
1387 
1388 		TASK_INIT(&crp->crp_task, 0, crypto_task_invoke, crp);
1389 		taskqueue_enqueue(crypto_tq, &crp->crp_task);
1390 		return (0);
1391 	}
1392 
1393 	if ((crp->crp_flags & CRYPTO_F_BATCH) == 0) {
1394 		/*
1395 		 * Caller marked the request to be processed
1396 		 * immediately; dispatch it directly to the
1397 		 * driver unless the driver is currently blocked.
1398 		 */
1399 		cap = crp->crp_session->cap;
1400 		if (!cap->cc_qblocked) {
1401 			result = crypto_invoke(cap, crp, 0);
1402 			if (result != ERESTART)
1403 				return (result);
1404 			/*
1405 			 * The driver ran out of resources, put the request on
1406 			 * the queue.
1407 			 */
1408 		}
1409 	}
1410 	crypto_batch_enqueue(crp);
1411 	return 0;
1412 }
1413 
1414 void
1415 crypto_batch_enqueue(struct cryptop *crp)
1416 {
1417 
1418 	CRYPTO_Q_LOCK();
1419 	TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
1420 	if (crp_sleep)
1421 		wakeup_one(&crp_q);
1422 	CRYPTO_Q_UNLOCK();
1423 }
1424 
1425 /*
1426  * Add an asymetric crypto request to a queue,
1427  * to be processed by the kernel thread.
1428  */
1429 int
1430 crypto_kdispatch(struct cryptkop *krp)
1431 {
1432 	int error;
1433 
1434 	cryptostats.cs_kops++;
1435 
1436 	krp->krp_cap = NULL;
1437 	error = crypto_kinvoke(krp);
1438 	if (error == ERESTART) {
1439 		CRYPTO_Q_LOCK();
1440 		TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
1441 		if (crp_sleep)
1442 			wakeup_one(&crp_q);
1443 		CRYPTO_Q_UNLOCK();
1444 		error = 0;
1445 	}
1446 	return error;
1447 }
1448 
1449 /*
1450  * Verify a driver is suitable for the specified operation.
1451  */
1452 static __inline int
1453 kdriver_suitable(const struct cryptocap *cap, const struct cryptkop *krp)
1454 {
1455 	return (cap->cc_kalg[krp->krp_op] & CRYPTO_ALG_FLAG_SUPPORTED) != 0;
1456 }
1457 
1458 /*
1459  * Select a driver for an asym operation.  The driver must
1460  * support the necessary algorithm.  The caller can constrain
1461  * which device is selected with the flags parameter.  The
1462  * algorithm we use here is pretty stupid; just use the first
1463  * driver that supports the algorithms we need. If there are
1464  * multiple suitable drivers we choose the driver with the
1465  * fewest active operations.  We prefer hardware-backed
1466  * drivers to software ones when either may be used.
1467  */
1468 static struct cryptocap *
1469 crypto_select_kdriver(const struct cryptkop *krp, int flags)
1470 {
1471 	struct cryptocap *cap, *best;
1472 	int match, hid;
1473 
1474 	CRYPTO_DRIVER_ASSERT();
1475 
1476 	/*
1477 	 * Look first for hardware crypto devices if permitted.
1478 	 */
1479 	if (flags & CRYPTOCAP_F_HARDWARE)
1480 		match = CRYPTOCAP_F_HARDWARE;
1481 	else
1482 		match = CRYPTOCAP_F_SOFTWARE;
1483 	best = NULL;
1484 again:
1485 	for (hid = 0; hid < crypto_drivers_size; hid++) {
1486 		/*
1487 		 * If there is no driver for this slot, or the driver
1488 		 * is not appropriate (hardware or software based on
1489 		 * match), then skip.
1490 		 */
1491 		cap = crypto_drivers[hid];
1492 		if (cap->cc_dev == NULL ||
1493 		    (cap->cc_flags & match) == 0)
1494 			continue;
1495 
1496 		/* verify all the algorithms are supported. */
1497 		if (kdriver_suitable(cap, krp)) {
1498 			if (best == NULL ||
1499 			    cap->cc_koperations < best->cc_koperations)
1500 				best = cap;
1501 		}
1502 	}
1503 	if (best != NULL)
1504 		return best;
1505 	if (match == CRYPTOCAP_F_HARDWARE && (flags & CRYPTOCAP_F_SOFTWARE)) {
1506 		/* sort of an Algol 68-style for loop */
1507 		match = CRYPTOCAP_F_SOFTWARE;
1508 		goto again;
1509 	}
1510 	return best;
1511 }
1512 
1513 /*
1514  * Choose a driver for an asymmetric crypto request.
1515  */
1516 static struct cryptocap *
1517 crypto_lookup_kdriver(struct cryptkop *krp)
1518 {
1519 	struct cryptocap *cap;
1520 	uint32_t crid;
1521 
1522 	/* If this request is requeued, it might already have a driver. */
1523 	cap = krp->krp_cap;
1524 	if (cap != NULL)
1525 		return (cap);
1526 
1527 	/* Use krp_crid to choose a driver. */
1528 	crid = krp->krp_crid;
1529 	if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
1530 		cap = crypto_checkdriver(crid);
1531 		if (cap != NULL) {
1532 			/*
1533 			 * Driver present, it must support the
1534 			 * necessary algorithm and, if s/w drivers are
1535 			 * excluded, it must be registered as
1536 			 * hardware-backed.
1537 			 */
1538 			if (!kdriver_suitable(cap, krp) ||
1539 			    (!crypto_devallowsoft &&
1540 			    (cap->cc_flags & CRYPTOCAP_F_HARDWARE) == 0))
1541 				cap = NULL;
1542 		}
1543 	} else {
1544 		/*
1545 		 * No requested driver; select based on crid flags.
1546 		 */
1547 		if (!crypto_devallowsoft)	/* NB: disallow s/w drivers */
1548 			crid &= ~CRYPTOCAP_F_SOFTWARE;
1549 		cap = crypto_select_kdriver(krp, crid);
1550 	}
1551 
1552 	if (cap != NULL) {
1553 		krp->krp_cap = cap_ref(cap);
1554 		krp->krp_hid = cap->cc_hid;
1555 	}
1556 	return (cap);
1557 }
1558 
1559 /*
1560  * Dispatch an asymmetric crypto request.
1561  */
1562 static int
1563 crypto_kinvoke(struct cryptkop *krp)
1564 {
1565 	struct cryptocap *cap = NULL;
1566 	int error;
1567 
1568 	KASSERT(krp != NULL, ("%s: krp == NULL", __func__));
1569 	KASSERT(krp->krp_callback != NULL,
1570 	    ("%s: krp->crp_callback == NULL", __func__));
1571 
1572 	CRYPTO_DRIVER_LOCK();
1573 	cap = crypto_lookup_kdriver(krp);
1574 	if (cap == NULL) {
1575 		CRYPTO_DRIVER_UNLOCK();
1576 		krp->krp_status = ENODEV;
1577 		crypto_kdone(krp);
1578 		return (0);
1579 	}
1580 
1581 	/*
1582 	 * If the device is blocked, return ERESTART to requeue it.
1583 	 */
1584 	if (cap->cc_kqblocked) {
1585 		/*
1586 		 * XXX: Previously this set krp_status to ERESTART and
1587 		 * invoked crypto_kdone but the caller would still
1588 		 * requeue it.
1589 		 */
1590 		CRYPTO_DRIVER_UNLOCK();
1591 		return (ERESTART);
1592 	}
1593 
1594 	cap->cc_koperations++;
1595 	CRYPTO_DRIVER_UNLOCK();
1596 	error = CRYPTODEV_KPROCESS(cap->cc_dev, krp, 0);
1597 	if (error == ERESTART) {
1598 		CRYPTO_DRIVER_LOCK();
1599 		cap->cc_koperations--;
1600 		CRYPTO_DRIVER_UNLOCK();
1601 		return (error);
1602 	}
1603 
1604 	KASSERT(error == 0, ("error %d returned from crypto_kprocess", error));
1605 	return (0);
1606 }
1607 
1608 #ifdef CRYPTO_TIMING
1609 static void
1610 crypto_tstat(struct cryptotstat *ts, struct bintime *bt)
1611 {
1612 	struct bintime now, delta;
1613 	struct timespec t;
1614 	uint64_t u;
1615 
1616 	binuptime(&now);
1617 	u = now.frac;
1618 	delta.frac = now.frac - bt->frac;
1619 	delta.sec = now.sec - bt->sec;
1620 	if (u < delta.frac)
1621 		delta.sec--;
1622 	bintime2timespec(&delta, &t);
1623 	timespecadd(&ts->acc, &t, &ts->acc);
1624 	if (timespeccmp(&t, &ts->min, <))
1625 		ts->min = t;
1626 	if (timespeccmp(&t, &ts->max, >))
1627 		ts->max = t;
1628 	ts->count++;
1629 
1630 	*bt = now;
1631 }
1632 #endif
1633 
1634 static void
1635 crypto_task_invoke(void *ctx, int pending)
1636 {
1637 	struct cryptocap *cap;
1638 	struct cryptop *crp;
1639 	int result;
1640 
1641 	crp = (struct cryptop *)ctx;
1642 	cap = crp->crp_session->cap;
1643 	result = crypto_invoke(cap, crp, 0);
1644 	if (result == ERESTART)
1645 		crypto_batch_enqueue(crp);
1646 }
1647 
1648 /*
1649  * Dispatch a crypto request to the appropriate crypto devices.
1650  */
1651 static int
1652 crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint)
1653 {
1654 
1655 	KASSERT(crp != NULL, ("%s: crp == NULL", __func__));
1656 	KASSERT(crp->crp_callback != NULL,
1657 	    ("%s: crp->crp_callback == NULL", __func__));
1658 	KASSERT(crp->crp_session != NULL,
1659 	    ("%s: crp->crp_session == NULL", __func__));
1660 
1661 #ifdef CRYPTO_TIMING
1662 	if (crypto_timing)
1663 		crypto_tstat(&cryptostats.cs_invoke, &crp->crp_tstamp);
1664 #endif
1665 	if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1666 		struct crypto_session_params csp;
1667 		crypto_session_t nses;
1668 
1669 		/*
1670 		 * Driver has unregistered; migrate the session and return
1671 		 * an error to the caller so they'll resubmit the op.
1672 		 *
1673 		 * XXX: What if there are more already queued requests for this
1674 		 *      session?
1675 		 *
1676 		 * XXX: Real solution is to make sessions refcounted
1677 		 * and force callers to hold a reference when
1678 		 * assigning to crp_session.  Could maybe change
1679 		 * crypto_getreq to accept a session pointer to make
1680 		 * that work.  Alternatively, we could abandon the
1681 		 * notion of rewriting crp_session in requests forcing
1682 		 * the caller to deal with allocating a new session.
1683 		 * Perhaps provide a method to allow a crp's session to
1684 		 * be swapped that callers could use.
1685 		 */
1686 		csp = crp->crp_session->csp;
1687 		crypto_freesession(crp->crp_session);
1688 
1689 		/*
1690 		 * XXX: Key pointers may no longer be valid.  If we
1691 		 * really want to support this we need to define the
1692 		 * KPI such that 'csp' is required to be valid for the
1693 		 * duration of a session by the caller perhaps.
1694 		 *
1695 		 * XXX: If the keys have been changed this will reuse
1696 		 * the old keys.  This probably suggests making
1697 		 * rekeying more explicit and updating the key
1698 		 * pointers in 'csp' when the keys change.
1699 		 */
1700 		if (crypto_newsession(&nses, &csp,
1701 		    CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE) == 0)
1702 			crp->crp_session = nses;
1703 
1704 		crp->crp_etype = EAGAIN;
1705 		crypto_done(crp);
1706 		return 0;
1707 	} else {
1708 		/*
1709 		 * Invoke the driver to process the request.
1710 		 */
1711 		return CRYPTODEV_PROCESS(cap->cc_dev, crp, hint);
1712 	}
1713 }
1714 
1715 void
1716 crypto_freereq(struct cryptop *crp)
1717 {
1718 
1719 	if (crp == NULL)
1720 		return;
1721 
1722 #ifdef DIAGNOSTIC
1723 	{
1724 		struct cryptop *crp2;
1725 		struct crypto_ret_worker *ret_worker;
1726 
1727 		CRYPTO_Q_LOCK();
1728 		TAILQ_FOREACH(crp2, &crp_q, crp_next) {
1729 			KASSERT(crp2 != crp,
1730 			    ("Freeing cryptop from the crypto queue (%p).",
1731 			    crp));
1732 		}
1733 		CRYPTO_Q_UNLOCK();
1734 
1735 		FOREACH_CRYPTO_RETW(ret_worker) {
1736 			CRYPTO_RETW_LOCK(ret_worker);
1737 			TAILQ_FOREACH(crp2, &ret_worker->crp_ret_q, crp_next) {
1738 				KASSERT(crp2 != crp,
1739 				    ("Freeing cryptop from the return queue (%p).",
1740 				    crp));
1741 			}
1742 			CRYPTO_RETW_UNLOCK(ret_worker);
1743 		}
1744 	}
1745 #endif
1746 
1747 	uma_zfree(cryptop_zone, crp);
1748 }
1749 
1750 struct cryptop *
1751 crypto_getreq(crypto_session_t cses, int how)
1752 {
1753 	struct cryptop *crp;
1754 
1755 	MPASS(how == M_WAITOK || how == M_NOWAIT);
1756 	crp = uma_zalloc(cryptop_zone, how | M_ZERO);
1757 	crp->crp_session = cses;
1758 	return (crp);
1759 }
1760 
1761 /*
1762  * Invoke the callback on behalf of the driver.
1763  */
1764 void
1765 crypto_done(struct cryptop *crp)
1766 {
1767 	KASSERT((crp->crp_flags & CRYPTO_F_DONE) == 0,
1768 		("crypto_done: op already done, flags 0x%x", crp->crp_flags));
1769 	crp->crp_flags |= CRYPTO_F_DONE;
1770 	if (crp->crp_etype != 0)
1771 		cryptostats.cs_errs++;
1772 #ifdef CRYPTO_TIMING
1773 	if (crypto_timing)
1774 		crypto_tstat(&cryptostats.cs_done, &crp->crp_tstamp);
1775 #endif
1776 	/*
1777 	 * CBIMM means unconditionally do the callback immediately;
1778 	 * CBIFSYNC means do the callback immediately only if the
1779 	 * operation was done synchronously.  Both are used to avoid
1780 	 * doing extraneous context switches; the latter is mostly
1781 	 * used with the software crypto driver.
1782 	 */
1783 	if (!CRYPTOP_ASYNC_KEEPORDER(crp) &&
1784 	    ((crp->crp_flags & CRYPTO_F_CBIMM) ||
1785 	    ((crp->crp_flags & CRYPTO_F_CBIFSYNC) &&
1786 	     (crypto_ses2caps(crp->crp_session) & CRYPTOCAP_F_SYNC)))) {
1787 		/*
1788 		 * Do the callback directly.  This is ok when the
1789 		 * callback routine does very little (e.g. the
1790 		 * /dev/crypto callback method just does a wakeup).
1791 		 */
1792 #ifdef CRYPTO_TIMING
1793 		if (crypto_timing) {
1794 			/*
1795 			 * NB: We must copy the timestamp before
1796 			 * doing the callback as the cryptop is
1797 			 * likely to be reclaimed.
1798 			 */
1799 			struct bintime t = crp->crp_tstamp;
1800 			crypto_tstat(&cryptostats.cs_cb, &t);
1801 			crp->crp_callback(crp);
1802 			crypto_tstat(&cryptostats.cs_finis, &t);
1803 		} else
1804 #endif
1805 			crp->crp_callback(crp);
1806 	} else {
1807 		struct crypto_ret_worker *ret_worker;
1808 		bool wake;
1809 
1810 		ret_worker = CRYPTO_RETW(crp->crp_retw_id);
1811 		wake = false;
1812 
1813 		/*
1814 		 * Normal case; queue the callback for the thread.
1815 		 */
1816 		CRYPTO_RETW_LOCK(ret_worker);
1817 		if (CRYPTOP_ASYNC_KEEPORDER(crp)) {
1818 			struct cryptop *tmp;
1819 
1820 			TAILQ_FOREACH_REVERSE(tmp, &ret_worker->crp_ordered_ret_q,
1821 					cryptop_q, crp_next) {
1822 				if (CRYPTO_SEQ_GT(crp->crp_seq, tmp->crp_seq)) {
1823 					TAILQ_INSERT_AFTER(&ret_worker->crp_ordered_ret_q,
1824 							tmp, crp, crp_next);
1825 					break;
1826 				}
1827 			}
1828 			if (tmp == NULL) {
1829 				TAILQ_INSERT_HEAD(&ret_worker->crp_ordered_ret_q,
1830 						crp, crp_next);
1831 			}
1832 
1833 			if (crp->crp_seq == ret_worker->reorder_cur_seq)
1834 				wake = true;
1835 		}
1836 		else {
1837 			if (CRYPTO_RETW_EMPTY(ret_worker))
1838 				wake = true;
1839 
1840 			TAILQ_INSERT_TAIL(&ret_worker->crp_ret_q, crp, crp_next);
1841 		}
1842 
1843 		if (wake)
1844 			wakeup_one(&ret_worker->crp_ret_q);	/* shared wait channel */
1845 		CRYPTO_RETW_UNLOCK(ret_worker);
1846 	}
1847 }
1848 
1849 /*
1850  * Invoke the callback on behalf of the driver.
1851  */
1852 void
1853 crypto_kdone(struct cryptkop *krp)
1854 {
1855 	struct crypto_ret_worker *ret_worker;
1856 	struct cryptocap *cap;
1857 
1858 	if (krp->krp_status != 0)
1859 		cryptostats.cs_kerrs++;
1860 	CRYPTO_DRIVER_LOCK();
1861 	cap = krp->krp_cap;
1862 	KASSERT(cap->cc_koperations > 0, ("cc_koperations == 0"));
1863 	cap->cc_koperations--;
1864 	if (cap->cc_koperations == 0 && cap->cc_flags & CRYPTOCAP_F_CLEANUP)
1865 		wakeup(cap);
1866 	CRYPTO_DRIVER_UNLOCK();
1867 	krp->krp_cap = NULL;
1868 	cap_rele(cap);
1869 
1870 	ret_worker = CRYPTO_RETW(0);
1871 
1872 	CRYPTO_RETW_LOCK(ret_worker);
1873 	if (CRYPTO_RETW_EMPTY(ret_worker))
1874 		wakeup_one(&ret_worker->crp_ret_q);		/* shared wait channel */
1875 	TAILQ_INSERT_TAIL(&ret_worker->crp_ret_kq, krp, krp_next);
1876 	CRYPTO_RETW_UNLOCK(ret_worker);
1877 }
1878 
1879 int
1880 crypto_getfeat(int *featp)
1881 {
1882 	int hid, kalg, feat = 0;
1883 
1884 	CRYPTO_DRIVER_LOCK();
1885 	for (hid = 0; hid < crypto_drivers_size; hid++) {
1886 		const struct cryptocap *cap = crypto_drivers[hid];
1887 
1888 		if (cap == NULL ||
1889 		    ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
1890 		    !crypto_devallowsoft)) {
1891 			continue;
1892 		}
1893 		for (kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
1894 			if (cap->cc_kalg[kalg] & CRYPTO_ALG_FLAG_SUPPORTED)
1895 				feat |=  1 << kalg;
1896 	}
1897 	CRYPTO_DRIVER_UNLOCK();
1898 	*featp = feat;
1899 	return (0);
1900 }
1901 
1902 /*
1903  * Terminate a thread at module unload.  The process that
1904  * initiated this is waiting for us to signal that we're gone;
1905  * wake it up and exit.  We use the driver table lock to insure
1906  * we don't do the wakeup before they're waiting.  There is no
1907  * race here because the waiter sleeps on the proc lock for the
1908  * thread so it gets notified at the right time because of an
1909  * extra wakeup that's done in exit1().
1910  */
1911 static void
1912 crypto_finis(void *chan)
1913 {
1914 	CRYPTO_DRIVER_LOCK();
1915 	wakeup_one(chan);
1916 	CRYPTO_DRIVER_UNLOCK();
1917 	kproc_exit(0);
1918 }
1919 
1920 /*
1921  * Crypto thread, dispatches crypto requests.
1922  */
1923 static void
1924 crypto_proc(void)
1925 {
1926 	struct cryptop *crp, *submit;
1927 	struct cryptkop *krp;
1928 	struct cryptocap *cap;
1929 	int result, hint;
1930 
1931 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
1932 	fpu_kern_thread(FPU_KERN_NORMAL);
1933 #endif
1934 
1935 	CRYPTO_Q_LOCK();
1936 	for (;;) {
1937 		/*
1938 		 * Find the first element in the queue that can be
1939 		 * processed and look-ahead to see if multiple ops
1940 		 * are ready for the same driver.
1941 		 */
1942 		submit = NULL;
1943 		hint = 0;
1944 		TAILQ_FOREACH(crp, &crp_q, crp_next) {
1945 			cap = crp->crp_session->cap;
1946 			/*
1947 			 * Driver cannot disappeared when there is an active
1948 			 * session.
1949 			 */
1950 			KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1951 			    __func__, __LINE__));
1952 			if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1953 				/* Op needs to be migrated, process it. */
1954 				if (submit == NULL)
1955 					submit = crp;
1956 				break;
1957 			}
1958 			if (!cap->cc_qblocked) {
1959 				if (submit != NULL) {
1960 					/*
1961 					 * We stop on finding another op,
1962 					 * regardless whether its for the same
1963 					 * driver or not.  We could keep
1964 					 * searching the queue but it might be
1965 					 * better to just use a per-driver
1966 					 * queue instead.
1967 					 */
1968 					if (submit->crp_session->cap == cap)
1969 						hint = CRYPTO_HINT_MORE;
1970 					break;
1971 				} else {
1972 					submit = crp;
1973 					if ((submit->crp_flags & CRYPTO_F_BATCH) == 0)
1974 						break;
1975 					/* keep scanning for more are q'd */
1976 				}
1977 			}
1978 		}
1979 		if (submit != NULL) {
1980 			TAILQ_REMOVE(&crp_q, submit, crp_next);
1981 			cap = submit->crp_session->cap;
1982 			KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1983 			    __func__, __LINE__));
1984 			CRYPTO_Q_UNLOCK();
1985 			result = crypto_invoke(cap, submit, hint);
1986 			CRYPTO_Q_LOCK();
1987 			if (result == ERESTART) {
1988 				/*
1989 				 * The driver ran out of resources, mark the
1990 				 * driver ``blocked'' for cryptop's and put
1991 				 * the request back in the queue.  It would
1992 				 * best to put the request back where we got
1993 				 * it but that's hard so for now we put it
1994 				 * at the front.  This should be ok; putting
1995 				 * it at the end does not work.
1996 				 */
1997 				cap->cc_qblocked = 1;
1998 				TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
1999 				cryptostats.cs_blocks++;
2000 			}
2001 		}
2002 
2003 		/* As above, but for key ops */
2004 		TAILQ_FOREACH(krp, &crp_kq, krp_next) {
2005 			cap = krp->krp_cap;
2006 			if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
2007 				/*
2008 				 * Operation needs to be migrated,
2009 				 * clear krp_cap so a new driver is
2010 				 * selected.
2011 				 */
2012 				krp->krp_cap = NULL;
2013 				cap_rele(cap);
2014 				break;
2015 			}
2016 			if (!cap->cc_kqblocked)
2017 				break;
2018 		}
2019 		if (krp != NULL) {
2020 			TAILQ_REMOVE(&crp_kq, krp, krp_next);
2021 			CRYPTO_Q_UNLOCK();
2022 			result = crypto_kinvoke(krp);
2023 			CRYPTO_Q_LOCK();
2024 			if (result == ERESTART) {
2025 				/*
2026 				 * The driver ran out of resources, mark the
2027 				 * driver ``blocked'' for cryptkop's and put
2028 				 * the request back in the queue.  It would
2029 				 * best to put the request back where we got
2030 				 * it but that's hard so for now we put it
2031 				 * at the front.  This should be ok; putting
2032 				 * it at the end does not work.
2033 				 */
2034 				krp->krp_cap->cc_kqblocked = 1;
2035 				TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
2036 				cryptostats.cs_kblocks++;
2037 			}
2038 		}
2039 
2040 		if (submit == NULL && krp == NULL) {
2041 			/*
2042 			 * Nothing more to be processed.  Sleep until we're
2043 			 * woken because there are more ops to process.
2044 			 * This happens either by submission or by a driver
2045 			 * becoming unblocked and notifying us through
2046 			 * crypto_unblock.  Note that when we wakeup we
2047 			 * start processing each queue again from the
2048 			 * front. It's not clear that it's important to
2049 			 * preserve this ordering since ops may finish
2050 			 * out of order if dispatched to different devices
2051 			 * and some become blocked while others do not.
2052 			 */
2053 			crp_sleep = 1;
2054 			msleep(&crp_q, &crypto_q_mtx, PWAIT, "crypto_wait", 0);
2055 			crp_sleep = 0;
2056 			if (cryptoproc == NULL)
2057 				break;
2058 			cryptostats.cs_intrs++;
2059 		}
2060 	}
2061 	CRYPTO_Q_UNLOCK();
2062 
2063 	crypto_finis(&crp_q);
2064 }
2065 
2066 /*
2067  * Crypto returns thread, does callbacks for processed crypto requests.
2068  * Callbacks are done here, rather than in the crypto drivers, because
2069  * callbacks typically are expensive and would slow interrupt handling.
2070  */
2071 static void
2072 crypto_ret_proc(struct crypto_ret_worker *ret_worker)
2073 {
2074 	struct cryptop *crpt;
2075 	struct cryptkop *krpt;
2076 
2077 	CRYPTO_RETW_LOCK(ret_worker);
2078 	for (;;) {
2079 		/* Harvest return q's for completed ops */
2080 		crpt = TAILQ_FIRST(&ret_worker->crp_ordered_ret_q);
2081 		if (crpt != NULL) {
2082 			if (crpt->crp_seq == ret_worker->reorder_cur_seq) {
2083 				TAILQ_REMOVE(&ret_worker->crp_ordered_ret_q, crpt, crp_next);
2084 				ret_worker->reorder_cur_seq++;
2085 			} else {
2086 				crpt = NULL;
2087 			}
2088 		}
2089 
2090 		if (crpt == NULL) {
2091 			crpt = TAILQ_FIRST(&ret_worker->crp_ret_q);
2092 			if (crpt != NULL)
2093 				TAILQ_REMOVE(&ret_worker->crp_ret_q, crpt, crp_next);
2094 		}
2095 
2096 		krpt = TAILQ_FIRST(&ret_worker->crp_ret_kq);
2097 		if (krpt != NULL)
2098 			TAILQ_REMOVE(&ret_worker->crp_ret_kq, krpt, krp_next);
2099 
2100 		if (crpt != NULL || krpt != NULL) {
2101 			CRYPTO_RETW_UNLOCK(ret_worker);
2102 			/*
2103 			 * Run callbacks unlocked.
2104 			 */
2105 			if (crpt != NULL) {
2106 #ifdef CRYPTO_TIMING
2107 				if (crypto_timing) {
2108 					/*
2109 					 * NB: We must copy the timestamp before
2110 					 * doing the callback as the cryptop is
2111 					 * likely to be reclaimed.
2112 					 */
2113 					struct bintime t = crpt->crp_tstamp;
2114 					crypto_tstat(&cryptostats.cs_cb, &t);
2115 					crpt->crp_callback(crpt);
2116 					crypto_tstat(&cryptostats.cs_finis, &t);
2117 				} else
2118 #endif
2119 					crpt->crp_callback(crpt);
2120 			}
2121 			if (krpt != NULL)
2122 				krpt->krp_callback(krpt);
2123 			CRYPTO_RETW_LOCK(ret_worker);
2124 		} else {
2125 			/*
2126 			 * Nothing more to be processed.  Sleep until we're
2127 			 * woken because there are more returns to process.
2128 			 */
2129 			msleep(&ret_worker->crp_ret_q, &ret_worker->crypto_ret_mtx, PWAIT,
2130 				"crypto_ret_wait", 0);
2131 			if (ret_worker->cryptoretproc == NULL)
2132 				break;
2133 			cryptostats.cs_rets++;
2134 		}
2135 	}
2136 	CRYPTO_RETW_UNLOCK(ret_worker);
2137 
2138 	crypto_finis(&ret_worker->crp_ret_q);
2139 }
2140 
2141 #ifdef DDB
2142 static void
2143 db_show_drivers(void)
2144 {
2145 	int hid;
2146 
2147 	db_printf("%12s %4s %4s %8s %2s %2s\n"
2148 		, "Device"
2149 		, "Ses"
2150 		, "Kops"
2151 		, "Flags"
2152 		, "QB"
2153 		, "KB"
2154 	);
2155 	for (hid = 0; hid < crypto_drivers_size; hid++) {
2156 		const struct cryptocap *cap = crypto_drivers[hid];
2157 		if (cap == NULL)
2158 			continue;
2159 		db_printf("%-12s %4u %4u %08x %2u %2u\n"
2160 		    , device_get_nameunit(cap->cc_dev)
2161 		    , cap->cc_sessions
2162 		    , cap->cc_koperations
2163 		    , cap->cc_flags
2164 		    , cap->cc_qblocked
2165 		    , cap->cc_kqblocked
2166 		);
2167 	}
2168 }
2169 
2170 DB_SHOW_COMMAND(crypto, db_show_crypto)
2171 {
2172 	struct cryptop *crp;
2173 	struct crypto_ret_worker *ret_worker;
2174 
2175 	db_show_drivers();
2176 	db_printf("\n");
2177 
2178 	db_printf("%4s %8s %4s %4s %4s %4s %8s %8s\n",
2179 	    "HID", "Caps", "Ilen", "Olen", "Etype", "Flags",
2180 	    "Device", "Callback");
2181 	TAILQ_FOREACH(crp, &crp_q, crp_next) {
2182 		db_printf("%4u %08x %4u %4u %4u %04x %8p %8p\n"
2183 		    , crp->crp_session->cap->cc_hid
2184 		    , (int) crypto_ses2caps(crp->crp_session)
2185 		    , crp->crp_ilen, crp->crp_olen
2186 		    , crp->crp_etype
2187 		    , crp->crp_flags
2188 		    , device_get_nameunit(crp->crp_session->cap->cc_dev)
2189 		    , crp->crp_callback
2190 		);
2191 	}
2192 	FOREACH_CRYPTO_RETW(ret_worker) {
2193 		db_printf("\n%8s %4s %4s %4s %8s\n",
2194 		    "ret_worker", "HID", "Etype", "Flags", "Callback");
2195 		if (!TAILQ_EMPTY(&ret_worker->crp_ret_q)) {
2196 			TAILQ_FOREACH(crp, &ret_worker->crp_ret_q, crp_next) {
2197 				db_printf("%8td %4u %4u %04x %8p\n"
2198 				    , CRYPTO_RETW_ID(ret_worker)
2199 				    , crp->crp_session->cap->cc_hid
2200 				    , crp->crp_etype
2201 				    , crp->crp_flags
2202 				    , crp->crp_callback
2203 				);
2204 			}
2205 		}
2206 	}
2207 }
2208 
2209 DB_SHOW_COMMAND(kcrypto, db_show_kcrypto)
2210 {
2211 	struct cryptkop *krp;
2212 	struct crypto_ret_worker *ret_worker;
2213 
2214 	db_show_drivers();
2215 	db_printf("\n");
2216 
2217 	db_printf("%4s %5s %4s %4s %8s %4s %8s\n",
2218 	    "Op", "Status", "#IP", "#OP", "CRID", "HID", "Callback");
2219 	TAILQ_FOREACH(krp, &crp_kq, krp_next) {
2220 		db_printf("%4u %5u %4u %4u %08x %4u %8p\n"
2221 		    , krp->krp_op
2222 		    , krp->krp_status
2223 		    , krp->krp_iparams, krp->krp_oparams
2224 		    , krp->krp_crid, krp->krp_hid
2225 		    , krp->krp_callback
2226 		);
2227 	}
2228 
2229 	ret_worker = CRYPTO_RETW(0);
2230 	if (!TAILQ_EMPTY(&ret_worker->crp_ret_q)) {
2231 		db_printf("%4s %5s %8s %4s %8s\n",
2232 		    "Op", "Status", "CRID", "HID", "Callback");
2233 		TAILQ_FOREACH(krp, &ret_worker->crp_ret_kq, krp_next) {
2234 			db_printf("%4u %5u %08x %4u %8p\n"
2235 			    , krp->krp_op
2236 			    , krp->krp_status
2237 			    , krp->krp_crid, krp->krp_hid
2238 			    , krp->krp_callback
2239 			);
2240 		}
2241 	}
2242 }
2243 #endif
2244 
2245 int crypto_modevent(module_t mod, int type, void *unused);
2246 
2247 /*
2248  * Initialization code, both for static and dynamic loading.
2249  * Note this is not invoked with the usual MODULE_DECLARE
2250  * mechanism but instead is listed as a dependency by the
2251  * cryptosoft driver.  This guarantees proper ordering of
2252  * calls on module load/unload.
2253  */
2254 int
2255 crypto_modevent(module_t mod, int type, void *unused)
2256 {
2257 	int error = EINVAL;
2258 
2259 	switch (type) {
2260 	case MOD_LOAD:
2261 		error = crypto_init();
2262 		if (error == 0 && bootverbose)
2263 			printf("crypto: <crypto core>\n");
2264 		break;
2265 	case MOD_UNLOAD:
2266 		/*XXX disallow if active sessions */
2267 		error = 0;
2268 		crypto_destroy();
2269 		return 0;
2270 	}
2271 	return error;
2272 }
2273 MODULE_VERSION(crypto, 1);
2274 MODULE_DEPEND(crypto, zlib, 1, 1, 1);
2275