Home | History | Annotate | Line # | Download | only in opencrypto
crypto.c revision 1.108
      1 /*	$NetBSD: crypto.c,v 1.108 2019/07/11 23:28:17 christos 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.108 2019/07/11 23:28:17 christos 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 int
    525 crypto_crp_ret_qs_init(void)
    526 {
    527 	int i, j;
    528 
    529 	crypto_crp_ret_qs_list = kmem_alloc(sizeof(struct crypto_crp_ret_qs *) * ncpu,
    530 	    KM_NOSLEEP);
    531 	if (crypto_crp_ret_qs_list == NULL) {
    532 		printf("crypto_init: crypto_crp_qs_list\n");
    533 		return ENOMEM;
    534 	}
    535 
    536 	for (i = 0; i < ncpu; i++) {
    537 		struct crypto_crp_ret_qs *qs;
    538 		qs = kmem_alloc(sizeof(struct crypto_crp_ret_qs), KM_NOSLEEP);
    539 		if (qs == NULL)
    540 			break;
    541 
    542 		mutex_init(&qs->crp_ret_q_mtx, MUTEX_DEFAULT, IPL_NET);
    543 		qs->crp_ret_q_exit_flag = false;
    544 
    545 		TAILQ_INIT(&qs->crp_ret_q);
    546 		qs->crp_ret_q_len = 0;
    547 		qs->crp_ret_q_maxlen = CRYPTO_RET_Q_MAXLEN;
    548 		qs->crp_ret_q_drops = 0;
    549 
    550 		TAILQ_INIT(&qs->crp_ret_kq);
    551 		qs->crp_ret_kq_len = 0;
    552 		qs->crp_ret_kq_maxlen = CRYPTO_RET_KQ_MAXLEN;
    553 		qs->crp_ret_kq_drops = 0;
    554 
    555 		crypto_crp_ret_qs_list[i] = qs;
    556 	}
    557 	if (i == ncpu)
    558 		return 0;
    559 
    560 	for (j = 0; j < i; j++) {
    561 		struct crypto_crp_ret_qs *qs = crypto_crp_ret_qs_list[j];
    562 
    563 		mutex_destroy(&qs->crp_ret_q_mtx);
    564 		kmem_free(qs, sizeof(struct crypto_crp_ret_qs));
    565 	}
    566 	kmem_free(crypto_crp_ret_qs_list, sizeof(struct crypto_crp_ret_qs *) * ncpu);
    567 
    568 	return ENOMEM;
    569 }
    570 
    571 static int
    572 crypto_init0(void)
    573 {
    574 	int error;
    575 
    576 	mutex_init(&crypto_drv_mtx, MUTEX_DEFAULT, IPL_NONE);
    577 	cryptop_cache = pool_cache_init(sizeof(struct cryptop),
    578 	    coherency_unit, 0, 0, "cryptop", NULL, IPL_NET, NULL, NULL, NULL);
    579 	cryptodesc_cache = pool_cache_init(sizeof(struct cryptodesc),
    580 	    coherency_unit, 0, 0, "cryptdesc", NULL, IPL_NET, NULL, NULL, NULL);
    581 	cryptkop_cache = pool_cache_init(sizeof(struct cryptkop),
    582 	    coherency_unit, 0, 0, "cryptkop", NULL, IPL_NET, NULL, NULL, NULL);
    583 
    584 	crypto_crp_qs_percpu = percpu_alloc(sizeof(struct crypto_crp_qs));
    585 	percpu_foreach(crypto_crp_qs_percpu, crypto_crp_qs_init_pc, NULL);
    586 
    587 	error = crypto_crp_ret_qs_init();
    588 	if (error) {
    589 		printf("crypto_init: cannot malloc ret_q list\n");
    590 		return ENOMEM;
    591 	}
    592 
    593 	crypto_drivers = kmem_zalloc(CRYPTO_DRIVERS_INITIAL *
    594 	    sizeof(struct cryptocap), KM_NOSLEEP);
    595 	if (crypto_drivers == NULL) {
    596 		printf("crypto_init: cannot malloc driver table\n");
    597 		return ENOMEM;
    598 	}
    599 	crypto_drivers_num = CRYPTO_DRIVERS_INITIAL;
    600 
    601 	crypto_q_si = softint_establish(SOFTINT_NET|SOFTINT_MPSAFE, cryptointr, NULL);
    602 	if (crypto_q_si == NULL) {
    603 		printf("crypto_init: cannot establish request queue handler\n");
    604 		return crypto_destroy(false);
    605 	}
    606 
    607 	/*
    608 	 * Some encryption devices (such as mvcesa) are attached before
    609 	 * ipi_sysinit(). That causes an assertion in ipi_register() as
    610 	 * crypto_ret_si softint uses SOFTINT_RCPU.
    611 	 */
    612 	if (config_finalize_register(NULL, crypto_init_finalize) != 0) {
    613 		printf("crypto_init: cannot register crypto_init_finalize\n");
    614 		return crypto_destroy(false);
    615 	}
    616 
    617 	sysctl_opencrypto_setup(&sysctl_opencrypto_clog);
    618 
    619 	return 0;
    620 }
    621 
    622 static int
    623 crypto_init_finalize(device_t self __unused)
    624 {
    625 
    626 	crypto_ret_si = softint_establish(SOFTINT_NET|SOFTINT_MPSAFE|SOFTINT_RCPU,
    627 	    &cryptoret_softint, NULL);
    628 	KASSERT(crypto_ret_si != NULL);
    629 
    630 	return 0;
    631 }
    632 
    633 int
    634 crypto_init(void)
    635 {
    636 	static ONCE_DECL(crypto_init_once);
    637 
    638 	return RUN_ONCE(&crypto_init_once, crypto_init0);
    639 }
    640 
    641 static int
    642 crypto_destroy(bool exit_kthread)
    643 {
    644 	int i;
    645 
    646 	if (exit_kthread) {
    647 		struct cryptocap *cap = NULL;
    648 		uint64_t where;
    649 		bool is_busy = false;
    650 
    651 		/* if we have any in-progress requests, don't unload */
    652 		percpu_foreach(crypto_crp_qs_percpu, crypto_crp_q_is_busy_pc,
    653 				   &is_busy);
    654 		if (is_busy)
    655 			return EBUSY;
    656 		/* FIXME:
    657 		 * prohibit enqueue to crp_q and crp_kq after here.
    658 		 */
    659 
    660 		mutex_enter(&crypto_drv_mtx);
    661 		for (i = 0; i < crypto_drivers_num; i++) {
    662 			cap = crypto_checkdriver(i);
    663 			if (cap == NULL)
    664 				continue;
    665 			if (cap->cc_sessions != 0) {
    666 				mutex_exit(&crypto_drv_mtx);
    667 				return EBUSY;
    668 			}
    669 		}
    670 		mutex_exit(&crypto_drv_mtx);
    671 		/* FIXME:
    672 		 * prohibit touch crypto_drivers[] and each element after here.
    673 		 */
    674 
    675 		/*
    676 		 * Ensure cryptoret_softint() is never scheduled and then wait
    677 		 * for last softint_execute().
    678 		 */
    679 		for (i = 0; i < ncpu; i++) {
    680 			struct crypto_crp_ret_qs *qs;
    681 			struct cpu_info *ci = cpu_lookup(i);
    682 
    683 			qs = crypto_get_crp_ret_qs(ci);
    684 			qs->crp_ret_q_exit_flag = true;
    685 			crypto_put_crp_ret_qs(ci);
    686 		}
    687 		where = xc_broadcast(0, (xcfunc_t)nullop, NULL, NULL);
    688 		xc_wait(where);
    689 	}
    690 
    691 	if (sysctl_opencrypto_clog != NULL)
    692 		sysctl_teardown(&sysctl_opencrypto_clog);
    693 
    694 	if (crypto_ret_si != NULL)
    695 		softint_disestablish(crypto_ret_si);
    696 
    697 	if (crypto_q_si != NULL)
    698 		softint_disestablish(crypto_q_si);
    699 
    700 	mutex_enter(&crypto_drv_mtx);
    701 	if (crypto_drivers != NULL)
    702 		kmem_free(crypto_drivers,
    703 		    crypto_drivers_num * sizeof(struct cryptocap));
    704 	mutex_exit(&crypto_drv_mtx);
    705 
    706 	percpu_free(crypto_crp_qs_percpu, sizeof(struct crypto_crp_qs));
    707 
    708 	pool_cache_destroy(cryptop_cache);
    709 	pool_cache_destroy(cryptodesc_cache);
    710 	pool_cache_destroy(cryptkop_cache);
    711 
    712 	mutex_destroy(&crypto_drv_mtx);
    713 
    714 	return 0;
    715 }
    716 
    717 static bool
    718 crypto_driver_suitable(struct cryptocap *cap, struct cryptoini *cri)
    719 {
    720 	struct cryptoini *cr;
    721 
    722 	for (cr = cri; cr; cr = cr->cri_next)
    723 		if (cap->cc_alg[cr->cri_alg] == 0) {
    724 			DPRINTF("alg %d not supported\n", cr->cri_alg);
    725 			return false;
    726 		}
    727 
    728 	return true;
    729 }
    730 
    731 #define CRYPTO_ACCEPT_HARDWARE 0x1
    732 #define CRYPTO_ACCEPT_SOFTWARE 0x2
    733 /*
    734  * The algorithm we use here is pretty stupid; just use the
    735  * first driver that supports all the algorithms we need.
    736  * If there are multiple drivers we choose the driver with
    737  * the fewest active sessions. We prefer hardware-backed
    738  * drivers to software ones.
    739  *
    740  * XXX We need more smarts here (in real life too, but that's
    741  * XXX another story altogether).
    742  */
    743 static struct cryptocap *
    744 crypto_select_driver_lock(struct cryptoini *cri, int hard)
    745 {
    746 	u_int32_t hid;
    747 	int accept;
    748 	struct cryptocap *cap, *best;
    749 	int error = 0;
    750 
    751 	best = NULL;
    752 	/*
    753 	 * hard == 0 can use both hardware and software drivers.
    754 	 * We use hardware drivers prior to software drivers, so search
    755 	 * hardware drivers at first time.
    756 	 */
    757 	if (hard >= 0)
    758 		accept = CRYPTO_ACCEPT_HARDWARE;
    759 	else
    760 		accept = CRYPTO_ACCEPT_SOFTWARE;
    761 again:
    762 	for (hid = 0; hid < crypto_drivers_num; hid++) {
    763 		cap = crypto_checkdriver(hid);
    764 		if (cap == NULL)
    765 			continue;
    766 
    767 		crypto_driver_lock(cap);
    768 
    769 		/*
    770 		 * If it's not initialized or has remaining sessions
    771 		 * referencing it, skip.
    772 		 */
    773 		if (cap->cc_newsession == NULL ||
    774 		    (cap->cc_flags & CRYPTOCAP_F_CLEANUP)) {
    775 			crypto_driver_unlock(cap);
    776 			continue;
    777 		}
    778 
    779 		/* Hardware required -- ignore software drivers. */
    780 		if ((accept & CRYPTO_ACCEPT_SOFTWARE) == 0
    781 		    && (cap->cc_flags & CRYPTOCAP_F_SOFTWARE)) {
    782 			crypto_driver_unlock(cap);
    783 			continue;
    784 		}
    785 		/* Software required -- ignore hardware drivers. */
    786 		if ((accept & CRYPTO_ACCEPT_HARDWARE) == 0
    787 		    && (cap->cc_flags & CRYPTOCAP_F_SOFTWARE) == 0) {
    788 			crypto_driver_unlock(cap);
    789 			continue;
    790 		}
    791 
    792 		/* See if all the algorithms are supported. */
    793 		if (crypto_driver_suitable(cap, cri)) {
    794 			if (best == NULL) {
    795 				/* keep holding crypto_driver_lock(cap) */
    796 				best = cap;
    797 				continue;
    798 			} else if (cap->cc_sessions < best->cc_sessions) {
    799 				crypto_driver_unlock(best);
    800 				/* keep holding crypto_driver_lock(cap) */
    801 				best = cap;
    802 				continue;
    803 			}
    804 		}
    805 
    806 		crypto_driver_unlock(cap);
    807 	}
    808 	if (best == NULL && hard == 0
    809 	    && (accept & CRYPTO_ACCEPT_SOFTWARE) == 0) {
    810 		accept = CRYPTO_ACCEPT_SOFTWARE;
    811 		goto again;
    812 	}
    813 
    814 	if (best == NULL && hard == 0 && error == 0) {
    815 		mutex_exit(&crypto_drv_mtx);
    816 		error = module_autoload("swcrypto", MODULE_CLASS_DRIVER);
    817 		mutex_enter(&crypto_drv_mtx);
    818 		if (error == 0) {
    819 			error = EINVAL;
    820 			goto again;
    821 		}
    822 	}
    823 
    824 	return best;
    825 }
    826 
    827 /*
    828  * Create a new session.
    829  */
    830 int
    831 crypto_newsession(u_int64_t *sid, struct cryptoini *cri, int hard)
    832 {
    833 	struct cryptocap *cap;
    834 	int err = EINVAL;
    835 
    836 	mutex_enter(&crypto_drv_mtx);
    837 
    838 	cap = crypto_select_driver_lock(cri, hard);
    839 	if (cap != NULL) {
    840 		u_int32_t hid, lid;
    841 
    842 		hid = cap - crypto_drivers;
    843 		/*
    844 		 * Can't do everything in one session.
    845 		 *
    846 		 * XXX Fix this. We need to inject a "virtual" session layer right
    847 		 * XXX about here.
    848 		 */
    849 
    850 		/* Call the driver initialization routine. */
    851 		lid = hid;		/* Pass the driver ID. */
    852 		crypto_driver_unlock(cap);
    853 		err = cap->cc_newsession(cap->cc_arg, &lid, cri);
    854 		crypto_driver_lock(cap);
    855 		if (err == 0) {
    856 			(*sid) = hid;
    857 			(*sid) <<= 32;
    858 			(*sid) |= (lid & 0xffffffff);
    859 			(cap->cc_sessions)++;
    860 		} else {
    861 			DPRINTF("crypto_drivers[%d].cc_newsession() failed. error=%d\n",
    862 			    hid, err);
    863 		}
    864 		crypto_driver_unlock(cap);
    865 	}
    866 
    867 	mutex_exit(&crypto_drv_mtx);
    868 
    869 	return err;
    870 }
    871 
    872 /*
    873  * Delete an existing session (or a reserved session on an unregistered
    874  * driver).
    875  */
    876 int
    877 crypto_freesession(u_int64_t sid)
    878 {
    879 	struct cryptocap *cap;
    880 	int err = 0;
    881 
    882 	/* Determine two IDs. */
    883 	cap = crypto_checkdriver_lock(CRYPTO_SESID2HID(sid));
    884 	if (cap == NULL)
    885 		return ENOENT;
    886 
    887 	if (cap->cc_sessions)
    888 		(cap->cc_sessions)--;
    889 
    890 	/* Call the driver cleanup routine, if available. */
    891 	if (cap->cc_freesession)
    892 		err = cap->cc_freesession(cap->cc_arg, sid);
    893 	else
    894 		err = 0;
    895 
    896 	/*
    897 	 * If this was the last session of a driver marked as invalid,
    898 	 * make the entry available for reuse.
    899 	 */
    900 	if ((cap->cc_flags & CRYPTOCAP_F_CLEANUP) && cap->cc_sessions == 0)
    901 		crypto_driver_clear(cap);
    902 
    903 	crypto_driver_unlock(cap);
    904 	return err;
    905 }
    906 
    907 static bool
    908 crypto_checkdriver_initialized(const struct cryptocap *cap)
    909 {
    910 
    911 	return cap->cc_process != NULL ||
    912 	    (cap->cc_flags & CRYPTOCAP_F_CLEANUP) != 0 ||
    913 	    cap->cc_sessions != 0;
    914 }
    915 
    916 /*
    917  * Return an unused driver id.  Used by drivers prior to registering
    918  * support for the algorithms they handle.
    919  */
    920 int32_t
    921 crypto_get_driverid(u_int32_t flags)
    922 {
    923 	struct cryptocap *newdrv;
    924 	struct cryptocap *cap = NULL;
    925 	int i;
    926 
    927 	(void)crypto_init();		/* XXX oh, this is foul! */
    928 
    929 	mutex_enter(&crypto_drv_mtx);
    930 	for (i = 0; i < crypto_drivers_num; i++) {
    931 		cap = crypto_checkdriver_uninit(i);
    932 		if (cap == NULL || crypto_checkdriver_initialized(cap))
    933 			continue;
    934 		break;
    935 	}
    936 
    937 	/* Out of entries, allocate some more. */
    938 	if (cap == NULL) {
    939 		/* Be careful about wrap-around. */
    940 		if (2 * crypto_drivers_num <= crypto_drivers_num) {
    941 			mutex_exit(&crypto_drv_mtx);
    942 			printf("crypto: driver count wraparound!\n");
    943 			return -1;
    944 		}
    945 
    946 		newdrv = kmem_zalloc(2 * crypto_drivers_num *
    947 		    sizeof(struct cryptocap), KM_NOSLEEP);
    948 		if (newdrv == NULL) {
    949 			mutex_exit(&crypto_drv_mtx);
    950 			printf("crypto: no space to expand driver table!\n");
    951 			return -1;
    952 		}
    953 
    954 		memcpy(newdrv, crypto_drivers,
    955 		    crypto_drivers_num * sizeof(struct cryptocap));
    956 		kmem_free(crypto_drivers,
    957 		    crypto_drivers_num * sizeof(struct cryptocap));
    958 
    959 		crypto_drivers_num *= 2;
    960 		crypto_drivers = newdrv;
    961 
    962 		cap = crypto_checkdriver_uninit(i);
    963 		KASSERT(cap != NULL);
    964 	}
    965 
    966 	/* NB: state is zero'd on free */
    967 	cap->cc_sessions = 1;	/* Mark */
    968 	cap->cc_flags = flags;
    969 	mutex_init(&cap->cc_lock, MUTEX_DEFAULT, IPL_NET);
    970 
    971 	if (bootverbose)
    972 		printf("crypto: assign driver %u, flags %u\n", i, flags);
    973 
    974 	mutex_exit(&crypto_drv_mtx);
    975 
    976 	return i;
    977 }
    978 
    979 static struct cryptocap *
    980 crypto_checkdriver_lock(u_int32_t hid)
    981 {
    982 	struct cryptocap *cap;
    983 
    984 	KASSERT(crypto_drivers != NULL);
    985 
    986 	if (hid >= crypto_drivers_num)
    987 		return NULL;
    988 
    989 	cap = &crypto_drivers[hid];
    990 	mutex_enter(&cap->cc_lock);
    991 	return cap;
    992 }
    993 
    994 /*
    995  * Use crypto_checkdriver_uninit() instead of crypto_checkdriver() below two
    996  * situations
    997  *     - crypto_drivers[] may not be allocated
    998  *     - crypto_drivers[hid] may not be initialized
    999  */
   1000 static struct cryptocap *
   1001 crypto_checkdriver_uninit(u_int32_t hid)
   1002 {
   1003 
   1004 	KASSERT(mutex_owned(&crypto_drv_mtx));
   1005 
   1006 	if (crypto_drivers == NULL)
   1007 		return NULL;
   1008 
   1009 	return (hid >= crypto_drivers_num ? NULL : &crypto_drivers[hid]);
   1010 }
   1011 
   1012 /*
   1013  * Use crypto_checkdriver_uninit() instead of crypto_checkdriver() below two
   1014  * situations
   1015  *     - crypto_drivers[] may not be allocated
   1016  *     - crypto_drivers[hid] may not be initialized
   1017  */
   1018 static struct cryptocap *
   1019 crypto_checkdriver(u_int32_t hid)
   1020 {
   1021 
   1022 	KASSERT(mutex_owned(&crypto_drv_mtx));
   1023 
   1024 	if (crypto_drivers == NULL || hid >= crypto_drivers_num)
   1025 		return NULL;
   1026 
   1027 	struct cryptocap *cap = &crypto_drivers[hid];
   1028 	return crypto_checkdriver_initialized(cap) ? cap : NULL;
   1029 }
   1030 
   1031 static inline void
   1032 crypto_driver_lock(struct cryptocap *cap)
   1033 {
   1034 
   1035 	KASSERT(cap != NULL);
   1036 
   1037 	mutex_enter(&cap->cc_lock);
   1038 }
   1039 
   1040 static inline void
   1041 crypto_driver_unlock(struct cryptocap *cap)
   1042 {
   1043 
   1044 	KASSERT(cap != NULL);
   1045 
   1046 	mutex_exit(&cap->cc_lock);
   1047 }
   1048 
   1049 static void
   1050 crypto_driver_clear(struct cryptocap *cap)
   1051 {
   1052 
   1053 	if (cap == NULL)
   1054 		return;
   1055 
   1056 	KASSERT(mutex_owned(&cap->cc_lock));
   1057 
   1058 	cap->cc_sessions = 0;
   1059 	memset(&cap->cc_max_op_len, 0, sizeof(cap->cc_max_op_len));
   1060 	memset(&cap->cc_alg, 0, sizeof(cap->cc_alg));
   1061 	memset(&cap->cc_kalg, 0, sizeof(cap->cc_kalg));
   1062 	cap->cc_flags = 0;
   1063 	cap->cc_qblocked = 0;
   1064 	cap->cc_kqblocked = 0;
   1065 
   1066 	cap->cc_arg = NULL;
   1067 	cap->cc_newsession = NULL;
   1068 	cap->cc_process = NULL;
   1069 	cap->cc_freesession = NULL;
   1070 	cap->cc_kprocess = NULL;
   1071 }
   1072 
   1073 /*
   1074  * Register support for a key-related algorithm.  This routine
   1075  * is called once for each algorithm supported a driver.
   1076  */
   1077 int
   1078 crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags,
   1079     int (*kprocess)(void *, struct cryptkop *, int),
   1080     void *karg)
   1081 {
   1082 	struct cryptocap *cap;
   1083 	int err;
   1084 
   1085 	mutex_enter(&crypto_drv_mtx);
   1086 
   1087 	cap = crypto_checkdriver_lock(driverid);
   1088 	if (cap != NULL &&
   1089 	    (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
   1090 		/*
   1091 		 * XXX Do some performance testing to determine placing.
   1092 		 * XXX We probably need an auxiliary data structure that
   1093 		 * XXX describes relative performances.
   1094 		 */
   1095 
   1096 		cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
   1097 		if (bootverbose) {
   1098 			printf("crypto: driver %u registers key alg %u "
   1099 			       " flags %u\n",
   1100 				driverid,
   1101 				kalg,
   1102 				flags
   1103 			);
   1104 		}
   1105 
   1106 		if (cap->cc_kprocess == NULL) {
   1107 			cap->cc_karg = karg;
   1108 			cap->cc_kprocess = kprocess;
   1109 		}
   1110 		err = 0;
   1111 	} else
   1112 		err = EINVAL;
   1113 
   1114 	mutex_exit(&crypto_drv_mtx);
   1115 	return err;
   1116 }
   1117 
   1118 /*
   1119  * Register support for a non-key-related algorithm.  This routine
   1120  * is called once for each such algorithm supported by a driver.
   1121  */
   1122 int
   1123 crypto_register(u_int32_t driverid, int alg, u_int16_t maxoplen,
   1124     u_int32_t flags,
   1125     int (*newses)(void *, u_int32_t*, struct cryptoini*),
   1126     int (*freeses)(void *, u_int64_t),
   1127     int (*process)(void *, struct cryptop *, int),
   1128     void *arg)
   1129 {
   1130 	struct cryptocap *cap;
   1131 	int err;
   1132 
   1133 	cap = crypto_checkdriver_lock(driverid);
   1134 	if (cap == NULL)
   1135 		return EINVAL;
   1136 
   1137 	/* NB: algorithms are in the range [1..max] */
   1138 	if (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX) {
   1139 		/*
   1140 		 * XXX Do some performance testing to determine placing.
   1141 		 * XXX We probably need an auxiliary data structure that
   1142 		 * XXX describes relative performances.
   1143 		 */
   1144 
   1145 		cap->cc_alg[alg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
   1146 		cap->cc_max_op_len[alg] = maxoplen;
   1147 		if (bootverbose) {
   1148 			printf("crypto: driver %u registers alg %u "
   1149 				"flags %u maxoplen %u\n",
   1150 				driverid,
   1151 				alg,
   1152 				flags,
   1153 				maxoplen
   1154 			);
   1155 		}
   1156 
   1157 		if (cap->cc_process == NULL) {
   1158 			cap->cc_arg = arg;
   1159 			cap->cc_newsession = newses;
   1160 			cap->cc_process = process;
   1161 			cap->cc_freesession = freeses;
   1162 			cap->cc_sessions = 0;		/* Unmark */
   1163 		}
   1164 		err = 0;
   1165 	} else
   1166 		err = EINVAL;
   1167 
   1168 	crypto_driver_unlock(cap);
   1169 
   1170 	return err;
   1171 }
   1172 
   1173 static int
   1174 crypto_unregister_locked(struct cryptocap *cap, int alg, bool all)
   1175 {
   1176 	int i;
   1177 	u_int32_t ses;
   1178 	bool lastalg = true;
   1179 
   1180 	KASSERT(cap != NULL);
   1181 	KASSERT(mutex_owned(&cap->cc_lock));
   1182 
   1183 	if (alg < CRYPTO_ALGORITHM_MIN || CRYPTO_ALGORITHM_MAX < alg)
   1184 		return EINVAL;
   1185 
   1186 	if (!all && cap->cc_alg[alg] == 0)
   1187 		return EINVAL;
   1188 
   1189 	cap->cc_alg[alg] = 0;
   1190 	cap->cc_max_op_len[alg] = 0;
   1191 
   1192 	if (all) {
   1193 		if (alg != CRYPTO_ALGORITHM_MAX)
   1194 			lastalg = false;
   1195 	} else {
   1196 		/* Was this the last algorithm ? */
   1197 		for (i = CRYPTO_ALGORITHM_MIN; i <= CRYPTO_ALGORITHM_MAX; i++)
   1198 			if (cap->cc_alg[i] != 0) {
   1199 				lastalg = false;
   1200 				break;
   1201 			}
   1202 	}
   1203 	if (lastalg) {
   1204 		ses = cap->cc_sessions;
   1205 		crypto_driver_clear(cap);
   1206 		if (ses != 0) {
   1207 			/*
   1208 			 * If there are pending sessions, just mark as invalid.
   1209 			 */
   1210 			cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
   1211 			cap->cc_sessions = ses;
   1212 		}
   1213 	}
   1214 
   1215 	return 0;
   1216 }
   1217 
   1218 /*
   1219  * Unregister a crypto driver. If there are pending sessions using it,
   1220  * leave enough information around so that subsequent calls using those
   1221  * sessions will correctly detect the driver has been unregistered and
   1222  * reroute requests.
   1223  */
   1224 int
   1225 crypto_unregister(u_int32_t driverid, int alg)
   1226 {
   1227 	int err;
   1228 	struct cryptocap *cap;
   1229 
   1230 	cap = crypto_checkdriver_lock(driverid);
   1231 	err = crypto_unregister_locked(cap, alg, false);
   1232 	crypto_driver_unlock(cap);
   1233 
   1234 	return err;
   1235 }
   1236 
   1237 /*
   1238  * Unregister all algorithms associated with a crypto driver.
   1239  * If there are pending sessions using it, leave enough information
   1240  * around so that subsequent calls using those sessions will
   1241  * correctly detect the driver has been unregistered and reroute
   1242  * requests.
   1243  */
   1244 int
   1245 crypto_unregister_all(u_int32_t driverid)
   1246 {
   1247 	int err, i;
   1248 	struct cryptocap *cap;
   1249 
   1250 	cap = crypto_checkdriver_lock(driverid);
   1251 	for (i = CRYPTO_ALGORITHM_MIN; i <= CRYPTO_ALGORITHM_MAX; i++) {
   1252 		err = crypto_unregister_locked(cap, i, true);
   1253 		if (err)
   1254 			break;
   1255 	}
   1256 	crypto_driver_unlock(cap);
   1257 
   1258 	return err;
   1259 }
   1260 
   1261 /*
   1262  * Clear blockage on a driver.  The what parameter indicates whether
   1263  * the driver is now ready for cryptop's and/or cryptokop's.
   1264  */
   1265 int
   1266 crypto_unblock(u_int32_t driverid, int what)
   1267 {
   1268 	struct cryptocap *cap;
   1269 	int needwakeup = 0;
   1270 
   1271 	cap = crypto_checkdriver_lock(driverid);
   1272 	if (cap == NULL)
   1273 		return EINVAL;
   1274 
   1275 	if (what & CRYPTO_SYMQ) {
   1276 		needwakeup |= cap->cc_qblocked;
   1277 		cap->cc_qblocked = 0;
   1278 	}
   1279 	if (what & CRYPTO_ASYMQ) {
   1280 		needwakeup |= cap->cc_kqblocked;
   1281 		cap->cc_kqblocked = 0;
   1282 	}
   1283 	crypto_driver_unlock(cap);
   1284 	if (needwakeup) {
   1285 		kpreempt_disable();
   1286 		softint_schedule(crypto_q_si);
   1287 		kpreempt_enable();
   1288 	}
   1289 
   1290 	return 0;
   1291 }
   1292 
   1293 /*
   1294  * Dispatch a crypto request to a driver or queue
   1295  * it, to be processed by the kernel thread.
   1296  */
   1297 int
   1298 crypto_dispatch(struct cryptop *crp)
   1299 {
   1300 	int result, s;
   1301 	struct cryptocap *cap;
   1302 	struct crypto_crp_qs *crp_qs;
   1303 	struct crypto_crp_q *crp_q;
   1304 
   1305 	KASSERT(crp != NULL);
   1306 
   1307 	DPRINTF("crp %p, alg %d\n", crp, crp->crp_desc->crd_alg);
   1308 
   1309 	cryptostats.cs_ops++;
   1310 
   1311 #ifdef CRYPTO_TIMING
   1312 	if (crypto_timing)
   1313 		nanouptime(&crp->crp_tstamp);
   1314 #endif
   1315 
   1316 	if ((crp->crp_flags & CRYPTO_F_BATCH) != 0) {
   1317 		int wasempty;
   1318 		/*
   1319 		 * Caller marked the request as ``ok to delay'';
   1320 		 * queue it for the swi thread.  This is desirable
   1321 		 * when the operation is low priority and/or suitable
   1322 		 * for batching.
   1323 		 *
   1324 		 * don't care list order in batch job.
   1325 		 */
   1326 		crp_qs = crypto_get_crp_qs(&s);
   1327 		crp_q = crp_qs->crp_q;
   1328 		wasempty  = TAILQ_EMPTY(crp_q);
   1329 		TAILQ_INSERT_TAIL(crp_q, crp, crp_next);
   1330 		crypto_put_crp_qs(&s);
   1331 		crp_q = NULL;
   1332 		if (wasempty) {
   1333 			kpreempt_disable();
   1334 			softint_schedule(crypto_q_si);
   1335 			kpreempt_enable();
   1336 		}
   1337 
   1338 		return 0;
   1339 	}
   1340 
   1341 	crp_qs = crypto_get_crp_qs(&s);
   1342 	crp_q = crp_qs->crp_q;
   1343 	cap = crypto_checkdriver_lock(CRYPTO_SESID2HID(crp->crp_sid));
   1344 	/*
   1345 	 * TODO:
   1346 	 * If we can ensure the driver has been valid until the driver is
   1347 	 * done crypto_unregister(), this migrate operation is not required.
   1348 	 */
   1349 	if (cap == NULL) {
   1350 		/*
   1351 		 * The driver must be detached, so this request will migrate
   1352 		 * to other drivers in cryptointr() later.
   1353 		 */
   1354 		TAILQ_INSERT_TAIL(crp_q, crp, crp_next);
   1355 		result = 0;
   1356 		goto out;
   1357 	}
   1358 
   1359 	if (cap->cc_qblocked != 0) {
   1360 		crypto_driver_unlock(cap);
   1361 		/*
   1362 		 * The driver is blocked, just queue the op until
   1363 		 * it unblocks and the swi thread gets kicked.
   1364 		 */
   1365 		TAILQ_INSERT_TAIL(crp_q, crp, crp_next);
   1366 		result = 0;
   1367 		goto out;
   1368 	}
   1369 
   1370 	/*
   1371 	 * Caller marked the request to be processed
   1372 	 * immediately; dispatch it directly to the
   1373 	 * driver unless the driver is currently blocked.
   1374 	 */
   1375 	crypto_driver_unlock(cap);
   1376 	result = crypto_invoke(crp, 0);
   1377 	if (result == ERESTART) {
   1378 		/*
   1379 		 * The driver ran out of resources, mark the
   1380 		 * driver ``blocked'' for cryptop's and put
   1381 		 * the op on the queue.
   1382 		 */
   1383 		crypto_driver_lock(cap);
   1384 		cap->cc_qblocked = 1;
   1385 		crypto_driver_unlock(cap);
   1386 		TAILQ_INSERT_HEAD(crp_q, crp, crp_next);
   1387 		cryptostats.cs_blocks++;
   1388 
   1389 		/*
   1390 		 * The crp is enqueued to crp_q, that is,
   1391 		 * no error occurs. So, this function should
   1392 		 * not return error.
   1393 		 */
   1394 		result = 0;
   1395 	}
   1396 
   1397 out:
   1398 	crypto_put_crp_qs(&s);
   1399 	return result;
   1400 }
   1401 
   1402 /*
   1403  * Add an asymetric crypto request to a queue,
   1404  * to be processed by the kernel thread.
   1405  */
   1406 int
   1407 crypto_kdispatch(struct cryptkop *krp)
   1408 {
   1409 	int result, s;
   1410 	struct cryptocap *cap;
   1411 	struct crypto_crp_qs *crp_qs;
   1412 	struct crypto_crp_kq *crp_kq;
   1413 
   1414 	KASSERT(krp != NULL);
   1415 
   1416 	cryptostats.cs_kops++;
   1417 
   1418 	crp_qs = crypto_get_crp_qs(&s);
   1419 	crp_kq = crp_qs->crp_kq;
   1420 	cap = crypto_checkdriver_lock(krp->krp_hid);
   1421 	/*
   1422 	 * TODO:
   1423 	 * If we can ensure the driver has been valid until the driver is
   1424 	 * done crypto_unregister(), this migrate operation is not required.
   1425 	 */
   1426 	if (cap == NULL) {
   1427 		TAILQ_INSERT_TAIL(crp_kq, krp, krp_next);
   1428 		result = 0;
   1429 		goto out;
   1430 	}
   1431 
   1432 	if (cap->cc_kqblocked != 0) {
   1433 		crypto_driver_unlock(cap);
   1434 		/*
   1435 		 * The driver is blocked, just queue the op until
   1436 		 * it unblocks and the swi thread gets kicked.
   1437 		 */
   1438 		TAILQ_INSERT_TAIL(crp_kq, krp, krp_next);
   1439 		result = 0;
   1440 		goto out;
   1441 	}
   1442 
   1443 	crypto_driver_unlock(cap);
   1444 	result = crypto_kinvoke(krp, 0);
   1445 	if (result == ERESTART) {
   1446 		/*
   1447 		 * The driver ran out of resources, mark the
   1448 		 * driver ``blocked'' for cryptop's and put
   1449 		 * the op on the queue.
   1450 		 */
   1451 		crypto_driver_lock(cap);
   1452 		cap->cc_kqblocked = 1;
   1453 		crypto_driver_unlock(cap);
   1454 		TAILQ_INSERT_HEAD(crp_kq, krp, krp_next);
   1455 		cryptostats.cs_kblocks++;
   1456 
   1457 		/*
   1458 		 * The krp is enqueued to crp_kq, that is,
   1459 		 * no error occurs. So, this function should
   1460 		 * not return error.
   1461 		 */
   1462 		result = 0;
   1463 	}
   1464 
   1465 out:
   1466 	crypto_put_crp_qs(&s);
   1467 	return result;
   1468 }
   1469 
   1470 /*
   1471  * Dispatch an assymetric crypto request to the appropriate crypto devices.
   1472  */
   1473 static int
   1474 crypto_kinvoke(struct cryptkop *krp, int hint)
   1475 {
   1476 	struct cryptocap *cap = NULL;
   1477 	u_int32_t hid;
   1478 	int error;
   1479 
   1480 	KASSERT(krp != NULL);
   1481 
   1482 	/* Sanity checks. */
   1483 	if (krp->krp_callback == NULL) {
   1484 		cv_destroy(&krp->krp_cv);
   1485 		crypto_kfreereq(krp);
   1486 		return EINVAL;
   1487 	}
   1488 
   1489 	mutex_enter(&crypto_drv_mtx);
   1490 	for (hid = 0; hid < crypto_drivers_num; hid++) {
   1491 		cap = crypto_checkdriver(hid);
   1492 		if (cap == NULL)
   1493 			continue;
   1494 		crypto_driver_lock(cap);
   1495 		if ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
   1496 		    crypto_devallowsoft == 0) {
   1497 			crypto_driver_unlock(cap);
   1498 			continue;
   1499 		}
   1500 		if (cap->cc_kprocess == NULL) {
   1501 			crypto_driver_unlock(cap);
   1502 			continue;
   1503 		}
   1504 		if ((cap->cc_kalg[krp->krp_op] &
   1505 			CRYPTO_ALG_FLAG_SUPPORTED) == 0) {
   1506 			crypto_driver_unlock(cap);
   1507 			continue;
   1508 		}
   1509 		break;
   1510 	}
   1511 	mutex_exit(&crypto_drv_mtx);
   1512 	if (cap != NULL) {
   1513 		int (*process)(void *, struct cryptkop *, int);
   1514 		void *arg;
   1515 
   1516 		process = cap->cc_kprocess;
   1517 		arg = cap->cc_karg;
   1518 		krp->krp_hid = hid;
   1519 		krp->reqcpu = curcpu();
   1520 		crypto_driver_unlock(cap);
   1521 		error = (*process)(arg, krp, hint);
   1522 	} else {
   1523 		error = ENODEV;
   1524 	}
   1525 
   1526 	if (error) {
   1527 		krp->krp_status = error;
   1528 		crypto_kdone(krp);
   1529 	}
   1530 	return 0;
   1531 }
   1532 
   1533 #ifdef CRYPTO_TIMING
   1534 static void
   1535 crypto_tstat(struct cryptotstat *ts, struct timespec *tv)
   1536 {
   1537 	struct timespec now, t;
   1538 
   1539 	nanouptime(&now);
   1540 	t.tv_sec = now.tv_sec - tv->tv_sec;
   1541 	t.tv_nsec = now.tv_nsec - tv->tv_nsec;
   1542 	if (t.tv_nsec < 0) {
   1543 		t.tv_sec--;
   1544 		t.tv_nsec += 1000000000;
   1545 	}
   1546 	timespecadd(&ts->acc, &t, &t);
   1547 	if (timespeccmp(&t, &ts->min, <))
   1548 		ts->min = t;
   1549 	if (timespeccmp(&t, &ts->max, >))
   1550 		ts->max = t;
   1551 	ts->count++;
   1552 
   1553 	*tv = now;
   1554 }
   1555 #endif
   1556 
   1557 /*
   1558  * Dispatch a crypto request to the appropriate crypto devices.
   1559  */
   1560 static int
   1561 crypto_invoke(struct cryptop *crp, int hint)
   1562 {
   1563 	struct cryptocap *cap;
   1564 
   1565 	KASSERT(crp != NULL);
   1566 
   1567 #ifdef CRYPTO_TIMING
   1568 	if (crypto_timing)
   1569 		crypto_tstat(&cryptostats.cs_invoke, &crp->crp_tstamp);
   1570 #endif
   1571 	/* Sanity checks. */
   1572 	if (crp->crp_callback == NULL) {
   1573 		return EINVAL;
   1574 	}
   1575 	if (crp->crp_desc == NULL) {
   1576 		crp->crp_etype = EINVAL;
   1577 		crypto_done(crp);
   1578 		return 0;
   1579 	}
   1580 
   1581 	cap = crypto_checkdriver_lock(CRYPTO_SESID2HID(crp->crp_sid));
   1582 	if (cap != NULL && (cap->cc_flags & CRYPTOCAP_F_CLEANUP) == 0) {
   1583 		int (*process)(void *, struct cryptop *, int);
   1584 		void *arg;
   1585 
   1586 		process = cap->cc_process;
   1587 		arg = cap->cc_arg;
   1588 		crp->reqcpu = curcpu();
   1589 
   1590 		/*
   1591 		 * Invoke the driver to process the request.
   1592 		 */
   1593 		DPRINTF("calling process for %p\n", crp);
   1594 		crypto_driver_unlock(cap);
   1595 		return (*process)(arg, crp, hint);
   1596 	} else {
   1597 		struct cryptodesc *crd;
   1598 		u_int64_t nid = 0;
   1599 
   1600 		if (cap != NULL)
   1601 			crypto_driver_unlock(cap);
   1602 
   1603 		/*
   1604 		 * Driver has unregistered; migrate the session and return
   1605 		 * an error to the caller so they'll resubmit the op.
   1606 		 */
   1607 		crypto_freesession(crp->crp_sid);
   1608 
   1609 		for (crd = crp->crp_desc; crd->crd_next; crd = crd->crd_next)
   1610 			crd->CRD_INI.cri_next = &(crd->crd_next->CRD_INI);
   1611 
   1612 		if (crypto_newsession(&nid, &(crp->crp_desc->CRD_INI), 0) == 0)
   1613 			crp->crp_sid = nid;
   1614 
   1615 		crp->crp_etype = EAGAIN;
   1616 
   1617 		crypto_done(crp);
   1618 		return 0;
   1619 	}
   1620 }
   1621 
   1622 /*
   1623  * Release a set of crypto descriptors.
   1624  */
   1625 void
   1626 crypto_freereq(struct cryptop *crp)
   1627 {
   1628 	struct cryptodesc *crd;
   1629 
   1630 	if (crp == NULL)
   1631 		return;
   1632 	DPRINTF("lid[%u]: crp %p\n", CRYPTO_SESID2LID(crp->crp_sid), crp);
   1633 
   1634 	/* sanity check */
   1635 	if (crp->crp_flags & CRYPTO_F_ONRETQ) {
   1636 		panic("crypto_freereq() freeing crp on RETQ\n");
   1637 	}
   1638 
   1639 	while ((crd = crp->crp_desc) != NULL) {
   1640 		crp->crp_desc = crd->crd_next;
   1641 		pool_cache_put(cryptodesc_cache, crd);
   1642 	}
   1643 	pool_cache_put(cryptop_cache, crp);
   1644 }
   1645 
   1646 /*
   1647  * Acquire a set of crypto descriptors.
   1648  */
   1649 struct cryptop *
   1650 crypto_getreq(int num)
   1651 {
   1652 	struct cryptodesc *crd;
   1653 	struct cryptop *crp;
   1654 	struct crypto_crp_ret_qs *qs;
   1655 
   1656 	/*
   1657 	 * When crp_ret_q is full, we restrict here to avoid crp_ret_q overflow
   1658 	 * by error callback.
   1659 	 */
   1660 	qs = crypto_get_crp_ret_qs(curcpu());
   1661 	if (qs->crp_ret_q_maxlen > 0
   1662 	    && qs->crp_ret_q_len > qs->crp_ret_q_maxlen) {
   1663 		qs->crp_ret_q_drops++;
   1664 		crypto_put_crp_ret_qs(curcpu());
   1665 		return NULL;
   1666 	}
   1667 	crypto_put_crp_ret_qs(curcpu());
   1668 
   1669 	crp = pool_cache_get(cryptop_cache, PR_NOWAIT);
   1670 	if (crp == NULL) {
   1671 		return NULL;
   1672 	}
   1673 	memset(crp, 0, sizeof(struct cryptop));
   1674 
   1675 	while (num--) {
   1676 		crd = pool_cache_get(cryptodesc_cache, PR_NOWAIT);
   1677 		if (crd == NULL) {
   1678 			crypto_freereq(crp);
   1679 			return NULL;
   1680 		}
   1681 
   1682 		memset(crd, 0, sizeof(struct cryptodesc));
   1683 		crd->crd_next = crp->crp_desc;
   1684 		crp->crp_desc = crd;
   1685 	}
   1686 
   1687 	return crp;
   1688 }
   1689 
   1690 /*
   1691  * Release a set of asymmetric crypto descriptors.
   1692  * Currently, support one descriptor only.
   1693  */
   1694 void
   1695 crypto_kfreereq(struct cryptkop *krp)
   1696 {
   1697 
   1698 	if (krp == NULL)
   1699 		return;
   1700 
   1701 	DPRINTF("krp %p\n", krp);
   1702 
   1703 	/* sanity check */
   1704 	if (krp->krp_flags & CRYPTO_F_ONRETQ) {
   1705 		panic("crypto_kfreereq() freeing krp on RETQ\n");
   1706 	}
   1707 
   1708 	pool_cache_put(cryptkop_cache, krp);
   1709 }
   1710 
   1711 /*
   1712  * Acquire a set of asymmetric crypto descriptors.
   1713  * Currently, support one descriptor only.
   1714  */
   1715 struct cryptkop *
   1716 crypto_kgetreq(int num __unused, int prflags)
   1717 {
   1718 	struct cryptkop *krp;
   1719 	struct crypto_crp_ret_qs *qs;
   1720 
   1721 	/*
   1722 	 * When crp_ret_kq is full, we restrict here to avoid crp_ret_kq
   1723 	 * overflow by error callback.
   1724 	 */
   1725 	qs = crypto_get_crp_ret_qs(curcpu());
   1726 	if (qs->crp_ret_kq_maxlen > 0
   1727 	    && qs->crp_ret_kq_len > qs->crp_ret_kq_maxlen) {
   1728 		qs->crp_ret_kq_drops++;
   1729 		crypto_put_crp_ret_qs(curcpu());
   1730 		return NULL;
   1731 	}
   1732 	crypto_put_crp_ret_qs(curcpu());
   1733 
   1734 	krp = pool_cache_get(cryptkop_cache, prflags);
   1735 	if (krp == NULL) {
   1736 		return NULL;
   1737 	}
   1738 	memset(krp, 0, sizeof(struct cryptkop));
   1739 
   1740 	return krp;
   1741 }
   1742 
   1743 /*
   1744  * Invoke the callback on behalf of the driver.
   1745  */
   1746 void
   1747 crypto_done(struct cryptop *crp)
   1748 {
   1749 
   1750 	KASSERT(crp != NULL);
   1751 
   1752 	if (crp->crp_etype != 0)
   1753 		cryptostats.cs_errs++;
   1754 #ifdef CRYPTO_TIMING
   1755 	if (crypto_timing)
   1756 		crypto_tstat(&cryptostats.cs_done, &crp->crp_tstamp);
   1757 #endif
   1758 	DPRINTF("lid[%u]: crp %p\n", CRYPTO_SESID2LID(crp->crp_sid), crp);
   1759 
   1760 	/*
   1761 	 * Normal case; queue the callback for the thread.
   1762 	 *
   1763 	 * The return queue is manipulated by the swi thread
   1764 	 * and, potentially, by crypto device drivers calling
   1765 	 * back to mark operations completed.  Thus we need
   1766 	 * to mask both while manipulating the return queue.
   1767 	 */
   1768   	if (crp->crp_flags & CRYPTO_F_CBIMM) {
   1769 		/*
   1770 	 	* Do the callback directly.  This is ok when the
   1771   	 	* callback routine does very little (e.g. the
   1772 	 	* /dev/crypto callback method just does a wakeup).
   1773 	 	*/
   1774 		crp->crp_flags |= CRYPTO_F_DONE;
   1775 
   1776 #ifdef CRYPTO_TIMING
   1777 		if (crypto_timing) {
   1778 			/*
   1779 		 	* NB: We must copy the timestamp before
   1780 		 	* doing the callback as the cryptop is
   1781 		 	* likely to be reclaimed.
   1782 		 	*/
   1783 			struct timespec t = crp->crp_tstamp;
   1784 			crypto_tstat(&cryptostats.cs_cb, &t);
   1785 			crp->crp_callback(crp);
   1786 			crypto_tstat(&cryptostats.cs_finis, &t);
   1787 		} else
   1788 #endif
   1789 		crp->crp_callback(crp);
   1790 	} else {
   1791 		crp->crp_flags |= CRYPTO_F_DONE;
   1792 #if 0
   1793 		if (crp->crp_flags & CRYPTO_F_USER) {
   1794 			/*
   1795 			 * TODO:
   1796 			 * If crp->crp_flags & CRYPTO_F_USER and the used
   1797 			 * encryption driver does all the processing in
   1798 			 * the same context, we can skip enqueueing crp_ret_q
   1799 			 * and softint_schedule(crypto_ret_si).
   1800 			 */
   1801 			DPRINTF("lid[%u]: crp %p CRYPTO_F_USER\n",
   1802 				CRYPTO_SESID2LID(crp->crp_sid), crp);
   1803 		} else
   1804 #endif
   1805 		{
   1806 			int wasempty;
   1807 			struct crypto_crp_ret_qs *qs;
   1808 			struct crypto_crp_ret_q *crp_ret_q;
   1809 
   1810 			qs = crypto_get_crp_ret_qs(crp->reqcpu);
   1811 			crp_ret_q = &qs->crp_ret_q;
   1812 			wasempty = TAILQ_EMPTY(crp_ret_q);
   1813 			DPRINTF("lid[%u]: queueing %p\n",
   1814 				CRYPTO_SESID2LID(crp->crp_sid), crp);
   1815 			crp->crp_flags |= CRYPTO_F_ONRETQ;
   1816 			TAILQ_INSERT_TAIL(crp_ret_q, crp, crp_next);
   1817 			qs->crp_ret_q_len++;
   1818 			if (wasempty && !qs->crp_ret_q_exit_flag) {
   1819 				DPRINTF("lid[%u]: waking cryptoret,"
   1820 					"crp %p hit empty queue\n.",
   1821 					CRYPTO_SESID2LID(crp->crp_sid), crp);
   1822 				softint_schedule_cpu(crypto_ret_si, crp->reqcpu);
   1823 			}
   1824 			crypto_put_crp_ret_qs(crp->reqcpu);
   1825 		}
   1826 	}
   1827 }
   1828 
   1829 /*
   1830  * Invoke the callback on behalf of the driver.
   1831  */
   1832 void
   1833 crypto_kdone(struct cryptkop *krp)
   1834 {
   1835 
   1836 	KASSERT(krp != NULL);
   1837 
   1838 	if (krp->krp_status != 0)
   1839 		cryptostats.cs_kerrs++;
   1840 
   1841 	krp->krp_flags |= CRYPTO_F_DONE;
   1842 
   1843 	/*
   1844 	 * The return queue is manipulated by the swi thread
   1845 	 * and, potentially, by crypto device drivers calling
   1846 	 * back to mark operations completed.  Thus we need
   1847 	 * to mask both while manipulating the return queue.
   1848 	 */
   1849 	if (krp->krp_flags & CRYPTO_F_CBIMM) {
   1850 		krp->krp_callback(krp);
   1851 	} else {
   1852 		int wasempty;
   1853 		struct crypto_crp_ret_qs *qs;
   1854 		struct crypto_crp_ret_kq *crp_ret_kq;
   1855 
   1856 		qs = crypto_get_crp_ret_qs(krp->reqcpu);
   1857 		crp_ret_kq = &qs->crp_ret_kq;
   1858 
   1859 		wasempty = TAILQ_EMPTY(crp_ret_kq);
   1860 		krp->krp_flags |= CRYPTO_F_ONRETQ;
   1861 		TAILQ_INSERT_TAIL(crp_ret_kq, krp, krp_next);
   1862 		qs->crp_ret_kq_len++;
   1863 		if (wasempty && !qs->crp_ret_q_exit_flag)
   1864 			softint_schedule_cpu(crypto_ret_si, krp->reqcpu);
   1865 		crypto_put_crp_ret_qs(krp->reqcpu);
   1866 	}
   1867 }
   1868 
   1869 int
   1870 crypto_getfeat(int *featp)
   1871 {
   1872 
   1873 	if (crypto_userasymcrypto == 0) {
   1874 		*featp = 0;
   1875 		return 0;
   1876 	}
   1877 
   1878 	mutex_enter(&crypto_drv_mtx);
   1879 
   1880 	int feat = 0;
   1881 	for (int hid = 0; hid < crypto_drivers_num; hid++) {
   1882 		struct cryptocap *cap;
   1883 		cap = crypto_checkdriver(hid);
   1884 		if (cap == NULL)
   1885 			continue;
   1886 
   1887 		crypto_driver_lock(cap);
   1888 
   1889 		if ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
   1890 		    crypto_devallowsoft == 0)
   1891 			goto unlock;
   1892 
   1893 		if (cap->cc_kprocess == NULL)
   1894 			goto unlock;
   1895 
   1896 		for (int kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
   1897 			if ((cap->cc_kalg[kalg] &
   1898 			    CRYPTO_ALG_FLAG_SUPPORTED) != 0)
   1899 				feat |=  1 << kalg;
   1900 
   1901 unlock:		crypto_driver_unlock(cap);
   1902 	}
   1903 
   1904 	mutex_exit(&crypto_drv_mtx);
   1905 	*featp = feat;
   1906 	return (0);
   1907 }
   1908 
   1909 /*
   1910  * Software interrupt thread to dispatch crypto requests.
   1911  */
   1912 static void
   1913 cryptointr(void *arg __unused)
   1914 {
   1915 	struct cryptop *crp, *submit, *cnext;
   1916 	struct cryptkop *krp, *knext;
   1917 	struct cryptocap *cap;
   1918 	struct crypto_crp_qs *crp_qs;
   1919 	struct crypto_crp_q *crp_q;
   1920 	struct crypto_crp_kq *crp_kq;
   1921 	int result, hint, s;
   1922 
   1923 	cryptostats.cs_intrs++;
   1924 	crp_qs = crypto_get_crp_qs(&s);
   1925 	crp_q = crp_qs->crp_q;
   1926 	crp_kq = crp_qs->crp_kq;
   1927 	do {
   1928 		/*
   1929 		 * Find the first element in the queue that can be
   1930 		 * processed and look-ahead to see if multiple ops
   1931 		 * are ready for the same driver.
   1932 		 */
   1933 		submit = NULL;
   1934 		hint = 0;
   1935 		TAILQ_FOREACH_SAFE(crp, crp_q, crp_next, cnext) {
   1936 			u_int32_t hid = CRYPTO_SESID2HID(crp->crp_sid);
   1937 			cap = crypto_checkdriver_lock(hid);
   1938 			if (cap == NULL || cap->cc_process == NULL) {
   1939 				if (cap != NULL)
   1940 					crypto_driver_unlock(cap);
   1941 				/* Op needs to be migrated, process it. */
   1942 				submit = crp;
   1943 				break;
   1944 			}
   1945 
   1946 			/*
   1947 			 * skip blocked crp regardless of CRYPTO_F_BATCH
   1948 			 */
   1949 			if (cap->cc_qblocked != 0) {
   1950 				crypto_driver_unlock(cap);
   1951 				continue;
   1952 			}
   1953 			crypto_driver_unlock(cap);
   1954 
   1955 			/*
   1956 			 * skip batch crp until the end of crp_q
   1957 			 */
   1958 			if ((crp->crp_flags & CRYPTO_F_BATCH) != 0) {
   1959 				if (submit == NULL) {
   1960 					submit = crp;
   1961 				} else {
   1962 					if (CRYPTO_SESID2HID(submit->crp_sid)
   1963 					    == hid)
   1964 						hint = CRYPTO_HINT_MORE;
   1965 				}
   1966 
   1967 				continue;
   1968 			}
   1969 
   1970 			/*
   1971 			 * found first crp which is neither blocked nor batch.
   1972 			 */
   1973 			submit = crp;
   1974 			/*
   1975 			 * batch crp can be processed much later, so clear hint.
   1976 			 */
   1977 			hint = 0;
   1978 			break;
   1979 		}
   1980 		if (submit != NULL) {
   1981 			TAILQ_REMOVE(crp_q, submit, crp_next);
   1982 			result = crypto_invoke(submit, hint);
   1983 			/* we must take here as the TAILQ op or kinvoke
   1984 			   may need this mutex below.  sigh. */
   1985 			if (result == ERESTART) {
   1986 				/*
   1987 				 * The driver ran out of resources, mark the
   1988 				 * driver ``blocked'' for cryptop's and put
   1989 				 * the request back in the queue.  It would
   1990 				 * best to put the request back where we got
   1991 				 * it but that's hard so for now we put it
   1992 				 * at the front.  This should be ok; putting
   1993 				 * it at the end does not work.
   1994 				 */
   1995 				/* validate sid again */
   1996 				cap = crypto_checkdriver_lock(CRYPTO_SESID2HID(submit->crp_sid));
   1997 				if (cap == NULL) {
   1998 					/* migrate again, sigh... */
   1999 					TAILQ_INSERT_TAIL(crp_q, submit, crp_next);
   2000 				} else {
   2001 					cap->cc_qblocked = 1;
   2002 					crypto_driver_unlock(cap);
   2003 					TAILQ_INSERT_HEAD(crp_q, submit, crp_next);
   2004 					cryptostats.cs_blocks++;
   2005 				}
   2006 			}
   2007 		}
   2008 
   2009 		/* As above, but for key ops */
   2010 		TAILQ_FOREACH_SAFE(krp, crp_kq, krp_next, knext) {
   2011 			cap = crypto_checkdriver_lock(krp->krp_hid);
   2012 			if (cap == NULL || cap->cc_kprocess == NULL) {
   2013 				if (cap != NULL)
   2014 					crypto_driver_unlock(cap);
   2015 				/* Op needs to be migrated, process it. */
   2016 				break;
   2017 			}
   2018 			if (!cap->cc_kqblocked) {
   2019 				crypto_driver_unlock(cap);
   2020 				break;
   2021 			}
   2022 			crypto_driver_unlock(cap);
   2023 		}
   2024 		if (krp != NULL) {
   2025 			TAILQ_REMOVE(crp_kq, krp, krp_next);
   2026 			result = crypto_kinvoke(krp, 0);
   2027 			/* the next iteration will want the mutex. :-/ */
   2028 			if (result == ERESTART) {
   2029 				/*
   2030 				 * The driver ran out of resources, mark the
   2031 				 * driver ``blocked'' for cryptkop's and put
   2032 				 * the request back in the queue.  It would
   2033 				 * best to put the request back where we got
   2034 				 * it but that's hard so for now we put it
   2035 				 * at the front.  This should be ok; putting
   2036 				 * it at the end does not work.
   2037 				 */
   2038 				/* validate sid again */
   2039 				cap = crypto_checkdriver_lock(krp->krp_hid);
   2040 				if (cap == NULL) {
   2041 					/* migrate again, sigh... */
   2042 					TAILQ_INSERT_TAIL(crp_kq, krp, krp_next);
   2043 				} else {
   2044 					cap->cc_kqblocked = 1;
   2045 					crypto_driver_unlock(cap);
   2046 					TAILQ_INSERT_HEAD(crp_kq, krp, krp_next);
   2047 					cryptostats.cs_kblocks++;
   2048 				}
   2049 			}
   2050 		}
   2051 	} while (submit != NULL || krp != NULL);
   2052 	crypto_put_crp_qs(&s);
   2053 }
   2054 
   2055 /*
   2056  * softint handler to do callbacks.
   2057  */
   2058 static void
   2059 cryptoret_softint(void *arg __unused)
   2060 {
   2061 	struct crypto_crp_ret_qs *qs;
   2062 	struct crypto_crp_ret_q *crp_ret_q;
   2063 	struct crypto_crp_ret_kq *crp_ret_kq;
   2064 
   2065 	qs = crypto_get_crp_ret_qs(curcpu());
   2066 	crp_ret_q = &qs->crp_ret_q;
   2067 	crp_ret_kq = &qs->crp_ret_kq;
   2068 	for (;;) {
   2069 		struct cryptop *crp;
   2070 		struct cryptkop *krp;
   2071 
   2072 		crp = TAILQ_FIRST(crp_ret_q);
   2073 		if (crp != NULL) {
   2074 			TAILQ_REMOVE(crp_ret_q, crp, crp_next);
   2075 			qs->crp_ret_q_len--;
   2076 			crp->crp_flags &= ~CRYPTO_F_ONRETQ;
   2077 		}
   2078 		krp = TAILQ_FIRST(crp_ret_kq);
   2079 		if (krp != NULL) {
   2080 			TAILQ_REMOVE(crp_ret_kq, krp, krp_next);
   2081 			qs->crp_ret_q_len--;
   2082 			krp->krp_flags &= ~CRYPTO_F_ONRETQ;
   2083 		}
   2084 
   2085 		/* drop before calling any callbacks. */
   2086 		if (crp == NULL && krp == NULL)
   2087 			break;
   2088 
   2089 		mutex_spin_exit(&qs->crp_ret_q_mtx);
   2090 		if (crp != NULL) {
   2091 #ifdef CRYPTO_TIMING
   2092 			if (crypto_timing) {
   2093 				/*
   2094 				 * NB: We must copy the timestamp before
   2095 				 * doing the callback as the cryptop is
   2096 				 * likely to be reclaimed.
   2097 				 */
   2098 				struct timespec t = crp->crp_tstamp;
   2099 				crypto_tstat(&cryptostats.cs_cb, &t);
   2100 				crp->crp_callback(crp);
   2101 				crypto_tstat(&cryptostats.cs_finis, &t);
   2102 			} else
   2103 #endif
   2104 			{
   2105 				crp->crp_callback(crp);
   2106 			}
   2107 		}
   2108 		if (krp != NULL)
   2109 			krp->krp_callback(krp);
   2110 
   2111 		mutex_spin_enter(&qs->crp_ret_q_mtx);
   2112 	}
   2113 	crypto_put_crp_ret_qs(curcpu());
   2114 }
   2115 
   2116 /* NetBSD module interface */
   2117 
   2118 MODULE(MODULE_CLASS_MISC, opencrypto, NULL);
   2119 
   2120 static int
   2121 opencrypto_modcmd(modcmd_t cmd, void *opaque)
   2122 {
   2123 	int error = 0;
   2124 
   2125 	switch (cmd) {
   2126 	case MODULE_CMD_INIT:
   2127 #ifdef _MODULE
   2128 		error = crypto_init();
   2129 #endif
   2130 		break;
   2131 	case MODULE_CMD_FINI:
   2132 #ifdef _MODULE
   2133 		error = crypto_destroy(true);
   2134 #endif
   2135 		break;
   2136 	default:
   2137 		error = ENOTTY;
   2138 	}
   2139 	return error;
   2140 }
   2141