xref: /freebsd/sys/opencrypto/crypto.c (revision 0e6acb26)
1 /*-
2  * Copyright (c) 2002-2006 Sam Leffler.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23  */
24 
25 #include <sys/cdefs.h>
26 __FBSDID("$FreeBSD$");
27 
28 /*
29  * Cryptographic Subsystem.
30  *
31  * This code is derived from the Openbsd Cryptographic Framework (OCF)
32  * that has the copyright shown below.  Very little of the original
33  * code remains.
34  */
35 
36 /*-
37  * The author of this code is Angelos D. Keromytis (angelos@cis.upenn.edu)
38  *
39  * This code was written by Angelos D. Keromytis in Athens, Greece, in
40  * February 2000. Network Security Technologies Inc. (NSTI) kindly
41  * supported the development of this code.
42  *
43  * Copyright (c) 2000, 2001 Angelos D. Keromytis
44  *
45  * Permission to use, copy, and modify this software with or without fee
46  * is hereby granted, provided that this entire notice is included in
47  * all source code copies of any software which is or includes a copy or
48  * modification of this software.
49  *
50  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
51  * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
52  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
53  * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
54  * PURPOSE.
55  */
56 
57 #define	CRYPTO_TIMING				/* enable timing support */
58 
59 #include "opt_ddb.h"
60 
61 #include <sys/param.h>
62 #include <sys/systm.h>
63 #include <sys/eventhandler.h>
64 #include <sys/kernel.h>
65 #include <sys/kthread.h>
66 #include <sys/linker.h>
67 #include <sys/lock.h>
68 #include <sys/module.h>
69 #include <sys/mutex.h>
70 #include <sys/malloc.h>
71 #include <sys/proc.h>
72 #include <sys/sdt.h>
73 #include <sys/sysctl.h>
74 
75 #include <ddb/ddb.h>
76 
77 #include <vm/uma.h>
78 #include <crypto/intake.h>
79 #include <opencrypto/cryptodev.h>
80 #include <opencrypto/xform.h>			/* XXX for M_XDATA */
81 
82 #include <sys/kobj.h>
83 #include <sys/bus.h>
84 #include "cryptodev_if.h"
85 
86 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
87 #include <machine/pcb.h>
88 #endif
89 
90 SDT_PROVIDER_DEFINE(opencrypto);
91 
92 /*
93  * Crypto drivers register themselves by allocating a slot in the
94  * crypto_drivers table with crypto_get_driverid() and then registering
95  * each algorithm they support with crypto_register() and crypto_kregister().
96  */
97 static	struct mtx crypto_drivers_mtx;		/* lock on driver table */
98 #define	CRYPTO_DRIVER_LOCK()	mtx_lock(&crypto_drivers_mtx)
99 #define	CRYPTO_DRIVER_UNLOCK()	mtx_unlock(&crypto_drivers_mtx)
100 #define	CRYPTO_DRIVER_ASSERT()	mtx_assert(&crypto_drivers_mtx, MA_OWNED)
101 
102 /*
103  * Crypto device/driver capabilities structure.
104  *
105  * Synchronization:
106  * (d) - protected by CRYPTO_DRIVER_LOCK()
107  * (q) - protected by CRYPTO_Q_LOCK()
108  * Not tagged fields are read-only.
109  */
110 struct cryptocap {
111 	device_t	cc_dev;			/* (d) device/driver */
112 	u_int32_t	cc_sessions;		/* (d) # of sessions */
113 	u_int32_t	cc_koperations;		/* (d) # os asym operations */
114 	/*
115 	 * Largest possible operator length (in bits) for each type of
116 	 * encryption algorithm. XXX not used
117 	 */
118 	u_int16_t	cc_max_op_len[CRYPTO_ALGORITHM_MAX + 1];
119 	u_int8_t	cc_alg[CRYPTO_ALGORITHM_MAX + 1];
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 };
127 static	struct cryptocap *crypto_drivers = NULL;
128 static	int crypto_drivers_num = 0;
129 
130 /*
131  * There are two queues for crypto requests; one for symmetric (e.g.
132  * cipher) operations and one for asymmetric (e.g. MOD)operations.
133  * A single mutex is used to lock access to both queues.  We could
134  * have one per-queue but having one simplifies handling of block/unblock
135  * operations.
136  */
137 static	int crp_sleep = 0;
138 static	TAILQ_HEAD(,cryptop) crp_q;		/* request queues */
139 static	TAILQ_HEAD(,cryptkop) crp_kq;
140 static	struct mtx crypto_q_mtx;
141 #define	CRYPTO_Q_LOCK()		mtx_lock(&crypto_q_mtx)
142 #define	CRYPTO_Q_UNLOCK()	mtx_unlock(&crypto_q_mtx)
143 
144 /*
145  * There are two queues for processing completed crypto requests; one
146  * for the symmetric and one for the asymmetric ops.  We only need one
147  * but have two to avoid type futzing (cryptop vs. cryptkop).  A single
148  * mutex is used to lock access to both queues.  Note that this lock
149  * must be separate from the lock on request queues to insure driver
150  * callbacks don't generate lock order reversals.
151  */
152 static	TAILQ_HEAD(,cryptop) crp_ret_q;		/* callback queues */
153 static	TAILQ_HEAD(,cryptkop) crp_ret_kq;
154 static	struct mtx crypto_ret_q_mtx;
155 #define	CRYPTO_RETQ_LOCK()	mtx_lock(&crypto_ret_q_mtx)
156 #define	CRYPTO_RETQ_UNLOCK()	mtx_unlock(&crypto_ret_q_mtx)
157 #define	CRYPTO_RETQ_EMPTY()	(TAILQ_EMPTY(&crp_ret_q) && TAILQ_EMPTY(&crp_ret_kq))
158 
159 static	uma_zone_t cryptop_zone;
160 static	uma_zone_t cryptodesc_zone;
161 
162 int	crypto_userasymcrypto = 1;	/* userland may do asym crypto reqs */
163 SYSCTL_INT(_kern, OID_AUTO, userasymcrypto, CTLFLAG_RW,
164 	   &crypto_userasymcrypto, 0,
165 	   "Enable/disable user-mode access to asymmetric crypto support");
166 int	crypto_devallowsoft = 0;	/* only use hardware crypto */
167 SYSCTL_INT(_kern, OID_AUTO, cryptodevallowsoft, CTLFLAG_RW,
168 	   &crypto_devallowsoft, 0,
169 	   "Enable/disable use of software crypto by /dev/crypto");
170 
171 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
172 
173 static	void crypto_proc(void);
174 static	struct proc *cryptoproc;
175 static	void crypto_ret_proc(void);
176 static	struct proc *cryptoretproc;
177 static	void crypto_destroy(void);
178 static	int crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint);
179 static	int crypto_kinvoke(struct cryptkop *krp, int flags);
180 
181 static	struct cryptostats cryptostats;
182 SYSCTL_STRUCT(_kern, OID_AUTO, crypto_stats, CTLFLAG_RW, &cryptostats,
183 	    cryptostats, "Crypto system statistics");
184 
185 #ifdef CRYPTO_TIMING
186 static	int crypto_timing = 0;
187 SYSCTL_INT(_debug, OID_AUTO, crypto_timing, CTLFLAG_RW,
188 	   &crypto_timing, 0, "Enable/disable crypto timing support");
189 #endif
190 
191 /* Try to avoid directly exposing the key buffer as a symbol */
192 static struct keybuf *keybuf;
193 
194 static struct keybuf empty_keybuf = {
195         .kb_nents = 0
196 };
197 
198 /* Obtain the key buffer from boot metadata */
199 static void
200 keybuf_init(void)
201 {
202 	caddr_t kmdp;
203 
204 	kmdp = preload_search_by_type("elf kernel");
205 
206 	if (kmdp == NULL)
207 		kmdp = preload_search_by_type("elf64 kernel");
208 
209 	keybuf = (struct keybuf *)preload_search_info(kmdp,
210 	    MODINFO_METADATA | MODINFOMD_KEYBUF);
211 
212         if (keybuf == NULL)
213                 keybuf = &empty_keybuf;
214 }
215 
216 /* It'd be nice if we could store these in some kind of secure memory... */
217 struct keybuf * get_keybuf(void) {
218 
219         return (keybuf);
220 }
221 
222 static int
223 crypto_init(void)
224 {
225 	int error;
226 
227 	mtx_init(&crypto_drivers_mtx, "crypto", "crypto driver table",
228 		MTX_DEF|MTX_QUIET);
229 
230 	TAILQ_INIT(&crp_q);
231 	TAILQ_INIT(&crp_kq);
232 	mtx_init(&crypto_q_mtx, "crypto", "crypto op queues", MTX_DEF);
233 
234 	TAILQ_INIT(&crp_ret_q);
235 	TAILQ_INIT(&crp_ret_kq);
236 	mtx_init(&crypto_ret_q_mtx, "crypto", "crypto return queues", MTX_DEF);
237 
238 	cryptop_zone = uma_zcreate("cryptop", sizeof (struct cryptop),
239 				    0, 0, 0, 0,
240 				    UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
241 	cryptodesc_zone = uma_zcreate("cryptodesc", sizeof (struct cryptodesc),
242 				    0, 0, 0, 0,
243 				    UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
244 	if (cryptodesc_zone == NULL || cryptop_zone == NULL) {
245 		printf("crypto_init: cannot setup crypto zones\n");
246 		error = ENOMEM;
247 		goto bad;
248 	}
249 
250 	crypto_drivers_num = CRYPTO_DRIVERS_INITIAL;
251 	crypto_drivers = malloc(crypto_drivers_num *
252 	    sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT | M_ZERO);
253 	if (crypto_drivers == NULL) {
254 		printf("crypto_init: cannot setup crypto drivers\n");
255 		error = ENOMEM;
256 		goto bad;
257 	}
258 
259 	error = kproc_create((void (*)(void *)) crypto_proc, NULL,
260 		    &cryptoproc, 0, 0, "crypto");
261 	if (error) {
262 		printf("crypto_init: cannot start crypto thread; error %d",
263 			error);
264 		goto bad;
265 	}
266 
267 	error = kproc_create((void (*)(void *)) crypto_ret_proc, NULL,
268 		    &cryptoretproc, 0, 0, "crypto returns");
269 	if (error) {
270 		printf("crypto_init: cannot start cryptoret thread; error %d",
271 			error);
272 		goto bad;
273 	}
274 
275         keybuf_init();
276 
277 	return 0;
278 bad:
279 	crypto_destroy();
280 	return error;
281 }
282 
283 /*
284  * Signal a crypto thread to terminate.  We use the driver
285  * table lock to synchronize the sleep/wakeups so that we
286  * are sure the threads have terminated before we release
287  * the data structures they use.  See crypto_finis below
288  * for the other half of this song-and-dance.
289  */
290 static void
291 crypto_terminate(struct proc **pp, void *q)
292 {
293 	struct proc *p;
294 
295 	mtx_assert(&crypto_drivers_mtx, MA_OWNED);
296 	p = *pp;
297 	*pp = NULL;
298 	if (p) {
299 		wakeup_one(q);
300 		PROC_LOCK(p);		/* NB: insure we don't miss wakeup */
301 		CRYPTO_DRIVER_UNLOCK();	/* let crypto_finis progress */
302 		msleep(p, &p->p_mtx, PWAIT, "crypto_destroy", 0);
303 		PROC_UNLOCK(p);
304 		CRYPTO_DRIVER_LOCK();
305 	}
306 }
307 
308 static void
309 crypto_destroy(void)
310 {
311 	/*
312 	 * Terminate any crypto threads.
313 	 */
314 	CRYPTO_DRIVER_LOCK();
315 	crypto_terminate(&cryptoproc, &crp_q);
316 	crypto_terminate(&cryptoretproc, &crp_ret_q);
317 	CRYPTO_DRIVER_UNLOCK();
318 
319 	/* XXX flush queues??? */
320 
321 	/*
322 	 * Reclaim dynamically allocated resources.
323 	 */
324 	if (crypto_drivers != NULL)
325 		free(crypto_drivers, M_CRYPTO_DATA);
326 
327 	if (cryptodesc_zone != NULL)
328 		uma_zdestroy(cryptodesc_zone);
329 	if (cryptop_zone != NULL)
330 		uma_zdestroy(cryptop_zone);
331 	mtx_destroy(&crypto_q_mtx);
332 	mtx_destroy(&crypto_ret_q_mtx);
333 	mtx_destroy(&crypto_drivers_mtx);
334 }
335 
336 static struct cryptocap *
337 crypto_checkdriver(u_int32_t hid)
338 {
339 	if (crypto_drivers == NULL)
340 		return NULL;
341 	return (hid >= crypto_drivers_num ? NULL : &crypto_drivers[hid]);
342 }
343 
344 /*
345  * Compare a driver's list of supported algorithms against another
346  * list; return non-zero if all algorithms are supported.
347  */
348 static int
349 driver_suitable(const struct cryptocap *cap, const struct cryptoini *cri)
350 {
351 	const struct cryptoini *cr;
352 
353 	/* See if all the algorithms are supported. */
354 	for (cr = cri; cr; cr = cr->cri_next)
355 		if (cap->cc_alg[cr->cri_alg] == 0)
356 			return 0;
357 	return 1;
358 }
359 
360 /*
361  * Select a driver for a new session that supports the specified
362  * algorithms and, optionally, is constrained according to the flags.
363  * The algorithm we use here is pretty stupid; just use the
364  * first driver that supports all the algorithms we need. If there
365  * are multiple drivers we choose the driver with the fewest active
366  * sessions.  We prefer hardware-backed drivers to software ones.
367  *
368  * XXX We need more smarts here (in real life too, but that's
369  * XXX another story altogether).
370  */
371 static struct cryptocap *
372 crypto_select_driver(const struct cryptoini *cri, int flags)
373 {
374 	struct cryptocap *cap, *best;
375 	int match, hid;
376 
377 	CRYPTO_DRIVER_ASSERT();
378 
379 	/*
380 	 * Look first for hardware crypto devices if permitted.
381 	 */
382 	if (flags & CRYPTOCAP_F_HARDWARE)
383 		match = CRYPTOCAP_F_HARDWARE;
384 	else
385 		match = CRYPTOCAP_F_SOFTWARE;
386 	best = NULL;
387 again:
388 	for (hid = 0; hid < crypto_drivers_num; hid++) {
389 		cap = &crypto_drivers[hid];
390 		/*
391 		 * If it's not initialized, is in the process of
392 		 * going away, or is not appropriate (hardware
393 		 * or software based on match), then skip.
394 		 */
395 		if (cap->cc_dev == NULL ||
396 		    (cap->cc_flags & CRYPTOCAP_F_CLEANUP) ||
397 		    (cap->cc_flags & match) == 0)
398 			continue;
399 
400 		/* verify all the algorithms are supported. */
401 		if (driver_suitable(cap, cri)) {
402 			if (best == NULL ||
403 			    cap->cc_sessions < best->cc_sessions)
404 				best = cap;
405 		}
406 	}
407 	if (best == NULL && match == CRYPTOCAP_F_HARDWARE &&
408 	    (flags & CRYPTOCAP_F_SOFTWARE)) {
409 		/* sort of an Algol 68-style for loop */
410 		match = CRYPTOCAP_F_SOFTWARE;
411 		goto again;
412 	}
413 	return best;
414 }
415 
416 /*
417  * Create a new session.  The crid argument specifies a crypto
418  * driver to use or constraints on a driver to select (hardware
419  * only, software only, either).  Whatever driver is selected
420  * must be capable of the requested crypto algorithms.
421  */
422 int
423 crypto_newsession(u_int64_t *sid, struct cryptoini *cri, int crid)
424 {
425 	struct cryptocap *cap;
426 	u_int32_t hid, lid;
427 	int err;
428 
429 	CRYPTO_DRIVER_LOCK();
430 	if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
431 		/*
432 		 * Use specified driver; verify it is capable.
433 		 */
434 		cap = crypto_checkdriver(crid);
435 		if (cap != NULL && !driver_suitable(cap, cri))
436 			cap = NULL;
437 	} else {
438 		/*
439 		 * No requested driver; select based on crid flags.
440 		 */
441 		cap = crypto_select_driver(cri, crid);
442 		/*
443 		 * if NULL then can't do everything in one session.
444 		 * XXX Fix this. We need to inject a "virtual" session
445 		 * XXX layer right about here.
446 		 */
447 	}
448 	if (cap != NULL) {
449 		/* Call the driver initialization routine. */
450 		hid = cap - crypto_drivers;
451 		lid = hid;		/* Pass the driver ID. */
452 		err = CRYPTODEV_NEWSESSION(cap->cc_dev, &lid, cri);
453 		if (err == 0) {
454 			(*sid) = (cap->cc_flags & 0xff000000)
455 			       | (hid & 0x00ffffff);
456 			(*sid) <<= 32;
457 			(*sid) |= (lid & 0xffffffff);
458 			cap->cc_sessions++;
459 		} else
460 			CRYPTDEB("dev newsession failed");
461 	} else {
462 		CRYPTDEB("no driver");
463 		err = EINVAL;
464 	}
465 	CRYPTO_DRIVER_UNLOCK();
466 	return err;
467 }
468 
469 static void
470 crypto_remove(struct cryptocap *cap)
471 {
472 
473 	mtx_assert(&crypto_drivers_mtx, MA_OWNED);
474 	if (cap->cc_sessions == 0 && cap->cc_koperations == 0)
475 		bzero(cap, sizeof(*cap));
476 }
477 
478 /*
479  * Delete an existing session (or a reserved session on an unregistered
480  * driver).
481  */
482 int
483 crypto_freesession(u_int64_t sid)
484 {
485 	struct cryptocap *cap;
486 	u_int32_t hid;
487 	int err;
488 
489 	CRYPTO_DRIVER_LOCK();
490 
491 	if (crypto_drivers == NULL) {
492 		err = EINVAL;
493 		goto done;
494 	}
495 
496 	/* Determine two IDs. */
497 	hid = CRYPTO_SESID2HID(sid);
498 
499 	if (hid >= crypto_drivers_num) {
500 		err = ENOENT;
501 		goto done;
502 	}
503 	cap = &crypto_drivers[hid];
504 
505 	if (cap->cc_sessions)
506 		cap->cc_sessions--;
507 
508 	/* Call the driver cleanup routine, if available. */
509 	err = CRYPTODEV_FREESESSION(cap->cc_dev, sid);
510 
511 	if (cap->cc_flags & CRYPTOCAP_F_CLEANUP)
512 		crypto_remove(cap);
513 
514 done:
515 	CRYPTO_DRIVER_UNLOCK();
516 	return err;
517 }
518 
519 /*
520  * Return an unused driver id.  Used by drivers prior to registering
521  * support for the algorithms they handle.
522  */
523 int32_t
524 crypto_get_driverid(device_t dev, int flags)
525 {
526 	struct cryptocap *newdrv;
527 	int i;
528 
529 	if ((flags & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
530 		printf("%s: no flags specified when registering driver\n",
531 		    device_get_nameunit(dev));
532 		return -1;
533 	}
534 
535 	CRYPTO_DRIVER_LOCK();
536 
537 	for (i = 0; i < crypto_drivers_num; i++) {
538 		if (crypto_drivers[i].cc_dev == NULL &&
539 		    (crypto_drivers[i].cc_flags & CRYPTOCAP_F_CLEANUP) == 0) {
540 			break;
541 		}
542 	}
543 
544 	/* Out of entries, allocate some more. */
545 	if (i == crypto_drivers_num) {
546 		/* Be careful about wrap-around. */
547 		if (2 * crypto_drivers_num <= crypto_drivers_num) {
548 			CRYPTO_DRIVER_UNLOCK();
549 			printf("crypto: driver count wraparound!\n");
550 			return -1;
551 		}
552 
553 		newdrv = malloc(2 * crypto_drivers_num *
554 		    sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT|M_ZERO);
555 		if (newdrv == NULL) {
556 			CRYPTO_DRIVER_UNLOCK();
557 			printf("crypto: no space to expand driver table!\n");
558 			return -1;
559 		}
560 
561 		bcopy(crypto_drivers, newdrv,
562 		    crypto_drivers_num * sizeof(struct cryptocap));
563 
564 		crypto_drivers_num *= 2;
565 
566 		free(crypto_drivers, M_CRYPTO_DATA);
567 		crypto_drivers = newdrv;
568 	}
569 
570 	/* NB: state is zero'd on free */
571 	crypto_drivers[i].cc_sessions = 1;	/* Mark */
572 	crypto_drivers[i].cc_dev = dev;
573 	crypto_drivers[i].cc_flags = flags;
574 	if (bootverbose)
575 		printf("crypto: assign %s driver id %u, flags %u\n",
576 		    device_get_nameunit(dev), i, flags);
577 
578 	CRYPTO_DRIVER_UNLOCK();
579 
580 	return i;
581 }
582 
583 /*
584  * Lookup a driver by name.  We match against the full device
585  * name and unit, and against just the name.  The latter gives
586  * us a simple widlcarding by device name.  On success return the
587  * driver/hardware identifier; otherwise return -1.
588  */
589 int
590 crypto_find_driver(const char *match)
591 {
592 	int i, len = strlen(match);
593 
594 	CRYPTO_DRIVER_LOCK();
595 	for (i = 0; i < crypto_drivers_num; i++) {
596 		device_t dev = crypto_drivers[i].cc_dev;
597 		if (dev == NULL ||
598 		    (crypto_drivers[i].cc_flags & CRYPTOCAP_F_CLEANUP))
599 			continue;
600 		if (strncmp(match, device_get_nameunit(dev), len) == 0 ||
601 		    strncmp(match, device_get_name(dev), len) == 0)
602 			break;
603 	}
604 	CRYPTO_DRIVER_UNLOCK();
605 	return i < crypto_drivers_num ? i : -1;
606 }
607 
608 /*
609  * Return the device_t for the specified driver or NULL
610  * if the driver identifier is invalid.
611  */
612 device_t
613 crypto_find_device_byhid(int hid)
614 {
615 	struct cryptocap *cap = crypto_checkdriver(hid);
616 	return cap != NULL ? cap->cc_dev : NULL;
617 }
618 
619 /*
620  * Return the device/driver capabilities.
621  */
622 int
623 crypto_getcaps(int hid)
624 {
625 	struct cryptocap *cap = crypto_checkdriver(hid);
626 	return cap != NULL ? cap->cc_flags : 0;
627 }
628 
629 /*
630  * Register support for a key-related algorithm.  This routine
631  * is called once for each algorithm supported a driver.
632  */
633 int
634 crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags)
635 {
636 	struct cryptocap *cap;
637 	int err;
638 
639 	CRYPTO_DRIVER_LOCK();
640 
641 	cap = crypto_checkdriver(driverid);
642 	if (cap != NULL &&
643 	    (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
644 		/*
645 		 * XXX Do some performance testing to determine placing.
646 		 * XXX We probably need an auxiliary data structure that
647 		 * XXX describes relative performances.
648 		 */
649 
650 		cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
651 		if (bootverbose)
652 			printf("crypto: %s registers key alg %u flags %u\n"
653 				, device_get_nameunit(cap->cc_dev)
654 				, kalg
655 				, flags
656 			);
657 		err = 0;
658 	} else
659 		err = EINVAL;
660 
661 	CRYPTO_DRIVER_UNLOCK();
662 	return err;
663 }
664 
665 /*
666  * Register support for a non-key-related algorithm.  This routine
667  * is called once for each such algorithm supported by a driver.
668  */
669 int
670 crypto_register(u_int32_t driverid, int alg, u_int16_t maxoplen,
671     u_int32_t flags)
672 {
673 	struct cryptocap *cap;
674 	int err;
675 
676 	CRYPTO_DRIVER_LOCK();
677 
678 	cap = crypto_checkdriver(driverid);
679 	/* NB: algorithms are in the range [1..max] */
680 	if (cap != NULL &&
681 	    (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX)) {
682 		/*
683 		 * XXX Do some performance testing to determine placing.
684 		 * XXX We probably need an auxiliary data structure that
685 		 * XXX describes relative performances.
686 		 */
687 
688 		cap->cc_alg[alg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
689 		cap->cc_max_op_len[alg] = maxoplen;
690 		if (bootverbose)
691 			printf("crypto: %s registers alg %u flags %u maxoplen %u\n"
692 				, device_get_nameunit(cap->cc_dev)
693 				, alg
694 				, flags
695 				, maxoplen
696 			);
697 		cap->cc_sessions = 0;		/* Unmark */
698 		err = 0;
699 	} else
700 		err = EINVAL;
701 
702 	CRYPTO_DRIVER_UNLOCK();
703 	return err;
704 }
705 
706 static void
707 driver_finis(struct cryptocap *cap)
708 {
709 	u_int32_t ses, kops;
710 
711 	CRYPTO_DRIVER_ASSERT();
712 
713 	ses = cap->cc_sessions;
714 	kops = cap->cc_koperations;
715 	bzero(cap, sizeof(*cap));
716 	if (ses != 0 || kops != 0) {
717 		/*
718 		 * If there are pending sessions,
719 		 * just mark as invalid.
720 		 */
721 		cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
722 		cap->cc_sessions = ses;
723 		cap->cc_koperations = kops;
724 	}
725 }
726 
727 /*
728  * Unregister a crypto driver. If there are pending sessions using it,
729  * leave enough information around so that subsequent calls using those
730  * sessions will correctly detect the driver has been unregistered and
731  * reroute requests.
732  */
733 int
734 crypto_unregister(u_int32_t driverid, int alg)
735 {
736 	struct cryptocap *cap;
737 	int i, err;
738 
739 	CRYPTO_DRIVER_LOCK();
740 	cap = crypto_checkdriver(driverid);
741 	if (cap != NULL &&
742 	    (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX) &&
743 	    cap->cc_alg[alg] != 0) {
744 		cap->cc_alg[alg] = 0;
745 		cap->cc_max_op_len[alg] = 0;
746 
747 		/* Was this the last algorithm ? */
748 		for (i = 1; i <= CRYPTO_ALGORITHM_MAX; i++)
749 			if (cap->cc_alg[i] != 0)
750 				break;
751 
752 		if (i == CRYPTO_ALGORITHM_MAX + 1)
753 			driver_finis(cap);
754 		err = 0;
755 	} else
756 		err = EINVAL;
757 	CRYPTO_DRIVER_UNLOCK();
758 
759 	return err;
760 }
761 
762 /*
763  * Unregister all algorithms associated with a crypto driver.
764  * If there are pending sessions using it, leave enough information
765  * around so that subsequent calls using those sessions will
766  * correctly detect the driver has been unregistered and reroute
767  * requests.
768  */
769 int
770 crypto_unregister_all(u_int32_t driverid)
771 {
772 	struct cryptocap *cap;
773 	int err;
774 
775 	CRYPTO_DRIVER_LOCK();
776 	cap = crypto_checkdriver(driverid);
777 	if (cap != NULL) {
778 		driver_finis(cap);
779 		err = 0;
780 	} else
781 		err = EINVAL;
782 	CRYPTO_DRIVER_UNLOCK();
783 
784 	return err;
785 }
786 
787 /*
788  * Clear blockage on a driver.  The what parameter indicates whether
789  * the driver is now ready for cryptop's and/or cryptokop's.
790  */
791 int
792 crypto_unblock(u_int32_t driverid, int what)
793 {
794 	struct cryptocap *cap;
795 	int err;
796 
797 	CRYPTO_Q_LOCK();
798 	cap = crypto_checkdriver(driverid);
799 	if (cap != NULL) {
800 		if (what & CRYPTO_SYMQ)
801 			cap->cc_qblocked = 0;
802 		if (what & CRYPTO_ASYMQ)
803 			cap->cc_kqblocked = 0;
804 		if (crp_sleep)
805 			wakeup_one(&crp_q);
806 		err = 0;
807 	} else
808 		err = EINVAL;
809 	CRYPTO_Q_UNLOCK();
810 
811 	return err;
812 }
813 
814 /*
815  * Add a crypto request to a queue, to be processed by the kernel thread.
816  */
817 int
818 crypto_dispatch(struct cryptop *crp)
819 {
820 	struct cryptocap *cap;
821 	u_int32_t hid;
822 	int result;
823 
824 	cryptostats.cs_ops++;
825 
826 #ifdef CRYPTO_TIMING
827 	if (crypto_timing)
828 		binuptime(&crp->crp_tstamp);
829 #endif
830 
831 	hid = CRYPTO_SESID2HID(crp->crp_sid);
832 
833 	if ((crp->crp_flags & CRYPTO_F_BATCH) == 0) {
834 		/*
835 		 * Caller marked the request to be processed
836 		 * immediately; dispatch it directly to the
837 		 * driver unless the driver is currently blocked.
838 		 */
839 		cap = crypto_checkdriver(hid);
840 		/* Driver cannot disappeared when there is an active session. */
841 		KASSERT(cap != NULL, ("%s: Driver disappeared.", __func__));
842 		if (!cap->cc_qblocked) {
843 			result = crypto_invoke(cap, crp, 0);
844 			if (result != ERESTART)
845 				return (result);
846 			/*
847 			 * The driver ran out of resources, put the request on
848 			 * the queue.
849 			 */
850 		}
851 	}
852 	CRYPTO_Q_LOCK();
853 	TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
854 	if (crp_sleep)
855 		wakeup_one(&crp_q);
856 	CRYPTO_Q_UNLOCK();
857 	return 0;
858 }
859 
860 /*
861  * Add an asymetric crypto request to a queue,
862  * to be processed by the kernel thread.
863  */
864 int
865 crypto_kdispatch(struct cryptkop *krp)
866 {
867 	int error;
868 
869 	cryptostats.cs_kops++;
870 
871 	error = crypto_kinvoke(krp, krp->krp_crid);
872 	if (error == ERESTART) {
873 		CRYPTO_Q_LOCK();
874 		TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
875 		if (crp_sleep)
876 			wakeup_one(&crp_q);
877 		CRYPTO_Q_UNLOCK();
878 		error = 0;
879 	}
880 	return error;
881 }
882 
883 /*
884  * Verify a driver is suitable for the specified operation.
885  */
886 static __inline int
887 kdriver_suitable(const struct cryptocap *cap, const struct cryptkop *krp)
888 {
889 	return (cap->cc_kalg[krp->krp_op] & CRYPTO_ALG_FLAG_SUPPORTED) != 0;
890 }
891 
892 /*
893  * Select a driver for an asym operation.  The driver must
894  * support the necessary algorithm.  The caller can constrain
895  * which device is selected with the flags parameter.  The
896  * algorithm we use here is pretty stupid; just use the first
897  * driver that supports the algorithms we need. If there are
898  * multiple suitable drivers we choose the driver with the
899  * fewest active operations.  We prefer hardware-backed
900  * drivers to software ones when either may be used.
901  */
902 static struct cryptocap *
903 crypto_select_kdriver(const struct cryptkop *krp, int flags)
904 {
905 	struct cryptocap *cap, *best, *blocked;
906 	int match, hid;
907 
908 	CRYPTO_DRIVER_ASSERT();
909 
910 	/*
911 	 * Look first for hardware crypto devices if permitted.
912 	 */
913 	if (flags & CRYPTOCAP_F_HARDWARE)
914 		match = CRYPTOCAP_F_HARDWARE;
915 	else
916 		match = CRYPTOCAP_F_SOFTWARE;
917 	best = NULL;
918 	blocked = NULL;
919 again:
920 	for (hid = 0; hid < crypto_drivers_num; hid++) {
921 		cap = &crypto_drivers[hid];
922 		/*
923 		 * If it's not initialized, is in the process of
924 		 * going away, or is not appropriate (hardware
925 		 * or software based on match), then skip.
926 		 */
927 		if (cap->cc_dev == NULL ||
928 		    (cap->cc_flags & CRYPTOCAP_F_CLEANUP) ||
929 		    (cap->cc_flags & match) == 0)
930 			continue;
931 
932 		/* verify all the algorithms are supported. */
933 		if (kdriver_suitable(cap, krp)) {
934 			if (best == NULL ||
935 			    cap->cc_koperations < best->cc_koperations)
936 				best = cap;
937 		}
938 	}
939 	if (best != NULL)
940 		return best;
941 	if (match == CRYPTOCAP_F_HARDWARE && (flags & CRYPTOCAP_F_SOFTWARE)) {
942 		/* sort of an Algol 68-style for loop */
943 		match = CRYPTOCAP_F_SOFTWARE;
944 		goto again;
945 	}
946 	return best;
947 }
948 
949 /*
950  * Dispatch an asymmetric crypto request.
951  */
952 static int
953 crypto_kinvoke(struct cryptkop *krp, int crid)
954 {
955 	struct cryptocap *cap = NULL;
956 	int error;
957 
958 	KASSERT(krp != NULL, ("%s: krp == NULL", __func__));
959 	KASSERT(krp->krp_callback != NULL,
960 	    ("%s: krp->crp_callback == NULL", __func__));
961 
962 	CRYPTO_DRIVER_LOCK();
963 	if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
964 		cap = crypto_checkdriver(crid);
965 		if (cap != NULL) {
966 			/*
967 			 * Driver present, it must support the necessary
968 			 * algorithm and, if s/w drivers are excluded,
969 			 * it must be registered as hardware-backed.
970 			 */
971 			if (!kdriver_suitable(cap, krp) ||
972 			    (!crypto_devallowsoft &&
973 			     (cap->cc_flags & CRYPTOCAP_F_HARDWARE) == 0))
974 				cap = NULL;
975 		}
976 	} else {
977 		/*
978 		 * No requested driver; select based on crid flags.
979 		 */
980 		if (!crypto_devallowsoft)	/* NB: disallow s/w drivers */
981 			crid &= ~CRYPTOCAP_F_SOFTWARE;
982 		cap = crypto_select_kdriver(krp, crid);
983 	}
984 	if (cap != NULL && !cap->cc_kqblocked) {
985 		krp->krp_hid = cap - crypto_drivers;
986 		cap->cc_koperations++;
987 		CRYPTO_DRIVER_UNLOCK();
988 		error = CRYPTODEV_KPROCESS(cap->cc_dev, krp, 0);
989 		CRYPTO_DRIVER_LOCK();
990 		if (error == ERESTART) {
991 			cap->cc_koperations--;
992 			CRYPTO_DRIVER_UNLOCK();
993 			return (error);
994 		}
995 	} else {
996 		/*
997 		 * NB: cap is !NULL if device is blocked; in
998 		 *     that case return ERESTART so the operation
999 		 *     is resubmitted if possible.
1000 		 */
1001 		error = (cap == NULL) ? ENODEV : ERESTART;
1002 	}
1003 	CRYPTO_DRIVER_UNLOCK();
1004 
1005 	if (error) {
1006 		krp->krp_status = error;
1007 		crypto_kdone(krp);
1008 	}
1009 	return 0;
1010 }
1011 
1012 #ifdef CRYPTO_TIMING
1013 static void
1014 crypto_tstat(struct cryptotstat *ts, struct bintime *bt)
1015 {
1016 	struct bintime now, delta;
1017 	struct timespec t;
1018 	uint64_t u;
1019 
1020 	binuptime(&now);
1021 	u = now.frac;
1022 	delta.frac = now.frac - bt->frac;
1023 	delta.sec = now.sec - bt->sec;
1024 	if (u < delta.frac)
1025 		delta.sec--;
1026 	bintime2timespec(&delta, &t);
1027 	timespecadd(&ts->acc, &t);
1028 	if (timespeccmp(&t, &ts->min, <))
1029 		ts->min = t;
1030 	if (timespeccmp(&t, &ts->max, >))
1031 		ts->max = t;
1032 	ts->count++;
1033 
1034 	*bt = now;
1035 }
1036 #endif
1037 
1038 /*
1039  * Dispatch a crypto request to the appropriate crypto devices.
1040  */
1041 static int
1042 crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint)
1043 {
1044 
1045 	KASSERT(crp != NULL, ("%s: crp == NULL", __func__));
1046 	KASSERT(crp->crp_callback != NULL,
1047 	    ("%s: crp->crp_callback == NULL", __func__));
1048 	KASSERT(crp->crp_desc != NULL, ("%s: crp->crp_desc == NULL", __func__));
1049 
1050 #ifdef CRYPTO_TIMING
1051 	if (crypto_timing)
1052 		crypto_tstat(&cryptostats.cs_invoke, &crp->crp_tstamp);
1053 #endif
1054 	if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1055 		struct cryptodesc *crd;
1056 		u_int64_t nid;
1057 
1058 		/*
1059 		 * Driver has unregistered; migrate the session and return
1060 		 * an error to the caller so they'll resubmit the op.
1061 		 *
1062 		 * XXX: What if there are more already queued requests for this
1063 		 *      session?
1064 		 */
1065 		crypto_freesession(crp->crp_sid);
1066 
1067 		for (crd = crp->crp_desc; crd->crd_next; crd = crd->crd_next)
1068 			crd->CRD_INI.cri_next = &(crd->crd_next->CRD_INI);
1069 
1070 		/* XXX propagate flags from initial session? */
1071 		if (crypto_newsession(&nid, &(crp->crp_desc->CRD_INI),
1072 		    CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE) == 0)
1073 			crp->crp_sid = nid;
1074 
1075 		crp->crp_etype = EAGAIN;
1076 		crypto_done(crp);
1077 		return 0;
1078 	} else {
1079 		/*
1080 		 * Invoke the driver to process the request.
1081 		 */
1082 		return CRYPTODEV_PROCESS(cap->cc_dev, crp, hint);
1083 	}
1084 }
1085 
1086 /*
1087  * Release a set of crypto descriptors.
1088  */
1089 void
1090 crypto_freereq(struct cryptop *crp)
1091 {
1092 	struct cryptodesc *crd;
1093 
1094 	if (crp == NULL)
1095 		return;
1096 
1097 #ifdef DIAGNOSTIC
1098 	{
1099 		struct cryptop *crp2;
1100 
1101 		CRYPTO_Q_LOCK();
1102 		TAILQ_FOREACH(crp2, &crp_q, crp_next) {
1103 			KASSERT(crp2 != crp,
1104 			    ("Freeing cryptop from the crypto queue (%p).",
1105 			    crp));
1106 		}
1107 		CRYPTO_Q_UNLOCK();
1108 		CRYPTO_RETQ_LOCK();
1109 		TAILQ_FOREACH(crp2, &crp_ret_q, crp_next) {
1110 			KASSERT(crp2 != crp,
1111 			    ("Freeing cryptop from the return queue (%p).",
1112 			    crp));
1113 		}
1114 		CRYPTO_RETQ_UNLOCK();
1115 	}
1116 #endif
1117 
1118 	while ((crd = crp->crp_desc) != NULL) {
1119 		crp->crp_desc = crd->crd_next;
1120 		uma_zfree(cryptodesc_zone, crd);
1121 	}
1122 	uma_zfree(cryptop_zone, crp);
1123 }
1124 
1125 /*
1126  * Acquire a set of crypto descriptors.
1127  */
1128 struct cryptop *
1129 crypto_getreq(int num)
1130 {
1131 	struct cryptodesc *crd;
1132 	struct cryptop *crp;
1133 
1134 	crp = uma_zalloc(cryptop_zone, M_NOWAIT|M_ZERO);
1135 	if (crp != NULL) {
1136 		while (num--) {
1137 			crd = uma_zalloc(cryptodesc_zone, M_NOWAIT|M_ZERO);
1138 			if (crd == NULL) {
1139 				crypto_freereq(crp);
1140 				return NULL;
1141 			}
1142 
1143 			crd->crd_next = crp->crp_desc;
1144 			crp->crp_desc = crd;
1145 		}
1146 	}
1147 	return crp;
1148 }
1149 
1150 /*
1151  * Invoke the callback on behalf of the driver.
1152  */
1153 void
1154 crypto_done(struct cryptop *crp)
1155 {
1156 	KASSERT((crp->crp_flags & CRYPTO_F_DONE) == 0,
1157 		("crypto_done: op already done, flags 0x%x", crp->crp_flags));
1158 	crp->crp_flags |= CRYPTO_F_DONE;
1159 	if (crp->crp_etype != 0)
1160 		cryptostats.cs_errs++;
1161 #ifdef CRYPTO_TIMING
1162 	if (crypto_timing)
1163 		crypto_tstat(&cryptostats.cs_done, &crp->crp_tstamp);
1164 #endif
1165 	/*
1166 	 * CBIMM means unconditionally do the callback immediately;
1167 	 * CBIFSYNC means do the callback immediately only if the
1168 	 * operation was done synchronously.  Both are used to avoid
1169 	 * doing extraneous context switches; the latter is mostly
1170 	 * used with the software crypto driver.
1171 	 */
1172 	if ((crp->crp_flags & CRYPTO_F_CBIMM) ||
1173 	    ((crp->crp_flags & CRYPTO_F_CBIFSYNC) &&
1174 	     (CRYPTO_SESID2CAPS(crp->crp_sid) & CRYPTOCAP_F_SYNC))) {
1175 		/*
1176 		 * Do the callback directly.  This is ok when the
1177 		 * callback routine does very little (e.g. the
1178 		 * /dev/crypto callback method just does a wakeup).
1179 		 */
1180 #ifdef CRYPTO_TIMING
1181 		if (crypto_timing) {
1182 			/*
1183 			 * NB: We must copy the timestamp before
1184 			 * doing the callback as the cryptop is
1185 			 * likely to be reclaimed.
1186 			 */
1187 			struct bintime t = crp->crp_tstamp;
1188 			crypto_tstat(&cryptostats.cs_cb, &t);
1189 			crp->crp_callback(crp);
1190 			crypto_tstat(&cryptostats.cs_finis, &t);
1191 		} else
1192 #endif
1193 			crp->crp_callback(crp);
1194 	} else {
1195 		/*
1196 		 * Normal case; queue the callback for the thread.
1197 		 */
1198 		CRYPTO_RETQ_LOCK();
1199 		if (CRYPTO_RETQ_EMPTY())
1200 			wakeup_one(&crp_ret_q);	/* shared wait channel */
1201 		TAILQ_INSERT_TAIL(&crp_ret_q, crp, crp_next);
1202 		CRYPTO_RETQ_UNLOCK();
1203 	}
1204 }
1205 
1206 /*
1207  * Invoke the callback on behalf of the driver.
1208  */
1209 void
1210 crypto_kdone(struct cryptkop *krp)
1211 {
1212 	struct cryptocap *cap;
1213 
1214 	if (krp->krp_status != 0)
1215 		cryptostats.cs_kerrs++;
1216 	CRYPTO_DRIVER_LOCK();
1217 	/* XXX: What if driver is loaded in the meantime? */
1218 	if (krp->krp_hid < crypto_drivers_num) {
1219 		cap = &crypto_drivers[krp->krp_hid];
1220 		KASSERT(cap->cc_koperations > 0, ("cc_koperations == 0"));
1221 		cap->cc_koperations--;
1222 		if (cap->cc_flags & CRYPTOCAP_F_CLEANUP)
1223 			crypto_remove(cap);
1224 	}
1225 	CRYPTO_DRIVER_UNLOCK();
1226 	CRYPTO_RETQ_LOCK();
1227 	if (CRYPTO_RETQ_EMPTY())
1228 		wakeup_one(&crp_ret_q);		/* shared wait channel */
1229 	TAILQ_INSERT_TAIL(&crp_ret_kq, krp, krp_next);
1230 	CRYPTO_RETQ_UNLOCK();
1231 }
1232 
1233 int
1234 crypto_getfeat(int *featp)
1235 {
1236 	int hid, kalg, feat = 0;
1237 
1238 	CRYPTO_DRIVER_LOCK();
1239 	for (hid = 0; hid < crypto_drivers_num; hid++) {
1240 		const struct cryptocap *cap = &crypto_drivers[hid];
1241 
1242 		if ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
1243 		    !crypto_devallowsoft) {
1244 			continue;
1245 		}
1246 		for (kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
1247 			if (cap->cc_kalg[kalg] & CRYPTO_ALG_FLAG_SUPPORTED)
1248 				feat |=  1 << kalg;
1249 	}
1250 	CRYPTO_DRIVER_UNLOCK();
1251 	*featp = feat;
1252 	return (0);
1253 }
1254 
1255 /*
1256  * Terminate a thread at module unload.  The process that
1257  * initiated this is waiting for us to signal that we're gone;
1258  * wake it up and exit.  We use the driver table lock to insure
1259  * we don't do the wakeup before they're waiting.  There is no
1260  * race here because the waiter sleeps on the proc lock for the
1261  * thread so it gets notified at the right time because of an
1262  * extra wakeup that's done in exit1().
1263  */
1264 static void
1265 crypto_finis(void *chan)
1266 {
1267 	CRYPTO_DRIVER_LOCK();
1268 	wakeup_one(chan);
1269 	CRYPTO_DRIVER_UNLOCK();
1270 	kproc_exit(0);
1271 }
1272 
1273 /*
1274  * Crypto thread, dispatches crypto requests.
1275  */
1276 static void
1277 crypto_proc(void)
1278 {
1279 	struct cryptop *crp, *submit;
1280 	struct cryptkop *krp;
1281 	struct cryptocap *cap;
1282 	u_int32_t hid;
1283 	int result, hint;
1284 
1285 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
1286 	fpu_kern_thread(FPU_KERN_NORMAL);
1287 #endif
1288 
1289 	CRYPTO_Q_LOCK();
1290 	for (;;) {
1291 		/*
1292 		 * Find the first element in the queue that can be
1293 		 * processed and look-ahead to see if multiple ops
1294 		 * are ready for the same driver.
1295 		 */
1296 		submit = NULL;
1297 		hint = 0;
1298 		TAILQ_FOREACH(crp, &crp_q, crp_next) {
1299 			hid = CRYPTO_SESID2HID(crp->crp_sid);
1300 			cap = crypto_checkdriver(hid);
1301 			/*
1302 			 * Driver cannot disappeared when there is an active
1303 			 * session.
1304 			 */
1305 			KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1306 			    __func__, __LINE__));
1307 			if (cap == NULL || cap->cc_dev == NULL) {
1308 				/* Op needs to be migrated, process it. */
1309 				if (submit == NULL)
1310 					submit = crp;
1311 				break;
1312 			}
1313 			if (!cap->cc_qblocked) {
1314 				if (submit != NULL) {
1315 					/*
1316 					 * We stop on finding another op,
1317 					 * regardless whether its for the same
1318 					 * driver or not.  We could keep
1319 					 * searching the queue but it might be
1320 					 * better to just use a per-driver
1321 					 * queue instead.
1322 					 */
1323 					if (CRYPTO_SESID2HID(submit->crp_sid) == hid)
1324 						hint = CRYPTO_HINT_MORE;
1325 					break;
1326 				} else {
1327 					submit = crp;
1328 					if ((submit->crp_flags & CRYPTO_F_BATCH) == 0)
1329 						break;
1330 					/* keep scanning for more are q'd */
1331 				}
1332 			}
1333 		}
1334 		if (submit != NULL) {
1335 			TAILQ_REMOVE(&crp_q, submit, crp_next);
1336 			hid = CRYPTO_SESID2HID(submit->crp_sid);
1337 			cap = crypto_checkdriver(hid);
1338 			KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1339 			    __func__, __LINE__));
1340 			result = crypto_invoke(cap, submit, hint);
1341 			if (result == ERESTART) {
1342 				/*
1343 				 * The driver ran out of resources, mark the
1344 				 * driver ``blocked'' for cryptop's and put
1345 				 * the request back in the queue.  It would
1346 				 * best to put the request back where we got
1347 				 * it but that's hard so for now we put it
1348 				 * at the front.  This should be ok; putting
1349 				 * it at the end does not work.
1350 				 */
1351 				/* XXX validate sid again? */
1352 				crypto_drivers[CRYPTO_SESID2HID(submit->crp_sid)].cc_qblocked = 1;
1353 				TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
1354 				cryptostats.cs_blocks++;
1355 			}
1356 		}
1357 
1358 		/* As above, but for key ops */
1359 		TAILQ_FOREACH(krp, &crp_kq, krp_next) {
1360 			cap = crypto_checkdriver(krp->krp_hid);
1361 			if (cap == NULL || cap->cc_dev == NULL) {
1362 				/*
1363 				 * Operation needs to be migrated, invalidate
1364 				 * the assigned device so it will reselect a
1365 				 * new one below.  Propagate the original
1366 				 * crid selection flags if supplied.
1367 				 */
1368 				krp->krp_hid = krp->krp_crid &
1369 				    (CRYPTOCAP_F_SOFTWARE|CRYPTOCAP_F_HARDWARE);
1370 				if (krp->krp_hid == 0)
1371 					krp->krp_hid =
1372 				    CRYPTOCAP_F_SOFTWARE|CRYPTOCAP_F_HARDWARE;
1373 				break;
1374 			}
1375 			if (!cap->cc_kqblocked)
1376 				break;
1377 		}
1378 		if (krp != NULL) {
1379 			TAILQ_REMOVE(&crp_kq, krp, krp_next);
1380 			result = crypto_kinvoke(krp, krp->krp_hid);
1381 			if (result == ERESTART) {
1382 				/*
1383 				 * The driver ran out of resources, mark the
1384 				 * driver ``blocked'' for cryptkop's and put
1385 				 * the request back in the queue.  It would
1386 				 * best to put the request back where we got
1387 				 * it but that's hard so for now we put it
1388 				 * at the front.  This should be ok; putting
1389 				 * it at the end does not work.
1390 				 */
1391 				/* XXX validate sid again? */
1392 				crypto_drivers[krp->krp_hid].cc_kqblocked = 1;
1393 				TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
1394 				cryptostats.cs_kblocks++;
1395 			}
1396 		}
1397 
1398 		if (submit == NULL && krp == NULL) {
1399 			/*
1400 			 * Nothing more to be processed.  Sleep until we're
1401 			 * woken because there are more ops to process.
1402 			 * This happens either by submission or by a driver
1403 			 * becoming unblocked and notifying us through
1404 			 * crypto_unblock.  Note that when we wakeup we
1405 			 * start processing each queue again from the
1406 			 * front. It's not clear that it's important to
1407 			 * preserve this ordering since ops may finish
1408 			 * out of order if dispatched to different devices
1409 			 * and some become blocked while others do not.
1410 			 */
1411 			crp_sleep = 1;
1412 			msleep(&crp_q, &crypto_q_mtx, PWAIT, "crypto_wait", 0);
1413 			crp_sleep = 0;
1414 			if (cryptoproc == NULL)
1415 				break;
1416 			cryptostats.cs_intrs++;
1417 		}
1418 	}
1419 	CRYPTO_Q_UNLOCK();
1420 
1421 	crypto_finis(&crp_q);
1422 }
1423 
1424 /*
1425  * Crypto returns thread, does callbacks for processed crypto requests.
1426  * Callbacks are done here, rather than in the crypto drivers, because
1427  * callbacks typically are expensive and would slow interrupt handling.
1428  */
1429 static void
1430 crypto_ret_proc(void)
1431 {
1432 	struct cryptop *crpt;
1433 	struct cryptkop *krpt;
1434 
1435 	CRYPTO_RETQ_LOCK();
1436 	for (;;) {
1437 		/* Harvest return q's for completed ops */
1438 		crpt = TAILQ_FIRST(&crp_ret_q);
1439 		if (crpt != NULL)
1440 			TAILQ_REMOVE(&crp_ret_q, crpt, crp_next);
1441 
1442 		krpt = TAILQ_FIRST(&crp_ret_kq);
1443 		if (krpt != NULL)
1444 			TAILQ_REMOVE(&crp_ret_kq, krpt, krp_next);
1445 
1446 		if (crpt != NULL || krpt != NULL) {
1447 			CRYPTO_RETQ_UNLOCK();
1448 			/*
1449 			 * Run callbacks unlocked.
1450 			 */
1451 			if (crpt != NULL) {
1452 #ifdef CRYPTO_TIMING
1453 				if (crypto_timing) {
1454 					/*
1455 					 * NB: We must copy the timestamp before
1456 					 * doing the callback as the cryptop is
1457 					 * likely to be reclaimed.
1458 					 */
1459 					struct bintime t = crpt->crp_tstamp;
1460 					crypto_tstat(&cryptostats.cs_cb, &t);
1461 					crpt->crp_callback(crpt);
1462 					crypto_tstat(&cryptostats.cs_finis, &t);
1463 				} else
1464 #endif
1465 					crpt->crp_callback(crpt);
1466 			}
1467 			if (krpt != NULL)
1468 				krpt->krp_callback(krpt);
1469 			CRYPTO_RETQ_LOCK();
1470 		} else {
1471 			/*
1472 			 * Nothing more to be processed.  Sleep until we're
1473 			 * woken because there are more returns to process.
1474 			 */
1475 			msleep(&crp_ret_q, &crypto_ret_q_mtx, PWAIT,
1476 				"crypto_ret_wait", 0);
1477 			if (cryptoretproc == NULL)
1478 				break;
1479 			cryptostats.cs_rets++;
1480 		}
1481 	}
1482 	CRYPTO_RETQ_UNLOCK();
1483 
1484 	crypto_finis(&crp_ret_q);
1485 }
1486 
1487 #ifdef DDB
1488 static void
1489 db_show_drivers(void)
1490 {
1491 	int hid;
1492 
1493 	db_printf("%12s %4s %4s %8s %2s %2s\n"
1494 		, "Device"
1495 		, "Ses"
1496 		, "Kops"
1497 		, "Flags"
1498 		, "QB"
1499 		, "KB"
1500 	);
1501 	for (hid = 0; hid < crypto_drivers_num; hid++) {
1502 		const struct cryptocap *cap = &crypto_drivers[hid];
1503 		if (cap->cc_dev == NULL)
1504 			continue;
1505 		db_printf("%-12s %4u %4u %08x %2u %2u\n"
1506 		    , device_get_nameunit(cap->cc_dev)
1507 		    , cap->cc_sessions
1508 		    , cap->cc_koperations
1509 		    , cap->cc_flags
1510 		    , cap->cc_qblocked
1511 		    , cap->cc_kqblocked
1512 		);
1513 	}
1514 }
1515 
1516 DB_SHOW_COMMAND(crypto, db_show_crypto)
1517 {
1518 	struct cryptop *crp;
1519 
1520 	db_show_drivers();
1521 	db_printf("\n");
1522 
1523 	db_printf("%4s %8s %4s %4s %4s %4s %8s %8s\n",
1524 	    "HID", "Caps", "Ilen", "Olen", "Etype", "Flags",
1525 	    "Desc", "Callback");
1526 	TAILQ_FOREACH(crp, &crp_q, crp_next) {
1527 		db_printf("%4u %08x %4u %4u %4u %04x %8p %8p\n"
1528 		    , (int) CRYPTO_SESID2HID(crp->crp_sid)
1529 		    , (int) CRYPTO_SESID2CAPS(crp->crp_sid)
1530 		    , crp->crp_ilen, crp->crp_olen
1531 		    , crp->crp_etype
1532 		    , crp->crp_flags
1533 		    , crp->crp_desc
1534 		    , crp->crp_callback
1535 		);
1536 	}
1537 	if (!TAILQ_EMPTY(&crp_ret_q)) {
1538 		db_printf("\n%4s %4s %4s %8s\n",
1539 		    "HID", "Etype", "Flags", "Callback");
1540 		TAILQ_FOREACH(crp, &crp_ret_q, crp_next) {
1541 			db_printf("%4u %4u %04x %8p\n"
1542 			    , (int) CRYPTO_SESID2HID(crp->crp_sid)
1543 			    , crp->crp_etype
1544 			    , crp->crp_flags
1545 			    , crp->crp_callback
1546 			);
1547 		}
1548 	}
1549 }
1550 
1551 DB_SHOW_COMMAND(kcrypto, db_show_kcrypto)
1552 {
1553 	struct cryptkop *krp;
1554 
1555 	db_show_drivers();
1556 	db_printf("\n");
1557 
1558 	db_printf("%4s %5s %4s %4s %8s %4s %8s\n",
1559 	    "Op", "Status", "#IP", "#OP", "CRID", "HID", "Callback");
1560 	TAILQ_FOREACH(krp, &crp_kq, krp_next) {
1561 		db_printf("%4u %5u %4u %4u %08x %4u %8p\n"
1562 		    , krp->krp_op
1563 		    , krp->krp_status
1564 		    , krp->krp_iparams, krp->krp_oparams
1565 		    , krp->krp_crid, krp->krp_hid
1566 		    , krp->krp_callback
1567 		);
1568 	}
1569 	if (!TAILQ_EMPTY(&crp_ret_q)) {
1570 		db_printf("%4s %5s %8s %4s %8s\n",
1571 		    "Op", "Status", "CRID", "HID", "Callback");
1572 		TAILQ_FOREACH(krp, &crp_ret_kq, krp_next) {
1573 			db_printf("%4u %5u %08x %4u %8p\n"
1574 			    , krp->krp_op
1575 			    , krp->krp_status
1576 			    , krp->krp_crid, krp->krp_hid
1577 			    , krp->krp_callback
1578 			);
1579 		}
1580 	}
1581 }
1582 #endif
1583 
1584 int crypto_modevent(module_t mod, int type, void *unused);
1585 
1586 /*
1587  * Initialization code, both for static and dynamic loading.
1588  * Note this is not invoked with the usual MODULE_DECLARE
1589  * mechanism but instead is listed as a dependency by the
1590  * cryptosoft driver.  This guarantees proper ordering of
1591  * calls on module load/unload.
1592  */
1593 int
1594 crypto_modevent(module_t mod, int type, void *unused)
1595 {
1596 	int error = EINVAL;
1597 
1598 	switch (type) {
1599 	case MOD_LOAD:
1600 		error = crypto_init();
1601 		if (error == 0 && bootverbose)
1602 			printf("crypto: <crypto core>\n");
1603 		break;
1604 	case MOD_UNLOAD:
1605 		/*XXX disallow if active sessions */
1606 		error = 0;
1607 		crypto_destroy();
1608 		return 0;
1609 	}
1610 	return error;
1611 }
1612 MODULE_VERSION(crypto, 1);
1613 MODULE_DEPEND(crypto, zlib, 1, 1, 1);
1614