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