Home | History | Annotate | Line # | Download | only in opencrypto
crypto.c revision 1.88
      1 /*	$NetBSD: crypto.c,v 1.88 2017/06/14 07:36:24 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.88 2017/06/14 07:36:24 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 /* Don't directly access crypto_drivers[i], use crypto_checkdriver(i). */
    103 static	struct cryptocap *crypto_drivers;
    104 static	int crypto_drivers_num;
    105 static	void *softintr_cookie;
    106 static	int crypto_exit_flag;
    107 
    108 /*
    109  * There are two queues for crypto requests; one for symmetric (e.g.
    110  * cipher) operations and one for asymmetric (e.g. MOD) operations.
    111  * See below for how synchronization is handled.
    112  */
    113 static	TAILQ_HEAD(,cryptop) crp_q =		/* request queues */
    114 		TAILQ_HEAD_INITIALIZER(crp_q);
    115 static	TAILQ_HEAD(,cryptkop) crp_kq =
    116 		TAILQ_HEAD_INITIALIZER(crp_kq);
    117 
    118 /*
    119  * There are two queues for processing completed crypto requests; one
    120  * for the symmetric and one for the asymmetric ops.  We only need one
    121  * but have two to avoid type futzing (cryptop vs. cryptkop).  See below
    122  * for how synchronization is handled.
    123  */
    124 static	TAILQ_HEAD(crprethead, cryptop) crp_ret_q =	/* callback queues */
    125 		TAILQ_HEAD_INITIALIZER(crp_ret_q);
    126 static	TAILQ_HEAD(krprethead, cryptkop) crp_ret_kq =
    127 		TAILQ_HEAD_INITIALIZER(crp_ret_kq);
    128 
    129 #define DEFINIT_CRYPTO_Q_LEN(name)		\
    130 	static int crypto_##name##_len = 0
    131 
    132 #define DEFINIT_CRYPTO_Q_DROPS(name)		\
    133 	static int crypto_##name##_drops = 0
    134 
    135 #define DEFINIT_CRYPTO_Q_MAXLEN(name, defval)		\
    136 	static int crypto_##name##_maxlen = defval
    137 
    138 #define CRYPTO_Q_INC(name)			\
    139 	do {					\
    140 		crypto_##name##_len++;		\
    141 	} while(0);
    142 
    143 #define CRYPTO_Q_DEC(name)			\
    144 	do {					\
    145 		crypto_##name##_len--;		\
    146 	} while(0);
    147 
    148 #define CRYPTO_Q_INC_DROPS(name)		\
    149 	do {					\
    150 		crypto_##name##_drops++;	\
    151 	} while(0);
    152 
    153 #define CRYPTO_Q_IS_FULL(name)					\
    154 	(crypto_##name##_maxlen > 0				\
    155 	    && (crypto_##name##_len > crypto_##name##_maxlen))
    156 
    157 /*
    158  * current queue length.
    159  */
    160 DEFINIT_CRYPTO_Q_LEN(crp_ret_q);
    161 DEFINIT_CRYPTO_Q_LEN(crp_ret_kq);
    162 
    163 /*
    164  * queue dropped count.
    165  */
    166 DEFINIT_CRYPTO_Q_DROPS(crp_ret_q);
    167 DEFINIT_CRYPTO_Q_DROPS(crp_ret_kq);
    168 
    169 #ifndef CRYPTO_RET_Q_MAXLEN
    170 #define CRYPTO_RET_Q_MAXLEN 0
    171 #endif
    172 #ifndef CRYPTO_RET_KQ_MAXLEN
    173 #define CRYPTO_RET_KQ_MAXLEN 0
    174 #endif
    175 /*
    176  * queue length limit.
    177  * default value is 0. <=0 means unlimited.
    178  */
    179 DEFINIT_CRYPTO_Q_MAXLEN(crp_ret_q, CRYPTO_RET_Q_MAXLEN);
    180 DEFINIT_CRYPTO_Q_MAXLEN(crp_ret_kq, CRYPTO_RET_KQ_MAXLEN);
    181 
    182 /*
    183  * TODO:
    184  * make percpu
    185  */
    186 static int
    187 sysctl_opencrypto_q_len(SYSCTLFN_ARGS)
    188 {
    189 	int error;
    190 
    191 	error = sysctl_lookup(SYSCTLFN_CALL(rnode));
    192 	if (error || newp == NULL)
    193 		return error;
    194 
    195 	return 0;
    196 }
    197 
    198 /*
    199  * TODO:
    200  * make percpu
    201  */
    202 static int
    203 sysctl_opencrypto_q_drops(SYSCTLFN_ARGS)
    204 {
    205 	int error;
    206 
    207 	error = sysctl_lookup(SYSCTLFN_CALL(rnode));
    208 	if (error || newp == NULL)
    209 		return error;
    210 
    211 	return 0;
    212 }
    213 
    214 /*
    215  * need to make percpu?
    216  */
    217 static int
    218 sysctl_opencrypto_q_maxlen(SYSCTLFN_ARGS)
    219 {
    220 	int error;
    221 
    222 	error = sysctl_lookup(SYSCTLFN_CALL(rnode));
    223 	if (error || newp == NULL)
    224 		return error;
    225 
    226 	return 0;
    227 }
    228 
    229 /*
    230  * Crypto op and desciptor data structures are allocated
    231  * from separate private zones(FreeBSD)/pools(netBSD/OpenBSD) .
    232  */
    233 struct pool cryptop_pool;
    234 struct pool cryptodesc_pool;
    235 struct pool cryptkop_pool;
    236 
    237 int	crypto_usercrypto = 1;		/* userland may open /dev/crypto */
    238 int	crypto_userasymcrypto = 1;	/* userland may do asym crypto reqs */
    239 /*
    240  * cryptodevallowsoft is (intended to be) sysctl'able, controlling
    241  * access to hardware versus software transforms as below:
    242  *
    243  * crypto_devallowsoft < 0:  Force userlevel requests to use software
    244  *                              transforms, always
    245  * crypto_devallowsoft = 0:  Use hardware if present, grant userlevel
    246  *                              requests for non-accelerated transforms
    247  *                              (handling the latter in software)
    248  * crypto_devallowsoft > 0:  Allow user requests only for transforms which
    249  *                               are hardware-accelerated.
    250  */
    251 int	crypto_devallowsoft = 1;	/* only use hardware crypto */
    252 
    253 static void
    254 sysctl_opencrypto_setup(struct sysctllog **clog)
    255 {
    256 	const struct sysctlnode *ocnode;
    257 	const struct sysctlnode *retqnode, *retkqnode;
    258 
    259 	sysctl_createv(clog, 0, NULL, NULL,
    260 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    261 		       CTLTYPE_INT, "usercrypto",
    262 		       SYSCTL_DESCR("Enable/disable user-mode access to "
    263 			   "crypto support"),
    264 		       NULL, 0, &crypto_usercrypto, 0,
    265 		       CTL_KERN, CTL_CREATE, CTL_EOL);
    266 	sysctl_createv(clog, 0, NULL, NULL,
    267 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    268 		       CTLTYPE_INT, "userasymcrypto",
    269 		       SYSCTL_DESCR("Enable/disable user-mode access to "
    270 			   "asymmetric crypto support"),
    271 		       NULL, 0, &crypto_userasymcrypto, 0,
    272 		       CTL_KERN, CTL_CREATE, CTL_EOL);
    273 	sysctl_createv(clog, 0, NULL, NULL,
    274 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    275 		       CTLTYPE_INT, "cryptodevallowsoft",
    276 		       SYSCTL_DESCR("Enable/disable use of software "
    277 			   "asymmetric crypto support"),
    278 		       NULL, 0, &crypto_devallowsoft, 0,
    279 		       CTL_KERN, CTL_CREATE, CTL_EOL);
    280 
    281 	sysctl_createv(clog, 0, NULL, &ocnode,
    282 		       CTLFLAG_PERMANENT,
    283 		       CTLTYPE_NODE, "opencrypto",
    284 		       SYSCTL_DESCR("opencrypto related entries"),
    285 		       NULL, 0, NULL, 0,
    286 		       CTL_CREATE, CTL_EOL);
    287 
    288 	sysctl_createv(clog, 0, &ocnode, &retqnode,
    289 		       CTLFLAG_PERMANENT,
    290 		       CTLTYPE_NODE, "crypto_ret_q",
    291 		       SYSCTL_DESCR("crypto_ret_q related entries"),
    292 		       NULL, 0, NULL, 0,
    293 		       CTL_CREATE, CTL_EOL);
    294 	sysctl_createv(clog, 0, &retqnode, NULL,
    295 		       CTLFLAG_PERMANENT|CTLFLAG_READONLY,
    296 		       CTLTYPE_INT, "len",
    297 		       SYSCTL_DESCR("Current queue length"),
    298 		       sysctl_opencrypto_q_len, 0,
    299 		       (void *)&crypto_crp_ret_q_len, 0,
    300 		       CTL_CREATE, CTL_EOL);
    301 	sysctl_createv(clog, 0, &retqnode, NULL,
    302 		       CTLFLAG_PERMANENT|CTLFLAG_READONLY,
    303 		       CTLTYPE_INT, "drops",
    304 		       SYSCTL_DESCR("Crypto requests dropped due to full ret queue"),
    305 		       sysctl_opencrypto_q_drops, 0,
    306 		       (void *)&crypto_crp_ret_q_drops, 0,
    307 		       CTL_CREATE, CTL_EOL);
    308 	sysctl_createv(clog, 0, &retqnode, NULL,
    309 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    310 		       CTLTYPE_INT, "maxlen",
    311 		       SYSCTL_DESCR("Maximum allowed queue length"),
    312 		       sysctl_opencrypto_q_maxlen, 0,
    313 		       (void *)&crypto_crp_ret_q_maxlen, 0,
    314 		       CTL_CREATE, CTL_EOL);
    315 
    316 	sysctl_createv(clog, 0, &ocnode, &retkqnode,
    317 		       CTLFLAG_PERMANENT,
    318 		       CTLTYPE_NODE, "crypto_ret_kq",
    319 		       SYSCTL_DESCR("crypto_ret_kq related entries"),
    320 		       NULL, 0, NULL, 0,
    321 		       CTL_CREATE, CTL_EOL);
    322 	sysctl_createv(clog, 0, &retkqnode, NULL,
    323 		       CTLFLAG_PERMANENT|CTLFLAG_READONLY,
    324 		       CTLTYPE_INT, "len",
    325 		       SYSCTL_DESCR("Current queue length"),
    326 		       sysctl_opencrypto_q_len, 0,
    327 		       (void *)&crypto_crp_ret_kq_len, 0,
    328 		       CTL_CREATE, CTL_EOL);
    329 	sysctl_createv(clog, 0, &retkqnode, NULL,
    330 		       CTLFLAG_PERMANENT|CTLFLAG_READONLY,
    331 		       CTLTYPE_INT, "drops",
    332 		       SYSCTL_DESCR("Crypto requests dropped due to full ret queue"),
    333 		       sysctl_opencrypto_q_drops, 0,
    334 		       (void *)&crypto_crp_ret_kq_drops, 0,
    335 		       CTL_CREATE, CTL_EOL);
    336 	sysctl_createv(clog, 0, &retkqnode, NULL,
    337 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    338 		       CTLTYPE_INT, "maxlen",
    339 		       SYSCTL_DESCR("Maximum allowed queue length"),
    340 		       sysctl_opencrypto_q_maxlen, 0,
    341 		       (void *)&crypto_crp_ret_kq_maxlen, 0,
    342 		       CTL_CREATE, CTL_EOL);
    343 }
    344 
    345 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
    346 
    347 /*
    348  * Synchronization: read carefully, this is non-trivial.
    349  *
    350  * Crypto requests are submitted via crypto_dispatch.  Typically
    351  * these come in from network protocols at spl0 (output path) or
    352  * spl[,soft]net (input path).
    353  *
    354  * Requests are typically passed on the driver directly, but they
    355  * may also be queued for processing by a software interrupt thread,
    356  * cryptointr, that runs at splsoftcrypto.  This thread dispatches
    357  * the requests to crypto drivers (h/w or s/w) who call crypto_done
    358  * when a request is complete.  Hardware crypto drivers are assumed
    359  * to register their IRQ's as network devices so their interrupt handlers
    360  * and subsequent "done callbacks" happen at spl[imp,net].
    361  *
    362  * Completed crypto ops are queued for a separate kernel thread that
    363  * handles the callbacks at spl0.  This decoupling insures the crypto
    364  * driver interrupt service routine is not delayed while the callback
    365  * takes place and that callbacks are delivered after a context switch
    366  * (as opposed to a software interrupt that clients must block).
    367  *
    368  * This scheme is not intended for SMP machines.
    369  */
    370 static	void cryptointr(void);		/* swi thread to dispatch ops */
    371 static	void cryptoret(void);		/* kernel thread for callbacks*/
    372 static	struct lwp *cryptothread;
    373 static	int crypto_destroy(bool);
    374 static	int crypto_invoke(struct cryptop *crp, int hint);
    375 static	int crypto_kinvoke(struct cryptkop *krp, int hint);
    376 
    377 static struct cryptocap *crypto_checkdriver_lock(u_int32_t);
    378 static struct cryptocap *crypto_checkdriver_uninit(u_int32_t);
    379 static struct cryptocap *crypto_checkdriver(u_int32_t);
    380 static void crypto_driver_lock(struct cryptocap *);
    381 static void crypto_driver_unlock(struct cryptocap *);
    382 static void crypto_driver_clear(struct cryptocap *);
    383 
    384 static struct cryptostats cryptostats;
    385 #ifdef CRYPTO_TIMING
    386 static	int crypto_timing = 0;
    387 #endif
    388 
    389 static struct sysctllog *sysctl_opencrypto_clog;
    390 
    391 static int
    392 crypto_init0(void)
    393 {
    394 	int error;
    395 
    396 	mutex_init(&crypto_drv_mtx, MUTEX_DEFAULT, IPL_NONE);
    397 	mutex_init(&crypto_q_mtx, MUTEX_DEFAULT, IPL_NONE);
    398 	mutex_init(&crypto_ret_q_mtx, MUTEX_DEFAULT, IPL_NET);
    399 	cv_init(&cryptoret_cv, "crypto_w");
    400 	pool_init(&cryptop_pool, sizeof(struct cryptop), 0, 0,
    401 		  0, "cryptop", NULL, IPL_NET);
    402 	pool_init(&cryptodesc_pool, sizeof(struct cryptodesc), 0, 0,
    403 		  0, "cryptodesc", NULL, IPL_NET);
    404 	pool_init(&cryptkop_pool, sizeof(struct cryptkop), 0, 0,
    405 		  0, "cryptkop", NULL, IPL_NET);
    406 
    407 	crypto_drivers = malloc(CRYPTO_DRIVERS_INITIAL *
    408 	    sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT | M_ZERO);
    409 	if (crypto_drivers == NULL) {
    410 		printf("crypto_init: cannot malloc driver table\n");
    411 		return ENOMEM;
    412 	}
    413 	crypto_drivers_num = CRYPTO_DRIVERS_INITIAL;
    414 
    415 	softintr_cookie = register_swi(SWI_CRYPTO, cryptointr);
    416 	error = kthread_create(PRI_NONE, KTHREAD_MPSAFE, NULL,
    417 	    (void (*)(void *))cryptoret, NULL, &cryptothread, "cryptoret");
    418 	if (error) {
    419 		printf("crypto_init: cannot start cryptoret thread; error %d",
    420 			error);
    421 		return crypto_destroy(false);
    422 	}
    423 
    424 	sysctl_opencrypto_setup(&sysctl_opencrypto_clog);
    425 
    426 	return 0;
    427 }
    428 
    429 int
    430 crypto_init(void)
    431 {
    432 	static ONCE_DECL(crypto_init_once);
    433 
    434 	return RUN_ONCE(&crypto_init_once, crypto_init0);
    435 }
    436 
    437 static int
    438 crypto_destroy(bool exit_kthread)
    439 {
    440 	int i;
    441 
    442 	if (exit_kthread) {
    443 		struct cryptocap *cap = NULL;
    444 
    445 		/* if we have any in-progress requests, don't unload */
    446 		mutex_enter(&crypto_q_mtx);
    447 		if (!TAILQ_EMPTY(&crp_q) || !TAILQ_EMPTY(&crp_kq)) {
    448 			mutex_exit(&crypto_q_mtx);
    449 			return EBUSY;
    450 		}
    451 		mutex_exit(&crypto_q_mtx);
    452 		/* FIXME:
    453 		 * prohibit enqueue to crp_q and crp_kq after here.
    454 		 */
    455 
    456 		mutex_enter(&crypto_drv_mtx);
    457 		for (i = 0; i < crypto_drivers_num; i++) {
    458 			cap = crypto_checkdriver(i);
    459 			if (cap == NULL)
    460 				continue;
    461 			if (cap->cc_sessions != 0) {
    462 				mutex_exit(&crypto_drv_mtx);
    463 				return EBUSY;
    464 			}
    465 		}
    466 		mutex_exit(&crypto_drv_mtx);
    467 		/* FIXME:
    468 		 * prohibit touch crypto_drivers[] and each element after here.
    469 		 */
    470 
    471 		mutex_spin_enter(&crypto_ret_q_mtx);
    472 		/* kick the cryptoret thread and wait for it to exit */
    473 		crypto_exit_flag = 1;
    474 		cv_signal(&cryptoret_cv);
    475 
    476 		while (crypto_exit_flag != 0)
    477 			cv_wait(&cryptoret_cv, &crypto_ret_q_mtx);
    478 		mutex_spin_exit(&crypto_ret_q_mtx);
    479 	}
    480 
    481 	if (sysctl_opencrypto_clog != NULL)
    482 		sysctl_teardown(&sysctl_opencrypto_clog);
    483 
    484 	unregister_swi(SWI_CRYPTO, cryptointr);
    485 
    486 	mutex_enter(&crypto_drv_mtx);
    487 	if (crypto_drivers != NULL)
    488 		free(crypto_drivers, M_CRYPTO_DATA);
    489 	mutex_exit(&crypto_drv_mtx);
    490 
    491 	pool_destroy(&cryptop_pool);
    492 	pool_destroy(&cryptodesc_pool);
    493 	pool_destroy(&cryptkop_pool);
    494 
    495 	cv_destroy(&cryptoret_cv);
    496 
    497 	mutex_destroy(&crypto_ret_q_mtx);
    498 	mutex_destroy(&crypto_q_mtx);
    499 	mutex_destroy(&crypto_drv_mtx);
    500 
    501 	return 0;
    502 }
    503 
    504 static bool
    505 crypto_driver_suitable(struct cryptocap *cap, struct cryptoini *cri)
    506 {
    507 	struct cryptoini *cr;
    508 
    509 	for (cr = cri; cr; cr = cr->cri_next)
    510 		if (cap->cc_alg[cr->cri_alg] == 0) {
    511 			DPRINTF("alg %d not supported\n", cr->cri_alg);
    512 			return false;
    513 		}
    514 
    515 	return true;
    516 }
    517 
    518 /*
    519  * The algorithm we use here is pretty stupid; just use the
    520  * first driver that supports all the algorithms we need.
    521  *
    522  * XXX We need more smarts here (in real life too, but that's
    523  * XXX another story altogether).
    524  */
    525 static struct cryptocap *
    526 crypto_select_driver_lock(struct cryptoini *cri, int hard)
    527 {
    528 	u_int32_t hid;
    529 
    530 	for (hid = 0; hid < crypto_drivers_num; hid++) {
    531 		struct cryptocap *cap = crypto_checkdriver(hid);
    532 		if (cap == NULL)
    533 			continue;
    534 
    535 		crypto_driver_lock(cap);
    536 
    537 		/*
    538 		 * If it's not initialized or has remaining sessions
    539 		 * referencing it, skip.
    540 		 */
    541 		if (cap->cc_newsession == NULL ||
    542 		    (cap->cc_flags & CRYPTOCAP_F_CLEANUP)) {
    543 			crypto_driver_unlock(cap);
    544 			continue;
    545 		}
    546 
    547 		/* Hardware required -- ignore software drivers. */
    548 		if (hard > 0 && (cap->cc_flags & CRYPTOCAP_F_SOFTWARE)) {
    549 			crypto_driver_unlock(cap);
    550 			continue;
    551 		}
    552 		/* Software required -- ignore hardware drivers. */
    553 		if (hard < 0 && (cap->cc_flags & CRYPTOCAP_F_SOFTWARE) == 0) {
    554 			crypto_driver_unlock(cap);
    555 			continue;
    556 		}
    557 
    558 		/* See if all the algorithms are supported. */
    559 		if (crypto_driver_suitable(cap, cri)) {
    560 			/* keep holding crypto_driver_lock(cap) */
    561 			return cap;
    562 		}
    563 
    564 		crypto_driver_unlock(cap);
    565 	}
    566 
    567 	return NULL;
    568 }
    569 
    570 /*
    571  * Create a new session.
    572  */
    573 int
    574 crypto_newsession(u_int64_t *sid, struct cryptoini *cri, int hard)
    575 {
    576 	struct cryptocap *cap;
    577 	int err = EINVAL;
    578 
    579 	mutex_enter(&crypto_drv_mtx);
    580 
    581 	cap = crypto_select_driver_lock(cri, hard);
    582 	if (cap != NULL) {
    583 		u_int32_t hid, lid;
    584 
    585 		hid = cap - crypto_drivers;
    586 		/*
    587 		 * Can't do everything in one session.
    588 		 *
    589 		 * XXX Fix this. We need to inject a "virtual" session layer right
    590 		 * XXX about here.
    591 		 */
    592 
    593 		/* Call the driver initialization routine. */
    594 		lid = hid;		/* Pass the driver ID. */
    595 		crypto_driver_unlock(cap);
    596 		err = cap->cc_newsession(cap->cc_arg, &lid, cri);
    597 		crypto_driver_lock(cap);
    598 		if (err == 0) {
    599 			(*sid) = hid;
    600 			(*sid) <<= 32;
    601 			(*sid) |= (lid & 0xffffffff);
    602 			(cap->cc_sessions)++;
    603 		} else {
    604 			DPRINTF("crypto_drivers[%d].cc_newsession() failed. error=%d\n",
    605 			    hid, err);
    606 		}
    607 		crypto_driver_unlock(cap);
    608 	}
    609 
    610 	mutex_exit(&crypto_drv_mtx);
    611 
    612 	return err;
    613 }
    614 
    615 /*
    616  * Delete an existing session (or a reserved session on an unregistered
    617  * driver).
    618  */
    619 int
    620 crypto_freesession(u_int64_t sid)
    621 {
    622 	struct cryptocap *cap;
    623 	int err = 0;
    624 
    625 	/* Determine two IDs. */
    626 	cap = crypto_checkdriver_lock(CRYPTO_SESID2HID(sid));
    627 	if (cap == NULL)
    628 		return ENOENT;
    629 
    630 	if (cap->cc_sessions)
    631 		(cap->cc_sessions)--;
    632 
    633 	/* Call the driver cleanup routine, if available. */
    634 	if (cap->cc_freesession)
    635 		err = cap->cc_freesession(cap->cc_arg, sid);
    636 	else
    637 		err = 0;
    638 
    639 	/*
    640 	 * If this was the last session of a driver marked as invalid,
    641 	 * make the entry available for reuse.
    642 	 */
    643 	if ((cap->cc_flags & CRYPTOCAP_F_CLEANUP) && cap->cc_sessions == 0)
    644 		crypto_driver_clear(cap);
    645 
    646 	crypto_driver_unlock(cap);
    647 	return err;
    648 }
    649 
    650 static bool
    651 crypto_checkdriver_initialized(const struct cryptocap *cap)
    652 {
    653 
    654 	return cap->cc_process != NULL ||
    655 	    (cap->cc_flags & CRYPTOCAP_F_CLEANUP) != 0 ||
    656 	    cap->cc_sessions != 0;
    657 }
    658 
    659 /*
    660  * Return an unused driver id.  Used by drivers prior to registering
    661  * support for the algorithms they handle.
    662  */
    663 int32_t
    664 crypto_get_driverid(u_int32_t flags)
    665 {
    666 	struct cryptocap *newdrv;
    667 	struct cryptocap *cap = NULL;
    668 	int i;
    669 
    670 	(void)crypto_init();		/* XXX oh, this is foul! */
    671 
    672 	mutex_enter(&crypto_drv_mtx);
    673 	for (i = 0; i < crypto_drivers_num; i++) {
    674 		cap = crypto_checkdriver_uninit(i);
    675 		if (cap == NULL || crypto_checkdriver_initialized(cap))
    676 			continue;
    677 		break;
    678 	}
    679 
    680 	/* Out of entries, allocate some more. */
    681 	if (cap == NULL) {
    682 		/* Be careful about wrap-around. */
    683 		if (2 * crypto_drivers_num <= crypto_drivers_num) {
    684 			mutex_exit(&crypto_drv_mtx);
    685 			printf("crypto: driver count wraparound!\n");
    686 			return -1;
    687 		}
    688 
    689 		newdrv = malloc(2 * crypto_drivers_num *
    690 		    sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT|M_ZERO);
    691 		if (newdrv == NULL) {
    692 			mutex_exit(&crypto_drv_mtx);
    693 			printf("crypto: no space to expand driver table!\n");
    694 			return -1;
    695 		}
    696 
    697 		memcpy(newdrv, crypto_drivers,
    698 		    crypto_drivers_num * sizeof(struct cryptocap));
    699 
    700 		crypto_drivers_num *= 2;
    701 
    702 		free(crypto_drivers, M_CRYPTO_DATA);
    703 		crypto_drivers = newdrv;
    704 
    705 		cap = crypto_checkdriver_uninit(i);
    706 		KASSERT(cap != NULL);
    707 	}
    708 
    709 	/* NB: state is zero'd on free */
    710 	cap->cc_sessions = 1;	/* Mark */
    711 	cap->cc_flags = flags;
    712 	mutex_init(&cap->cc_lock, MUTEX_DEFAULT, IPL_NET);
    713 
    714 	if (bootverbose)
    715 		printf("crypto: assign driver %u, flags %u\n", i, flags);
    716 
    717 	mutex_exit(&crypto_drv_mtx);
    718 
    719 	return i;
    720 }
    721 
    722 static struct cryptocap *
    723 crypto_checkdriver_lock(u_int32_t hid)
    724 {
    725 	struct cryptocap *cap;
    726 
    727 	KASSERT(crypto_drivers != NULL);
    728 
    729 	if (hid >= crypto_drivers_num)
    730 		return NULL;
    731 
    732 	cap = &crypto_drivers[hid];
    733 	mutex_enter(&cap->cc_lock);
    734 	return cap;
    735 }
    736 
    737 /*
    738  * Use crypto_checkdriver_uninit() instead of crypto_checkdriver() below two
    739  * situations
    740  *     - crypto_drivers[] may not be allocated
    741  *     - crypto_drivers[hid] may not be initialized
    742  */
    743 static struct cryptocap *
    744 crypto_checkdriver_uninit(u_int32_t hid)
    745 {
    746 
    747 	KASSERT(mutex_owned(&crypto_drv_mtx));
    748 
    749 	if (crypto_drivers == NULL)
    750 		return NULL;
    751 
    752 	return (hid >= crypto_drivers_num ? NULL : &crypto_drivers[hid]);
    753 }
    754 
    755 /*
    756  * Use crypto_checkdriver_uninit() instead of crypto_checkdriver() below two
    757  * situations
    758  *     - crypto_drivers[] may not be allocated
    759  *     - crypto_drivers[hid] may not be initialized
    760  */
    761 static struct cryptocap *
    762 crypto_checkdriver(u_int32_t hid)
    763 {
    764 
    765 	KASSERT(mutex_owned(&crypto_drv_mtx));
    766 
    767 	if (crypto_drivers == NULL || hid >= crypto_drivers_num)
    768 		return NULL;
    769 
    770 	struct cryptocap *cap = &crypto_drivers[hid];
    771 	return crypto_checkdriver_initialized(cap) ? cap : NULL;
    772 }
    773 
    774 static inline void
    775 crypto_driver_lock(struct cryptocap *cap)
    776 {
    777 
    778 	KASSERT(cap != NULL);
    779 
    780 	mutex_enter(&cap->cc_lock);
    781 }
    782 
    783 static inline void
    784 crypto_driver_unlock(struct cryptocap *cap)
    785 {
    786 
    787 	KASSERT(cap != NULL);
    788 
    789 	mutex_exit(&cap->cc_lock);
    790 }
    791 
    792 static void
    793 crypto_driver_clear(struct cryptocap *cap)
    794 {
    795 
    796 	if (cap == NULL)
    797 		return;
    798 
    799 	KASSERT(mutex_owned(&cap->cc_lock));
    800 
    801 	cap->cc_sessions = 0;
    802 	memset(&cap->cc_max_op_len, 0, sizeof(cap->cc_max_op_len));
    803 	memset(&cap->cc_alg, 0, sizeof(cap->cc_alg));
    804 	memset(&cap->cc_kalg, 0, sizeof(cap->cc_kalg));
    805 	cap->cc_flags = 0;
    806 	cap->cc_qblocked = 0;
    807 	cap->cc_kqblocked = 0;
    808 
    809 	cap->cc_arg = NULL;
    810 	cap->cc_newsession = NULL;
    811 	cap->cc_process = NULL;
    812 	cap->cc_freesession = NULL;
    813 	cap->cc_kprocess = NULL;
    814 }
    815 
    816 /*
    817  * Register support for a key-related algorithm.  This routine
    818  * is called once for each algorithm supported a driver.
    819  */
    820 int
    821 crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags,
    822     int (*kprocess)(void *, struct cryptkop *, int),
    823     void *karg)
    824 {
    825 	struct cryptocap *cap;
    826 	int err;
    827 
    828 	mutex_enter(&crypto_drv_mtx);
    829 
    830 	cap = crypto_checkdriver_lock(driverid);
    831 	if (cap != NULL &&
    832 	    (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
    833 		/*
    834 		 * XXX Do some performance testing to determine placing.
    835 		 * XXX We probably need an auxiliary data structure that
    836 		 * XXX describes relative performances.
    837 		 */
    838 
    839 		cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
    840 		if (bootverbose) {
    841 			printf("crypto: driver %u registers key alg %u "
    842 			       " flags %u\n",
    843 				driverid,
    844 				kalg,
    845 				flags
    846 			);
    847 		}
    848 
    849 		if (cap->cc_kprocess == NULL) {
    850 			cap->cc_karg = karg;
    851 			cap->cc_kprocess = kprocess;
    852 		}
    853 		err = 0;
    854 	} else
    855 		err = EINVAL;
    856 
    857 	mutex_exit(&crypto_drv_mtx);
    858 	return err;
    859 }
    860 
    861 /*
    862  * Register support for a non-key-related algorithm.  This routine
    863  * is called once for each such algorithm supported by a driver.
    864  */
    865 int
    866 crypto_register(u_int32_t driverid, int alg, u_int16_t maxoplen,
    867     u_int32_t flags,
    868     int (*newses)(void *, u_int32_t*, struct cryptoini*),
    869     int (*freeses)(void *, u_int64_t),
    870     int (*process)(void *, struct cryptop *, int),
    871     void *arg)
    872 {
    873 	struct cryptocap *cap;
    874 	int err;
    875 
    876 	cap = crypto_checkdriver_lock(driverid);
    877 	if (cap == NULL)
    878 		return EINVAL;
    879 
    880 	/* NB: algorithms are in the range [1..max] */
    881 	if (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX) {
    882 		/*
    883 		 * XXX Do some performance testing to determine placing.
    884 		 * XXX We probably need an auxiliary data structure that
    885 		 * XXX describes relative performances.
    886 		 */
    887 
    888 		cap->cc_alg[alg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
    889 		cap->cc_max_op_len[alg] = maxoplen;
    890 		if (bootverbose) {
    891 			printf("crypto: driver %u registers alg %u "
    892 				"flags %u maxoplen %u\n",
    893 				driverid,
    894 				alg,
    895 				flags,
    896 				maxoplen
    897 			);
    898 		}
    899 
    900 		if (cap->cc_process == NULL) {
    901 			cap->cc_arg = arg;
    902 			cap->cc_newsession = newses;
    903 			cap->cc_process = process;
    904 			cap->cc_freesession = freeses;
    905 			cap->cc_sessions = 0;		/* Unmark */
    906 		}
    907 		err = 0;
    908 	} else
    909 		err = EINVAL;
    910 
    911 	crypto_driver_unlock(cap);
    912 
    913 	return err;
    914 }
    915 
    916 static int
    917 crypto_unregister_locked(struct cryptocap *cap, int alg, bool all)
    918 {
    919 	int i;
    920 	u_int32_t ses;
    921 	bool lastalg = true;
    922 
    923 	KASSERT(cap != NULL);
    924 	KASSERT(mutex_owned(&cap->cc_lock));
    925 
    926 	if (alg < CRYPTO_ALGORITHM_MIN || CRYPTO_ALGORITHM_MAX < alg)
    927 		return EINVAL;
    928 
    929 	if (!all && cap->cc_alg[alg] == 0)
    930 		return EINVAL;
    931 
    932 	cap->cc_alg[alg] = 0;
    933 	cap->cc_max_op_len[alg] = 0;
    934 
    935 	if (all) {
    936 		if (alg != CRYPTO_ALGORITHM_MAX)
    937 			lastalg = false;
    938 	} else {
    939 		/* Was this the last algorithm ? */
    940 		for (i = CRYPTO_ALGORITHM_MIN; i <= CRYPTO_ALGORITHM_MAX; i++)
    941 			if (cap->cc_alg[i] != 0) {
    942 				lastalg = false;
    943 				break;
    944 			}
    945 	}
    946 	if (lastalg) {
    947 		ses = cap->cc_sessions;
    948 		crypto_driver_clear(cap);
    949 		if (ses != 0) {
    950 			/*
    951 			 * If there are pending sessions, just mark as invalid.
    952 			 */
    953 			cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
    954 			cap->cc_sessions = ses;
    955 		}
    956 	}
    957 
    958 	return 0;
    959 }
    960 
    961 /*
    962  * Unregister a crypto driver. If there are pending sessions using it,
    963  * leave enough information around so that subsequent calls using those
    964  * sessions will correctly detect the driver has been unregistered and
    965  * reroute requests.
    966  */
    967 int
    968 crypto_unregister(u_int32_t driverid, int alg)
    969 {
    970 	int err;
    971 	struct cryptocap *cap;
    972 
    973 	cap = crypto_checkdriver_lock(driverid);
    974 	err = crypto_unregister_locked(cap, alg, false);
    975 	crypto_driver_unlock(cap);
    976 
    977 	return err;
    978 }
    979 
    980 /*
    981  * Unregister all algorithms associated with a crypto driver.
    982  * If there are pending sessions using it, leave enough information
    983  * around so that subsequent calls using those sessions will
    984  * correctly detect the driver has been unregistered and reroute
    985  * requests.
    986  */
    987 int
    988 crypto_unregister_all(u_int32_t driverid)
    989 {
    990 	int err, i;
    991 	struct cryptocap *cap;
    992 
    993 	cap = crypto_checkdriver_lock(driverid);
    994 	for (i = CRYPTO_ALGORITHM_MIN; i <= CRYPTO_ALGORITHM_MAX; i++) {
    995 		err = crypto_unregister_locked(cap, i, true);
    996 		if (err)
    997 			break;
    998 	}
    999 	crypto_driver_unlock(cap);
   1000 
   1001 	return err;
   1002 }
   1003 
   1004 /*
   1005  * Clear blockage on a driver.  The what parameter indicates whether
   1006  * the driver is now ready for cryptop's and/or cryptokop's.
   1007  */
   1008 int
   1009 crypto_unblock(u_int32_t driverid, int what)
   1010 {
   1011 	struct cryptocap *cap;
   1012 	int needwakeup = 0;
   1013 
   1014 	cap = crypto_checkdriver_lock(driverid);
   1015 	if (cap == NULL)
   1016 		return EINVAL;
   1017 
   1018 	if (what & CRYPTO_SYMQ) {
   1019 		needwakeup |= cap->cc_qblocked;
   1020 		cap->cc_qblocked = 0;
   1021 	}
   1022 	if (what & CRYPTO_ASYMQ) {
   1023 		needwakeup |= cap->cc_kqblocked;
   1024 		cap->cc_kqblocked = 0;
   1025 	}
   1026 	crypto_driver_unlock(cap);
   1027 	if (needwakeup)
   1028 		setsoftcrypto(softintr_cookie);
   1029 
   1030 	return 0;
   1031 }
   1032 
   1033 /*
   1034  * Dispatch a crypto request to a driver or queue
   1035  * it, to be processed by the kernel thread.
   1036  */
   1037 int
   1038 crypto_dispatch(struct cryptop *crp)
   1039 {
   1040 	int result;
   1041 	struct cryptocap *cap;
   1042 
   1043 	KASSERT(crp != NULL);
   1044 
   1045 	DPRINTF("crp %p, alg %d\n", crp, crp->crp_desc->crd_alg);
   1046 
   1047 	cryptostats.cs_ops++;
   1048 
   1049 #ifdef CRYPTO_TIMING
   1050 	if (crypto_timing)
   1051 		nanouptime(&crp->crp_tstamp);
   1052 #endif
   1053 
   1054 	if ((crp->crp_flags & CRYPTO_F_BATCH) != 0) {
   1055 		int wasempty;
   1056 		/*
   1057 		 * Caller marked the request as ``ok to delay'';
   1058 		 * queue it for the swi thread.  This is desirable
   1059 		 * when the operation is low priority and/or suitable
   1060 		 * for batching.
   1061 		 *
   1062 		 * don't care list order in batch job.
   1063 		 */
   1064 		mutex_enter(&crypto_q_mtx);
   1065 		wasempty  = TAILQ_EMPTY(&crp_q);
   1066 		TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
   1067 		mutex_exit(&crypto_q_mtx);
   1068 		if (wasempty)
   1069 			setsoftcrypto(softintr_cookie);
   1070 
   1071 		return 0;
   1072 	}
   1073 
   1074 	mutex_enter(&crypto_q_mtx);
   1075 	cap = crypto_checkdriver_lock(CRYPTO_SESID2HID(crp->crp_sid));
   1076 	/*
   1077 	 * TODO:
   1078 	 * If we can ensure the driver has been valid until the driver is
   1079 	 * done crypto_unregister(), this migrate operation is not required.
   1080 	 */
   1081 	if (cap == NULL) {
   1082 		/*
   1083 		 * The driver must be detached, so this request will migrate
   1084 		 * to other drivers in cryptointr() later.
   1085 		 */
   1086 		TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
   1087 		mutex_exit(&crypto_q_mtx);
   1088 		return 0;
   1089 	}
   1090 
   1091 	if (cap->cc_qblocked != 0) {
   1092 		crypto_driver_unlock(cap);
   1093 		/*
   1094 		 * The driver is blocked, just queue the op until
   1095 		 * it unblocks and the swi thread gets kicked.
   1096 		 */
   1097 		TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
   1098 		mutex_exit(&crypto_q_mtx);
   1099 		return 0;
   1100 	}
   1101 
   1102 	/*
   1103 	 * Caller marked the request to be processed
   1104 	 * immediately; dispatch it directly to the
   1105 	 * driver unless the driver is currently blocked.
   1106 	 */
   1107 	crypto_driver_unlock(cap);
   1108 	result = crypto_invoke(crp, 0);
   1109 	if (result == ERESTART) {
   1110 		/*
   1111 		 * The driver ran out of resources, mark the
   1112 		 * driver ``blocked'' for cryptop's and put
   1113 		 * the op on the queue.
   1114 		 */
   1115 		crypto_driver_lock(cap);
   1116 		cap->cc_qblocked = 1;
   1117 		crypto_driver_unlock(cap);
   1118 		TAILQ_INSERT_HEAD(&crp_q, crp, crp_next);
   1119 		cryptostats.cs_blocks++;
   1120 
   1121 		/*
   1122 		 * The crp is enqueued to crp_q, that is,
   1123 		 * no error occurs. So, this function should
   1124 		 * not return error.
   1125 		 */
   1126 		result = 0;
   1127 	}
   1128 
   1129 	mutex_exit(&crypto_q_mtx);
   1130 	return result;
   1131 }
   1132 
   1133 /*
   1134  * Add an asymetric crypto request to a queue,
   1135  * to be processed by the kernel thread.
   1136  */
   1137 int
   1138 crypto_kdispatch(struct cryptkop *krp)
   1139 {
   1140 	struct cryptocap *cap;
   1141 	int result;
   1142 
   1143 	KASSERT(krp != NULL);
   1144 
   1145 	cryptostats.cs_kops++;
   1146 
   1147 	mutex_enter(&crypto_q_mtx);
   1148 	cap = crypto_checkdriver_lock(krp->krp_hid);
   1149 	/*
   1150 	 * TODO:
   1151 	 * If we can ensure the driver has been valid until the driver is
   1152 	 * done crypto_unregister(), this migrate operation is not required.
   1153 	 */
   1154 	if (cap == NULL) {
   1155 		TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
   1156 		mutex_exit(&crypto_q_mtx);
   1157 		return 0;
   1158 	}
   1159 
   1160 	if (cap->cc_kqblocked != 0) {
   1161 		crypto_driver_unlock(cap);
   1162 		/*
   1163 		 * The driver is blocked, just queue the op until
   1164 		 * it unblocks and the swi thread gets kicked.
   1165 		 */
   1166 		TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
   1167 		mutex_exit(&crypto_q_mtx);
   1168 		return 0;
   1169 	}
   1170 
   1171 	crypto_driver_unlock(cap);
   1172 	result = crypto_kinvoke(krp, 0);
   1173 	if (result == ERESTART) {
   1174 		/*
   1175 		 * The driver ran out of resources, mark the
   1176 		 * driver ``blocked'' for cryptop's and put
   1177 		 * the op on the queue.
   1178 		 */
   1179 		crypto_driver_lock(cap);
   1180 		cap->cc_kqblocked = 1;
   1181 		crypto_driver_unlock(cap);
   1182 		TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
   1183 		cryptostats.cs_kblocks++;
   1184 		mutex_exit(&crypto_q_mtx);
   1185 
   1186 		/*
   1187 		 * The krp is enqueued to crp_kq, that is,
   1188 		 * no error occurs. So, this function should
   1189 		 * not return error.
   1190 		 */
   1191 		result = 0;
   1192 	}
   1193 
   1194 	return result;
   1195 }
   1196 
   1197 /*
   1198  * Dispatch an assymetric crypto request to the appropriate crypto devices.
   1199  */
   1200 static int
   1201 crypto_kinvoke(struct cryptkop *krp, int hint)
   1202 {
   1203 	struct cryptocap *cap = NULL;
   1204 	u_int32_t hid;
   1205 	int error;
   1206 
   1207 	KASSERT(krp != NULL);
   1208 
   1209 	/* Sanity checks. */
   1210 	if (krp->krp_callback == NULL) {
   1211 		cv_destroy(&krp->krp_cv);
   1212 		crypto_kfreereq(krp);
   1213 		return EINVAL;
   1214 	}
   1215 
   1216 	mutex_enter(&crypto_drv_mtx);
   1217 	for (hid = 0; hid < crypto_drivers_num; hid++) {
   1218 		cap = crypto_checkdriver(hid);
   1219 		if (cap == NULL)
   1220 			continue;
   1221 		crypto_driver_lock(cap);
   1222 		if ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
   1223 		    crypto_devallowsoft == 0) {
   1224 			crypto_driver_unlock(cap);
   1225 			continue;
   1226 		}
   1227 		if (cap->cc_kprocess == NULL) {
   1228 			crypto_driver_unlock(cap);
   1229 			continue;
   1230 		}
   1231 		if ((cap->cc_kalg[krp->krp_op] &
   1232 			CRYPTO_ALG_FLAG_SUPPORTED) == 0) {
   1233 			crypto_driver_unlock(cap);
   1234 			continue;
   1235 		}
   1236 		break;
   1237 	}
   1238 	mutex_exit(&crypto_drv_mtx);
   1239 	if (cap != NULL) {
   1240 		int (*process)(void *, struct cryptkop *, int);
   1241 		void *arg;
   1242 
   1243 		process = cap->cc_kprocess;
   1244 		arg = cap->cc_karg;
   1245 		krp->krp_hid = hid;
   1246 		crypto_driver_unlock(cap);
   1247 		error = (*process)(arg, krp, hint);
   1248 	} else {
   1249 		error = ENODEV;
   1250 	}
   1251 
   1252 	if (error) {
   1253 		krp->krp_status = error;
   1254 		crypto_kdone(krp);
   1255 	}
   1256 	return 0;
   1257 }
   1258 
   1259 #ifdef CRYPTO_TIMING
   1260 static void
   1261 crypto_tstat(struct cryptotstat *ts, struct timespec *tv)
   1262 {
   1263 	struct timespec now, t;
   1264 
   1265 	nanouptime(&now);
   1266 	t.tv_sec = now.tv_sec - tv->tv_sec;
   1267 	t.tv_nsec = now.tv_nsec - tv->tv_nsec;
   1268 	if (t.tv_nsec < 0) {
   1269 		t.tv_sec--;
   1270 		t.tv_nsec += 1000000000;
   1271 	}
   1272 	timespecadd(&ts->acc, &t, &t);
   1273 	if (timespeccmp(&t, &ts->min, <))
   1274 		ts->min = t;
   1275 	if (timespeccmp(&t, &ts->max, >))
   1276 		ts->max = t;
   1277 	ts->count++;
   1278 
   1279 	*tv = now;
   1280 }
   1281 #endif
   1282 
   1283 /*
   1284  * Dispatch a crypto request to the appropriate crypto devices.
   1285  */
   1286 static int
   1287 crypto_invoke(struct cryptop *crp, int hint)
   1288 {
   1289 	struct cryptocap *cap;
   1290 
   1291 	KASSERT(crp != NULL);
   1292 
   1293 #ifdef CRYPTO_TIMING
   1294 	if (crypto_timing)
   1295 		crypto_tstat(&cryptostats.cs_invoke, &crp->crp_tstamp);
   1296 #endif
   1297 	/* Sanity checks. */
   1298 	if (crp->crp_callback == NULL) {
   1299 		return EINVAL;
   1300 	}
   1301 	if (crp->crp_desc == NULL) {
   1302 		crp->crp_etype = EINVAL;
   1303 		crypto_done(crp);
   1304 		return 0;
   1305 	}
   1306 
   1307 	cap = crypto_checkdriver_lock(CRYPTO_SESID2HID(crp->crp_sid));
   1308 	if (cap != NULL && (cap->cc_flags & CRYPTOCAP_F_CLEANUP) == 0) {
   1309 		int (*process)(void *, struct cryptop *, int);
   1310 		void *arg;
   1311 
   1312 		process = cap->cc_process;
   1313 		arg = cap->cc_arg;
   1314 
   1315 		/*
   1316 		 * Invoke the driver to process the request.
   1317 		 */
   1318 		DPRINTF("calling process for %p\n", crp);
   1319 		crypto_driver_unlock(cap);
   1320 		return (*process)(arg, crp, hint);
   1321 	} else {
   1322 		struct cryptodesc *crd;
   1323 		u_int64_t nid = 0;
   1324 
   1325 		if (cap != NULL)
   1326 			crypto_driver_unlock(cap);
   1327 
   1328 		/*
   1329 		 * Driver has unregistered; migrate the session and return
   1330 		 * an error to the caller so they'll resubmit the op.
   1331 		 */
   1332 		crypto_freesession(crp->crp_sid);
   1333 
   1334 		for (crd = crp->crp_desc; crd->crd_next; crd = crd->crd_next)
   1335 			crd->CRD_INI.cri_next = &(crd->crd_next->CRD_INI);
   1336 
   1337 		if (crypto_newsession(&nid, &(crp->crp_desc->CRD_INI), 0) == 0)
   1338 			crp->crp_sid = nid;
   1339 
   1340 		crp->crp_etype = EAGAIN;
   1341 
   1342 		crypto_done(crp);
   1343 		return 0;
   1344 	}
   1345 }
   1346 
   1347 /*
   1348  * Release a set of crypto descriptors.
   1349  */
   1350 void
   1351 crypto_freereq(struct cryptop *crp)
   1352 {
   1353 	struct cryptodesc *crd;
   1354 
   1355 	if (crp == NULL)
   1356 		return;
   1357 	DPRINTF("lid[%u]: crp %p\n", CRYPTO_SESID2LID(crp->crp_sid), crp);
   1358 
   1359 	/* sanity check */
   1360 	if (crp->crp_flags & CRYPTO_F_ONRETQ) {
   1361 		panic("crypto_freereq() freeing crp on RETQ\n");
   1362 	}
   1363 
   1364 	while ((crd = crp->crp_desc) != NULL) {
   1365 		crp->crp_desc = crd->crd_next;
   1366 		pool_put(&cryptodesc_pool, crd);
   1367 	}
   1368 	pool_put(&cryptop_pool, crp);
   1369 }
   1370 
   1371 /*
   1372  * Acquire a set of crypto descriptors.
   1373  */
   1374 struct cryptop *
   1375 crypto_getreq(int num)
   1376 {
   1377 	struct cryptodesc *crd;
   1378 	struct cryptop *crp;
   1379 
   1380 	/*
   1381 	 * When crp_ret_q is full, we restrict here to avoid crp_ret_q overflow
   1382 	 * by error callback.
   1383 	 */
   1384 	if (CRYPTO_Q_IS_FULL(crp_ret_q)) {
   1385 		CRYPTO_Q_INC_DROPS(crp_ret_q);
   1386 		return NULL;
   1387 	}
   1388 
   1389 	crp = pool_get(&cryptop_pool, 0);
   1390 	if (crp == NULL) {
   1391 		return NULL;
   1392 	}
   1393 	memset(crp, 0, sizeof(struct cryptop));
   1394 
   1395 	while (num--) {
   1396 		crd = pool_get(&cryptodesc_pool, 0);
   1397 		if (crd == NULL) {
   1398 			crypto_freereq(crp);
   1399 			return NULL;
   1400 		}
   1401 
   1402 		memset(crd, 0, sizeof(struct cryptodesc));
   1403 		crd->crd_next = crp->crp_desc;
   1404 		crp->crp_desc = crd;
   1405 	}
   1406 
   1407 	return crp;
   1408 }
   1409 
   1410 /*
   1411  * Release a set of asymmetric crypto descriptors.
   1412  * Currently, support one descriptor only.
   1413  */
   1414 void
   1415 crypto_kfreereq(struct cryptkop *krp)
   1416 {
   1417 
   1418 	if (krp == NULL)
   1419 		return;
   1420 
   1421 	DPRINTF("krp %p\n", krp);
   1422 
   1423 	/* sanity check */
   1424 	if (krp->krp_flags & CRYPTO_F_ONRETQ) {
   1425 		panic("crypto_kfreereq() freeing krp on RETQ\n");
   1426 	}
   1427 
   1428 	pool_put(&cryptkop_pool, krp);
   1429 }
   1430 
   1431 /*
   1432  * Acquire a set of asymmetric crypto descriptors.
   1433  * Currently, support one descriptor only.
   1434  */
   1435 struct cryptkop *
   1436 crypto_kgetreq(int num __unused, int prflags)
   1437 {
   1438 	struct cryptkop *krp;
   1439 
   1440 	/*
   1441 	 * When crp_ret_kq is full, we restrict here to avoid crp_ret_kq
   1442 	 * overflow by error callback.
   1443 	 */
   1444 	if (CRYPTO_Q_IS_FULL(crp_ret_kq)) {
   1445 		CRYPTO_Q_INC_DROPS(crp_ret_kq);
   1446 		return NULL;
   1447 	}
   1448 
   1449 	krp = pool_get(&cryptkop_pool, prflags);
   1450 	if (krp == NULL) {
   1451 		return NULL;
   1452 	}
   1453 	memset(krp, 0, sizeof(struct cryptkop));
   1454 
   1455 	return krp;
   1456 }
   1457 
   1458 /*
   1459  * Invoke the callback on behalf of the driver.
   1460  */
   1461 void
   1462 crypto_done(struct cryptop *crp)
   1463 {
   1464 	int wasempty;
   1465 
   1466 	KASSERT(crp != NULL);
   1467 
   1468 	if (crp->crp_etype != 0)
   1469 		cryptostats.cs_errs++;
   1470 #ifdef CRYPTO_TIMING
   1471 	if (crypto_timing)
   1472 		crypto_tstat(&cryptostats.cs_done, &crp->crp_tstamp);
   1473 #endif
   1474 	DPRINTF("lid[%u]: crp %p\n", CRYPTO_SESID2LID(crp->crp_sid), crp);
   1475 
   1476 	/*
   1477 	 * Normal case; queue the callback for the thread.
   1478 	 *
   1479 	 * The return queue is manipulated by the swi thread
   1480 	 * and, potentially, by crypto device drivers calling
   1481 	 * back to mark operations completed.  Thus we need
   1482 	 * to mask both while manipulating the return queue.
   1483 	 */
   1484   	if (crp->crp_flags & CRYPTO_F_CBIMM) {
   1485 		/*
   1486 	 	* Do the callback directly.  This is ok when the
   1487   	 	* callback routine does very little (e.g. the
   1488 	 	* /dev/crypto callback method just does a wakeup).
   1489 	 	*/
   1490 		mutex_spin_enter(&crypto_ret_q_mtx);
   1491 		crp->crp_flags |= CRYPTO_F_DONE;
   1492 		mutex_spin_exit(&crypto_ret_q_mtx);
   1493 
   1494 #ifdef CRYPTO_TIMING
   1495 		if (crypto_timing) {
   1496 			/*
   1497 		 	* NB: We must copy the timestamp before
   1498 		 	* doing the callback as the cryptop is
   1499 		 	* likely to be reclaimed.
   1500 		 	*/
   1501 			struct timespec t = crp->crp_tstamp;
   1502 			crypto_tstat(&cryptostats.cs_cb, &t);
   1503 			crp->crp_callback(crp);
   1504 			crypto_tstat(&cryptostats.cs_finis, &t);
   1505 		} else
   1506 #endif
   1507 		crp->crp_callback(crp);
   1508 	} else {
   1509 		mutex_spin_enter(&crypto_ret_q_mtx);
   1510 		crp->crp_flags |= CRYPTO_F_DONE;
   1511 #if 0
   1512 		if (crp->crp_flags & CRYPTO_F_USER) {
   1513 			/*
   1514 			 * TODO:
   1515 			 * If crp->crp_flags & CRYPTO_F_USER and the used
   1516 			 * encryption driver does all the processing in
   1517 			 * the same context, we can skip enqueueing crp_ret_q
   1518 			 * and cv_signal(&cryptoret_cv).
   1519 			 */
   1520 			DPRINTF("lid[%u]: crp %p CRYPTO_F_USER\n",
   1521 				CRYPTO_SESID2LID(crp->crp_sid), crp);
   1522 		} else
   1523 #endif
   1524 		{
   1525 			wasempty = TAILQ_EMPTY(&crp_ret_q);
   1526 			DPRINTF("lid[%u]: queueing %p\n",
   1527 				CRYPTO_SESID2LID(crp->crp_sid), crp);
   1528 			crp->crp_flags |= CRYPTO_F_ONRETQ;
   1529 			TAILQ_INSERT_TAIL(&crp_ret_q, crp, crp_next);
   1530 			CRYPTO_Q_INC(crp_ret_q);
   1531 			if (wasempty) {
   1532 				DPRINTF("lid[%u]: waking cryptoret, "
   1533 					"crp %p hit empty queue\n.",
   1534 					CRYPTO_SESID2LID(crp->crp_sid), crp);
   1535 				cv_signal(&cryptoret_cv);
   1536 			}
   1537 		}
   1538 		mutex_spin_exit(&crypto_ret_q_mtx);
   1539 	}
   1540 }
   1541 
   1542 /*
   1543  * Invoke the callback on behalf of the driver.
   1544  */
   1545 void
   1546 crypto_kdone(struct cryptkop *krp)
   1547 {
   1548 	int wasempty;
   1549 
   1550 	KASSERT(krp != NULL);
   1551 
   1552 	if (krp->krp_status != 0)
   1553 		cryptostats.cs_kerrs++;
   1554 
   1555 	krp->krp_flags |= CRYPTO_F_DONE;
   1556 
   1557 	/*
   1558 	 * The return queue is manipulated by the swi thread
   1559 	 * and, potentially, by crypto device drivers calling
   1560 	 * back to mark operations completed.  Thus we need
   1561 	 * to mask both while manipulating the return queue.
   1562 	 */
   1563 	if (krp->krp_flags & CRYPTO_F_CBIMM) {
   1564 		krp->krp_callback(krp);
   1565 	} else {
   1566 		mutex_spin_enter(&crypto_ret_q_mtx);
   1567 		wasempty = TAILQ_EMPTY(&crp_ret_kq);
   1568 		krp->krp_flags |= CRYPTO_F_ONRETQ;
   1569 		TAILQ_INSERT_TAIL(&crp_ret_kq, krp, krp_next);
   1570 		CRYPTO_Q_INC(crp_ret_kq);
   1571 		if (wasempty)
   1572 			cv_signal(&cryptoret_cv);
   1573 		mutex_spin_exit(&crypto_ret_q_mtx);
   1574 	}
   1575 }
   1576 
   1577 int
   1578 crypto_getfeat(int *featp)
   1579 {
   1580 
   1581 	if (crypto_userasymcrypto == 0) {
   1582 		*featp = 0;
   1583 		return 0;
   1584 	}
   1585 
   1586 	mutex_enter(&crypto_drv_mtx);
   1587 
   1588 	int feat = 0;
   1589 	for (int hid = 0; hid < crypto_drivers_num; hid++) {
   1590 		struct cryptocap *cap;
   1591 		cap = crypto_checkdriver(hid);
   1592 		if (cap == NULL)
   1593 			continue;
   1594 
   1595 		crypto_driver_lock(cap);
   1596 
   1597 		if ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
   1598 		    crypto_devallowsoft == 0)
   1599 			goto unlock;
   1600 
   1601 		if (cap->cc_kprocess == NULL)
   1602 			goto unlock;
   1603 
   1604 		for (int kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
   1605 			if ((cap->cc_kalg[kalg] &
   1606 			    CRYPTO_ALG_FLAG_SUPPORTED) != 0)
   1607 				feat |=  1 << kalg;
   1608 
   1609 unlock:		crypto_driver_unlock(cap);
   1610 	}
   1611 
   1612 	mutex_exit(&crypto_drv_mtx);
   1613 	*featp = feat;
   1614 	return (0);
   1615 }
   1616 
   1617 /*
   1618  * Software interrupt thread to dispatch crypto requests.
   1619  */
   1620 static void
   1621 cryptointr(void)
   1622 {
   1623 	struct cryptop *crp, *submit, *cnext;
   1624 	struct cryptkop *krp, *knext;
   1625 	struct cryptocap *cap;
   1626 	int result, hint;
   1627 
   1628 	cryptostats.cs_intrs++;
   1629 	mutex_enter(&crypto_q_mtx);
   1630 	do {
   1631 		/*
   1632 		 * Find the first element in the queue that can be
   1633 		 * processed and look-ahead to see if multiple ops
   1634 		 * are ready for the same driver.
   1635 		 */
   1636 		submit = NULL;
   1637 		hint = 0;
   1638 		TAILQ_FOREACH_SAFE(crp, &crp_q, crp_next, cnext) {
   1639 			u_int32_t hid = CRYPTO_SESID2HID(crp->crp_sid);
   1640 			cap = crypto_checkdriver_lock(hid);
   1641 			if (cap == NULL || cap->cc_process == NULL) {
   1642 				if (cap != NULL)
   1643 					crypto_driver_unlock(cap);
   1644 				/* Op needs to be migrated, process it. */
   1645 				submit = crp;
   1646 				break;
   1647 			}
   1648 
   1649 			/*
   1650 			 * skip blocked crp regardless of CRYPTO_F_BATCH
   1651 			 */
   1652 			if (cap->cc_qblocked != 0) {
   1653 				crypto_driver_unlock(cap);
   1654 				continue;
   1655 			}
   1656 			crypto_driver_unlock(cap);
   1657 
   1658 			/*
   1659 			 * skip batch crp until the end of crp_q
   1660 			 */
   1661 			if ((crp->crp_flags & CRYPTO_F_BATCH) != 0) {
   1662 				if (submit == NULL) {
   1663 					submit = crp;
   1664 				} else {
   1665 					if (CRYPTO_SESID2HID(submit->crp_sid)
   1666 					    == hid)
   1667 						hint = CRYPTO_HINT_MORE;
   1668 				}
   1669 
   1670 				continue;
   1671 			}
   1672 
   1673 			/*
   1674 			 * found first crp which is neither blocked nor batch.
   1675 			 */
   1676 			submit = crp;
   1677 			/*
   1678 			 * batch crp can be processed much later, so clear hint.
   1679 			 */
   1680 			hint = 0;
   1681 			break;
   1682 		}
   1683 		if (submit != NULL) {
   1684 			TAILQ_REMOVE(&crp_q, submit, crp_next);
   1685 			result = crypto_invoke(submit, hint);
   1686 			/* we must take here as the TAILQ op or kinvoke
   1687 			   may need this mutex below.  sigh. */
   1688 			if (result == ERESTART) {
   1689 				/*
   1690 				 * The driver ran out of resources, mark the
   1691 				 * driver ``blocked'' for cryptop's and put
   1692 				 * the request back in the queue.  It would
   1693 				 * best to put the request back where we got
   1694 				 * it but that's hard so for now we put it
   1695 				 * at the front.  This should be ok; putting
   1696 				 * it at the end does not work.
   1697 				 */
   1698 				/* validate sid again */
   1699 				cap = crypto_checkdriver_lock(CRYPTO_SESID2HID(submit->crp_sid));
   1700 				if (cap == NULL) {
   1701 					/* migrate again, sigh... */
   1702 					TAILQ_INSERT_TAIL(&crp_q, submit, crp_next);
   1703 				} else {
   1704 					cap->cc_qblocked = 1;
   1705 					crypto_driver_unlock(cap);
   1706 					TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
   1707 					cryptostats.cs_blocks++;
   1708 				}
   1709 			}
   1710 		}
   1711 
   1712 		/* As above, but for key ops */
   1713 		TAILQ_FOREACH_SAFE(krp, &crp_kq, krp_next, knext) {
   1714 			cap = crypto_checkdriver_lock(krp->krp_hid);
   1715 			if (cap == NULL || cap->cc_kprocess == NULL) {
   1716 				if (cap != NULL)
   1717 					crypto_driver_unlock(cap);
   1718 				/* Op needs to be migrated, process it. */
   1719 				break;
   1720 			}
   1721 			if (!cap->cc_kqblocked) {
   1722 				crypto_driver_unlock(cap);
   1723 				break;
   1724 			}
   1725 			crypto_driver_unlock(cap);
   1726 		}
   1727 		if (krp != NULL) {
   1728 			TAILQ_REMOVE(&crp_kq, krp, krp_next);
   1729 			result = crypto_kinvoke(krp, 0);
   1730 			/* the next iteration will want the mutex. :-/ */
   1731 			if (result == ERESTART) {
   1732 				/*
   1733 				 * The driver ran out of resources, mark the
   1734 				 * driver ``blocked'' for cryptkop's and put
   1735 				 * the request back in the queue.  It would
   1736 				 * best to put the request back where we got
   1737 				 * it but that's hard so for now we put it
   1738 				 * at the front.  This should be ok; putting
   1739 				 * it at the end does not work.
   1740 				 */
   1741 				/* validate sid again */
   1742 				cap = crypto_checkdriver_lock(krp->krp_hid);
   1743 				if (cap == NULL) {
   1744 					/* migrate again, sigh... */
   1745 					TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
   1746 				} else {
   1747 					cap->cc_kqblocked = 1;
   1748 					crypto_driver_unlock(cap);
   1749 					TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
   1750 					cryptostats.cs_kblocks++;
   1751 				}
   1752 			}
   1753 		}
   1754 	} while (submit != NULL || krp != NULL);
   1755 	mutex_exit(&crypto_q_mtx);
   1756 }
   1757 
   1758 /*
   1759  * Kernel thread to do callbacks.
   1760  */
   1761 static void
   1762 cryptoret(void)
   1763 {
   1764 	struct cryptop *crp;
   1765 	struct cryptkop *krp;
   1766 
   1767 	mutex_spin_enter(&crypto_ret_q_mtx);
   1768 	for (;;) {
   1769 		crp = TAILQ_FIRST(&crp_ret_q);
   1770 		if (crp != NULL) {
   1771 			TAILQ_REMOVE(&crp_ret_q, crp, crp_next);
   1772 			CRYPTO_Q_DEC(crp_ret_q);
   1773 			crp->crp_flags &= ~CRYPTO_F_ONRETQ;
   1774 		}
   1775 		krp = TAILQ_FIRST(&crp_ret_kq);
   1776 		if (krp != NULL) {
   1777 			TAILQ_REMOVE(&crp_ret_kq, krp, krp_next);
   1778 			CRYPTO_Q_DEC(crp_ret_kq);
   1779 			krp->krp_flags &= ~CRYPTO_F_ONRETQ;
   1780 		}
   1781 
   1782 		/* drop before calling any callbacks. */
   1783 		if (crp == NULL && krp == NULL) {
   1784 
   1785                         /* Check for the exit condition. */
   1786 			if (crypto_exit_flag != 0) {
   1787 
   1788         			/* Time to die. */
   1789 				crypto_exit_flag = 0;
   1790         			cv_broadcast(&cryptoret_cv);
   1791 				mutex_spin_exit(&crypto_ret_q_mtx);
   1792         			kthread_exit(0);
   1793 			}
   1794 
   1795 			cryptostats.cs_rets++;
   1796 			cv_wait(&cryptoret_cv, &crypto_ret_q_mtx);
   1797 			continue;
   1798 		}
   1799 
   1800 		mutex_spin_exit(&crypto_ret_q_mtx);
   1801 
   1802 		if (crp != NULL) {
   1803 #ifdef CRYPTO_TIMING
   1804 			if (crypto_timing) {
   1805 				/*
   1806 				 * NB: We must copy the timestamp before
   1807 				 * doing the callback as the cryptop is
   1808 				 * likely to be reclaimed.
   1809 				 */
   1810 				struct timespec t = crp->crp_tstamp;
   1811 				crypto_tstat(&cryptostats.cs_cb, &t);
   1812 				crp->crp_callback(crp);
   1813 				crypto_tstat(&cryptostats.cs_finis, &t);
   1814 			} else
   1815 #endif
   1816 			{
   1817 				crp->crp_callback(crp);
   1818 			}
   1819 		}
   1820 		if (krp != NULL)
   1821 			krp->krp_callback(krp);
   1822 
   1823 		mutex_spin_enter(&crypto_ret_q_mtx);
   1824 	}
   1825 }
   1826 
   1827 /* NetBSD module interface */
   1828 
   1829 MODULE(MODULE_CLASS_MISC, opencrypto, NULL);
   1830 
   1831 static int
   1832 opencrypto_modcmd(modcmd_t cmd, void *opaque)
   1833 {
   1834 	int error = 0;
   1835 
   1836 	switch (cmd) {
   1837 	case MODULE_CMD_INIT:
   1838 #ifdef _MODULE
   1839 		error = crypto_init();
   1840 #endif
   1841 		break;
   1842 	case MODULE_CMD_FINI:
   1843 #ifdef _MODULE
   1844 		error = crypto_destroy(true);
   1845 #endif
   1846 		break;
   1847 	default:
   1848 		error = ENOTTY;
   1849 	}
   1850 	return error;
   1851 }
   1852