Home | History | Annotate | Line # | Download | only in opencrypto
crypto.c revision 1.25
      1 /*	$NetBSD: crypto.c,v 1.25 2008/02/05 01:43:22 tls 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  * The author of this code is Angelos D. Keromytis (angelos (at) cis.upenn.edu)
      7  *
      8  * This code was written by Angelos D. Keromytis in Athens, Greece, in
      9  * February 2000. Network Security Technologies Inc. (NSTI) kindly
     10  * supported the development of this code.
     11  *
     12  * Copyright (c) 2000, 2001 Angelos D. Keromytis
     13  *
     14  * Permission to use, copy, and modify this software with or without fee
     15  * is hereby granted, provided that this entire notice is included in
     16  * all source code copies of any software which is or includes a copy or
     17  * modification of this software.
     18  *
     19  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
     20  * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
     21  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
     22  * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
     23  * PURPOSE.
     24  */
     25 
     26 #include <sys/cdefs.h>
     27 __KERNEL_RCSID(0, "$NetBSD: crypto.c,v 1.25 2008/02/05 01:43:22 tls Exp $");
     28 
     29 #include <sys/param.h>
     30 #include <sys/reboot.h>
     31 #include <sys/systm.h>
     32 #include <sys/malloc.h>
     33 #include <sys/proc.h>
     34 #include <sys/pool.h>
     35 #include <sys/kthread.h>
     36 #include <sys/once.h>
     37 #include <sys/sysctl.h>
     38 #include <sys/intr.h>
     39 
     40 #include "opt_ocf.h"
     41 #include <opencrypto/cryptodev.h>
     42 #include <opencrypto/xform.h>			/* XXX for M_XDATA */
     43 
     44 kcondvar_t cryptoret_cv;
     45 kmutex_t crypto_mtx;
     46 
     47 /* below are kludges for residual code wrtitten to FreeBSD interfaces */
     48   #define SWI_CRYPTO 17
     49   #define register_swi(lvl, fn)  \
     50   softint_establish(SOFTINT_NET, (void (*)(void*))fn, NULL)
     51   #define unregister_swi(lvl, fn)  softint_disestablish(softintr_cookie)
     52   #define setsoftcrypto(x) softint_schedule(x)
     53 
     54 #define	SESID2HID(sid)	(((sid) >> 32) & 0xffffffff)
     55 
     56 /*
     57  * Crypto drivers register themselves by allocating a slot in the
     58  * crypto_drivers table with crypto_get_driverid() and then registering
     59  * each algorithm they support with crypto_register() and crypto_kregister().
     60  */
     61 static	struct cryptocap *crypto_drivers;
     62 static	int crypto_drivers_num;
     63 static	void* softintr_cookie;
     64 
     65 /*
     66  * There are two queues for crypto requests; one for symmetric (e.g.
     67  * cipher) operations and one for asymmetric (e.g. MOD) operations.
     68  * See below for how synchronization is handled.
     69  */
     70 static	TAILQ_HEAD(,cryptop) crp_q =		/* request queues */
     71 		TAILQ_HEAD_INITIALIZER(crp_q);
     72 static	TAILQ_HEAD(,cryptkop) crp_kq =
     73 		TAILQ_HEAD_INITIALIZER(crp_kq);
     74 
     75 /*
     76  * There are two queues for processing completed crypto requests; one
     77  * for the symmetric and one for the asymmetric ops.  We only need one
     78  * but have two to avoid type futzing (cryptop vs. cryptkop).  See below
     79  * for how synchronization is handled.
     80  */
     81 static	TAILQ_HEAD(crprethead, cryptop) crp_ret_q =	/* callback queues */
     82 		TAILQ_HEAD_INITIALIZER(crp_ret_q);
     83 static	TAILQ_HEAD(krprethead, cryptkop) crp_ret_kq =
     84 		TAILQ_HEAD_INITIALIZER(crp_ret_kq);
     85 
     86 /*
     87  * XXX these functions are ghastly hacks for when the submission
     88  * XXX routines discover a request that was not CBIMM is already
     89  * XXX done, and must be yanked from the retq (where _done) put it
     90  * XXX as cryptoret won't get the chance.  The queue is walked backwards
     91  * XXX as the request is generally the last one queued.
     92  *
     93  *	 call with the lock held, or else.
     94  */
     95 int
     96 crypto_ret_q_remove(struct cryptop *crp)
     97 {
     98 	struct cryptop * acrp;
     99 
    100 	TAILQ_FOREACH_REVERSE(acrp, &crp_ret_q, crprethead, crp_next) {
    101 		if (acrp == crp) {
    102 			TAILQ_REMOVE(&crp_ret_q, crp, crp_next);
    103 			crp->crp_flags &= (~CRYPTO_F_ONRETQ);
    104 			return 1;
    105 		}
    106 	}
    107 	return 0;
    108 }
    109 
    110 int
    111 crypto_ret_kq_remove(struct cryptkop *krp)
    112 {
    113 	struct cryptkop * akrp;
    114 
    115 	TAILQ_FOREACH_REVERSE(akrp, &crp_ret_kq, krprethead, krp_next) {
    116 		if (akrp == krp) {
    117 			TAILQ_REMOVE(&crp_ret_kq, krp, krp_next);
    118 			krp->krp_flags &= (~CRYPTO_F_ONRETQ);
    119 			return 1;
    120 		}
    121 	}
    122 	return 0;
    123 }
    124 
    125 /*
    126  * Crypto op and desciptor data structures are allocated
    127  * from separate private zones(FreeBSD)/pools(netBSD/OpenBSD) .
    128  */
    129 struct pool cryptop_pool;
    130 struct pool cryptodesc_pool;
    131 struct pool cryptkop_pool;
    132 
    133 int	crypto_usercrypto = 1;		/* userland may open /dev/crypto */
    134 int	crypto_userasymcrypto = 1;	/* userland may do asym crypto reqs */
    135 /*
    136  * cryptodevallowsoft is (intended to be) sysctl'able, controlling
    137  * access to hardware versus software transforms as below:
    138  *
    139  * crypto_devallowsoft < 0:  Force userlevel requests to use software
    140  *                              transforms, always
    141  * crypto_devallowsoft = 0:  Use hardware if present, grant userlevel
    142  *                              requests for non-accelerated transforms
    143  *                              (handling the latter in software)
    144  * crypto_devallowsoft > 0:  Allow user requests only for transforms which
    145  *                               are hardware-accelerated.
    146  */
    147 int	crypto_devallowsoft = 1;	/* only use hardware crypto */
    148 
    149 SYSCTL_SETUP(sysctl_opencrypto_setup, "sysctl opencrypto subtree setup")
    150 {
    151 	sysctl_createv(clog, 0, NULL, NULL,
    152 		       CTLFLAG_PERMANENT,
    153 		       CTLTYPE_NODE, "kern", NULL,
    154 		       NULL, 0, NULL, 0,
    155 		       CTL_KERN, CTL_EOL);
    156 	sysctl_createv(clog, 0, NULL, NULL,
    157 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    158 		       CTLTYPE_INT, "usercrypto",
    159 		       SYSCTL_DESCR("Enable/disable user-mode access to "
    160 			   "crypto support"),
    161 		       NULL, 0, &crypto_usercrypto, 0,
    162 		       CTL_KERN, CTL_CREATE, CTL_EOL);
    163 	sysctl_createv(clog, 0, NULL, NULL,
    164 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    165 		       CTLTYPE_INT, "userasymcrypto",
    166 		       SYSCTL_DESCR("Enable/disable user-mode access to "
    167 			   "asymmetric crypto support"),
    168 		       NULL, 0, &crypto_userasymcrypto, 0,
    169 		       CTL_KERN, CTL_CREATE, CTL_EOL);
    170 	sysctl_createv(clog, 0, NULL, NULL,
    171 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    172 		       CTLTYPE_INT, "cryptodevallowsoft",
    173 		       SYSCTL_DESCR("Enable/disable use of software "
    174 			   "asymmetric crypto support"),
    175 		       NULL, 0, &crypto_devallowsoft, 0,
    176 		       CTL_KERN, CTL_CREATE, CTL_EOL);
    177 }
    178 
    179 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
    180 
    181 /*
    182  * Synchronization: read carefully, this is non-trivial.
    183  *
    184  * Crypto requests are submitted via crypto_dispatch.  Typically
    185  * these come in from network protocols at spl0 (output path) or
    186  * spl[,soft]net (input path).
    187  *
    188  * Requests are typically passed on the driver directly, but they
    189  * may also be queued for processing by a software interrupt thread,
    190  * cryptointr, that runs at splsoftcrypto.  This thread dispatches
    191  * the requests to crypto drivers (h/w or s/w) who call crypto_done
    192  * when a request is complete.  Hardware crypto drivers are assumed
    193  * to register their IRQ's as network devices so their interrupt handlers
    194  * and subsequent "done callbacks" happen at spl[imp,net].
    195  *
    196  * Completed crypto ops are queued for a separate kernel thread that
    197  * handles the callbacks at spl0.  This decoupling insures the crypto
    198  * driver interrupt service routine is not delayed while the callback
    199  * takes place and that callbacks are delivered after a context switch
    200  * (as opposed to a software interrupt that clients must block).
    201  *
    202  * This scheme is not intended for SMP machines.
    203  */
    204 static	void cryptointr(void);		/* swi thread to dispatch ops */
    205 static	void cryptoret(void);		/* kernel thread for callbacks*/
    206 static	struct lwp *cryptothread;
    207 static	void crypto_destroy(void);
    208 static	int crypto_invoke(struct cryptop *crp, int hint);
    209 static	int crypto_kinvoke(struct cryptkop *krp, int hint);
    210 
    211 static struct cryptostats cryptostats;
    212 #ifdef CRYPTO_TIMING
    213 static	int crypto_timing = 0;
    214 #endif
    215 
    216 static int
    217 crypto_init0(void)
    218 {
    219 	int error;
    220 
    221 	mutex_init(&crypto_mtx, MUTEX_DEFAULT, IPL_NET);
    222 	cv_init(&cryptoret_cv, "crypto_wait");
    223 	pool_init(&cryptop_pool, sizeof(struct cryptop), 0, 0,
    224 		  0, "cryptop", NULL, IPL_NET);
    225 	pool_init(&cryptodesc_pool, sizeof(struct cryptodesc), 0, 0,
    226 		  0, "cryptodesc", NULL, IPL_NET);
    227 	pool_init(&cryptkop_pool, sizeof(struct cryptkop), 0, 0,
    228 		  0, "cryptkop", NULL, IPL_NET);
    229 
    230 	crypto_drivers = malloc(CRYPTO_DRIVERS_INITIAL *
    231 	    sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT | M_ZERO);
    232 	if (crypto_drivers == NULL) {
    233 		printf("crypto_init: cannot malloc driver table\n");
    234 		return 0;
    235 	}
    236 	crypto_drivers_num = CRYPTO_DRIVERS_INITIAL;
    237 
    238 	softintr_cookie = register_swi(SWI_CRYPTO, cryptointr);
    239 	error = kthread_create(PRI_NONE, KTHREAD_MPSAFE, NULL,
    240 	    (void (*)(void*))cryptoret, NULL, &cryptothread, "cryptoret");
    241 	if (error) {
    242 		printf("crypto_init: cannot start cryptoret thread; error %d",
    243 			error);
    244 		crypto_destroy();
    245 	}
    246 
    247 	return 0;
    248 }
    249 
    250 void
    251 crypto_init(void)
    252 {
    253 	static ONCE_DECL(crypto_init_once);
    254 
    255 	RUN_ONCE(&crypto_init_once, crypto_init0);
    256 }
    257 
    258 static void
    259 crypto_destroy(void)
    260 {
    261 	/* XXX no wait to reclaim zones */
    262 	if (crypto_drivers != NULL)
    263 		free(crypto_drivers, M_CRYPTO_DATA);
    264 	unregister_swi(SWI_CRYPTO, cryptointr);
    265 }
    266 
    267 /*
    268  * Create a new session.  Must be called with crypto_mtx held.
    269  */
    270 int
    271 crypto_newsession(u_int64_t *sid, struct cryptoini *cri, int hard)
    272 {
    273 	struct cryptoini *cr;
    274 	u_int32_t hid, lid;
    275 	int err = EINVAL;
    276 
    277 	KASSERT(mutex_owned(&crypto_mtx));
    278 
    279 	if (crypto_drivers == NULL)
    280 		goto done;
    281 
    282 	/*
    283 	 * The algorithm we use here is pretty stupid; just use the
    284 	 * first driver that supports all the algorithms we need.
    285 	 *
    286 	 * XXX We need more smarts here (in real life too, but that's
    287 	 * XXX another story altogether).
    288 	 */
    289 
    290 	for (hid = 0; hid < crypto_drivers_num; hid++) {
    291 		/*
    292 		 * If it's not initialized or has remaining sessions
    293 		 * referencing it, skip.
    294 		 */
    295 		if (crypto_drivers[hid].cc_newsession == NULL ||
    296 		    (crypto_drivers[hid].cc_flags & CRYPTOCAP_F_CLEANUP))
    297 			continue;
    298 
    299 		/* Hardware required -- ignore software drivers. */
    300 		if (hard > 0 &&
    301 		    (crypto_drivers[hid].cc_flags & CRYPTOCAP_F_SOFTWARE))
    302 			continue;
    303 		/* Software required -- ignore hardware drivers. */
    304 		if (hard < 0 &&
    305 		    (crypto_drivers[hid].cc_flags & CRYPTOCAP_F_SOFTWARE) == 0)
    306 			continue;
    307 
    308 		/* See if all the algorithms are supported. */
    309 		for (cr = cri; cr; cr = cr->cri_next)
    310 			if (crypto_drivers[hid].cc_alg[cr->cri_alg] == 0)
    311 				break;
    312 
    313 		if (cr == NULL) {
    314 			/* Ok, all algorithms are supported. */
    315 
    316 			/*
    317 			 * Can't do everything in one session.
    318 			 *
    319 			 * XXX Fix this. We need to inject a "virtual" session layer right
    320 			 * XXX about here.
    321 			 */
    322 
    323 			/* Call the driver initialization routine. */
    324 			lid = hid;		/* Pass the driver ID. */
    325 			err = crypto_drivers[hid].cc_newsession(
    326 					crypto_drivers[hid].cc_arg, &lid, cri);
    327 			if (err == 0) {
    328 				(*sid) = hid;
    329 				(*sid) <<= 32;
    330 				(*sid) |= (lid & 0xffffffff);
    331 				crypto_drivers[hid].cc_sessions++;
    332 			}
    333 			goto done;
    334 			/*break;*/
    335 		}
    336 	}
    337 done:
    338 	return err;
    339 }
    340 
    341 /*
    342  * Delete an existing session (or a reserved session on an unregistered
    343  * driver).  Must be called with crypto_mtx mutex held.
    344  */
    345 int
    346 crypto_freesession(u_int64_t sid)
    347 {
    348 	u_int32_t hid;
    349 	int err = 0;
    350 
    351 	KASSERT(mutex_owned(&crypto_mtx));
    352 
    353 	if (crypto_drivers == NULL) {
    354 		err = EINVAL;
    355 		goto done;
    356 	}
    357 
    358 	/* Determine two IDs. */
    359 	hid = SESID2HID(sid);
    360 
    361 	if (hid >= crypto_drivers_num) {
    362 		err = ENOENT;
    363 		goto done;
    364 	}
    365 
    366 	if (crypto_drivers[hid].cc_sessions)
    367 		crypto_drivers[hid].cc_sessions--;
    368 
    369 	/* Call the driver cleanup routine, if available. */
    370 	if (crypto_drivers[hid].cc_freesession) {
    371 		err = crypto_drivers[hid].cc_freesession(
    372 				crypto_drivers[hid].cc_arg, sid);
    373 	}
    374 	else
    375 		err = 0;
    376 
    377 	/*
    378 	 * If this was the last session of a driver marked as invalid,
    379 	 * make the entry available for reuse.
    380 	 */
    381 	if ((crypto_drivers[hid].cc_flags & CRYPTOCAP_F_CLEANUP) &&
    382 	    crypto_drivers[hid].cc_sessions == 0)
    383 		bzero(&crypto_drivers[hid], sizeof(struct cryptocap));
    384 
    385 done:
    386 	return err;
    387 }
    388 
    389 /*
    390  * Return an unused driver id.  Used by drivers prior to registering
    391  * support for the algorithms they handle.
    392  */
    393 int32_t
    394 crypto_get_driverid(u_int32_t flags)
    395 {
    396 	struct cryptocap *newdrv;
    397 	int i;
    398 
    399 	crypto_init();		/* XXX oh, this is foul! */
    400 
    401 	mutex_spin_enter(&crypto_mtx);
    402 	for (i = 0; i < crypto_drivers_num; i++)
    403 		if (crypto_drivers[i].cc_process == NULL &&
    404 		    (crypto_drivers[i].cc_flags & CRYPTOCAP_F_CLEANUP) == 0 &&
    405 		    crypto_drivers[i].cc_sessions == 0)
    406 			break;
    407 
    408 	/* Out of entries, allocate some more. */
    409 	if (i == crypto_drivers_num) {
    410 		/* Be careful about wrap-around. */
    411 		if (2 * crypto_drivers_num <= crypto_drivers_num) {
    412 			mutex_spin_exit(&crypto_mtx);
    413 			printf("crypto: driver count wraparound!\n");
    414 			return -1;
    415 		}
    416 
    417 		newdrv = malloc(2 * crypto_drivers_num *
    418 		    sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT|M_ZERO);
    419 		if (newdrv == NULL) {
    420 			mutex_spin_exit(&crypto_mtx);
    421 			printf("crypto: no space to expand driver table!\n");
    422 			return -1;
    423 		}
    424 
    425 		bcopy(crypto_drivers, newdrv,
    426 		    crypto_drivers_num * sizeof(struct cryptocap));
    427 
    428 		crypto_drivers_num *= 2;
    429 
    430 		free(crypto_drivers, M_CRYPTO_DATA);
    431 		crypto_drivers = newdrv;
    432 	}
    433 
    434 	/* NB: state is zero'd on free */
    435 	crypto_drivers[i].cc_sessions = 1;	/* Mark */
    436 	crypto_drivers[i].cc_flags = flags;
    437 
    438 	if (bootverbose)
    439 		printf("crypto: assign driver %u, flags %u\n", i, flags);
    440 
    441 	mutex_spin_exit(&crypto_mtx);
    442 
    443 	return i;
    444 }
    445 
    446 static struct cryptocap *
    447 crypto_checkdriver(u_int32_t hid)
    448 {
    449 	if (crypto_drivers == NULL)
    450 		return NULL;
    451 	return (hid >= crypto_drivers_num ? NULL : &crypto_drivers[hid]);
    452 }
    453 
    454 /*
    455  * Register support for a key-related algorithm.  This routine
    456  * is called once for each algorithm supported a driver.
    457  */
    458 int
    459 crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags,
    460     int (*kprocess)(void*, struct cryptkop *, int),
    461     void *karg)
    462 {
    463 	struct cryptocap *cap;
    464 	int err;
    465 
    466 	mutex_spin_enter(&crypto_mtx);
    467 
    468 	cap = crypto_checkdriver(driverid);
    469 	if (cap != NULL &&
    470 	    (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
    471 		/*
    472 		 * XXX Do some performance testing to determine placing.
    473 		 * XXX We probably need an auxiliary data structure that
    474 		 * XXX describes relative performances.
    475 		 */
    476 
    477 		cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
    478 		if (bootverbose) {
    479 			printf("crypto: driver %u registers key alg %u "
    480 			       " flags %u\n",
    481 				driverid,
    482 				kalg,
    483 				flags
    484 			);
    485 		}
    486 
    487 		if (cap->cc_kprocess == NULL) {
    488 			cap->cc_karg = karg;
    489 			cap->cc_kprocess = kprocess;
    490 		}
    491 		err = 0;
    492 	} else
    493 		err = EINVAL;
    494 
    495 	mutex_spin_exit(&crypto_mtx);
    496 	return err;
    497 }
    498 
    499 /*
    500  * Register support for a non-key-related algorithm.  This routine
    501  * is called once for each such algorithm supported by a driver.
    502  */
    503 int
    504 crypto_register(u_int32_t driverid, int alg, u_int16_t maxoplen,
    505     u_int32_t flags,
    506     int (*newses)(void*, u_int32_t*, struct cryptoini*),
    507     int (*freeses)(void*, u_int64_t),
    508     int (*process)(void*, struct cryptop *, int),
    509     void *arg)
    510 {
    511 	struct cryptocap *cap;
    512 	int err;
    513 
    514 	mutex_spin_enter(&crypto_mtx);
    515 
    516 	cap = crypto_checkdriver(driverid);
    517 	/* NB: algorithms are in the range [1..max] */
    518 	if (cap != NULL &&
    519 	    (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX)) {
    520 		/*
    521 		 * XXX Do some performance testing to determine placing.
    522 		 * XXX We probably need an auxiliary data structure that
    523 		 * XXX describes relative performances.
    524 		 */
    525 
    526 		cap->cc_alg[alg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
    527 		cap->cc_max_op_len[alg] = maxoplen;
    528 		if (bootverbose) {
    529 			printf("crypto: driver %u registers alg %u "
    530 				"flags %u maxoplen %u\n",
    531 				driverid,
    532 				alg,
    533 				flags,
    534 				maxoplen
    535 			);
    536 		}
    537 
    538 		if (cap->cc_process == NULL) {
    539 			cap->cc_arg = arg;
    540 			cap->cc_newsession = newses;
    541 			cap->cc_process = process;
    542 			cap->cc_freesession = freeses;
    543 			cap->cc_sessions = 0;		/* Unmark */
    544 		}
    545 		err = 0;
    546 	} else
    547 		err = EINVAL;
    548 
    549 	mutex_spin_exit(&crypto_mtx);
    550 	return err;
    551 }
    552 
    553 /*
    554  * Unregister a crypto driver. If there are pending sessions using it,
    555  * leave enough information around so that subsequent calls using those
    556  * sessions will correctly detect the driver has been unregistered and
    557  * reroute requests.
    558  */
    559 int
    560 crypto_unregister(u_int32_t driverid, int alg)
    561 {
    562 	int i, err;
    563 	u_int32_t ses;
    564 	struct cryptocap *cap;
    565 
    566 	mutex_spin_enter(&crypto_mtx);
    567 
    568 	cap = crypto_checkdriver(driverid);
    569 	if (cap != NULL &&
    570 	    (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX) &&
    571 	    cap->cc_alg[alg] != 0) {
    572 		cap->cc_alg[alg] = 0;
    573 		cap->cc_max_op_len[alg] = 0;
    574 
    575 		/* Was this the last algorithm ? */
    576 		for (i = 1; i <= CRYPTO_ALGORITHM_MAX; i++)
    577 			if (cap->cc_alg[i] != 0)
    578 				break;
    579 
    580 		if (i == CRYPTO_ALGORITHM_MAX + 1) {
    581 			ses = cap->cc_sessions;
    582 			bzero(cap, sizeof(struct cryptocap));
    583 			if (ses != 0) {
    584 				/*
    585 				 * If there are pending sessions, just mark as invalid.
    586 				 */
    587 				cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
    588 				cap->cc_sessions = ses;
    589 			}
    590 		}
    591 		err = 0;
    592 	} else
    593 		err = EINVAL;
    594 
    595 	mutex_spin_exit(&crypto_mtx);
    596 	return err;
    597 }
    598 
    599 /*
    600  * Unregister all algorithms associated with a crypto driver.
    601  * If there are pending sessions using it, leave enough information
    602  * around so that subsequent calls using those sessions will
    603  * correctly detect the driver has been unregistered and reroute
    604  * requests.
    605  *
    606  * XXX careful.  Don't change this to call crypto_unregister() for each
    607  * XXX registered algorithm unless you drop the mutex across the calls;
    608  * XXX you can't take it recursively.
    609  */
    610 int
    611 crypto_unregister_all(u_int32_t driverid)
    612 {
    613 	int i, err;
    614 	u_int32_t ses;
    615 	struct cryptocap *cap;
    616 
    617 	mutex_spin_enter(&crypto_mtx);
    618 	cap = crypto_checkdriver(driverid);
    619 	if (cap != NULL) {
    620 		for (i = CRYPTO_ALGORITHM_MIN; i <= CRYPTO_ALGORITHM_MAX; i++) {
    621 			cap->cc_alg[i] = 0;
    622 			cap->cc_max_op_len[i] = 0;
    623 		}
    624 		ses = cap->cc_sessions;
    625 		bzero(cap, sizeof(struct cryptocap));
    626 		if (ses != 0) {
    627 			/*
    628 			 * If there are pending sessions, just mark as invalid.
    629 			 */
    630 			cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
    631 			cap->cc_sessions = ses;
    632 		}
    633 		err = 0;
    634 	} else
    635 		err = EINVAL;
    636 
    637 	mutex_spin_exit(&crypto_mtx);
    638 	return err;
    639 }
    640 
    641 /*
    642  * Clear blockage on a driver.  The what parameter indicates whether
    643  * the driver is now ready for cryptop's and/or cryptokop's.
    644  */
    645 int
    646 crypto_unblock(u_int32_t driverid, int what)
    647 {
    648 	struct cryptocap *cap;
    649 	int needwakeup, err;
    650 
    651 	mutex_spin_enter(&crypto_mtx);
    652 	cap = crypto_checkdriver(driverid);
    653 	if (cap != NULL) {
    654 		needwakeup = 0;
    655 		if (what & CRYPTO_SYMQ) {
    656 			needwakeup |= cap->cc_qblocked;
    657 			cap->cc_qblocked = 0;
    658 		}
    659 		if (what & CRYPTO_ASYMQ) {
    660 			needwakeup |= cap->cc_kqblocked;
    661 			cap->cc_kqblocked = 0;
    662 		}
    663 		err = 0;
    664 		mutex_spin_exit(&crypto_mtx);
    665 		if (needwakeup)
    666 			setsoftcrypto(softintr_cookie);
    667 	} else {
    668 		err = EINVAL;
    669 		mutex_spin_exit(&crypto_mtx);
    670 	}
    671 
    672 	return err;
    673 }
    674 
    675 /*
    676  * Dispatch a crypto request to a driver or queue
    677  * it, to be processed by the kernel thread.
    678  */
    679 int
    680 crypto_dispatch(struct cryptop *crp)
    681 {
    682 	u_int32_t hid = SESID2HID(crp->crp_sid);
    683 	int result;
    684 
    685 	mutex_spin_enter(&crypto_mtx);
    686 
    687 	cryptostats.cs_ops++;
    688 
    689 #ifdef CRYPTO_TIMING
    690 	if (crypto_timing)
    691 		nanouptime(&crp->crp_tstamp);
    692 #endif
    693 	if ((crp->crp_flags & CRYPTO_F_BATCH) == 0) {
    694 		struct cryptocap *cap;
    695 		/*
    696 		 * Caller marked the request to be processed
    697 		 * immediately; dispatch it directly to the
    698 		 * driver unless the driver is currently blocked.
    699 		 */
    700 		cap = crypto_checkdriver(hid);
    701 		if (cap && !cap->cc_qblocked) {
    702 			mutex_spin_exit(&crypto_mtx);
    703 			result = crypto_invoke(crp, 0);
    704 			if (result == ERESTART) {
    705 				/*
    706 				 * The driver ran out of resources, mark the
    707 				 * driver ``blocked'' for cryptop's and put
    708 				 * the op on the queue.
    709 				 */
    710 				mutex_spin_enter(&crypto_mtx);
    711 				crypto_drivers[hid].cc_qblocked = 1;
    712 				TAILQ_INSERT_HEAD(&crp_q, crp, crp_next);
    713 				cryptostats.cs_blocks++;
    714 				mutex_spin_exit(&crypto_mtx);
    715 			}
    716 			goto out_released;
    717 		} else {
    718 			/*
    719 			 * The driver is blocked, just queue the op until
    720 			 * it unblocks and the swi thread gets kicked.
    721 			 */
    722 			TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
    723 			result = 0;
    724 		}
    725 	} else {
    726 		int wasempty = TAILQ_EMPTY(&crp_q);
    727 		/*
    728 		 * Caller marked the request as ``ok to delay'';
    729 		 * queue it for the swi thread.  This is desirable
    730 		 * when the operation is low priority and/or suitable
    731 		 * for batching.
    732 		 */
    733 		TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
    734 		if (wasempty) {
    735 			mutex_spin_exit(&crypto_mtx);
    736 			setsoftcrypto(softintr_cookie);
    737 			result = 0;
    738 			goto out_released;
    739 		}
    740 
    741 		result = 0;
    742 	}
    743 
    744 	mutex_spin_exit(&crypto_mtx);
    745 out_released:
    746 	return result;
    747 }
    748 
    749 /*
    750  * Add an asymetric crypto request to a queue,
    751  * to be processed by the kernel thread.
    752  */
    753 int
    754 crypto_kdispatch(struct cryptkop *krp)
    755 {
    756 	struct cryptocap *cap;
    757 	int result;
    758 
    759 	mutex_spin_enter(&crypto_mtx);
    760 	cryptostats.cs_kops++;
    761 
    762 	cap = crypto_checkdriver(krp->krp_hid);
    763 	if (cap && !cap->cc_kqblocked) {
    764 		mutex_spin_exit(&crypto_mtx);
    765 		result = crypto_kinvoke(krp, 0);
    766 		if (result == ERESTART) {
    767 			/*
    768 			 * The driver ran out of resources, mark the
    769 			 * driver ``blocked'' for cryptop's and put
    770 			 * the op on the queue.
    771 			 */
    772 			mutex_spin_enter(&crypto_mtx);
    773 			crypto_drivers[krp->krp_hid].cc_kqblocked = 1;
    774 			TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
    775 			cryptostats.cs_kblocks++;
    776 			mutex_spin_exit(&crypto_mtx);
    777 		}
    778 	} else {
    779 		/*
    780 		 * The driver is blocked, just queue the op until
    781 		 * it unblocks and the swi thread gets kicked.
    782 		 */
    783 		TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
    784 		result = 0;
    785 		mutex_spin_exit(&crypto_mtx);
    786 	}
    787 
    788 	return result;
    789 }
    790 
    791 /*
    792  * Dispatch an assymetric crypto request to the appropriate crypto devices.
    793  */
    794 static int
    795 crypto_kinvoke(struct cryptkop *krp, int hint)
    796 {
    797 	u_int32_t hid;
    798 	int error;
    799 
    800 	/* Sanity checks. */
    801 	if (krp == NULL)
    802 		return EINVAL;
    803 	if (krp->krp_callback == NULL) {
    804 		pool_put(&cryptkop_pool, krp);
    805 		return EINVAL;
    806 	}
    807 
    808 	for (hid = 0; hid < crypto_drivers_num; hid++) {
    809 		if ((crypto_drivers[hid].cc_flags & CRYPTOCAP_F_SOFTWARE) &&
    810 		    crypto_devallowsoft == 0)
    811 			continue;
    812 		if (crypto_drivers[hid].cc_kprocess == NULL)
    813 			continue;
    814 		if ((crypto_drivers[hid].cc_kalg[krp->krp_op] &
    815 		    CRYPTO_ALG_FLAG_SUPPORTED) == 0)
    816 			continue;
    817 		break;
    818 	}
    819 	if (hid < crypto_drivers_num) {
    820 		krp->krp_hid = hid;
    821 		error = crypto_drivers[hid].cc_kprocess(
    822 				crypto_drivers[hid].cc_karg, krp, hint);
    823 	} else {
    824 		error = ENODEV;
    825 	}
    826 
    827 	if (error) {
    828 		krp->krp_status = error;
    829 		crypto_kdone(krp);
    830 	}
    831 	return 0;
    832 }
    833 
    834 #ifdef CRYPTO_TIMING
    835 static void
    836 crypto_tstat(struct cryptotstat *ts, struct timespec *tv)
    837 {
    838 	struct timespec now, t;
    839 
    840 	nanouptime(&now);
    841 	t.tv_sec = now.tv_sec - tv->tv_sec;
    842 	t.tv_nsec = now.tv_nsec - tv->tv_nsec;
    843 	if (t.tv_nsec < 0) {
    844 		t.tv_sec--;
    845 		t.tv_nsec += 1000000000;
    846 	}
    847 	timespecadd(&ts->acc, &t, &t);
    848 	if (timespeccmp(&t, &ts->min, <))
    849 		ts->min = t;
    850 	if (timespeccmp(&t, &ts->max, >))
    851 		ts->max = t;
    852 	ts->count++;
    853 
    854 	*tv = now;
    855 }
    856 #endif
    857 
    858 /*
    859  * Dispatch a crypto request to the appropriate crypto devices.
    860  */
    861 static int
    862 crypto_invoke(struct cryptop *crp, int hint)
    863 {
    864 	u_int32_t hid;
    865 	int (*process)(void*, struct cryptop *, int);
    866 
    867 #ifdef CRYPTO_TIMING
    868 	if (crypto_timing)
    869 		crypto_tstat(&cryptostats.cs_invoke, &crp->crp_tstamp);
    870 #endif
    871 	/* Sanity checks. */
    872 	if (crp == NULL)
    873 		return EINVAL;
    874 	if (crp->crp_callback == NULL) {
    875 		crypto_freereq(crp);
    876 		return EINVAL;
    877 	}
    878 	if (crp->crp_desc == NULL) {
    879 		crp->crp_etype = EINVAL;
    880 		crypto_done(crp);
    881 		return 0;
    882 	}
    883 
    884 	hid = SESID2HID(crp->crp_sid);
    885 	if (hid < crypto_drivers_num) {
    886 		mutex_enter(&crypto_mtx);
    887 		if (crypto_drivers[hid].cc_flags & CRYPTOCAP_F_CLEANUP)
    888 			crypto_freesession(crp->crp_sid);
    889 		process = crypto_drivers[hid].cc_process;
    890 		mutex_exit(&crypto_mtx);
    891 	} else {
    892 		process = NULL;
    893 	}
    894 
    895 	if (process == NULL) {
    896 		struct cryptodesc *crd;
    897 		u_int64_t nid = 0;
    898 
    899 		/*
    900 		 * Driver has unregistered; migrate the session and return
    901 		 * an error to the caller so they'll resubmit the op.
    902 		 */
    903 		mutex_enter(&crypto_mtx);
    904 		for (crd = crp->crp_desc; crd->crd_next; crd = crd->crd_next)
    905 			crd->CRD_INI.cri_next = &(crd->crd_next->CRD_INI);
    906 
    907 		if (crypto_newsession(&nid, &(crp->crp_desc->CRD_INI), 0) == 0)
    908 			crp->crp_sid = nid;
    909 
    910 		crp->crp_etype = EAGAIN;
    911 		mutex_exit(&crypto_mtx);
    912 
    913 		crypto_done(crp);
    914 		return 0;
    915 	} else {
    916 		/*
    917 		 * Invoke the driver to process the request.
    918 		 */
    919 		DPRINTF(("calling process for %08x\n", (uint32_t)crp));
    920 		return (*process)(crypto_drivers[hid].cc_arg, crp, hint);
    921 	}
    922 }
    923 
    924 /*
    925  * Release a set of crypto descriptors.
    926  */
    927 void
    928 crypto_freereq(struct cryptop *crp)
    929 {
    930 	struct cryptodesc *crd;
    931 
    932 	if (crp == NULL)
    933 		return;
    934 
    935 	while ((crd = crp->crp_desc) != NULL) {
    936 		crp->crp_desc = crd->crd_next;
    937 		pool_put(&cryptodesc_pool, crd);
    938 	}
    939 	pool_put(&cryptop_pool, crp);
    940 }
    941 
    942 /*
    943  * Acquire a set of crypto descriptors.
    944  */
    945 struct cryptop *
    946 crypto_getreq(int num)
    947 {
    948 	struct cryptodesc *crd;
    949 	struct cryptop *crp;
    950 
    951 	crp = pool_get(&cryptop_pool, 0);
    952 	if (crp == NULL) {
    953 		return NULL;
    954 	}
    955 	bzero(crp, sizeof(struct cryptop));
    956 	cv_init(&crp->crp_cv, "crydev");
    957 
    958 	while (num--) {
    959 		crd = pool_get(&cryptodesc_pool, 0);
    960 		if (crd == NULL) {
    961 			crypto_freereq(crp);
    962 			return NULL;
    963 		}
    964 
    965 		bzero(crd, sizeof(struct cryptodesc));
    966 		crd->crd_next = crp->crp_desc;
    967 		crp->crp_desc = crd;
    968 	}
    969 
    970 	return crp;
    971 }
    972 
    973 /*
    974  * Invoke the callback on behalf of the driver.
    975  */
    976 void
    977 crypto_done(struct cryptop *crp)
    978 {
    979 	int wasempty;
    980 
    981 	if (crp->crp_etype != 0)
    982 		cryptostats.cs_errs++;
    983 #ifdef CRYPTO_TIMING
    984 	if (crypto_timing)
    985 		crypto_tstat(&cryptostats.cs_done, &crp->crp_tstamp);
    986 #endif
    987 	/*
    988 	 * Normal case; queue the callback for the thread.
    989 	 *
    990 	 * The return queue is manipulated by the swi thread
    991 	 * and, potentially, by crypto device drivers calling
    992 	 * back to mark operations completed.  Thus we need
    993 	 * to mask both while manipulating the return queue.
    994 	 */
    995 	mutex_spin_enter(&crypto_mtx);
    996 	wasempty = TAILQ_EMPTY(&crp_ret_q);
    997 	DPRINTF(("crypto_done: queueing %08x\n", (uint32_t)crp));
    998 	crp->crp_flags |= CRYPTO_F_ONRETQ|CRYPTO_F_DONE;
    999 	TAILQ_INSERT_TAIL(&crp_ret_q, crp, crp_next);
   1000 	if (wasempty) {
   1001 		DPRINTF(("crypto_done: waking cryptoret, %08x " \
   1002 			"hit empty queue\n.", (uint32_t)crp));
   1003 		cv_signal(&cryptoret_cv);
   1004 	}
   1005 	mutex_spin_exit(&crypto_mtx);
   1006 }
   1007 
   1008 /*
   1009  * Invoke the callback on behalf of the driver.
   1010  */
   1011 void
   1012 crypto_kdone(struct cryptkop *krp)
   1013 {
   1014 	int wasempty;
   1015 
   1016 	if (krp->krp_status != 0)
   1017 		cryptostats.cs_kerrs++;
   1018 	/*
   1019 	 * The return queue is manipulated by the swi thread
   1020 	 * and, potentially, by crypto device drivers calling
   1021 	 * back to mark operations completed.  Thus we need
   1022 	 * to mask both while manipulating the return queue.
   1023 	 */
   1024 	mutex_spin_enter(&crypto_mtx);
   1025 	wasempty = TAILQ_EMPTY(&crp_ret_kq);
   1026 	krp->krp_flags |= CRYPTO_F_ONRETQ|CRYPTO_F_DONE;
   1027 	TAILQ_INSERT_TAIL(&crp_ret_kq, krp, krp_next);
   1028 	if (wasempty)
   1029 		cv_signal(&cryptoret_cv);
   1030 	mutex_spin_exit(&crypto_mtx);
   1031 }
   1032 
   1033 int
   1034 crypto_getfeat(int *featp)
   1035 {
   1036 	int hid, kalg, feat = 0;
   1037 
   1038 	mutex_spin_enter(&crypto_mtx);
   1039 
   1040 	if (crypto_userasymcrypto == 0)
   1041 		goto out;
   1042 
   1043 	for (hid = 0; hid < crypto_drivers_num; hid++) {
   1044 		if ((crypto_drivers[hid].cc_flags & CRYPTOCAP_F_SOFTWARE) &&
   1045 		    crypto_devallowsoft == 0) {
   1046 			continue;
   1047 		}
   1048 		if (crypto_drivers[hid].cc_kprocess == NULL)
   1049 			continue;
   1050 		for (kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
   1051 			if ((crypto_drivers[hid].cc_kalg[kalg] &
   1052 			    CRYPTO_ALG_FLAG_SUPPORTED) != 0)
   1053 				feat |=  1 << kalg;
   1054 	}
   1055 out:
   1056 	mutex_spin_exit(&crypto_mtx);
   1057 	*featp = feat;
   1058 	return (0);
   1059 }
   1060 
   1061 /*
   1062  * Software interrupt thread to dispatch crypto requests.
   1063  */
   1064 static void
   1065 cryptointr(void)
   1066 {
   1067 	struct cryptop *crp, *submit;
   1068 	struct cryptkop *krp;
   1069 	struct cryptocap *cap;
   1070 	int result, hint;
   1071 
   1072 	printf("crypto softint\n");
   1073 	cryptostats.cs_intrs++;
   1074 	mutex_spin_enter(&crypto_mtx);
   1075 	do {
   1076 		/*
   1077 		 * Find the first element in the queue that can be
   1078 		 * processed and look-ahead to see if multiple ops
   1079 		 * are ready for the same driver.
   1080 		 */
   1081 		submit = NULL;
   1082 		hint = 0;
   1083 		TAILQ_FOREACH(crp, &crp_q, crp_next) {
   1084 			u_int32_t hid = SESID2HID(crp->crp_sid);
   1085 			cap = crypto_checkdriver(hid);
   1086 			if (cap == NULL || cap->cc_process == NULL) {
   1087 				/* Op needs to be migrated, process it. */
   1088 				if (submit == NULL)
   1089 					submit = crp;
   1090 				break;
   1091 			}
   1092 			if (!cap->cc_qblocked) {
   1093 				if (submit != NULL) {
   1094 					/*
   1095 					 * We stop on finding another op,
   1096 					 * regardless whether its for the same
   1097 					 * driver or not.  We could keep
   1098 					 * searching the queue but it might be
   1099 					 * better to just use a per-driver
   1100 					 * queue instead.
   1101 					 */
   1102 					if (SESID2HID(submit->crp_sid) == hid)
   1103 						hint = CRYPTO_HINT_MORE;
   1104 					break;
   1105 				} else {
   1106 					submit = crp;
   1107 					if ((submit->crp_flags & CRYPTO_F_BATCH) == 0)
   1108 						break;
   1109 					/* keep scanning for more are q'd */
   1110 				}
   1111 			}
   1112 		}
   1113 		if (submit != NULL) {
   1114 			TAILQ_REMOVE(&crp_q, submit, crp_next);
   1115 			mutex_spin_exit(&crypto_mtx);
   1116 			result = crypto_invoke(submit, hint);
   1117 			/* we must take here as the TAILQ op or kinvoke
   1118 			   may need this mutex below.  sigh. */
   1119 			mutex_spin_enter(&crypto_mtx);
   1120 			if (result == ERESTART) {
   1121 				/*
   1122 				 * The driver ran out of resources, mark the
   1123 				 * driver ``blocked'' for cryptop's and put
   1124 				 * the request back in the queue.  It would
   1125 				 * best to put the request back where we got
   1126 				 * it but that's hard so for now we put it
   1127 				 * at the front.  This should be ok; putting
   1128 				 * it at the end does not work.
   1129 				 */
   1130 				/* XXX validate sid again? */
   1131 				crypto_drivers[SESID2HID(submit->crp_sid)].cc_qblocked = 1;
   1132 				TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
   1133 				cryptostats.cs_blocks++;
   1134 			}
   1135 		}
   1136 
   1137 		/* As above, but for key ops */
   1138 		TAILQ_FOREACH(krp, &crp_kq, krp_next) {
   1139 			cap = crypto_checkdriver(krp->krp_hid);
   1140 			if (cap == NULL || cap->cc_kprocess == NULL) {
   1141 				/* Op needs to be migrated, process it. */
   1142 				break;
   1143 			}
   1144 			if (!cap->cc_kqblocked)
   1145 				break;
   1146 		}
   1147 		if (krp != NULL) {
   1148 			TAILQ_REMOVE(&crp_kq, krp, krp_next);
   1149 			mutex_spin_exit(&crypto_mtx);
   1150 			result = crypto_kinvoke(krp, 0);
   1151 			/* the next iteration will want the mutex. :-/ */
   1152 			mutex_spin_enter(&crypto_mtx);
   1153 			if (result == ERESTART) {
   1154 				/*
   1155 				 * The driver ran out of resources, mark the
   1156 				 * driver ``blocked'' for cryptkop's and put
   1157 				 * the request back in the queue.  It would
   1158 				 * best to put the request back where we got
   1159 				 * it but that's hard so for now we put it
   1160 				 * at the front.  This should be ok; putting
   1161 				 * it at the end does not work.
   1162 				 */
   1163 				/* XXX validate sid again? */
   1164 				crypto_drivers[krp->krp_hid].cc_kqblocked = 1;
   1165 				TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
   1166 				cryptostats.cs_kblocks++;
   1167 			}
   1168 		}
   1169 	} while (submit != NULL || krp != NULL);
   1170 	mutex_spin_exit(&crypto_mtx);
   1171 }
   1172 
   1173 /*
   1174  * Kernel thread to do callbacks.
   1175  */
   1176 static void
   1177 cryptoret(void)
   1178 {
   1179 	struct cryptop *crp;
   1180 	struct cryptkop *krp;
   1181 
   1182 	for (;;) {
   1183 		mutex_spin_enter(&crypto_mtx);
   1184 
   1185 		crp = TAILQ_FIRST(&crp_ret_q);
   1186 		if (crp != NULL) {
   1187 			TAILQ_REMOVE(&crp_ret_q, crp, crp_next);
   1188 			crp->crp_flags &= ~CRYPTO_F_ONRETQ;
   1189 		}
   1190 		krp = TAILQ_FIRST(&crp_ret_kq);
   1191 		if (krp != NULL) {
   1192 			TAILQ_REMOVE(&crp_ret_kq, krp, krp_next);
   1193 			krp->krp_flags &= ~CRYPTO_F_ONRETQ;
   1194 		}
   1195 
   1196 		/* drop before calling any callbacks. */
   1197 		mutex_spin_exit(&crypto_mtx);
   1198 		if (crp != NULL || krp != NULL) {
   1199 			if (crp != NULL) {
   1200 #ifdef CRYPTO_TIMING
   1201 				if (crypto_timing) {
   1202 					/*
   1203 					 * NB: We must copy the timestamp before
   1204 					 * doing the callback as the cryptop is
   1205 					 * likely to be reclaimed.
   1206 					 */
   1207 					struct timespec t = crp->crp_tstamp;
   1208 					crypto_tstat(&cryptostats.cs_cb, &t);
   1209 					crp->crp_callback(crp);
   1210 					crypto_tstat(&cryptostats.cs_finis, &t);
   1211 				} else
   1212 #endif
   1213 				{
   1214 					crp->crp_callback(crp);
   1215 				}
   1216 			}
   1217 			if (krp != NULL)
   1218 				krp->krp_callback(krp);
   1219 		} else {
   1220 			mutex_spin_enter(&crypto_mtx);
   1221 			cv_wait(&cryptoret_cv, &crypto_mtx);
   1222 			mutex_spin_exit(&crypto_mtx);
   1223 			cryptostats.cs_rets++;
   1224 		}
   1225 	}
   1226 }
   1227