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