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