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