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