xref: /netbsd-src/sys/opencrypto/crypto.c (revision 46f5119e40af2e51998f686b2fdcc76b5488f7f3)
1 /*	$NetBSD: crypto.c,v 1.39 2011/05/06 21:48:46 drochner Exp $ */
2 /*	$FreeBSD: src/sys/opencrypto/crypto.c,v 1.4.2.5 2003/02/26 00:14:05 sam Exp $	*/
3 /*	$OpenBSD: crypto.c,v 1.41 2002/07/17 23:52:38 art Exp $	*/
4 
5 /*-
6  * Copyright (c) 2008 The NetBSD Foundation, Inc.
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to The NetBSD Foundation
10  * by Coyote Point Systems, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 /*
35  * The author of this code is Angelos D. Keromytis (angelos@cis.upenn.edu)
36  *
37  * This code was written by Angelos D. Keromytis in Athens, Greece, in
38  * February 2000. Network Security Technologies Inc. (NSTI) kindly
39  * supported the development of this code.
40  *
41  * Copyright (c) 2000, 2001 Angelos D. Keromytis
42  *
43  * Permission to use, copy, and modify this software with or without fee
44  * is hereby granted, provided that this entire notice is included in
45  * all source code copies of any software which is or includes a copy or
46  * modification of this software.
47  *
48  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
49  * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
50  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
51  * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
52  * PURPOSE.
53  */
54 
55 #include <sys/cdefs.h>
56 __KERNEL_RCSID(0, "$NetBSD: crypto.c,v 1.39 2011/05/06 21:48:46 drochner Exp $");
57 
58 #include <sys/param.h>
59 #include <sys/reboot.h>
60 #include <sys/systm.h>
61 #include <sys/malloc.h>
62 #include <sys/proc.h>
63 #include <sys/pool.h>
64 #include <sys/kthread.h>
65 #include <sys/once.h>
66 #include <sys/sysctl.h>
67 #include <sys/intr.h>
68 
69 #include "opt_ocf.h"
70 #include <opencrypto/cryptodev.h>
71 #include <opencrypto/xform.h>			/* XXX for M_XDATA */
72 
73 kcondvar_t cryptoret_cv;
74 kmutex_t crypto_mtx;
75 
76 /* below are kludges for residual code wrtitten to FreeBSD interfaces */
77   #define SWI_CRYPTO 17
78   #define register_swi(lvl, fn)  \
79   softint_establish(SOFTINT_NET|SOFTINT_MPSAFE, (void (*)(void *))fn, NULL)
80   #define unregister_swi(lvl, fn)  softint_disestablish(softintr_cookie)
81   #define setsoftcrypto(x) softint_schedule(x)
82 
83 int crypto_ret_q_check(struct cryptop *);
84 
85 /*
86  * Crypto drivers register themselves by allocating a slot in the
87  * crypto_drivers table with crypto_get_driverid() and then registering
88  * each algorithm they support with crypto_register() and crypto_kregister().
89  */
90 static	struct cryptocap *crypto_drivers;
91 static	int crypto_drivers_num;
92 static	void *softintr_cookie;
93 
94 /*
95  * There are two queues for crypto requests; one for symmetric (e.g.
96  * cipher) operations and one for asymmetric (e.g. MOD) operations.
97  * See below for how synchronization is handled.
98  */
99 static	TAILQ_HEAD(,cryptop) crp_q =		/* request queues */
100 		TAILQ_HEAD_INITIALIZER(crp_q);
101 static	TAILQ_HEAD(,cryptkop) crp_kq =
102 		TAILQ_HEAD_INITIALIZER(crp_kq);
103 
104 /*
105  * There are two queues for processing completed crypto requests; one
106  * for the symmetric and one for the asymmetric ops.  We only need one
107  * but have two to avoid type futzing (cryptop vs. cryptkop).  See below
108  * for how synchronization is handled.
109  */
110 static	TAILQ_HEAD(crprethead, cryptop) crp_ret_q =	/* callback queues */
111 		TAILQ_HEAD_INITIALIZER(crp_ret_q);
112 static	TAILQ_HEAD(krprethead, cryptkop) crp_ret_kq =
113 		TAILQ_HEAD_INITIALIZER(crp_ret_kq);
114 
115 /*
116  * XXX these functions are ghastly hacks for when the submission
117  * XXX routines discover a request that was not CBIMM is already
118  * XXX done, and must be yanked from the retq (where _done) put it
119  * XXX as cryptoret won't get the chance.  The queue is walked backwards
120  * XXX as the request is generally the last one queued.
121  *
122  *	 call with the lock held, or else.
123  */
124 int
125 crypto_ret_q_remove(struct cryptop *crp)
126 {
127 	struct cryptop * acrp, *next;
128 
129 	TAILQ_FOREACH_REVERSE_SAFE(acrp, &crp_ret_q, crprethead, crp_next, next) {
130 		if (acrp == crp) {
131 			TAILQ_REMOVE(&crp_ret_q, crp, crp_next);
132 			crp->crp_flags &= (~CRYPTO_F_ONRETQ);
133 			return 1;
134 		}
135 	}
136 	return 0;
137 }
138 
139 int
140 crypto_ret_kq_remove(struct cryptkop *krp)
141 {
142 	struct cryptkop * akrp, *next;
143 
144 	TAILQ_FOREACH_REVERSE_SAFE(akrp, &crp_ret_kq, krprethead, krp_next, next) {
145 		if (akrp == krp) {
146 			TAILQ_REMOVE(&crp_ret_kq, krp, krp_next);
147 			krp->krp_flags &= (~CRYPTO_F_ONRETQ);
148 			return 1;
149 		}
150 	}
151 	return 0;
152 }
153 
154 /*
155  * Crypto op and desciptor data structures are allocated
156  * from separate private zones(FreeBSD)/pools(netBSD/OpenBSD) .
157  */
158 struct pool cryptop_pool;
159 struct pool cryptodesc_pool;
160 struct pool cryptkop_pool;
161 
162 int	crypto_usercrypto = 1;		/* userland may open /dev/crypto */
163 int	crypto_userasymcrypto = 1;	/* userland may do asym crypto reqs */
164 /*
165  * cryptodevallowsoft is (intended to be) sysctl'able, controlling
166  * access to hardware versus software transforms as below:
167  *
168  * crypto_devallowsoft < 0:  Force userlevel requests to use software
169  *                              transforms, always
170  * crypto_devallowsoft = 0:  Use hardware if present, grant userlevel
171  *                              requests for non-accelerated transforms
172  *                              (handling the latter in software)
173  * crypto_devallowsoft > 0:  Allow user requests only for transforms which
174  *                               are hardware-accelerated.
175  */
176 int	crypto_devallowsoft = 1;	/* only use hardware crypto */
177 
178 SYSCTL_SETUP(sysctl_opencrypto_setup, "sysctl opencrypto subtree setup")
179 {
180 	sysctl_createv(clog, 0, NULL, NULL,
181 		       CTLFLAG_PERMANENT,
182 		       CTLTYPE_NODE, "kern", NULL,
183 		       NULL, 0, NULL, 0,
184 		       CTL_KERN, CTL_EOL);
185 	sysctl_createv(clog, 0, NULL, NULL,
186 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
187 		       CTLTYPE_INT, "usercrypto",
188 		       SYSCTL_DESCR("Enable/disable user-mode access to "
189 			   "crypto support"),
190 		       NULL, 0, &crypto_usercrypto, 0,
191 		       CTL_KERN, CTL_CREATE, CTL_EOL);
192 	sysctl_createv(clog, 0, NULL, NULL,
193 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
194 		       CTLTYPE_INT, "userasymcrypto",
195 		       SYSCTL_DESCR("Enable/disable user-mode access to "
196 			   "asymmetric crypto support"),
197 		       NULL, 0, &crypto_userasymcrypto, 0,
198 		       CTL_KERN, CTL_CREATE, CTL_EOL);
199 	sysctl_createv(clog, 0, NULL, NULL,
200 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
201 		       CTLTYPE_INT, "cryptodevallowsoft",
202 		       SYSCTL_DESCR("Enable/disable use of software "
203 			   "asymmetric crypto support"),
204 		       NULL, 0, &crypto_devallowsoft, 0,
205 		       CTL_KERN, CTL_CREATE, CTL_EOL);
206 }
207 
208 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
209 
210 /*
211  * Synchronization: read carefully, this is non-trivial.
212  *
213  * Crypto requests are submitted via crypto_dispatch.  Typically
214  * these come in from network protocols at spl0 (output path) or
215  * spl[,soft]net (input path).
216  *
217  * Requests are typically passed on the driver directly, but they
218  * may also be queued for processing by a software interrupt thread,
219  * cryptointr, that runs at splsoftcrypto.  This thread dispatches
220  * the requests to crypto drivers (h/w or s/w) who call crypto_done
221  * when a request is complete.  Hardware crypto drivers are assumed
222  * to register their IRQ's as network devices so their interrupt handlers
223  * and subsequent "done callbacks" happen at spl[imp,net].
224  *
225  * Completed crypto ops are queued for a separate kernel thread that
226  * handles the callbacks at spl0.  This decoupling insures the crypto
227  * driver interrupt service routine is not delayed while the callback
228  * takes place and that callbacks are delivered after a context switch
229  * (as opposed to a software interrupt that clients must block).
230  *
231  * This scheme is not intended for SMP machines.
232  */
233 static	void cryptointr(void);		/* swi thread to dispatch ops */
234 static	void cryptoret(void);		/* kernel thread for callbacks*/
235 static	struct lwp *cryptothread;
236 static	void crypto_destroy(void);
237 static	int crypto_invoke(struct cryptop *crp, int hint);
238 static	int crypto_kinvoke(struct cryptkop *krp, int hint);
239 
240 static struct cryptostats cryptostats;
241 #ifdef CRYPTO_TIMING
242 static	int crypto_timing = 0;
243 #endif
244 
245 static int
246 crypto_init0(void)
247 {
248 	int error;
249 
250 	mutex_init(&crypto_mtx, MUTEX_DEFAULT, IPL_NET);
251 	cv_init(&cryptoret_cv, "crypto_w");
252 	pool_init(&cryptop_pool, sizeof(struct cryptop), 0, 0,
253 		  0, "cryptop", NULL, IPL_NET);
254 	pool_init(&cryptodesc_pool, sizeof(struct cryptodesc), 0, 0,
255 		  0, "cryptodesc", NULL, IPL_NET);
256 	pool_init(&cryptkop_pool, sizeof(struct cryptkop), 0, 0,
257 		  0, "cryptkop", NULL, IPL_NET);
258 
259 	crypto_drivers = malloc(CRYPTO_DRIVERS_INITIAL *
260 	    sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT | M_ZERO);
261 	if (crypto_drivers == NULL) {
262 		printf("crypto_init: cannot malloc driver table\n");
263 		return 0;
264 	}
265 	crypto_drivers_num = CRYPTO_DRIVERS_INITIAL;
266 
267 	softintr_cookie = register_swi(SWI_CRYPTO, cryptointr);
268 	error = kthread_create(PRI_NONE, KTHREAD_MPSAFE, NULL,
269 	    (void (*)(void *))cryptoret, NULL, &cryptothread, "cryptoret");
270 	if (error) {
271 		printf("crypto_init: cannot start cryptoret thread; error %d",
272 			error);
273 		crypto_destroy();
274 	}
275 
276 	return 0;
277 }
278 
279 void
280 crypto_init(void)
281 {
282 	static ONCE_DECL(crypto_init_once);
283 
284 	RUN_ONCE(&crypto_init_once, crypto_init0);
285 }
286 
287 static void
288 crypto_destroy(void)
289 {
290 	/* XXX no wait to reclaim zones */
291 	if (crypto_drivers != NULL)
292 		free(crypto_drivers, M_CRYPTO_DATA);
293 	unregister_swi(SWI_CRYPTO, cryptointr);
294 }
295 
296 /*
297  * Create a new session.  Must be called with crypto_mtx held.
298  */
299 int
300 crypto_newsession(u_int64_t *sid, struct cryptoini *cri, int hard)
301 {
302 	struct cryptoini *cr;
303 	u_int32_t hid, lid;
304 	int err = EINVAL;
305 
306 	mutex_spin_enter(&crypto_mtx);
307 
308 	if (crypto_drivers == NULL)
309 		goto done;
310 
311 	/*
312 	 * The algorithm we use here is pretty stupid; just use the
313 	 * first driver that supports all the algorithms we need.
314 	 *
315 	 * XXX We need more smarts here (in real life too, but that's
316 	 * XXX another story altogether).
317 	 */
318 
319 	for (hid = 0; hid < crypto_drivers_num; hid++) {
320 		/*
321 		 * If it's not initialized or has remaining sessions
322 		 * referencing it, skip.
323 		 */
324 		if (crypto_drivers[hid].cc_newsession == NULL ||
325 		    (crypto_drivers[hid].cc_flags & CRYPTOCAP_F_CLEANUP))
326 			continue;
327 
328 		/* Hardware required -- ignore software drivers. */
329 		if (hard > 0 &&
330 		    (crypto_drivers[hid].cc_flags & CRYPTOCAP_F_SOFTWARE))
331 			continue;
332 		/* Software required -- ignore hardware drivers. */
333 		if (hard < 0 &&
334 		    (crypto_drivers[hid].cc_flags & CRYPTOCAP_F_SOFTWARE) == 0)
335 			continue;
336 
337 		/* See if all the algorithms are supported. */
338 		for (cr = cri; cr; cr = cr->cri_next)
339 			if (crypto_drivers[hid].cc_alg[cr->cri_alg] == 0) {
340 				DPRINTF(("crypto_newsession: alg %d not supported\n", cr->cri_alg));
341 				break;
342 			}
343 
344 		if (cr == NULL) {
345 			/* Ok, all algorithms are supported. */
346 
347 			/*
348 			 * Can't do everything in one session.
349 			 *
350 			 * XXX Fix this. We need to inject a "virtual" session layer right
351 			 * XXX about here.
352 			 */
353 
354 			/* Call the driver initialization routine. */
355 			lid = hid;		/* Pass the driver ID. */
356 			err = crypto_drivers[hid].cc_newsession(
357 					crypto_drivers[hid].cc_arg, &lid, cri);
358 			if (err == 0) {
359 				(*sid) = hid;
360 				(*sid) <<= 32;
361 				(*sid) |= (lid & 0xffffffff);
362 				crypto_drivers[hid].cc_sessions++;
363 			}
364 			goto done;
365 			/*break;*/
366 		}
367 	}
368 done:
369 	mutex_spin_exit(&crypto_mtx);
370 	return err;
371 }
372 
373 /*
374  * Delete an existing session (or a reserved session on an unregistered
375  * driver).  Must be called with crypto_mtx mutex held.
376  */
377 int
378 crypto_freesession(u_int64_t sid)
379 {
380 	u_int32_t hid;
381 	int err = 0;
382 
383 	mutex_spin_enter(&crypto_mtx);
384 
385 	if (crypto_drivers == NULL) {
386 		err = EINVAL;
387 		goto done;
388 	}
389 
390 	/* Determine two IDs. */
391 	hid = CRYPTO_SESID2HID(sid);
392 
393 	if (hid >= crypto_drivers_num) {
394 		err = ENOENT;
395 		goto done;
396 	}
397 
398 	if (crypto_drivers[hid].cc_sessions)
399 		crypto_drivers[hid].cc_sessions--;
400 
401 	/* Call the driver cleanup routine, if available. */
402 	if (crypto_drivers[hid].cc_freesession) {
403 		err = crypto_drivers[hid].cc_freesession(
404 				crypto_drivers[hid].cc_arg, sid);
405 	}
406 	else
407 		err = 0;
408 
409 	/*
410 	 * If this was the last session of a driver marked as invalid,
411 	 * make the entry available for reuse.
412 	 */
413 	if ((crypto_drivers[hid].cc_flags & CRYPTOCAP_F_CLEANUP) &&
414 	    crypto_drivers[hid].cc_sessions == 0)
415 		memset(&crypto_drivers[hid], 0, sizeof(struct cryptocap));
416 
417 done:
418 	mutex_spin_exit(&crypto_mtx);
419 	return err;
420 }
421 
422 /*
423  * Return an unused driver id.  Used by drivers prior to registering
424  * support for the algorithms they handle.
425  */
426 int32_t
427 crypto_get_driverid(u_int32_t flags)
428 {
429 	struct cryptocap *newdrv;
430 	int i;
431 
432 	crypto_init();		/* XXX oh, this is foul! */
433 
434 	mutex_spin_enter(&crypto_mtx);
435 	for (i = 0; i < crypto_drivers_num; i++)
436 		if (crypto_drivers[i].cc_process == NULL &&
437 		    (crypto_drivers[i].cc_flags & CRYPTOCAP_F_CLEANUP) == 0 &&
438 		    crypto_drivers[i].cc_sessions == 0)
439 			break;
440 
441 	/* Out of entries, allocate some more. */
442 	if (i == crypto_drivers_num) {
443 		/* Be careful about wrap-around. */
444 		if (2 * crypto_drivers_num <= crypto_drivers_num) {
445 			mutex_spin_exit(&crypto_mtx);
446 			printf("crypto: driver count wraparound!\n");
447 			return -1;
448 		}
449 
450 		newdrv = malloc(2 * crypto_drivers_num *
451 		    sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT|M_ZERO);
452 		if (newdrv == NULL) {
453 			mutex_spin_exit(&crypto_mtx);
454 			printf("crypto: no space to expand driver table!\n");
455 			return -1;
456 		}
457 
458 		memcpy(newdrv, crypto_drivers,
459 		    crypto_drivers_num * sizeof(struct cryptocap));
460 
461 		crypto_drivers_num *= 2;
462 
463 		free(crypto_drivers, M_CRYPTO_DATA);
464 		crypto_drivers = newdrv;
465 	}
466 
467 	/* NB: state is zero'd on free */
468 	crypto_drivers[i].cc_sessions = 1;	/* Mark */
469 	crypto_drivers[i].cc_flags = flags;
470 
471 	if (bootverbose)
472 		printf("crypto: assign driver %u, flags %u\n", i, flags);
473 
474 	mutex_spin_exit(&crypto_mtx);
475 
476 	return i;
477 }
478 
479 static struct cryptocap *
480 crypto_checkdriver(u_int32_t hid)
481 {
482 	if (crypto_drivers == NULL)
483 		return NULL;
484 	return (hid >= crypto_drivers_num ? NULL : &crypto_drivers[hid]);
485 }
486 
487 /*
488  * Register support for a key-related algorithm.  This routine
489  * is called once for each algorithm supported a driver.
490  */
491 int
492 crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags,
493     int (*kprocess)(void *, struct cryptkop *, int),
494     void *karg)
495 {
496 	struct cryptocap *cap;
497 	int err;
498 
499 	mutex_spin_enter(&crypto_mtx);
500 
501 	cap = crypto_checkdriver(driverid);
502 	if (cap != NULL &&
503 	    (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
504 		/*
505 		 * XXX Do some performance testing to determine placing.
506 		 * XXX We probably need an auxiliary data structure that
507 		 * XXX describes relative performances.
508 		 */
509 
510 		cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
511 		if (bootverbose) {
512 			printf("crypto: driver %u registers key alg %u "
513 			       " flags %u\n",
514 				driverid,
515 				kalg,
516 				flags
517 			);
518 		}
519 
520 		if (cap->cc_kprocess == NULL) {
521 			cap->cc_karg = karg;
522 			cap->cc_kprocess = kprocess;
523 		}
524 		err = 0;
525 	} else
526 		err = EINVAL;
527 
528 	mutex_spin_exit(&crypto_mtx);
529 	return err;
530 }
531 
532 /*
533  * Register support for a non-key-related algorithm.  This routine
534  * is called once for each such algorithm supported by a driver.
535  */
536 int
537 crypto_register(u_int32_t driverid, int alg, u_int16_t maxoplen,
538     u_int32_t flags,
539     int (*newses)(void *, u_int32_t*, struct cryptoini*),
540     int (*freeses)(void *, u_int64_t),
541     int (*process)(void *, struct cryptop *, int),
542     void *arg)
543 {
544 	struct cryptocap *cap;
545 	int err;
546 
547 	mutex_spin_enter(&crypto_mtx);
548 
549 	cap = crypto_checkdriver(driverid);
550 	/* NB: algorithms are in the range [1..max] */
551 	if (cap != NULL &&
552 	    (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX)) {
553 		/*
554 		 * XXX Do some performance testing to determine placing.
555 		 * XXX We probably need an auxiliary data structure that
556 		 * XXX describes relative performances.
557 		 */
558 
559 		cap->cc_alg[alg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
560 		cap->cc_max_op_len[alg] = maxoplen;
561 		if (bootverbose) {
562 			printf("crypto: driver %u registers alg %u "
563 				"flags %u maxoplen %u\n",
564 				driverid,
565 				alg,
566 				flags,
567 				maxoplen
568 			);
569 		}
570 
571 		if (cap->cc_process == NULL) {
572 			cap->cc_arg = arg;
573 			cap->cc_newsession = newses;
574 			cap->cc_process = process;
575 			cap->cc_freesession = freeses;
576 			cap->cc_sessions = 0;		/* Unmark */
577 		}
578 		err = 0;
579 	} else
580 		err = EINVAL;
581 
582 	mutex_spin_exit(&crypto_mtx);
583 	return err;
584 }
585 
586 /*
587  * Unregister a crypto driver. If there are pending sessions using it,
588  * leave enough information around so that subsequent calls using those
589  * sessions will correctly detect the driver has been unregistered and
590  * reroute requests.
591  */
592 int
593 crypto_unregister(u_int32_t driverid, int alg)
594 {
595 	int i, err;
596 	u_int32_t ses;
597 	struct cryptocap *cap;
598 
599 	mutex_spin_enter(&crypto_mtx);
600 
601 	cap = crypto_checkdriver(driverid);
602 	if (cap != NULL &&
603 	    (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX) &&
604 	    cap->cc_alg[alg] != 0) {
605 		cap->cc_alg[alg] = 0;
606 		cap->cc_max_op_len[alg] = 0;
607 
608 		/* Was this the last algorithm ? */
609 		for (i = 1; i <= CRYPTO_ALGORITHM_MAX; i++)
610 			if (cap->cc_alg[i] != 0)
611 				break;
612 
613 		if (i == CRYPTO_ALGORITHM_MAX + 1) {
614 			ses = cap->cc_sessions;
615 			memset(cap, 0, sizeof(struct cryptocap));
616 			if (ses != 0) {
617 				/*
618 				 * If there are pending sessions, just mark as invalid.
619 				 */
620 				cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
621 				cap->cc_sessions = ses;
622 			}
623 		}
624 		err = 0;
625 	} else
626 		err = EINVAL;
627 
628 	mutex_spin_exit(&crypto_mtx);
629 	return err;
630 }
631 
632 /*
633  * Unregister all algorithms associated with a crypto driver.
634  * If there are pending sessions using it, leave enough information
635  * around so that subsequent calls using those sessions will
636  * correctly detect the driver has been unregistered and reroute
637  * requests.
638  *
639  * XXX careful.  Don't change this to call crypto_unregister() for each
640  * XXX registered algorithm unless you drop the mutex across the calls;
641  * XXX you can't take it recursively.
642  */
643 int
644 crypto_unregister_all(u_int32_t driverid)
645 {
646 	int i, err;
647 	u_int32_t ses;
648 	struct cryptocap *cap;
649 
650 	mutex_spin_enter(&crypto_mtx);
651 	cap = crypto_checkdriver(driverid);
652 	if (cap != NULL) {
653 		for (i = CRYPTO_ALGORITHM_MIN; i <= CRYPTO_ALGORITHM_MAX; i++) {
654 			cap->cc_alg[i] = 0;
655 			cap->cc_max_op_len[i] = 0;
656 		}
657 		ses = cap->cc_sessions;
658 		memset(cap, 0, sizeof(struct cryptocap));
659 		if (ses != 0) {
660 			/*
661 			 * If there are pending sessions, just mark as invalid.
662 			 */
663 			cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
664 			cap->cc_sessions = ses;
665 		}
666 		err = 0;
667 	} else
668 		err = EINVAL;
669 
670 	mutex_spin_exit(&crypto_mtx);
671 	return err;
672 }
673 
674 /*
675  * Clear blockage on a driver.  The what parameter indicates whether
676  * the driver is now ready for cryptop's and/or cryptokop's.
677  */
678 int
679 crypto_unblock(u_int32_t driverid, int what)
680 {
681 	struct cryptocap *cap;
682 	int needwakeup, err;
683 
684 	mutex_spin_enter(&crypto_mtx);
685 	cap = crypto_checkdriver(driverid);
686 	if (cap != NULL) {
687 		needwakeup = 0;
688 		if (what & CRYPTO_SYMQ) {
689 			needwakeup |= cap->cc_qblocked;
690 			cap->cc_qblocked = 0;
691 		}
692 		if (what & CRYPTO_ASYMQ) {
693 			needwakeup |= cap->cc_kqblocked;
694 			cap->cc_kqblocked = 0;
695 		}
696 		err = 0;
697 		mutex_spin_exit(&crypto_mtx);
698 		if (needwakeup)
699 			setsoftcrypto(softintr_cookie);
700 	} else {
701 		err = EINVAL;
702 		mutex_spin_exit(&crypto_mtx);
703 	}
704 
705 	return err;
706 }
707 
708 /*
709  * Dispatch a crypto request to a driver or queue
710  * it, to be processed by the kernel thread.
711  */
712 int
713 crypto_dispatch(struct cryptop *crp)
714 {
715 	u_int32_t hid = CRYPTO_SESID2HID(crp->crp_sid);
716 	int result;
717 
718 	mutex_spin_enter(&crypto_mtx);
719 	DPRINTF(("crypto_dispatch: crp %p, reqid 0x%x, alg %d\n",
720 		crp, crp->crp_reqid, crp->crp_desc->crd_alg));
721 
722 	cryptostats.cs_ops++;
723 
724 #ifdef CRYPTO_TIMING
725 	if (crypto_timing)
726 		nanouptime(&crp->crp_tstamp);
727 #endif
728 	if ((crp->crp_flags & CRYPTO_F_BATCH) == 0) {
729 		struct cryptocap *cap;
730 		/*
731 		 * Caller marked the request to be processed
732 		 * immediately; dispatch it directly to the
733 		 * driver unless the driver is currently blocked.
734 		 */
735 		cap = crypto_checkdriver(hid);
736 		if (cap && !cap->cc_qblocked) {
737 			mutex_spin_exit(&crypto_mtx);
738 			result = crypto_invoke(crp, 0);
739 			if (result == ERESTART) {
740 				/*
741 				 * The driver ran out of resources, mark the
742 				 * driver ``blocked'' for cryptop's and put
743 				 * the op on the queue.
744 				 */
745 				mutex_spin_enter(&crypto_mtx);
746 				crypto_drivers[hid].cc_qblocked = 1;
747 				TAILQ_INSERT_HEAD(&crp_q, crp, crp_next);
748 				cryptostats.cs_blocks++;
749 				mutex_spin_exit(&crypto_mtx);
750 			}
751 			goto out_released;
752 		} else {
753 			/*
754 			 * The driver is blocked, just queue the op until
755 			 * it unblocks and the swi thread gets kicked.
756 			 */
757 			TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
758 			result = 0;
759 		}
760 	} else {
761 		int wasempty = TAILQ_EMPTY(&crp_q);
762 		/*
763 		 * Caller marked the request as ``ok to delay'';
764 		 * queue it for the swi thread.  This is desirable
765 		 * when the operation is low priority and/or suitable
766 		 * for batching.
767 		 */
768 		TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
769 		if (wasempty) {
770 			mutex_spin_exit(&crypto_mtx);
771 			setsoftcrypto(softintr_cookie);
772 			result = 0;
773 			goto out_released;
774 		}
775 
776 		result = 0;
777 	}
778 
779 	mutex_spin_exit(&crypto_mtx);
780 out_released:
781 	return result;
782 }
783 
784 /*
785  * Add an asymetric crypto request to a queue,
786  * to be processed by the kernel thread.
787  */
788 int
789 crypto_kdispatch(struct cryptkop *krp)
790 {
791 	struct cryptocap *cap;
792 	int result;
793 
794 	mutex_spin_enter(&crypto_mtx);
795 	cryptostats.cs_kops++;
796 
797 	cap = crypto_checkdriver(krp->krp_hid);
798 	if (cap && !cap->cc_kqblocked) {
799 		mutex_spin_exit(&crypto_mtx);
800 		result = crypto_kinvoke(krp, 0);
801 		if (result == ERESTART) {
802 			/*
803 			 * The driver ran out of resources, mark the
804 			 * driver ``blocked'' for cryptop's and put
805 			 * the op on the queue.
806 			 */
807 			mutex_spin_enter(&crypto_mtx);
808 			crypto_drivers[krp->krp_hid].cc_kqblocked = 1;
809 			TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
810 			cryptostats.cs_kblocks++;
811 			mutex_spin_exit(&crypto_mtx);
812 		}
813 	} else {
814 		/*
815 		 * The driver is blocked, just queue the op until
816 		 * it unblocks and the swi thread gets kicked.
817 		 */
818 		TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
819 		result = 0;
820 		mutex_spin_exit(&crypto_mtx);
821 	}
822 
823 	return result;
824 }
825 
826 /*
827  * Dispatch an assymetric crypto request to the appropriate crypto devices.
828  */
829 static int
830 crypto_kinvoke(struct cryptkop *krp, int hint)
831 {
832 	u_int32_t hid;
833 	int error;
834 
835 	/* Sanity checks. */
836 	if (krp == NULL)
837 		return EINVAL;
838 	if (krp->krp_callback == NULL) {
839 		cv_destroy(&krp->krp_cv);
840 		pool_put(&cryptkop_pool, krp);
841 		return EINVAL;
842 	}
843 
844 	mutex_spin_enter(&crypto_mtx);
845 	for (hid = 0; hid < crypto_drivers_num; hid++) {
846 		if ((crypto_drivers[hid].cc_flags & CRYPTOCAP_F_SOFTWARE) &&
847 		    crypto_devallowsoft == 0)
848 			continue;
849 		if (crypto_drivers[hid].cc_kprocess == NULL)
850 			continue;
851 		if ((crypto_drivers[hid].cc_kalg[krp->krp_op] &
852 		    CRYPTO_ALG_FLAG_SUPPORTED) == 0)
853 			continue;
854 		break;
855 	}
856 	if (hid < crypto_drivers_num) {
857 		int (*process)(void *, struct cryptkop *, int);
858 		void *arg;
859 
860 		process = crypto_drivers[hid].cc_kprocess;
861 		arg = crypto_drivers[hid].cc_karg;
862 		mutex_spin_exit(&crypto_mtx);
863 		krp->krp_hid = hid;
864 		error = (*process)(arg, krp, hint);
865 	} else {
866 		mutex_spin_exit(&crypto_mtx);
867 		error = ENODEV;
868 	}
869 
870 	if (error) {
871 		krp->krp_status = error;
872 		crypto_kdone(krp);
873 	}
874 	return 0;
875 }
876 
877 #ifdef CRYPTO_TIMING
878 static void
879 crypto_tstat(struct cryptotstat *ts, struct timespec *tv)
880 {
881 	struct timespec now, t;
882 
883 	nanouptime(&now);
884 	t.tv_sec = now.tv_sec - tv->tv_sec;
885 	t.tv_nsec = now.tv_nsec - tv->tv_nsec;
886 	if (t.tv_nsec < 0) {
887 		t.tv_sec--;
888 		t.tv_nsec += 1000000000;
889 	}
890 	timespecadd(&ts->acc, &t, &t);
891 	if (timespeccmp(&t, &ts->min, <))
892 		ts->min = t;
893 	if (timespeccmp(&t, &ts->max, >))
894 		ts->max = t;
895 	ts->count++;
896 
897 	*tv = now;
898 }
899 #endif
900 
901 /*
902  * Dispatch a crypto request to the appropriate crypto devices.
903  */
904 static int
905 crypto_invoke(struct cryptop *crp, int hint)
906 {
907 	u_int32_t hid;
908 
909 #ifdef CRYPTO_TIMING
910 	if (crypto_timing)
911 		crypto_tstat(&cryptostats.cs_invoke, &crp->crp_tstamp);
912 #endif
913 	/* Sanity checks. */
914 	if (crp == NULL)
915 		return EINVAL;
916 	if (crp->crp_callback == NULL) {
917 		return EINVAL;
918 	}
919 	if (crp->crp_desc == NULL) {
920 		crp->crp_etype = EINVAL;
921 		crypto_done(crp);
922 		return 0;
923 	}
924 
925 	hid = CRYPTO_SESID2HID(crp->crp_sid);
926 
927 	mutex_spin_enter(&crypto_mtx);
928 	if (hid < crypto_drivers_num) {
929 		int (*process)(void *, struct cryptop *, int);
930 		void *arg;
931 
932 		if (crypto_drivers[hid].cc_flags & CRYPTOCAP_F_CLEANUP)
933 			crypto_freesession(crp->crp_sid);
934 		process = crypto_drivers[hid].cc_process;
935 		arg = crypto_drivers[hid].cc_arg;
936 		mutex_spin_exit(&crypto_mtx);
937 
938 		/*
939 		 * Invoke the driver to process the request.
940 		 */
941 		DPRINTF(("calling process for %p\n", crp));
942 		return (*process)(arg, crp, hint);
943 	} else {
944 		struct cryptodesc *crd;
945 		u_int64_t nid = 0;
946 
947 		/*
948 		 * Driver has unregistered; migrate the session and return
949 		 * an error to the caller so they'll resubmit the op.
950 		 */
951 		for (crd = crp->crp_desc; crd->crd_next; crd = crd->crd_next)
952 			crd->CRD_INI.cri_next = &(crd->crd_next->CRD_INI);
953 
954 		if (crypto_newsession(&nid, &(crp->crp_desc->CRD_INI), 0) == 0)
955 			crp->crp_sid = nid;
956 
957 		crp->crp_etype = EAGAIN;
958 		mutex_spin_exit(&crypto_mtx);
959 
960 		crypto_done(crp);
961 		return 0;
962 	}
963 }
964 
965 /*
966  * Release a set of crypto descriptors.
967  */
968 void
969 crypto_freereq(struct cryptop *crp)
970 {
971 	struct cryptodesc *crd;
972 
973 	if (crp == NULL)
974 		return;
975 	DPRINTF(("crypto_freereq[%u]: crp %p\n",
976 		CRYPTO_SESID2LID(crp->crp_sid), crp));
977 
978 	/* sanity check */
979 	if (crp->crp_flags & CRYPTO_F_ONRETQ) {
980 		panic("crypto_freereq() freeing crp on RETQ\n");
981 	}
982 
983 	while ((crd = crp->crp_desc) != NULL) {
984 		crp->crp_desc = crd->crd_next;
985 		pool_put(&cryptodesc_pool, crd);
986 	}
987 	cv_destroy(&crp->crp_cv);
988 	pool_put(&cryptop_pool, crp);
989 }
990 
991 /*
992  * Acquire a set of crypto descriptors.
993  */
994 struct cryptop *
995 crypto_getreq(int num)
996 {
997 	struct cryptodesc *crd;
998 	struct cryptop *crp;
999 
1000 	crp = pool_get(&cryptop_pool, 0);
1001 	if (crp == NULL) {
1002 		return NULL;
1003 	}
1004 	memset(crp, 0, sizeof(struct cryptop));
1005 	cv_init(&crp->crp_cv, "crydev");
1006 
1007 	while (num--) {
1008 		crd = pool_get(&cryptodesc_pool, 0);
1009 		if (crd == NULL) {
1010 			crypto_freereq(crp);
1011 			return NULL;
1012 		}
1013 
1014 		memset(crd, 0, sizeof(struct cryptodesc));
1015 		crd->crd_next = crp->crp_desc;
1016 		crp->crp_desc = crd;
1017 	}
1018 
1019 	return crp;
1020 }
1021 
1022 /*
1023  * Invoke the callback on behalf of the driver.
1024  */
1025 void
1026 crypto_done(struct cryptop *crp)
1027 {
1028 	int wasempty;
1029 
1030 	if (crp->crp_etype != 0)
1031 		cryptostats.cs_errs++;
1032 #ifdef CRYPTO_TIMING
1033 	if (crypto_timing)
1034 		crypto_tstat(&cryptostats.cs_done, &crp->crp_tstamp);
1035 #endif
1036 	DPRINTF(("crypto_done[%u]: crp %p\n",
1037 		CRYPTO_SESID2LID(crp->crp_sid), crp));
1038 
1039 	/*
1040 	 * Normal case; queue the callback for the thread.
1041 	 *
1042 	 * The return queue is manipulated by the swi thread
1043 	 * and, potentially, by crypto device drivers calling
1044 	 * back to mark operations completed.  Thus we need
1045 	 * to mask both while manipulating the return queue.
1046 	 */
1047   	if (crp->crp_flags & CRYPTO_F_CBIMM) {
1048 		/*
1049 	 	* Do the callback directly.  This is ok when the
1050   	 	* callback routine does very little (e.g. the
1051 	 	* /dev/crypto callback method just does a wakeup).
1052 	 	*/
1053 		mutex_spin_enter(&crypto_mtx);
1054 		crp->crp_flags |= CRYPTO_F_DONE;
1055 		mutex_spin_exit(&crypto_mtx);
1056 
1057 #ifdef CRYPTO_TIMING
1058 		if (crypto_timing) {
1059 			/*
1060 		 	* NB: We must copy the timestamp before
1061 		 	* doing the callback as the cryptop is
1062 		 	* likely to be reclaimed.
1063 		 	*/
1064 			struct timespec t = crp->crp_tstamp;
1065 			crypto_tstat(&cryptostats.cs_cb, &t);
1066 			crp->crp_callback(crp);
1067 			crypto_tstat(&cryptostats.cs_finis, &t);
1068 		} else
1069 #endif
1070 		crp->crp_callback(crp);
1071 	} else {
1072 		mutex_spin_enter(&crypto_mtx);
1073 		crp->crp_flags |= CRYPTO_F_DONE;
1074 
1075 		if (crp->crp_flags & CRYPTO_F_USER) {
1076 			/* the request has completed while
1077 			 * running in the user context
1078 			 * so don't queue it - the user
1079 			 * thread won't sleep when it sees
1080 			 * the CRYPTO_F_DONE flag.
1081 			 * This is an optimization to avoid
1082 			 * unecessary context switches.
1083 			 */
1084 			DPRINTF(("crypto_done[%u]: crp %p CRYPTO_F_USER\n",
1085 				CRYPTO_SESID2LID(crp->crp_sid), crp));
1086 		} else {
1087 			wasempty = TAILQ_EMPTY(&crp_ret_q);
1088 			DPRINTF(("crypto_done[%u]: queueing %p\n",
1089 				CRYPTO_SESID2LID(crp->crp_sid), crp));
1090 			crp->crp_flags |= CRYPTO_F_ONRETQ;
1091 			TAILQ_INSERT_TAIL(&crp_ret_q, crp, crp_next);
1092 			if (wasempty) {
1093 				DPRINTF(("crypto_done[%u]: waking cryptoret, "
1094 					"crp %p hit empty queue\n.",
1095 					CRYPTO_SESID2LID(crp->crp_sid), crp));
1096 				cv_signal(&cryptoret_cv);
1097 			}
1098 		}
1099 		mutex_spin_exit(&crypto_mtx);
1100 	}
1101 }
1102 
1103 /*
1104  * Invoke the callback on behalf of the driver.
1105  */
1106 void
1107 crypto_kdone(struct cryptkop *krp)
1108 {
1109 	int wasempty;
1110 
1111 	if (krp->krp_status != 0)
1112 		cryptostats.cs_kerrs++;
1113 
1114 	krp->krp_flags |= CRYPTO_F_DONE;
1115 
1116 	/*
1117 	 * The return queue is manipulated by the swi thread
1118 	 * and, potentially, by crypto device drivers calling
1119 	 * back to mark operations completed.  Thus we need
1120 	 * to mask both while manipulating the return queue.
1121 	 */
1122 	if (krp->krp_flags & CRYPTO_F_CBIMM) {
1123 		krp->krp_callback(krp);
1124 	} else {
1125 		mutex_spin_enter(&crypto_mtx);
1126 		wasempty = TAILQ_EMPTY(&crp_ret_kq);
1127 		krp->krp_flags |= CRYPTO_F_ONRETQ;
1128 		TAILQ_INSERT_TAIL(&crp_ret_kq, krp, krp_next);
1129 		if (wasempty)
1130 			cv_signal(&cryptoret_cv);
1131 		mutex_spin_exit(&crypto_mtx);
1132 	}
1133 }
1134 
1135 int
1136 crypto_getfeat(int *featp)
1137 {
1138 	int hid, kalg, feat = 0;
1139 
1140 	mutex_spin_enter(&crypto_mtx);
1141 
1142 	if (crypto_userasymcrypto == 0)
1143 		goto out;
1144 
1145 	for (hid = 0; hid < crypto_drivers_num; hid++) {
1146 		if ((crypto_drivers[hid].cc_flags & CRYPTOCAP_F_SOFTWARE) &&
1147 		    crypto_devallowsoft == 0) {
1148 			continue;
1149 		}
1150 		if (crypto_drivers[hid].cc_kprocess == NULL)
1151 			continue;
1152 		for (kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
1153 			if ((crypto_drivers[hid].cc_kalg[kalg] &
1154 			    CRYPTO_ALG_FLAG_SUPPORTED) != 0)
1155 				feat |=  1 << kalg;
1156 	}
1157 out:
1158 	mutex_spin_exit(&crypto_mtx);
1159 	*featp = feat;
1160 	return (0);
1161 }
1162 
1163 /*
1164  * Software interrupt thread to dispatch crypto requests.
1165  */
1166 static void
1167 cryptointr(void)
1168 {
1169 	struct cryptop *crp, *submit, *cnext;
1170 	struct cryptkop *krp, *knext;
1171 	struct cryptocap *cap;
1172 	int result, hint;
1173 
1174 	cryptostats.cs_intrs++;
1175 	mutex_spin_enter(&crypto_mtx);
1176 	do {
1177 		/*
1178 		 * Find the first element in the queue that can be
1179 		 * processed and look-ahead to see if multiple ops
1180 		 * are ready for the same driver.
1181 		 */
1182 		submit = NULL;
1183 		hint = 0;
1184 		TAILQ_FOREACH_SAFE(crp, &crp_q, crp_next, cnext) {
1185 			u_int32_t hid = CRYPTO_SESID2HID(crp->crp_sid);
1186 			cap = crypto_checkdriver(hid);
1187 			if (cap == NULL || cap->cc_process == NULL) {
1188 				/* Op needs to be migrated, process it. */
1189 				if (submit == NULL)
1190 					submit = crp;
1191 				break;
1192 			}
1193 			if (!cap->cc_qblocked) {
1194 				if (submit != NULL) {
1195 					/*
1196 					 * We stop on finding another op,
1197 					 * regardless whether its for the same
1198 					 * driver or not.  We could keep
1199 					 * searching the queue but it might be
1200 					 * better to just use a per-driver
1201 					 * queue instead.
1202 					 */
1203 					if (CRYPTO_SESID2HID(submit->crp_sid)
1204 					    == hid)
1205 						hint = CRYPTO_HINT_MORE;
1206 					break;
1207 				} else {
1208 					submit = crp;
1209 					if ((submit->crp_flags & CRYPTO_F_BATCH) == 0)
1210 						break;
1211 					/* keep scanning for more are q'd */
1212 				}
1213 			}
1214 		}
1215 		if (submit != NULL) {
1216 			TAILQ_REMOVE(&crp_q, submit, crp_next);
1217 			mutex_spin_exit(&crypto_mtx);
1218 			result = crypto_invoke(submit, hint);
1219 			/* we must take here as the TAILQ op or kinvoke
1220 			   may need this mutex below.  sigh. */
1221 			mutex_spin_enter(&crypto_mtx);
1222 			if (result == ERESTART) {
1223 				/*
1224 				 * The driver ran out of resources, mark the
1225 				 * driver ``blocked'' for cryptop's and put
1226 				 * the request back in the queue.  It would
1227 				 * best to put the request back where we got
1228 				 * it but that's hard so for now we put it
1229 				 * at the front.  This should be ok; putting
1230 				 * it at the end does not work.
1231 				 */
1232 				/* XXX validate sid again? */
1233 				crypto_drivers[CRYPTO_SESID2HID(submit->crp_sid)].cc_qblocked = 1;
1234 				TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
1235 				cryptostats.cs_blocks++;
1236 			}
1237 		}
1238 
1239 		/* As above, but for key ops */
1240 		TAILQ_FOREACH_SAFE(krp, &crp_kq, krp_next, knext) {
1241 			cap = crypto_checkdriver(krp->krp_hid);
1242 			if (cap == NULL || cap->cc_kprocess == NULL) {
1243 				/* Op needs to be migrated, process it. */
1244 				break;
1245 			}
1246 			if (!cap->cc_kqblocked)
1247 				break;
1248 		}
1249 		if (krp != NULL) {
1250 			TAILQ_REMOVE(&crp_kq, krp, krp_next);
1251 			mutex_spin_exit(&crypto_mtx);
1252 			result = crypto_kinvoke(krp, 0);
1253 			/* the next iteration will want the mutex. :-/ */
1254 			mutex_spin_enter(&crypto_mtx);
1255 			if (result == ERESTART) {
1256 				/*
1257 				 * The driver ran out of resources, mark the
1258 				 * driver ``blocked'' for cryptkop's and put
1259 				 * the request back in the queue.  It would
1260 				 * best to put the request back where we got
1261 				 * it but that's hard so for now we put it
1262 				 * at the front.  This should be ok; putting
1263 				 * it at the end does not work.
1264 				 */
1265 				/* XXX validate sid again? */
1266 				crypto_drivers[krp->krp_hid].cc_kqblocked = 1;
1267 				TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
1268 				cryptostats.cs_kblocks++;
1269 			}
1270 		}
1271 	} while (submit != NULL || krp != NULL);
1272 	mutex_spin_exit(&crypto_mtx);
1273 }
1274 
1275 /*
1276  * Kernel thread to do callbacks.
1277  */
1278 static void
1279 cryptoret(void)
1280 {
1281 	struct cryptop *crp;
1282 	struct cryptkop *krp;
1283 
1284 	mutex_spin_enter(&crypto_mtx);
1285 	for (;;) {
1286 		crp = TAILQ_FIRST(&crp_ret_q);
1287 		if (crp != NULL) {
1288 			TAILQ_REMOVE(&crp_ret_q, crp, crp_next);
1289 			crp->crp_flags &= ~CRYPTO_F_ONRETQ;
1290 		}
1291 		krp = TAILQ_FIRST(&crp_ret_kq);
1292 		if (krp != NULL) {
1293 			TAILQ_REMOVE(&crp_ret_kq, krp, krp_next);
1294 			krp->krp_flags &= ~CRYPTO_F_ONRETQ;
1295 		}
1296 
1297 		/* drop before calling any callbacks. */
1298 		if (crp == NULL && krp == NULL) {
1299 			cryptostats.cs_rets++;
1300 			cv_wait(&cryptoret_cv, &crypto_mtx);
1301 			continue;
1302 		}
1303 
1304 		mutex_spin_exit(&crypto_mtx);
1305 
1306 		if (crp != NULL) {
1307 #ifdef CRYPTO_TIMING
1308 			if (crypto_timing) {
1309 				/*
1310 				 * NB: We must copy the timestamp before
1311 				 * doing the callback as the cryptop is
1312 				 * likely to be reclaimed.
1313 				 */
1314 				struct timespec t = crp->crp_tstamp;
1315 				crypto_tstat(&cryptostats.cs_cb, &t);
1316 				crp->crp_callback(crp);
1317 				crypto_tstat(&cryptostats.cs_finis, &t);
1318 			} else
1319 #endif
1320 			{
1321 				crp->crp_callback(crp);
1322 			}
1323 		}
1324 		if (krp != NULL)
1325 			krp->krp_callback(krp);
1326 
1327 		mutex_spin_enter(&crypto_mtx);
1328 	}
1329 }
1330