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