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