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