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