xref: /freebsd/sys/opencrypto/crypto.c (revision 58101517cb3be0c47dba3696327e15f627765f02)
1 /*-
2  * Copyright (c) 2002-2006 Sam Leffler.  All rights reserved.
3  * Copyright (c) 2021 The FreeBSD Foundation
4  *
5  * Portions of this software were developed by Ararat River
6  * Consulting, LLC under sponsorship of the FreeBSD Foundation.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 /*
33  * Cryptographic Subsystem.
34  *
35  * This code is derived from the Openbsd Cryptographic Framework (OCF)
36  * that has the copyright shown below.  Very little of the original
37  * code remains.
38  */
39 
40 /*-
41  * The author of this code is Angelos D. Keromytis (angelos@cis.upenn.edu)
42  *
43  * This code was written by Angelos D. Keromytis in Athens, Greece, in
44  * February 2000. Network Security Technologies Inc. (NSTI) kindly
45  * supported the development of this code.
46  *
47  * Copyright (c) 2000, 2001 Angelos D. Keromytis
48  *
49  * Permission to use, copy, and modify this software with or without fee
50  * is hereby granted, provided that this entire notice is included in
51  * all source code copies of any software which is or includes a copy or
52  * modification of this software.
53  *
54  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
55  * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
56  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
57  * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
58  * PURPOSE.
59  */
60 
61 #include "opt_compat.h"
62 #include "opt_ddb.h"
63 
64 #include <sys/param.h>
65 #include <sys/systm.h>
66 #include <sys/counter.h>
67 #include <sys/kernel.h>
68 #include <sys/kthread.h>
69 #include <sys/linker.h>
70 #include <sys/lock.h>
71 #include <sys/module.h>
72 #include <sys/mutex.h>
73 #include <sys/malloc.h>
74 #include <sys/mbuf.h>
75 #include <sys/proc.h>
76 #include <sys/refcount.h>
77 #include <sys/sdt.h>
78 #include <sys/smp.h>
79 #include <sys/sysctl.h>
80 #include <sys/taskqueue.h>
81 #include <sys/uio.h>
82 
83 #include <ddb/ddb.h>
84 
85 #include <machine/vmparam.h>
86 #include <vm/uma.h>
87 
88 #include <crypto/intake.h>
89 #include <opencrypto/cryptodev.h>
90 #include <opencrypto/xform_auth.h>
91 #include <opencrypto/xform_enc.h>
92 
93 #include <sys/kobj.h>
94 #include <sys/bus.h>
95 #include "cryptodev_if.h"
96 
97 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
98 #include <machine/pcb.h>
99 #endif
100 
101 SDT_PROVIDER_DEFINE(opencrypto);
102 
103 /*
104  * Crypto drivers register themselves by allocating a slot in the
105  * crypto_drivers table with crypto_get_driverid().
106  */
107 static	struct mtx crypto_drivers_mtx;		/* lock on driver table */
108 #define	CRYPTO_DRIVER_LOCK()	mtx_lock(&crypto_drivers_mtx)
109 #define	CRYPTO_DRIVER_UNLOCK()	mtx_unlock(&crypto_drivers_mtx)
110 #define	CRYPTO_DRIVER_ASSERT()	mtx_assert(&crypto_drivers_mtx, MA_OWNED)
111 
112 /*
113  * Crypto device/driver capabilities structure.
114  *
115  * Synchronization:
116  * (d) - protected by CRYPTO_DRIVER_LOCK()
117  * (q) - protected by CRYPTO_Q_LOCK()
118  * Not tagged fields are read-only.
119  */
120 struct cryptocap {
121 	device_t	cc_dev;
122 	uint32_t	cc_hid;
123 	uint32_t	cc_sessions;		/* (d) # of sessions */
124 
125 	int		cc_flags;		/* (d) flags */
126 #define CRYPTOCAP_F_CLEANUP	0x80000000	/* needs resource cleanup */
127 	int		cc_qblocked;		/* (q) symmetric q blocked */
128 	size_t		cc_session_size;
129 	volatile int	cc_refs;
130 };
131 
132 static	struct cryptocap **crypto_drivers = NULL;
133 static	int crypto_drivers_size = 0;
134 
135 struct crypto_session {
136 	struct cryptocap *cap;
137 	struct crypto_session_params csp;
138 	uint64_t id;
139 	/* Driver softc follows. */
140 };
141 
142 static	int crp_sleep = 0;
143 static	TAILQ_HEAD(cryptop_q ,cryptop) crp_q;		/* request queues */
144 static	struct mtx crypto_q_mtx;
145 #define	CRYPTO_Q_LOCK()		mtx_lock(&crypto_q_mtx)
146 #define	CRYPTO_Q_UNLOCK()	mtx_unlock(&crypto_q_mtx)
147 
148 SYSCTL_NODE(_kern, OID_AUTO, crypto, CTLFLAG_RW, 0,
149     "In-kernel cryptography");
150 
151 /*
152  * Taskqueue used to dispatch the crypto requests
153  * that have the CRYPTO_F_ASYNC flag
154  */
155 static struct taskqueue *crypto_tq;
156 
157 /*
158  * Crypto seq numbers are operated on with modular arithmetic
159  */
160 #define	CRYPTO_SEQ_GT(a,b)	((int)((a)-(b)) > 0)
161 
162 struct crypto_ret_worker {
163 	struct mtx crypto_ret_mtx;
164 
165 	TAILQ_HEAD(,cryptop) crp_ordered_ret_q;	/* ordered callback queue for symetric jobs */
166 	TAILQ_HEAD(,cryptop) crp_ret_q;		/* callback queue for symetric jobs */
167 
168 	uint32_t reorder_ops;		/* total ordered sym jobs received */
169 	uint32_t reorder_cur_seq;	/* current sym job dispatched */
170 
171 	struct thread *td;
172 };
173 static struct crypto_ret_worker *crypto_ret_workers = NULL;
174 
175 #define CRYPTO_RETW(i)		(&crypto_ret_workers[i])
176 #define CRYPTO_RETW_ID(w)	((w) - crypto_ret_workers)
177 #define FOREACH_CRYPTO_RETW(w) \
178 	for (w = crypto_ret_workers; w < crypto_ret_workers + crypto_workers_num; ++w)
179 
180 #define	CRYPTO_RETW_LOCK(w)	mtx_lock(&w->crypto_ret_mtx)
181 #define	CRYPTO_RETW_UNLOCK(w)	mtx_unlock(&w->crypto_ret_mtx)
182 
183 static int crypto_workers_num = 0;
184 SYSCTL_INT(_kern_crypto, OID_AUTO, num_workers, CTLFLAG_RDTUN,
185 	   &crypto_workers_num, 0,
186 	   "Number of crypto workers used to dispatch crypto jobs");
187 #ifdef COMPAT_FREEBSD12
188 SYSCTL_INT(_kern, OID_AUTO, crypto_workers_num, CTLFLAG_RDTUN,
189 	   &crypto_workers_num, 0,
190 	   "Number of crypto workers used to dispatch crypto jobs");
191 #endif
192 
193 static	uma_zone_t cryptop_zone;
194 
195 int	crypto_devallowsoft = 0;
196 SYSCTL_INT(_kern_crypto, OID_AUTO, allow_soft, CTLFLAG_RWTUN,
197 	   &crypto_devallowsoft, 0,
198 	   "Enable use of software crypto by /dev/crypto");
199 #ifdef COMPAT_FREEBSD12
200 SYSCTL_INT(_kern, OID_AUTO, cryptodevallowsoft, CTLFLAG_RWTUN,
201 	   &crypto_devallowsoft, 0,
202 	   "Enable/disable use of software crypto by /dev/crypto");
203 #endif
204 
205 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
206 
207 static	void crypto_dispatch_thread(void *arg);
208 static	struct thread *cryptotd;
209 static	void crypto_ret_thread(void *arg);
210 static	void crypto_destroy(void);
211 static	int crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint);
212 static	void crypto_task_invoke(void *ctx, int pending);
213 static void crypto_batch_enqueue(struct cryptop *crp);
214 
215 static counter_u64_t cryptostats[sizeof(struct cryptostats) / sizeof(uint64_t)];
216 SYSCTL_COUNTER_U64_ARRAY(_kern_crypto, OID_AUTO, stats, CTLFLAG_RW,
217     cryptostats, nitems(cryptostats),
218     "Crypto system statistics");
219 
220 #define	CRYPTOSTAT_INC(stat) do {					\
221 	counter_u64_add(						\
222 	    cryptostats[offsetof(struct cryptostats, stat) / sizeof(uint64_t)],\
223 	    1);								\
224 } while (0)
225 
226 static void
227 cryptostats_init(void *arg __unused)
228 {
229 	COUNTER_ARRAY_ALLOC(cryptostats, nitems(cryptostats), M_WAITOK);
230 }
231 SYSINIT(cryptostats_init, SI_SUB_COUNTER, SI_ORDER_ANY, cryptostats_init, NULL);
232 
233 static void
234 cryptostats_fini(void *arg __unused)
235 {
236 	COUNTER_ARRAY_FREE(cryptostats, nitems(cryptostats));
237 }
238 SYSUNINIT(cryptostats_fini, SI_SUB_COUNTER, SI_ORDER_ANY, cryptostats_fini,
239     NULL);
240 
241 /* Try to avoid directly exposing the key buffer as a symbol */
242 static struct keybuf *keybuf;
243 
244 static struct keybuf empty_keybuf = {
245         .kb_nents = 0
246 };
247 
248 /* Obtain the key buffer from boot metadata */
249 static void
250 keybuf_init(void)
251 {
252 	caddr_t kmdp;
253 
254 	kmdp = preload_search_by_type("elf kernel");
255 
256 	if (kmdp == NULL)
257 		kmdp = preload_search_by_type("elf64 kernel");
258 
259 	keybuf = (struct keybuf *)preload_search_info(kmdp,
260 	    MODINFO_METADATA | MODINFOMD_KEYBUF);
261 
262         if (keybuf == NULL)
263                 keybuf = &empty_keybuf;
264 }
265 
266 /* It'd be nice if we could store these in some kind of secure memory... */
267 struct keybuf *
268 get_keybuf(void)
269 {
270 
271         return (keybuf);
272 }
273 
274 static struct cryptocap *
275 cap_ref(struct cryptocap *cap)
276 {
277 
278 	refcount_acquire(&cap->cc_refs);
279 	return (cap);
280 }
281 
282 static void
283 cap_rele(struct cryptocap *cap)
284 {
285 
286 	if (refcount_release(&cap->cc_refs) == 0)
287 		return;
288 
289 	KASSERT(cap->cc_sessions == 0,
290 	    ("freeing crypto driver with active sessions"));
291 
292 	free(cap, M_CRYPTO_DATA);
293 }
294 
295 static int
296 crypto_init(void)
297 {
298 	struct crypto_ret_worker *ret_worker;
299 	struct proc *p;
300 	int error;
301 
302 	mtx_init(&crypto_drivers_mtx, "crypto driver table", NULL, MTX_DEF);
303 
304 	TAILQ_INIT(&crp_q);
305 	mtx_init(&crypto_q_mtx, "crypto op queues", NULL, MTX_DEF);
306 
307 	cryptop_zone = uma_zcreate("cryptop",
308 	    sizeof(struct cryptop), NULL, NULL, NULL, NULL,
309 	    UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
310 
311 	crypto_drivers_size = CRYPTO_DRIVERS_INITIAL;
312 	crypto_drivers = malloc(crypto_drivers_size *
313 	    sizeof(struct cryptocap), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
314 
315 	if (crypto_workers_num < 1 || crypto_workers_num > mp_ncpus)
316 		crypto_workers_num = mp_ncpus;
317 
318 	crypto_tq = taskqueue_create("crypto", M_WAITOK | M_ZERO,
319 	    taskqueue_thread_enqueue, &crypto_tq);
320 
321 	taskqueue_start_threads(&crypto_tq, crypto_workers_num, PRI_MIN_KERN,
322 	    "crypto");
323 
324 	p = NULL;
325 	error = kproc_kthread_add(crypto_dispatch_thread, NULL, &p, &cryptotd,
326 	    0, 0, "crypto", "crypto");
327 	if (error) {
328 		printf("crypto_init: cannot start crypto thread; error %d",
329 			error);
330 		goto bad;
331 	}
332 
333 	crypto_ret_workers = mallocarray(crypto_workers_num,
334 	    sizeof(struct crypto_ret_worker), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
335 
336 	FOREACH_CRYPTO_RETW(ret_worker) {
337 		TAILQ_INIT(&ret_worker->crp_ordered_ret_q);
338 		TAILQ_INIT(&ret_worker->crp_ret_q);
339 
340 		ret_worker->reorder_ops = 0;
341 		ret_worker->reorder_cur_seq = 0;
342 
343 		mtx_init(&ret_worker->crypto_ret_mtx, "crypto return queues",
344 		    NULL, MTX_DEF);
345 
346 		error = kthread_add(crypto_ret_thread, ret_worker, p,
347 		    &ret_worker->td, 0, 0, "crypto returns %td",
348 		    CRYPTO_RETW_ID(ret_worker));
349 		if (error) {
350 			printf("crypto_init: cannot start cryptoret thread; error %d",
351 				error);
352 			goto bad;
353 		}
354 	}
355 
356 	keybuf_init();
357 
358 	return 0;
359 bad:
360 	crypto_destroy();
361 	return error;
362 }
363 
364 /*
365  * Signal a crypto thread to terminate.  We use the driver
366  * table lock to synchronize the sleep/wakeups so that we
367  * are sure the threads have terminated before we release
368  * the data structures they use.  See crypto_finis below
369  * for the other half of this song-and-dance.
370  */
371 static void
372 crypto_terminate(struct thread **tdp, void *q)
373 {
374 	struct thread *td;
375 
376 	mtx_assert(&crypto_drivers_mtx, MA_OWNED);
377 	td = *tdp;
378 	*tdp = NULL;
379 	if (td != NULL) {
380 		wakeup_one(q);
381 		mtx_sleep(td, &crypto_drivers_mtx, PWAIT, "crypto_destroy", 0);
382 	}
383 }
384 
385 static void
386 hmac_init_pad(const struct auth_hash *axf, const char *key, int klen,
387     void *auth_ctx, uint8_t padval)
388 {
389 	uint8_t hmac_key[HMAC_MAX_BLOCK_LEN];
390 	u_int i;
391 
392 	KASSERT(axf->blocksize <= sizeof(hmac_key),
393 	    ("Invalid HMAC block size %d", axf->blocksize));
394 
395 	/*
396 	 * If the key is larger than the block size, use the digest of
397 	 * the key as the key instead.
398 	 */
399 	memset(hmac_key, 0, sizeof(hmac_key));
400 	if (klen > axf->blocksize) {
401 		axf->Init(auth_ctx);
402 		axf->Update(auth_ctx, key, klen);
403 		axf->Final(hmac_key, auth_ctx);
404 		klen = axf->hashsize;
405 	} else
406 		memcpy(hmac_key, key, klen);
407 
408 	for (i = 0; i < axf->blocksize; i++)
409 		hmac_key[i] ^= padval;
410 
411 	axf->Init(auth_ctx);
412 	axf->Update(auth_ctx, hmac_key, axf->blocksize);
413 	explicit_bzero(hmac_key, sizeof(hmac_key));
414 }
415 
416 void
417 hmac_init_ipad(const struct auth_hash *axf, const char *key, int klen,
418     void *auth_ctx)
419 {
420 
421 	hmac_init_pad(axf, key, klen, auth_ctx, HMAC_IPAD_VAL);
422 }
423 
424 void
425 hmac_init_opad(const struct auth_hash *axf, const char *key, int klen,
426     void *auth_ctx)
427 {
428 
429 	hmac_init_pad(axf, key, klen, auth_ctx, HMAC_OPAD_VAL);
430 }
431 
432 static void
433 crypto_destroy(void)
434 {
435 	struct crypto_ret_worker *ret_worker;
436 	int i;
437 
438 	/*
439 	 * Terminate any crypto threads.
440 	 */
441 	if (crypto_tq != NULL)
442 		taskqueue_drain_all(crypto_tq);
443 	CRYPTO_DRIVER_LOCK();
444 	crypto_terminate(&cryptotd, &crp_q);
445 	FOREACH_CRYPTO_RETW(ret_worker)
446 		crypto_terminate(&ret_worker->td, &ret_worker->crp_ret_q);
447 	CRYPTO_DRIVER_UNLOCK();
448 
449 	/* XXX flush queues??? */
450 
451 	/*
452 	 * Reclaim dynamically allocated resources.
453 	 */
454 	for (i = 0; i < crypto_drivers_size; i++) {
455 		if (crypto_drivers[i] != NULL)
456 			cap_rele(crypto_drivers[i]);
457 	}
458 	free(crypto_drivers, M_CRYPTO_DATA);
459 
460 	if (cryptop_zone != NULL)
461 		uma_zdestroy(cryptop_zone);
462 	mtx_destroy(&crypto_q_mtx);
463 	FOREACH_CRYPTO_RETW(ret_worker)
464 		mtx_destroy(&ret_worker->crypto_ret_mtx);
465 	free(crypto_ret_workers, M_CRYPTO_DATA);
466 	if (crypto_tq != NULL)
467 		taskqueue_free(crypto_tq);
468 	mtx_destroy(&crypto_drivers_mtx);
469 }
470 
471 uint32_t
472 crypto_ses2hid(crypto_session_t crypto_session)
473 {
474 	return (crypto_session->cap->cc_hid);
475 }
476 
477 uint32_t
478 crypto_ses2caps(crypto_session_t crypto_session)
479 {
480 	return (crypto_session->cap->cc_flags & 0xff000000);
481 }
482 
483 void *
484 crypto_get_driver_session(crypto_session_t crypto_session)
485 {
486 	return (crypto_session + 1);
487 }
488 
489 const struct crypto_session_params *
490 crypto_get_params(crypto_session_t crypto_session)
491 {
492 	return (&crypto_session->csp);
493 }
494 
495 const struct auth_hash *
496 crypto_auth_hash(const struct crypto_session_params *csp)
497 {
498 
499 	switch (csp->csp_auth_alg) {
500 	case CRYPTO_SHA1_HMAC:
501 		return (&auth_hash_hmac_sha1);
502 	case CRYPTO_SHA2_224_HMAC:
503 		return (&auth_hash_hmac_sha2_224);
504 	case CRYPTO_SHA2_256_HMAC:
505 		return (&auth_hash_hmac_sha2_256);
506 	case CRYPTO_SHA2_384_HMAC:
507 		return (&auth_hash_hmac_sha2_384);
508 	case CRYPTO_SHA2_512_HMAC:
509 		return (&auth_hash_hmac_sha2_512);
510 	case CRYPTO_NULL_HMAC:
511 		return (&auth_hash_null);
512 	case CRYPTO_RIPEMD160_HMAC:
513 		return (&auth_hash_hmac_ripemd_160);
514 	case CRYPTO_RIPEMD160:
515 		return (&auth_hash_ripemd_160);
516 	case CRYPTO_SHA1:
517 		return (&auth_hash_sha1);
518 	case CRYPTO_SHA2_224:
519 		return (&auth_hash_sha2_224);
520 	case CRYPTO_SHA2_256:
521 		return (&auth_hash_sha2_256);
522 	case CRYPTO_SHA2_384:
523 		return (&auth_hash_sha2_384);
524 	case CRYPTO_SHA2_512:
525 		return (&auth_hash_sha2_512);
526 	case CRYPTO_AES_NIST_GMAC:
527 		switch (csp->csp_auth_klen) {
528 		case 128 / 8:
529 			return (&auth_hash_nist_gmac_aes_128);
530 		case 192 / 8:
531 			return (&auth_hash_nist_gmac_aes_192);
532 		case 256 / 8:
533 			return (&auth_hash_nist_gmac_aes_256);
534 		default:
535 			return (NULL);
536 		}
537 	case CRYPTO_BLAKE2B:
538 		return (&auth_hash_blake2b);
539 	case CRYPTO_BLAKE2S:
540 		return (&auth_hash_blake2s);
541 	case CRYPTO_POLY1305:
542 		return (&auth_hash_poly1305);
543 	case CRYPTO_AES_CCM_CBC_MAC:
544 		switch (csp->csp_auth_klen) {
545 		case 128 / 8:
546 			return (&auth_hash_ccm_cbc_mac_128);
547 		case 192 / 8:
548 			return (&auth_hash_ccm_cbc_mac_192);
549 		case 256 / 8:
550 			return (&auth_hash_ccm_cbc_mac_256);
551 		default:
552 			return (NULL);
553 		}
554 	default:
555 		return (NULL);
556 	}
557 }
558 
559 const struct enc_xform *
560 crypto_cipher(const struct crypto_session_params *csp)
561 {
562 
563 	switch (csp->csp_cipher_alg) {
564 	case CRYPTO_AES_CBC:
565 		return (&enc_xform_aes_cbc);
566 	case CRYPTO_AES_XTS:
567 		return (&enc_xform_aes_xts);
568 	case CRYPTO_AES_ICM:
569 		return (&enc_xform_aes_icm);
570 	case CRYPTO_AES_NIST_GCM_16:
571 		return (&enc_xform_aes_nist_gcm);
572 	case CRYPTO_CAMELLIA_CBC:
573 		return (&enc_xform_camellia);
574 	case CRYPTO_NULL_CBC:
575 		return (&enc_xform_null);
576 	case CRYPTO_CHACHA20:
577 		return (&enc_xform_chacha20);
578 	case CRYPTO_AES_CCM_16:
579 		return (&enc_xform_ccm);
580 	case CRYPTO_CHACHA20_POLY1305:
581 		return (&enc_xform_chacha20_poly1305);
582 	default:
583 		return (NULL);
584 	}
585 }
586 
587 static struct cryptocap *
588 crypto_checkdriver(uint32_t hid)
589 {
590 
591 	return (hid >= crypto_drivers_size ? NULL : crypto_drivers[hid]);
592 }
593 
594 /*
595  * Select a driver for a new session that supports the specified
596  * algorithms and, optionally, is constrained according to the flags.
597  */
598 static struct cryptocap *
599 crypto_select_driver(const struct crypto_session_params *csp, int flags)
600 {
601 	struct cryptocap *cap, *best;
602 	int best_match, error, hid;
603 
604 	CRYPTO_DRIVER_ASSERT();
605 
606 	best = NULL;
607 	for (hid = 0; hid < crypto_drivers_size; hid++) {
608 		/*
609 		 * If there is no driver for this slot, or the driver
610 		 * is not appropriate (hardware or software based on
611 		 * match), then skip.
612 		 */
613 		cap = crypto_drivers[hid];
614 		if (cap == NULL ||
615 		    (cap->cc_flags & flags) == 0)
616 			continue;
617 
618 		error = CRYPTODEV_PROBESESSION(cap->cc_dev, csp);
619 		if (error >= 0)
620 			continue;
621 
622 		/*
623 		 * Use the driver with the highest probe value.
624 		 * Hardware drivers use a higher probe value than
625 		 * software.  In case of a tie, prefer the driver with
626 		 * the fewest active sessions.
627 		 */
628 		if (best == NULL || error > best_match ||
629 		    (error == best_match &&
630 		    cap->cc_sessions < best->cc_sessions)) {
631 			best = cap;
632 			best_match = error;
633 		}
634 	}
635 	return best;
636 }
637 
638 static enum alg_type {
639 	ALG_NONE = 0,
640 	ALG_CIPHER,
641 	ALG_DIGEST,
642 	ALG_KEYED_DIGEST,
643 	ALG_COMPRESSION,
644 	ALG_AEAD
645 } alg_types[] = {
646 	[CRYPTO_SHA1_HMAC] = ALG_KEYED_DIGEST,
647 	[CRYPTO_RIPEMD160_HMAC] = ALG_KEYED_DIGEST,
648 	[CRYPTO_AES_CBC] = ALG_CIPHER,
649 	[CRYPTO_SHA1] = ALG_DIGEST,
650 	[CRYPTO_NULL_HMAC] = ALG_DIGEST,
651 	[CRYPTO_NULL_CBC] = ALG_CIPHER,
652 	[CRYPTO_DEFLATE_COMP] = ALG_COMPRESSION,
653 	[CRYPTO_SHA2_256_HMAC] = ALG_KEYED_DIGEST,
654 	[CRYPTO_SHA2_384_HMAC] = ALG_KEYED_DIGEST,
655 	[CRYPTO_SHA2_512_HMAC] = ALG_KEYED_DIGEST,
656 	[CRYPTO_CAMELLIA_CBC] = ALG_CIPHER,
657 	[CRYPTO_AES_XTS] = ALG_CIPHER,
658 	[CRYPTO_AES_ICM] = ALG_CIPHER,
659 	[CRYPTO_AES_NIST_GMAC] = ALG_KEYED_DIGEST,
660 	[CRYPTO_AES_NIST_GCM_16] = ALG_AEAD,
661 	[CRYPTO_BLAKE2B] = ALG_KEYED_DIGEST,
662 	[CRYPTO_BLAKE2S] = ALG_KEYED_DIGEST,
663 	[CRYPTO_CHACHA20] = ALG_CIPHER,
664 	[CRYPTO_SHA2_224_HMAC] = ALG_KEYED_DIGEST,
665 	[CRYPTO_RIPEMD160] = ALG_DIGEST,
666 	[CRYPTO_SHA2_224] = ALG_DIGEST,
667 	[CRYPTO_SHA2_256] = ALG_DIGEST,
668 	[CRYPTO_SHA2_384] = ALG_DIGEST,
669 	[CRYPTO_SHA2_512] = ALG_DIGEST,
670 	[CRYPTO_POLY1305] = ALG_KEYED_DIGEST,
671 	[CRYPTO_AES_CCM_CBC_MAC] = ALG_KEYED_DIGEST,
672 	[CRYPTO_AES_CCM_16] = ALG_AEAD,
673 	[CRYPTO_CHACHA20_POLY1305] = ALG_AEAD,
674 };
675 
676 static enum alg_type
677 alg_type(int alg)
678 {
679 
680 	if (alg < nitems(alg_types))
681 		return (alg_types[alg]);
682 	return (ALG_NONE);
683 }
684 
685 static bool
686 alg_is_compression(int alg)
687 {
688 
689 	return (alg_type(alg) == ALG_COMPRESSION);
690 }
691 
692 static bool
693 alg_is_cipher(int alg)
694 {
695 
696 	return (alg_type(alg) == ALG_CIPHER);
697 }
698 
699 static bool
700 alg_is_digest(int alg)
701 {
702 
703 	return (alg_type(alg) == ALG_DIGEST ||
704 	    alg_type(alg) == ALG_KEYED_DIGEST);
705 }
706 
707 static bool
708 alg_is_keyed_digest(int alg)
709 {
710 
711 	return (alg_type(alg) == ALG_KEYED_DIGEST);
712 }
713 
714 static bool
715 alg_is_aead(int alg)
716 {
717 
718 	return (alg_type(alg) == ALG_AEAD);
719 }
720 
721 static bool
722 ccm_tag_length_valid(int len)
723 {
724 	/* RFC 3610 */
725 	switch (len) {
726 	case 4:
727 	case 6:
728 	case 8:
729 	case 10:
730 	case 12:
731 	case 14:
732 	case 16:
733 		return (true);
734 	default:
735 		return (false);
736 	}
737 }
738 
739 #define SUPPORTED_SES (CSP_F_SEPARATE_OUTPUT | CSP_F_SEPARATE_AAD | CSP_F_ESN)
740 
741 /* Various sanity checks on crypto session parameters. */
742 static bool
743 check_csp(const struct crypto_session_params *csp)
744 {
745 	const struct auth_hash *axf;
746 
747 	/* Mode-independent checks. */
748 	if ((csp->csp_flags & ~(SUPPORTED_SES)) != 0)
749 		return (false);
750 	if (csp->csp_ivlen < 0 || csp->csp_cipher_klen < 0 ||
751 	    csp->csp_auth_klen < 0 || csp->csp_auth_mlen < 0)
752 		return (false);
753 	if (csp->csp_auth_key != NULL && csp->csp_auth_klen == 0)
754 		return (false);
755 	if (csp->csp_cipher_key != NULL && csp->csp_cipher_klen == 0)
756 		return (false);
757 
758 	switch (csp->csp_mode) {
759 	case CSP_MODE_COMPRESS:
760 		if (!alg_is_compression(csp->csp_cipher_alg))
761 			return (false);
762 		if (csp->csp_flags & CSP_F_SEPARATE_OUTPUT)
763 			return (false);
764 		if (csp->csp_flags & CSP_F_SEPARATE_AAD)
765 			return (false);
766 		if (csp->csp_cipher_klen != 0 || csp->csp_ivlen != 0 ||
767 		    csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0 ||
768 		    csp->csp_auth_mlen != 0)
769 			return (false);
770 		break;
771 	case CSP_MODE_CIPHER:
772 		if (!alg_is_cipher(csp->csp_cipher_alg))
773 			return (false);
774 		if (csp->csp_flags & CSP_F_SEPARATE_AAD)
775 			return (false);
776 		if (csp->csp_cipher_alg != CRYPTO_NULL_CBC) {
777 			if (csp->csp_cipher_klen == 0)
778 				return (false);
779 			if (csp->csp_ivlen == 0)
780 				return (false);
781 		}
782 		if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
783 			return (false);
784 		if (csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0 ||
785 		    csp->csp_auth_mlen != 0)
786 			return (false);
787 		break;
788 	case CSP_MODE_DIGEST:
789 		if (csp->csp_cipher_alg != 0 || csp->csp_cipher_klen != 0)
790 			return (false);
791 
792 		if (csp->csp_flags & CSP_F_SEPARATE_AAD)
793 			return (false);
794 
795 		/* IV is optional for digests (e.g. GMAC). */
796 		switch (csp->csp_auth_alg) {
797 		case CRYPTO_AES_CCM_CBC_MAC:
798 			if (csp->csp_ivlen < 7 || csp->csp_ivlen > 13)
799 				return (false);
800 			break;
801 		case CRYPTO_AES_NIST_GMAC:
802 			if (csp->csp_ivlen != AES_GCM_IV_LEN)
803 				return (false);
804 			break;
805 		default:
806 			if (csp->csp_ivlen != 0)
807 				return (false);
808 			break;
809 		}
810 
811 		if (!alg_is_digest(csp->csp_auth_alg))
812 			return (false);
813 
814 		/* Key is optional for BLAKE2 digests. */
815 		if (csp->csp_auth_alg == CRYPTO_BLAKE2B ||
816 		    csp->csp_auth_alg == CRYPTO_BLAKE2S)
817 			;
818 		else if (alg_is_keyed_digest(csp->csp_auth_alg)) {
819 			if (csp->csp_auth_klen == 0)
820 				return (false);
821 		} else {
822 			if (csp->csp_auth_klen != 0)
823 				return (false);
824 		}
825 		if (csp->csp_auth_mlen != 0) {
826 			axf = crypto_auth_hash(csp);
827 			if (axf == NULL || csp->csp_auth_mlen > axf->hashsize)
828 				return (false);
829 
830 			if (csp->csp_auth_alg == CRYPTO_AES_CCM_CBC_MAC &&
831 			    !ccm_tag_length_valid(csp->csp_auth_mlen))
832 				return (false);
833 		}
834 		break;
835 	case CSP_MODE_AEAD:
836 		if (!alg_is_aead(csp->csp_cipher_alg))
837 			return (false);
838 		if (csp->csp_cipher_klen == 0)
839 			return (false);
840 		if (csp->csp_ivlen == 0 ||
841 		    csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
842 			return (false);
843 		if (csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0)
844 			return (false);
845 
846 		switch (csp->csp_cipher_alg) {
847 		case CRYPTO_AES_CCM_16:
848 			if (csp->csp_auth_mlen != 0 &&
849 			    !ccm_tag_length_valid(csp->csp_auth_mlen))
850 				return (false);
851 
852 			if (csp->csp_ivlen < 7 || csp->csp_ivlen > 13)
853 				return (false);
854 			break;
855 		case CRYPTO_AES_NIST_GCM_16:
856 			if (csp->csp_auth_mlen > AES_GMAC_HASH_LEN)
857 				return (false);
858 
859 			if (csp->csp_ivlen != AES_GCM_IV_LEN)
860 				return (false);
861 			break;
862 		case CRYPTO_CHACHA20_POLY1305:
863 			if (csp->csp_ivlen != 8 && csp->csp_ivlen != 12)
864 				return (false);
865 			if (csp->csp_auth_mlen > POLY1305_HASH_LEN)
866 				return (false);
867 			break;
868 		}
869 		break;
870 	case CSP_MODE_ETA:
871 		if (!alg_is_cipher(csp->csp_cipher_alg))
872 			return (false);
873 		if (csp->csp_cipher_alg != CRYPTO_NULL_CBC) {
874 			if (csp->csp_cipher_klen == 0)
875 				return (false);
876 			if (csp->csp_ivlen == 0)
877 				return (false);
878 		}
879 		if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
880 			return (false);
881 		if (!alg_is_digest(csp->csp_auth_alg))
882 			return (false);
883 
884 		/* Key is optional for BLAKE2 digests. */
885 		if (csp->csp_auth_alg == CRYPTO_BLAKE2B ||
886 		    csp->csp_auth_alg == CRYPTO_BLAKE2S)
887 			;
888 		else if (alg_is_keyed_digest(csp->csp_auth_alg)) {
889 			if (csp->csp_auth_klen == 0)
890 				return (false);
891 		} else {
892 			if (csp->csp_auth_klen != 0)
893 				return (false);
894 		}
895 		if (csp->csp_auth_mlen != 0) {
896 			axf = crypto_auth_hash(csp);
897 			if (axf == NULL || csp->csp_auth_mlen > axf->hashsize)
898 				return (false);
899 		}
900 		break;
901 	default:
902 		return (false);
903 	}
904 
905 	return (true);
906 }
907 
908 /*
909  * Delete a session after it has been detached from its driver.
910  */
911 static void
912 crypto_deletesession(crypto_session_t cses)
913 {
914 	struct cryptocap *cap;
915 
916 	cap = cses->cap;
917 
918 	zfree(cses, M_CRYPTO_DATA);
919 
920 	CRYPTO_DRIVER_LOCK();
921 	cap->cc_sessions--;
922 	if (cap->cc_sessions == 0 && cap->cc_flags & CRYPTOCAP_F_CLEANUP)
923 		wakeup(cap);
924 	CRYPTO_DRIVER_UNLOCK();
925 	cap_rele(cap);
926 }
927 
928 /*
929  * Create a new session.  The crid argument specifies a crypto
930  * driver to use or constraints on a driver to select (hardware
931  * only, software only, either).  Whatever driver is selected
932  * must be capable of the requested crypto algorithms.
933  */
934 int
935 crypto_newsession(crypto_session_t *cses,
936     const struct crypto_session_params *csp, int crid)
937 {
938 	static uint64_t sessid = 0;
939 	crypto_session_t res;
940 	struct cryptocap *cap;
941 	int err;
942 
943 	if (!check_csp(csp))
944 		return (EINVAL);
945 
946 	res = NULL;
947 
948 	CRYPTO_DRIVER_LOCK();
949 	if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
950 		/*
951 		 * Use specified driver; verify it is capable.
952 		 */
953 		cap = crypto_checkdriver(crid);
954 		if (cap != NULL && CRYPTODEV_PROBESESSION(cap->cc_dev, csp) > 0)
955 			cap = NULL;
956 	} else {
957 		/*
958 		 * No requested driver; select based on crid flags.
959 		 */
960 		cap = crypto_select_driver(csp, crid);
961 	}
962 	if (cap == NULL) {
963 		CRYPTO_DRIVER_UNLOCK();
964 		CRYPTDEB("no driver");
965 		return (EOPNOTSUPP);
966 	}
967 	cap_ref(cap);
968 	cap->cc_sessions++;
969 	CRYPTO_DRIVER_UNLOCK();
970 
971 	/* Allocate a single block for the generic session and driver softc. */
972 	res = malloc(sizeof(*res) + cap->cc_session_size, M_CRYPTO_DATA,
973 	    M_WAITOK | M_ZERO);
974 	res->cap = cap;
975 	res->csp = *csp;
976 	res->id = atomic_fetchadd_64(&sessid, 1);
977 
978 	/* Call the driver initialization routine. */
979 	err = CRYPTODEV_NEWSESSION(cap->cc_dev, res, csp);
980 	if (err != 0) {
981 		CRYPTDEB("dev newsession failed: %d", err);
982 		crypto_deletesession(res);
983 		return (err);
984 	}
985 
986 	*cses = res;
987 	return (0);
988 }
989 
990 /*
991  * Delete an existing session (or a reserved session on an unregistered
992  * driver).
993  */
994 void
995 crypto_freesession(crypto_session_t cses)
996 {
997 	struct cryptocap *cap;
998 
999 	if (cses == NULL)
1000 		return;
1001 
1002 	cap = cses->cap;
1003 
1004 	/* Call the driver cleanup routine, if available. */
1005 	CRYPTODEV_FREESESSION(cap->cc_dev, cses);
1006 
1007 	crypto_deletesession(cses);
1008 }
1009 
1010 /*
1011  * Return a new driver id.  Registers a driver with the system so that
1012  * it can be probed by subsequent sessions.
1013  */
1014 int32_t
1015 crypto_get_driverid(device_t dev, size_t sessionsize, int flags)
1016 {
1017 	struct cryptocap *cap, **newdrv;
1018 	int i;
1019 
1020 	if ((flags & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
1021 		device_printf(dev,
1022 		    "no flags specified when registering driver\n");
1023 		return -1;
1024 	}
1025 
1026 	cap = malloc(sizeof(*cap), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
1027 	cap->cc_dev = dev;
1028 	cap->cc_session_size = sessionsize;
1029 	cap->cc_flags = flags;
1030 	refcount_init(&cap->cc_refs, 1);
1031 
1032 	CRYPTO_DRIVER_LOCK();
1033 	for (;;) {
1034 		for (i = 0; i < crypto_drivers_size; i++) {
1035 			if (crypto_drivers[i] == NULL)
1036 				break;
1037 		}
1038 
1039 		if (i < crypto_drivers_size)
1040 			break;
1041 
1042 		/* Out of entries, allocate some more. */
1043 
1044 		if (2 * crypto_drivers_size <= crypto_drivers_size) {
1045 			CRYPTO_DRIVER_UNLOCK();
1046 			printf("crypto: driver count wraparound!\n");
1047 			cap_rele(cap);
1048 			return (-1);
1049 		}
1050 		CRYPTO_DRIVER_UNLOCK();
1051 
1052 		newdrv = malloc(2 * crypto_drivers_size *
1053 		    sizeof(*crypto_drivers), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
1054 
1055 		CRYPTO_DRIVER_LOCK();
1056 		memcpy(newdrv, crypto_drivers,
1057 		    crypto_drivers_size * sizeof(*crypto_drivers));
1058 
1059 		crypto_drivers_size *= 2;
1060 
1061 		free(crypto_drivers, M_CRYPTO_DATA);
1062 		crypto_drivers = newdrv;
1063 	}
1064 
1065 	cap->cc_hid = i;
1066 	crypto_drivers[i] = cap;
1067 	CRYPTO_DRIVER_UNLOCK();
1068 
1069 	if (bootverbose)
1070 		printf("crypto: assign %s driver id %u, flags 0x%x\n",
1071 		    device_get_nameunit(dev), i, flags);
1072 
1073 	return i;
1074 }
1075 
1076 /*
1077  * Lookup a driver by name.  We match against the full device
1078  * name and unit, and against just the name.  The latter gives
1079  * us a simple widlcarding by device name.  On success return the
1080  * driver/hardware identifier; otherwise return -1.
1081  */
1082 int
1083 crypto_find_driver(const char *match)
1084 {
1085 	struct cryptocap *cap;
1086 	int i, len = strlen(match);
1087 
1088 	CRYPTO_DRIVER_LOCK();
1089 	for (i = 0; i < crypto_drivers_size; i++) {
1090 		if (crypto_drivers[i] == NULL)
1091 			continue;
1092 		cap = crypto_drivers[i];
1093 		if (strncmp(match, device_get_nameunit(cap->cc_dev), len) == 0 ||
1094 		    strncmp(match, device_get_name(cap->cc_dev), len) == 0) {
1095 			CRYPTO_DRIVER_UNLOCK();
1096 			return (i);
1097 		}
1098 	}
1099 	CRYPTO_DRIVER_UNLOCK();
1100 	return (-1);
1101 }
1102 
1103 /*
1104  * Return the device_t for the specified driver or NULL
1105  * if the driver identifier is invalid.
1106  */
1107 device_t
1108 crypto_find_device_byhid(int hid)
1109 {
1110 	struct cryptocap *cap;
1111 	device_t dev;
1112 
1113 	dev = NULL;
1114 	CRYPTO_DRIVER_LOCK();
1115 	cap = crypto_checkdriver(hid);
1116 	if (cap != NULL)
1117 		dev = cap->cc_dev;
1118 	CRYPTO_DRIVER_UNLOCK();
1119 	return (dev);
1120 }
1121 
1122 /*
1123  * Return the device/driver capabilities.
1124  */
1125 int
1126 crypto_getcaps(int hid)
1127 {
1128 	struct cryptocap *cap;
1129 	int flags;
1130 
1131 	flags = 0;
1132 	CRYPTO_DRIVER_LOCK();
1133 	cap = crypto_checkdriver(hid);
1134 	if (cap != NULL)
1135 		flags = cap->cc_flags;
1136 	CRYPTO_DRIVER_UNLOCK();
1137 	return (flags);
1138 }
1139 
1140 /*
1141  * Unregister all algorithms associated with a crypto driver.
1142  * If there are pending sessions using it, leave enough information
1143  * around so that subsequent calls using those sessions will
1144  * correctly detect the driver has been unregistered and reroute
1145  * requests.
1146  */
1147 int
1148 crypto_unregister_all(uint32_t driverid)
1149 {
1150 	struct cryptocap *cap;
1151 
1152 	CRYPTO_DRIVER_LOCK();
1153 	cap = crypto_checkdriver(driverid);
1154 	if (cap == NULL) {
1155 		CRYPTO_DRIVER_UNLOCK();
1156 		return (EINVAL);
1157 	}
1158 
1159 	cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
1160 	crypto_drivers[driverid] = NULL;
1161 
1162 	/*
1163 	 * XXX: This doesn't do anything to kick sessions that
1164 	 * have no pending operations.
1165 	 */
1166 	while (cap->cc_sessions != 0)
1167 		mtx_sleep(cap, &crypto_drivers_mtx, 0, "cryunreg", 0);
1168 	CRYPTO_DRIVER_UNLOCK();
1169 	cap_rele(cap);
1170 
1171 	return (0);
1172 }
1173 
1174 /*
1175  * Clear blockage on a driver.  The what parameter indicates whether
1176  * the driver is now ready for cryptop's and/or cryptokop's.
1177  */
1178 int
1179 crypto_unblock(uint32_t driverid, int what)
1180 {
1181 	struct cryptocap *cap;
1182 	int err;
1183 
1184 	CRYPTO_Q_LOCK();
1185 	cap = crypto_checkdriver(driverid);
1186 	if (cap != NULL) {
1187 		if (what & CRYPTO_SYMQ)
1188 			cap->cc_qblocked = 0;
1189 		if (crp_sleep)
1190 			wakeup_one(&crp_q);
1191 		err = 0;
1192 	} else
1193 		err = EINVAL;
1194 	CRYPTO_Q_UNLOCK();
1195 
1196 	return err;
1197 }
1198 
1199 size_t
1200 crypto_buffer_len(struct crypto_buffer *cb)
1201 {
1202 	switch (cb->cb_type) {
1203 	case CRYPTO_BUF_CONTIG:
1204 		return (cb->cb_buf_len);
1205 	case CRYPTO_BUF_MBUF:
1206 		if (cb->cb_mbuf->m_flags & M_PKTHDR)
1207 			return (cb->cb_mbuf->m_pkthdr.len);
1208 		return (m_length(cb->cb_mbuf, NULL));
1209 	case CRYPTO_BUF_SINGLE_MBUF:
1210 		return (cb->cb_mbuf->m_len);
1211 	case CRYPTO_BUF_VMPAGE:
1212 		return (cb->cb_vm_page_len);
1213 	case CRYPTO_BUF_UIO:
1214 		return (cb->cb_uio->uio_resid);
1215 	default:
1216 		return (0);
1217 	}
1218 }
1219 
1220 #ifdef INVARIANTS
1221 /* Various sanity checks on crypto requests. */
1222 static void
1223 cb_sanity(struct crypto_buffer *cb, const char *name)
1224 {
1225 	KASSERT(cb->cb_type > CRYPTO_BUF_NONE && cb->cb_type <= CRYPTO_BUF_LAST,
1226 	    ("incoming crp with invalid %s buffer type", name));
1227 	switch (cb->cb_type) {
1228 	case CRYPTO_BUF_CONTIG:
1229 		KASSERT(cb->cb_buf_len >= 0,
1230 		    ("incoming crp with -ve %s buffer length", name));
1231 		break;
1232 	case CRYPTO_BUF_VMPAGE:
1233 		KASSERT(CRYPTO_HAS_VMPAGE,
1234 		    ("incoming crp uses dmap on supported arch"));
1235 		KASSERT(cb->cb_vm_page_len >= 0,
1236 		    ("incoming crp with -ve %s buffer length", name));
1237 		KASSERT(cb->cb_vm_page_offset >= 0,
1238 		    ("incoming crp with -ve %s buffer offset", name));
1239 		KASSERT(cb->cb_vm_page_offset < PAGE_SIZE,
1240 		    ("incoming crp with %s buffer offset greater than page size"
1241 		     , name));
1242 		break;
1243 	default:
1244 		break;
1245 	}
1246 }
1247 
1248 static void
1249 crp_sanity(struct cryptop *crp)
1250 {
1251 	struct crypto_session_params *csp;
1252 	struct crypto_buffer *out;
1253 	size_t ilen, len, olen;
1254 
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"));
1262 
1263 	csp = &crp->crp_session->csp;
1264 	cb_sanity(&crp->crp_buf, "input");
1265 	ilen = crypto_buffer_len(&crp->crp_buf);
1266 	olen = ilen;
1267 	out = NULL;
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);
1273 		}
1274 	} else
1275 		KASSERT(crp->crp_obuf.cb_type == CRYPTO_BUF_NONE,
1276 		    ("incoming crp with separate output buffer "
1277 		    "but no session support"));
1278 
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));
1284 		break;
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));
1289 		break;
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));
1294 		break;
1295 	case CSP_MODE_AEAD:
1296 		KASSERT(crp->crp_op ==
1297 		    (CRYPTO_OP_ENCRYPT | CRYPTO_OP_COMPUTE_DIGEST) ||
1298 		    crp->crp_op ==
1299 		    (CRYPTO_OP_DECRYPT | CRYPTO_OP_VERIFY_DIGEST),
1300 		    ("invalid AEAD op %x", crp->crp_op));
1301 		KASSERT(crp->crp_flags & CRYPTO_F_IV_SEPARATE,
1302 		    ("AEAD without a separate IV"));
1303 		break;
1304 	case CSP_MODE_ETA:
1305 		KASSERT(crp->crp_op ==
1306 		    (CRYPTO_OP_ENCRYPT | CRYPTO_OP_COMPUTE_DIGEST) ||
1307 		    crp->crp_op ==
1308 		    (CRYPTO_OP_DECRYPT | CRYPTO_OP_VERIFY_DIGEST),
1309 		    ("invalid ETA op %x", crp->crp_op));
1310 		break;
1311 	}
1312 	if (csp->csp_mode == CSP_MODE_AEAD || csp->csp_mode == CSP_MODE_ETA) {
1313 		if (crp->crp_aad == NULL) {
1314 			KASSERT(crp->crp_aad_start == 0 ||
1315 			    crp->crp_aad_start < ilen,
1316 			    ("invalid AAD start"));
1317 			KASSERT(crp->crp_aad_length != 0 ||
1318 			    crp->crp_aad_start == 0,
1319 			    ("AAD with zero length and non-zero start"));
1320 			KASSERT(crp->crp_aad_length == 0 ||
1321 			    crp->crp_aad_start + crp->crp_aad_length <= ilen,
1322 			    ("AAD outside input length"));
1323 		} else {
1324 			KASSERT(csp->csp_flags & CSP_F_SEPARATE_AAD,
1325 			    ("session doesn't support separate AAD buffer"));
1326 			KASSERT(crp->crp_aad_start == 0,
1327 			    ("separate AAD buffer with non-zero AAD start"));
1328 			KASSERT(crp->crp_aad_length != 0,
1329 			    ("separate AAD buffer with zero length"));
1330 		}
1331 	} else {
1332 		KASSERT(crp->crp_aad == NULL && crp->crp_aad_start == 0 &&
1333 		    crp->crp_aad_length == 0,
1334 		    ("AAD region in request not supporting AAD"));
1335 	}
1336 	if (csp->csp_ivlen == 0) {
1337 		KASSERT((crp->crp_flags & CRYPTO_F_IV_SEPARATE) == 0,
1338 		    ("IV_SEPARATE set when IV isn't used"));
1339 		KASSERT(crp->crp_iv_start == 0,
1340 		    ("crp_iv_start set when IV isn't used"));
1341 	} else if (crp->crp_flags & CRYPTO_F_IV_SEPARATE) {
1342 		KASSERT(crp->crp_iv_start == 0,
1343 		    ("IV_SEPARATE used with non-zero IV start"));
1344 	} else {
1345 		KASSERT(crp->crp_iv_start < ilen,
1346 		    ("invalid IV start"));
1347 		KASSERT(crp->crp_iv_start + csp->csp_ivlen <= ilen,
1348 		    ("IV outside buffer length"));
1349 	}
1350 	/* XXX: payload_start of 0 should always be < ilen? */
1351 	KASSERT(crp->crp_payload_start == 0 ||
1352 	    crp->crp_payload_start < ilen,
1353 	    ("invalid payload start"));
1354 	KASSERT(crp->crp_payload_start + crp->crp_payload_length <=
1355 	    ilen, ("payload outside input buffer"));
1356 	if (out == NULL) {
1357 		KASSERT(crp->crp_payload_output_start == 0,
1358 		    ("payload output start non-zero without output buffer"));
1359 	} else {
1360 		KASSERT(crp->crp_payload_output_start == 0 ||
1361 		    crp->crp_payload_output_start < olen,
1362 		    ("invalid payload output start"));
1363 		KASSERT(crp->crp_payload_output_start +
1364 		    crp->crp_payload_length <= olen,
1365 		    ("payload outside output buffer"));
1366 	}
1367 	if (csp->csp_mode == CSP_MODE_DIGEST ||
1368 	    csp->csp_mode == CSP_MODE_AEAD || csp->csp_mode == CSP_MODE_ETA) {
1369 		if (crp->crp_op & CRYPTO_OP_VERIFY_DIGEST)
1370 			len = ilen;
1371 		else
1372 			len = olen;
1373 		KASSERT(crp->crp_digest_start == 0 ||
1374 		    crp->crp_digest_start < len,
1375 		    ("invalid digest start"));
1376 		/* XXX: For the mlen == 0 case this check isn't perfect. */
1377 		KASSERT(crp->crp_digest_start + csp->csp_auth_mlen <= len,
1378 		    ("digest outside buffer"));
1379 	} else {
1380 		KASSERT(crp->crp_digest_start == 0,
1381 		    ("non-zero digest start for request without a digest"));
1382 	}
1383 	if (csp->csp_cipher_klen != 0)
1384 		KASSERT(csp->csp_cipher_key != NULL ||
1385 		    crp->crp_cipher_key != NULL,
1386 		    ("cipher request without a key"));
1387 	if (csp->csp_auth_klen != 0)
1388 		KASSERT(csp->csp_auth_key != NULL || crp->crp_auth_key != NULL,
1389 		    ("auth request without a key"));
1390 	KASSERT(crp->crp_callback != NULL, ("incoming crp without callback"));
1391 }
1392 #endif
1393 
1394 static int
1395 crypto_dispatch_one(struct cryptop *crp, int hint)
1396 {
1397 	struct cryptocap *cap;
1398 	int result;
1399 
1400 #ifdef INVARIANTS
1401 	crp_sanity(crp);
1402 #endif
1403 	CRYPTOSTAT_INC(cs_ops);
1404 
1405 	crp->crp_retw_id = crp->crp_session->id % crypto_workers_num;
1406 
1407 	/*
1408 	 * Caller marked the request to be processed immediately; dispatch it
1409 	 * directly to the driver unless the driver is currently blocked, in
1410 	 * which case it is queued for deferred dispatch.
1411 	 */
1412 	cap = crp->crp_session->cap;
1413 	if (!atomic_load_int(&cap->cc_qblocked)) {
1414 		result = crypto_invoke(cap, crp, hint);
1415 		if (result != ERESTART)
1416 			return (result);
1417 
1418 		/*
1419 		 * The driver ran out of resources, put the request on the
1420 		 * queue.
1421 		 */
1422 	}
1423 	crypto_batch_enqueue(crp);
1424 	return (0);
1425 }
1426 
1427 int
1428 crypto_dispatch(struct cryptop *crp)
1429 {
1430 	return (crypto_dispatch_one(crp, 0));
1431 }
1432 
1433 int
1434 crypto_dispatch_async(struct cryptop *crp, int flags)
1435 {
1436 	struct crypto_ret_worker *ret_worker;
1437 
1438 	if (!CRYPTO_SESS_SYNC(crp->crp_session)) {
1439 		/*
1440 		 * The driver issues completions asynchonously, don't bother
1441 		 * deferring dispatch to a worker thread.
1442 		 */
1443 		return (crypto_dispatch(crp));
1444 	}
1445 
1446 #ifdef INVARIANTS
1447 	crp_sanity(crp);
1448 #endif
1449 	CRYPTOSTAT_INC(cs_ops);
1450 
1451 	crp->crp_retw_id = crp->crp_session->id % crypto_workers_num;
1452 	if ((flags & CRYPTO_ASYNC_ORDERED) != 0) {
1453 		crp->crp_flags |= CRYPTO_F_ASYNC_ORDERED;
1454 		ret_worker = CRYPTO_RETW(crp->crp_retw_id);
1455 		CRYPTO_RETW_LOCK(ret_worker);
1456 		crp->crp_seq = ret_worker->reorder_ops++;
1457 		CRYPTO_RETW_UNLOCK(ret_worker);
1458 	}
1459 	TASK_INIT(&crp->crp_task, 0, crypto_task_invoke, crp);
1460 	taskqueue_enqueue(crypto_tq, &crp->crp_task);
1461 	return (0);
1462 }
1463 
1464 void
1465 crypto_dispatch_batch(struct cryptopq *crpq, int flags)
1466 {
1467 	struct cryptop *crp;
1468 	int hint;
1469 
1470 	while ((crp = TAILQ_FIRST(crpq)) != NULL) {
1471 		hint = TAILQ_NEXT(crp, crp_next) != NULL ? CRYPTO_HINT_MORE : 0;
1472 		TAILQ_REMOVE(crpq, crp, crp_next);
1473 		if (crypto_dispatch_one(crp, hint) != 0)
1474 			crypto_batch_enqueue(crp);
1475 	}
1476 }
1477 
1478 static void
1479 crypto_batch_enqueue(struct cryptop *crp)
1480 {
1481 
1482 	CRYPTO_Q_LOCK();
1483 	TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
1484 	if (crp_sleep)
1485 		wakeup_one(&crp_q);
1486 	CRYPTO_Q_UNLOCK();
1487 }
1488 
1489 static void
1490 crypto_task_invoke(void *ctx, int pending)
1491 {
1492 	struct cryptocap *cap;
1493 	struct cryptop *crp;
1494 	int result;
1495 
1496 	crp = (struct cryptop *)ctx;
1497 	cap = crp->crp_session->cap;
1498 	result = crypto_invoke(cap, crp, 0);
1499 	if (result == ERESTART)
1500 		crypto_batch_enqueue(crp);
1501 }
1502 
1503 /*
1504  * Dispatch a crypto request to the appropriate crypto devices.
1505  */
1506 static int
1507 crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint)
1508 {
1509 
1510 	KASSERT(crp != NULL, ("%s: crp == NULL", __func__));
1511 	KASSERT(crp->crp_callback != NULL,
1512 	    ("%s: crp->crp_callback == NULL", __func__));
1513 	KASSERT(crp->crp_session != NULL,
1514 	    ("%s: crp->crp_session == NULL", __func__));
1515 
1516 	if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1517 		struct crypto_session_params csp;
1518 		crypto_session_t nses;
1519 
1520 		/*
1521 		 * Driver has unregistered; migrate the session and return
1522 		 * an error to the caller so they'll resubmit the op.
1523 		 *
1524 		 * XXX: What if there are more already queued requests for this
1525 		 *      session?
1526 		 *
1527 		 * XXX: Real solution is to make sessions refcounted
1528 		 * and force callers to hold a reference when
1529 		 * assigning to crp_session.  Could maybe change
1530 		 * crypto_getreq to accept a session pointer to make
1531 		 * that work.  Alternatively, we could abandon the
1532 		 * notion of rewriting crp_session in requests forcing
1533 		 * the caller to deal with allocating a new session.
1534 		 * Perhaps provide a method to allow a crp's session to
1535 		 * be swapped that callers could use.
1536 		 */
1537 		csp = crp->crp_session->csp;
1538 		crypto_freesession(crp->crp_session);
1539 
1540 		/*
1541 		 * XXX: Key pointers may no longer be valid.  If we
1542 		 * really want to support this we need to define the
1543 		 * KPI such that 'csp' is required to be valid for the
1544 		 * duration of a session by the caller perhaps.
1545 		 *
1546 		 * XXX: If the keys have been changed this will reuse
1547 		 * the old keys.  This probably suggests making
1548 		 * rekeying more explicit and updating the key
1549 		 * pointers in 'csp' when the keys change.
1550 		 */
1551 		if (crypto_newsession(&nses, &csp,
1552 		    CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE) == 0)
1553 			crp->crp_session = nses;
1554 
1555 		crp->crp_etype = EAGAIN;
1556 		crypto_done(crp);
1557 		return 0;
1558 	} else {
1559 		/*
1560 		 * Invoke the driver to process the request.
1561 		 */
1562 		return CRYPTODEV_PROCESS(cap->cc_dev, crp, hint);
1563 	}
1564 }
1565 
1566 void
1567 crypto_destroyreq(struct cryptop *crp)
1568 {
1569 #ifdef DIAGNOSTIC
1570 	{
1571 		struct cryptop *crp2;
1572 		struct crypto_ret_worker *ret_worker;
1573 
1574 		CRYPTO_Q_LOCK();
1575 		TAILQ_FOREACH(crp2, &crp_q, crp_next) {
1576 			KASSERT(crp2 != crp,
1577 			    ("Freeing cryptop from the crypto queue (%p).",
1578 			    crp));
1579 		}
1580 		CRYPTO_Q_UNLOCK();
1581 
1582 		FOREACH_CRYPTO_RETW(ret_worker) {
1583 			CRYPTO_RETW_LOCK(ret_worker);
1584 			TAILQ_FOREACH(crp2, &ret_worker->crp_ret_q, crp_next) {
1585 				KASSERT(crp2 != crp,
1586 				    ("Freeing cryptop from the return queue (%p).",
1587 				    crp));
1588 			}
1589 			CRYPTO_RETW_UNLOCK(ret_worker);
1590 		}
1591 	}
1592 #endif
1593 }
1594 
1595 void
1596 crypto_freereq(struct cryptop *crp)
1597 {
1598 	if (crp == NULL)
1599 		return;
1600 
1601 	crypto_destroyreq(crp);
1602 	uma_zfree(cryptop_zone, crp);
1603 }
1604 
1605 static void
1606 _crypto_initreq(struct cryptop *crp, crypto_session_t cses)
1607 {
1608 	crp->crp_session = cses;
1609 }
1610 
1611 void
1612 crypto_initreq(struct cryptop *crp, crypto_session_t cses)
1613 {
1614 	memset(crp, 0, sizeof(*crp));
1615 	_crypto_initreq(crp, cses);
1616 }
1617 
1618 struct cryptop *
1619 crypto_getreq(crypto_session_t cses, int how)
1620 {
1621 	struct cryptop *crp;
1622 
1623 	MPASS(how == M_WAITOK || how == M_NOWAIT);
1624 	crp = uma_zalloc(cryptop_zone, how | M_ZERO);
1625 	if (crp != NULL)
1626 		_crypto_initreq(crp, cses);
1627 	return (crp);
1628 }
1629 
1630 /*
1631  * Invoke the callback on behalf of the driver.
1632  */
1633 void
1634 crypto_done(struct cryptop *crp)
1635 {
1636 	KASSERT((crp->crp_flags & CRYPTO_F_DONE) == 0,
1637 		("crypto_done: op already done, flags 0x%x", crp->crp_flags));
1638 	crp->crp_flags |= CRYPTO_F_DONE;
1639 	if (crp->crp_etype != 0)
1640 		CRYPTOSTAT_INC(cs_errs);
1641 
1642 	/*
1643 	 * CBIMM means unconditionally do the callback immediately;
1644 	 * CBIFSYNC means do the callback immediately only if the
1645 	 * operation was done synchronously.  Both are used to avoid
1646 	 * doing extraneous context switches; the latter is mostly
1647 	 * used with the software crypto driver.
1648 	 */
1649 	if ((crp->crp_flags & CRYPTO_F_ASYNC_ORDERED) == 0 &&
1650 	    ((crp->crp_flags & CRYPTO_F_CBIMM) != 0 ||
1651 	    ((crp->crp_flags & CRYPTO_F_CBIFSYNC) != 0 &&
1652 	    CRYPTO_SESS_SYNC(crp->crp_session)))) {
1653 		/*
1654 		 * Do the callback directly.  This is ok when the
1655 		 * callback routine does very little (e.g. the
1656 		 * /dev/crypto callback method just does a wakeup).
1657 		 */
1658 		crp->crp_callback(crp);
1659 	} else {
1660 		struct crypto_ret_worker *ret_worker;
1661 		bool wake;
1662 
1663 		ret_worker = CRYPTO_RETW(crp->crp_retw_id);
1664 
1665 		/*
1666 		 * Normal case; queue the callback for the thread.
1667 		 */
1668 		CRYPTO_RETW_LOCK(ret_worker);
1669 		if ((crp->crp_flags & CRYPTO_F_ASYNC_ORDERED) != 0) {
1670 			struct cryptop *tmp;
1671 
1672 			TAILQ_FOREACH_REVERSE(tmp,
1673 			    &ret_worker->crp_ordered_ret_q, cryptop_q,
1674 			    crp_next) {
1675 				if (CRYPTO_SEQ_GT(crp->crp_seq, tmp->crp_seq)) {
1676 					TAILQ_INSERT_AFTER(
1677 					    &ret_worker->crp_ordered_ret_q, tmp,
1678 					    crp, crp_next);
1679 					break;
1680 				}
1681 			}
1682 			if (tmp == NULL) {
1683 				TAILQ_INSERT_HEAD(
1684 				    &ret_worker->crp_ordered_ret_q, crp,
1685 				    crp_next);
1686 			}
1687 
1688 			wake = crp->crp_seq == ret_worker->reorder_cur_seq;
1689 		} else {
1690 			wake = TAILQ_EMPTY(&ret_worker->crp_ret_q);
1691 			TAILQ_INSERT_TAIL(&ret_worker->crp_ret_q, crp,
1692 			    crp_next);
1693 		}
1694 
1695 		if (wake)
1696 			wakeup_one(&ret_worker->crp_ret_q);	/* shared wait channel */
1697 		CRYPTO_RETW_UNLOCK(ret_worker);
1698 	}
1699 }
1700 
1701 /*
1702  * Terminate a thread at module unload.  The process that
1703  * initiated this is waiting for us to signal that we're gone;
1704  * wake it up and exit.  We use the driver table lock to insure
1705  * we don't do the wakeup before they're waiting.  There is no
1706  * race here because the waiter sleeps on the proc lock for the
1707  * thread so it gets notified at the right time because of an
1708  * extra wakeup that's done in exit1().
1709  */
1710 static void
1711 crypto_finis(void *chan)
1712 {
1713 	CRYPTO_DRIVER_LOCK();
1714 	wakeup_one(chan);
1715 	CRYPTO_DRIVER_UNLOCK();
1716 	kthread_exit();
1717 }
1718 
1719 /*
1720  * Crypto thread, dispatches crypto requests.
1721  */
1722 static void
1723 crypto_dispatch_thread(void *arg __unused)
1724 {
1725 	struct cryptop *crp, *submit;
1726 	struct cryptocap *cap;
1727 	int result, hint;
1728 
1729 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
1730 	fpu_kern_thread(FPU_KERN_NORMAL);
1731 #endif
1732 
1733 	CRYPTO_Q_LOCK();
1734 	for (;;) {
1735 		/*
1736 		 * Find the first element in the queue that can be
1737 		 * processed and look-ahead to see if multiple ops
1738 		 * are ready for the same driver.
1739 		 */
1740 		submit = NULL;
1741 		hint = 0;
1742 		TAILQ_FOREACH(crp, &crp_q, crp_next) {
1743 			cap = crp->crp_session->cap;
1744 			/*
1745 			 * Driver cannot disappeared when there is an active
1746 			 * session.
1747 			 */
1748 			KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1749 			    __func__, __LINE__));
1750 			if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1751 				/* Op needs to be migrated, process it. */
1752 				if (submit == NULL)
1753 					submit = crp;
1754 				break;
1755 			}
1756 			if (!cap->cc_qblocked) {
1757 				if (submit != NULL) {
1758 					/*
1759 					 * We stop on finding another op,
1760 					 * regardless whether its for the same
1761 					 * driver or not.  We could keep
1762 					 * searching the queue but it might be
1763 					 * better to just use a per-driver
1764 					 * queue instead.
1765 					 */
1766 					if (submit->crp_session->cap == cap)
1767 						hint = CRYPTO_HINT_MORE;
1768 				} else {
1769 					submit = crp;
1770 				}
1771 				break;
1772 			}
1773 		}
1774 		if (submit != NULL) {
1775 			TAILQ_REMOVE(&crp_q, submit, crp_next);
1776 			cap = submit->crp_session->cap;
1777 			KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1778 			    __func__, __LINE__));
1779 			CRYPTO_Q_UNLOCK();
1780 			result = crypto_invoke(cap, submit, hint);
1781 			CRYPTO_Q_LOCK();
1782 			if (result == ERESTART) {
1783 				/*
1784 				 * The driver ran out of resources, mark the
1785 				 * driver ``blocked'' for cryptop's and put
1786 				 * the request back in the queue.  It would
1787 				 * best to put the request back where we got
1788 				 * it but that's hard so for now we put it
1789 				 * at the front.  This should be ok; putting
1790 				 * it at the end does not work.
1791 				 */
1792 				cap->cc_qblocked = 1;
1793 				TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
1794 				CRYPTOSTAT_INC(cs_blocks);
1795 			}
1796 		} else {
1797 			/*
1798 			 * Nothing more to be processed.  Sleep until we're
1799 			 * woken because there are more ops to process.
1800 			 * This happens either by submission or by a driver
1801 			 * becoming unblocked and notifying us through
1802 			 * crypto_unblock.  Note that when we wakeup we
1803 			 * start processing each queue again from the
1804 			 * front. It's not clear that it's important to
1805 			 * preserve this ordering since ops may finish
1806 			 * out of order if dispatched to different devices
1807 			 * and some become blocked while others do not.
1808 			 */
1809 			crp_sleep = 1;
1810 			msleep(&crp_q, &crypto_q_mtx, PWAIT, "crypto_wait", 0);
1811 			crp_sleep = 0;
1812 			if (cryptotd == NULL)
1813 				break;
1814 			CRYPTOSTAT_INC(cs_intrs);
1815 		}
1816 	}
1817 	CRYPTO_Q_UNLOCK();
1818 
1819 	crypto_finis(&crp_q);
1820 }
1821 
1822 /*
1823  * Crypto returns thread, does callbacks for processed crypto requests.
1824  * Callbacks are done here, rather than in the crypto drivers, because
1825  * callbacks typically are expensive and would slow interrupt handling.
1826  */
1827 static void
1828 crypto_ret_thread(void *arg)
1829 {
1830 	struct crypto_ret_worker *ret_worker = arg;
1831 	struct cryptop *crpt;
1832 
1833 	CRYPTO_RETW_LOCK(ret_worker);
1834 	for (;;) {
1835 		/* Harvest return q's for completed ops */
1836 		crpt = TAILQ_FIRST(&ret_worker->crp_ordered_ret_q);
1837 		if (crpt != NULL) {
1838 			if (crpt->crp_seq == ret_worker->reorder_cur_seq) {
1839 				TAILQ_REMOVE(&ret_worker->crp_ordered_ret_q, crpt, crp_next);
1840 				ret_worker->reorder_cur_seq++;
1841 			} else {
1842 				crpt = NULL;
1843 			}
1844 		}
1845 
1846 		if (crpt == NULL) {
1847 			crpt = TAILQ_FIRST(&ret_worker->crp_ret_q);
1848 			if (crpt != NULL)
1849 				TAILQ_REMOVE(&ret_worker->crp_ret_q, crpt, crp_next);
1850 		}
1851 
1852 		if (crpt != NULL) {
1853 			CRYPTO_RETW_UNLOCK(ret_worker);
1854 			/*
1855 			 * Run callbacks unlocked.
1856 			 */
1857 			if (crpt != NULL)
1858 				crpt->crp_callback(crpt);
1859 			CRYPTO_RETW_LOCK(ret_worker);
1860 		} else {
1861 			/*
1862 			 * Nothing more to be processed.  Sleep until we're
1863 			 * woken because there are more returns to process.
1864 			 */
1865 			msleep(&ret_worker->crp_ret_q, &ret_worker->crypto_ret_mtx, PWAIT,
1866 				"crypto_ret_wait", 0);
1867 			if (ret_worker->td == NULL)
1868 				break;
1869 			CRYPTOSTAT_INC(cs_rets);
1870 		}
1871 	}
1872 	CRYPTO_RETW_UNLOCK(ret_worker);
1873 
1874 	crypto_finis(&ret_worker->crp_ret_q);
1875 }
1876 
1877 #ifdef DDB
1878 static void
1879 db_show_drivers(void)
1880 {
1881 	int hid;
1882 
1883 	db_printf("%12s %4s %8s %2s\n"
1884 		, "Device"
1885 		, "Ses"
1886 		, "Flags"
1887 		, "QB"
1888 	);
1889 	for (hid = 0; hid < crypto_drivers_size; hid++) {
1890 		const struct cryptocap *cap = crypto_drivers[hid];
1891 		if (cap == NULL)
1892 			continue;
1893 		db_printf("%-12s %4u %08x %2u\n"
1894 		    , device_get_nameunit(cap->cc_dev)
1895 		    , cap->cc_sessions
1896 		    , cap->cc_flags
1897 		    , cap->cc_qblocked
1898 		);
1899 	}
1900 }
1901 
1902 DB_SHOW_COMMAND(crypto, db_show_crypto)
1903 {
1904 	struct cryptop *crp;
1905 	struct crypto_ret_worker *ret_worker;
1906 
1907 	db_show_drivers();
1908 	db_printf("\n");
1909 
1910 	db_printf("%4s %8s %4s %4s %4s %4s %8s %8s\n",
1911 	    "HID", "Caps", "Ilen", "Olen", "Etype", "Flags",
1912 	    "Device", "Callback");
1913 	TAILQ_FOREACH(crp, &crp_q, crp_next) {
1914 		db_printf("%4u %08x %4u %4u %04x %8p %8p\n"
1915 		    , crp->crp_session->cap->cc_hid
1916 		    , (int) crypto_ses2caps(crp->crp_session)
1917 		    , crp->crp_olen
1918 		    , crp->crp_etype
1919 		    , crp->crp_flags
1920 		    , device_get_nameunit(crp->crp_session->cap->cc_dev)
1921 		    , crp->crp_callback
1922 		);
1923 	}
1924 	FOREACH_CRYPTO_RETW(ret_worker) {
1925 		db_printf("\n%8s %4s %4s %4s %8s\n",
1926 		    "ret_worker", "HID", "Etype", "Flags", "Callback");
1927 		if (!TAILQ_EMPTY(&ret_worker->crp_ret_q)) {
1928 			TAILQ_FOREACH(crp, &ret_worker->crp_ret_q, crp_next) {
1929 				db_printf("%8td %4u %4u %04x %8p\n"
1930 				    , CRYPTO_RETW_ID(ret_worker)
1931 				    , crp->crp_session->cap->cc_hid
1932 				    , crp->crp_etype
1933 				    , crp->crp_flags
1934 				    , crp->crp_callback
1935 				);
1936 			}
1937 		}
1938 	}
1939 }
1940 #endif
1941 
1942 int crypto_modevent(module_t mod, int type, void *unused);
1943 
1944 /*
1945  * Initialization code, both for static and dynamic loading.
1946  * Note this is not invoked with the usual MODULE_DECLARE
1947  * mechanism but instead is listed as a dependency by the
1948  * cryptosoft driver.  This guarantees proper ordering of
1949  * calls on module load/unload.
1950  */
1951 int
1952 crypto_modevent(module_t mod, int type, void *unused)
1953 {
1954 	int error = EINVAL;
1955 
1956 	switch (type) {
1957 	case MOD_LOAD:
1958 		error = crypto_init();
1959 		if (error == 0 && bootverbose)
1960 			printf("crypto: <crypto core>\n");
1961 		break;
1962 	case MOD_UNLOAD:
1963 		/*XXX disallow if active sessions */
1964 		error = 0;
1965 		crypto_destroy();
1966 		return 0;
1967 	}
1968 	return error;
1969 }
1970 MODULE_VERSION(crypto, 1);
1971 MODULE_DEPEND(crypto, zlib, 1, 1, 1);
1972