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