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