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