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