xref: /dragonfly/sys/opencrypto/crypto.c (revision cfd1aba3)
1 /*	$FreeBSD: src/sys/opencrypto/crypto.c,v 1.28 2007/10/20 23:23:22 julian Exp $	*/
2 /*-
3  * Copyright (c) 2002-2006 Sam Leffler.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25 
26 /*
27  * Cryptographic Subsystem.
28  *
29  * This code is derived from the Openbsd Cryptographic Framework (OCF)
30  * that has the copyright shown below.  Very little of the original
31  * code remains.
32  */
33 
34 /*-
35  * The author of this code is Angelos D. Keromytis (angelos@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 #define	CRYPTO_TIMING				/* enable timing support */
56 
57 #include "opt_ddb.h"
58 
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/eventhandler.h>
62 #include <sys/kernel.h>
63 #include <sys/kthread.h>
64 #include <sys/lock.h>
65 #include <sys/module.h>
66 #include <sys/malloc.h>
67 #include <sys/proc.h>
68 #include <sys/sysctl.h>
69 #include <sys/objcache.h>
70 
71 #include <sys/thread2.h>
72 #include <sys/mplock2.h>
73 
74 #include <ddb/ddb.h>
75 
76 #include <opencrypto/cryptodev.h>
77 #include <opencrypto/xform.h>			/* XXX for M_XDATA */
78 
79 #include <sys/kobj.h>
80 #include <sys/bus.h>
81 #include "cryptodev_if.h"
82 
83 /*
84  * Crypto drivers register themselves by allocating a slot in the
85  * crypto_drivers table with crypto_get_driverid() and then registering
86  * each algorithm they support with crypto_register() and crypto_kregister().
87  */
88 static	struct lock crypto_drivers_lock;	/* lock on driver table */
89 #define	CRYPTO_DRIVER_LOCK()	lockmgr(&crypto_drivers_lock, LK_EXCLUSIVE)
90 #define	CRYPTO_DRIVER_UNLOCK()	lockmgr(&crypto_drivers_lock, LK_RELEASE)
91 #define	CRYPTO_DRIVER_ASSERT()	KKASSERT(lockstatus(&crypto_drivers_lock, curthread) != 0)
92 
93 /*
94  * Crypto device/driver capabilities structure.
95  *
96  * Synchronization:
97  * (d) - protected by CRYPTO_DRIVER_LOCK()
98  * (q) - protected by CRYPTO_Q_LOCK()
99  * Not tagged fields are read-only.
100  */
101 struct cryptocap {
102 	device_t	cc_dev;			/* (d) device/driver */
103 	u_int32_t	cc_sessions;		/* (d) # of sessions */
104 	u_int32_t	cc_koperations;		/* (d) # os asym operations */
105 	/*
106 	 * Largest possible operator length (in bits) for each type of
107 	 * encryption algorithm. XXX not used
108 	 */
109 	u_int16_t	cc_max_op_len[CRYPTO_ALGORITHM_MAX + 1];
110 	u_int8_t	cc_alg[CRYPTO_ALGORITHM_MAX + 1];
111 	u_int8_t	cc_kalg[CRK_ALGORITHM_MAX + 1];
112 
113 	int		cc_flags;		/* (d) flags */
114 #define CRYPTOCAP_F_CLEANUP	0x80000000	/* needs resource cleanup */
115 	int		cc_qblocked;		/* (q) symmetric q blocked */
116 	int		cc_kqblocked;		/* (q) asymmetric q blocked */
117 };
118 static	struct cryptocap *crypto_drivers = NULL;
119 static	int crypto_drivers_num = 0;
120 
121 typedef struct crypto_tdinfo {
122 	TAILQ_HEAD(,cryptop)	crp_q;		/* request queues */
123 	TAILQ_HEAD(,cryptkop)	crp_kq;
124 	thread_t		crp_td;
125 	struct lock		crp_lock;
126 	int			crp_sleep;
127 } *crypto_tdinfo_t;
128 
129 /*
130  * There are two queues for crypto requests; one for symmetric (e.g.
131  * cipher) operations and one for asymmetric (e.g. MOD) operations.
132  * See below for how synchronization is handled.
133  * A single lock is used to lock access to both queues.  We could
134  * have one per-queue but having one simplifies handling of block/unblock
135  * operations.
136  */
137 static  struct crypto_tdinfo tdinfo_array[MAXCPU];
138 
139 #define	CRYPTO_Q_LOCK(tdinfo)	lockmgr(&tdinfo->crp_lock, LK_EXCLUSIVE)
140 #define	CRYPTO_Q_UNLOCK(tdinfo)	lockmgr(&tdinfo->crp_lock, LK_RELEASE)
141 
142 /*
143  * There are two queues for processing completed crypto requests; one
144  * for the symmetric and one for the asymmetric ops.  We only need one
145  * but have two to avoid type futzing (cryptop vs. cryptkop).  A single
146  * lock is used to lock access to both queues.  Note that this lock
147  * must be separate from the lock on request queues to insure driver
148  * callbacks don't generate lock order reversals.
149  */
150 static	TAILQ_HEAD(,cryptop) crp_ret_q;		/* callback queues */
151 static	TAILQ_HEAD(,cryptkop) crp_ret_kq;
152 static	struct lock crypto_ret_q_lock;
153 #define	CRYPTO_RETQ_LOCK()	lockmgr(&crypto_ret_q_lock, LK_EXCLUSIVE)
154 #define	CRYPTO_RETQ_UNLOCK()	lockmgr(&crypto_ret_q_lock, LK_RELEASE)
155 #define	CRYPTO_RETQ_EMPTY()	(TAILQ_EMPTY(&crp_ret_q) && TAILQ_EMPTY(&crp_ret_kq))
156 
157 /*
158  * Crypto op and desciptor data structures are allocated
159  * from separate object caches.
160  */
161 static struct objcache *cryptop_oc, *cryptodesc_oc;
162 
163 static MALLOC_DEFINE(M_CRYPTO_OP, "crypto op", "crypto op");
164 static MALLOC_DEFINE(M_CRYPTO_DESC, "crypto desc", "crypto desc");
165 
166 int	crypto_userasymcrypto = 1;	/* userland may do asym crypto reqs */
167 SYSCTL_INT(_kern, OID_AUTO, userasymcrypto, CTLFLAG_RW,
168 	   &crypto_userasymcrypto, 0,
169 	   "Enable/disable user-mode access to asymmetric crypto support");
170 int	crypto_devallowsoft = 0;	/* only use hardware crypto for asym */
171 SYSCTL_INT(_kern, OID_AUTO, cryptodevallowsoft, CTLFLAG_RW,
172 	   &crypto_devallowsoft, 0,
173 	   "Enable/disable use of software asym crypto support");
174 int	crypto_altdispatch = 0;		/* dispatch to alternative cpu */
175 SYSCTL_INT(_kern, OID_AUTO, cryptoaltdispatch, CTLFLAG_RW,
176 	   &crypto_altdispatch, 0,
177 	   "Do not queue crypto op on current cpu");
178 
179 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
180 
181 static	void crypto_proc(void *dummy);
182 static	void crypto_ret_proc(void *dummy);
183 static	struct thread *cryptoretthread;
184 static	void crypto_destroy(void);
185 static	int crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint);
186 static	int crypto_kinvoke(struct cryptkop *krp, int flags);
187 
188 static struct cryptostats cryptostats;
189 SYSCTL_STRUCT(_kern, OID_AUTO, crypto_stats, CTLFLAG_RW, &cryptostats,
190 	    cryptostats, "Crypto system statistics");
191 
192 #ifdef CRYPTO_TIMING
193 static	int crypto_timing = 0;
194 SYSCTL_INT(_debug, OID_AUTO, crypto_timing, CTLFLAG_RW,
195 	   &crypto_timing, 0, "Enable/disable crypto timing support");
196 #endif
197 
198 static int
199 crypto_init(void)
200 {
201 	crypto_tdinfo_t tdinfo;
202 	int error;
203 	int n;
204 
205 	lockinit(&crypto_drivers_lock, "crypto driver table", 0, LK_CANRECURSE);
206 
207 	TAILQ_INIT(&crp_ret_q);
208 	TAILQ_INIT(&crp_ret_kq);
209 	lockinit(&crypto_ret_q_lock, "crypto return queues", 0, LK_CANRECURSE);
210 
211 	cryptop_oc = objcache_create_simple(M_CRYPTO_OP, sizeof(struct cryptop));
212 	cryptodesc_oc = objcache_create_simple(M_CRYPTO_DESC,
213 				sizeof(struct cryptodesc));
214 	if (cryptodesc_oc == NULL || cryptop_oc == NULL) {
215 		kprintf("crypto_init: cannot setup crypto caches\n");
216 		error = ENOMEM;
217 		goto bad;
218 	}
219 
220 	crypto_drivers_num = CRYPTO_DRIVERS_INITIAL;
221 	crypto_drivers = kmalloc(crypto_drivers_num * sizeof(struct cryptocap),
222 				 M_CRYPTO_DATA, M_WAITOK | M_ZERO);
223 
224 	for (n = 0; n < ncpus; ++n) {
225 		tdinfo = &tdinfo_array[n];
226 		TAILQ_INIT(&tdinfo->crp_q);
227 		TAILQ_INIT(&tdinfo->crp_kq);
228 		lockinit(&tdinfo->crp_lock, "crypto op queues",
229 			 0, LK_CANRECURSE);
230 		kthread_create_cpu(crypto_proc, tdinfo, &tdinfo->crp_td,
231 				   n, "crypto %d", n);
232 	}
233 	kthread_create(crypto_ret_proc, NULL,
234 		       &cryptoretthread, "crypto returns");
235 	return 0;
236 bad:
237 	crypto_destroy();
238 	return error;
239 }
240 
241 /*
242  * Signal a crypto thread to terminate.  We use the driver
243  * table lock to synchronize the sleep/wakeups so that we
244  * are sure the threads have terminated before we release
245  * the data structures they use.  See crypto_finis below
246  * for the other half of this song-and-dance.
247  */
248 static void
249 crypto_terminate(struct thread **tp, void *q)
250 {
251 	struct thread *t;
252 
253 	KKASSERT(lockstatus(&crypto_drivers_lock, curthread) != 0);
254 	t = *tp;
255 	*tp = NULL;
256 	if (t) {
257 		kprintf("crypto_terminate: start\n");
258 		wakeup_one(q);
259 		crit_enter();
260 		tsleep_interlock(t, 0);
261 		CRYPTO_DRIVER_UNLOCK();	/* let crypto_finis progress */
262 		crit_exit();
263 		tsleep(t, PINTERLOCKED, "crypto_destroy", 0);
264 		CRYPTO_DRIVER_LOCK();
265 		kprintf("crypto_terminate: end\n");
266 	}
267 }
268 
269 static void
270 crypto_destroy(void)
271 {
272 	crypto_tdinfo_t tdinfo;
273 	int n;
274 
275 	/*
276 	 * Terminate any crypto threads.
277 	 */
278 	CRYPTO_DRIVER_LOCK();
279 	for (n = 0; n < ncpus; ++n) {
280 		tdinfo = &tdinfo_array[n];
281 		crypto_terminate(&tdinfo->crp_td, &tdinfo->crp_q);
282 		lockuninit(&tdinfo->crp_lock);
283 	}
284 	crypto_terminate(&cryptoretthread, &crp_ret_q);
285 	CRYPTO_DRIVER_UNLOCK();
286 
287 	/* XXX flush queues??? */
288 
289 	/*
290 	 * Reclaim dynamically allocated resources.
291 	 */
292 	if (crypto_drivers != NULL)
293 		kfree(crypto_drivers, M_CRYPTO_DATA);
294 
295 	if (cryptodesc_oc != NULL)
296 		objcache_destroy(cryptodesc_oc);
297 	if (cryptop_oc != NULL)
298 		objcache_destroy(cryptop_oc);
299 	lockuninit(&crypto_ret_q_lock);
300 	lockuninit(&crypto_drivers_lock);
301 }
302 
303 static struct cryptocap *
304 crypto_checkdriver(u_int32_t hid)
305 {
306 	if (crypto_drivers == NULL)
307 		return NULL;
308 	return (hid >= crypto_drivers_num ? NULL : &crypto_drivers[hid]);
309 }
310 
311 /*
312  * Compare a driver's list of supported algorithms against another
313  * list; return non-zero if all algorithms are supported.
314  */
315 static int
316 driver_suitable(const struct cryptocap *cap, const struct cryptoini *cri)
317 {
318 	const struct cryptoini *cr;
319 
320 	/* See if all the algorithms are supported. */
321 	for (cr = cri; cr; cr = cr->cri_next)
322 		if (cap->cc_alg[cr->cri_alg] == 0)
323 			return 0;
324 	return 1;
325 }
326 
327 /*
328  * Select a driver for a new session that supports the specified
329  * algorithms and, optionally, is constrained according to the flags.
330  * The algorithm we use here is pretty stupid; just use the
331  * first driver that supports all the algorithms we need. If there
332  * are multiple drivers we choose the driver with the fewest active
333  * sessions.  We prefer hardware-backed drivers to software ones.
334  *
335  * XXX We need more smarts here (in real life too, but that's
336  * XXX another story altogether).
337  */
338 static struct cryptocap *
339 crypto_select_driver(const struct cryptoini *cri, int flags)
340 {
341 	struct cryptocap *cap, *best;
342 	int match, hid;
343 
344 	CRYPTO_DRIVER_ASSERT();
345 
346 	/*
347 	 * Look first for hardware crypto devices if permitted.
348 	 */
349 	if (flags & CRYPTOCAP_F_HARDWARE)
350 		match = CRYPTOCAP_F_HARDWARE;
351 	else
352 		match = CRYPTOCAP_F_SOFTWARE;
353 	best = NULL;
354 again:
355 	for (hid = 0; hid < crypto_drivers_num; hid++) {
356 		cap = &crypto_drivers[hid];
357 		/*
358 		 * If it's not initialized, is in the process of
359 		 * going away, or is not appropriate (hardware
360 		 * or software based on match), then skip.
361 		 */
362 		if (cap->cc_dev == NULL ||
363 		    (cap->cc_flags & CRYPTOCAP_F_CLEANUP) ||
364 		    (cap->cc_flags & match) == 0)
365 			continue;
366 
367 		/* verify all the algorithms are supported. */
368 		if (driver_suitable(cap, cri)) {
369 			if (best == NULL ||
370 			    cap->cc_sessions < best->cc_sessions)
371 				best = cap;
372 		}
373 	}
374 	if (best != NULL)
375 		return best;
376 	if (match == CRYPTOCAP_F_HARDWARE && (flags & CRYPTOCAP_F_SOFTWARE)) {
377 		/* sort of an Algol 68-style for loop */
378 		match = CRYPTOCAP_F_SOFTWARE;
379 		goto again;
380 	}
381 	return best;
382 }
383 
384 /*
385  * Create a new session.  The crid argument specifies a crypto
386  * driver to use or constraints on a driver to select (hardware
387  * only, software only, either).  Whatever driver is selected
388  * must be capable of the requested crypto algorithms.
389  */
390 int
391 crypto_newsession(u_int64_t *sid, struct cryptoini *cri, int crid)
392 {
393 	struct cryptocap *cap;
394 	u_int32_t hid, lid;
395 	int err;
396 
397 	CRYPTO_DRIVER_LOCK();
398 	if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
399 		/*
400 		 * Use specified driver; verify it is capable.
401 		 */
402 		cap = crypto_checkdriver(crid);
403 		if (cap != NULL && !driver_suitable(cap, cri))
404 			cap = NULL;
405 	} else {
406 		/*
407 		 * No requested driver; select based on crid flags.
408 		 */
409 		cap = crypto_select_driver(cri, crid);
410 		/*
411 		 * if NULL then can't do everything in one session.
412 		 * XXX Fix this. We need to inject a "virtual" session
413 		 * XXX layer right about here.
414 		 */
415 	}
416 	if (cap != NULL) {
417 		/* Call the driver initialization routine. */
418 		hid = cap - crypto_drivers;
419 		lid = hid;		/* Pass the driver ID. */
420 		err = CRYPTODEV_NEWSESSION(cap->cc_dev, &lid, cri);
421 		if (err == 0) {
422 			(*sid) = (cap->cc_flags & 0xff000000)
423 			       | (hid & 0x00ffffff);
424 			(*sid) <<= 32;
425 			(*sid) |= (lid & 0xffffffff);
426 			cap->cc_sessions++;
427 		}
428 	} else
429 		err = EINVAL;
430 	CRYPTO_DRIVER_UNLOCK();
431 	return err;
432 }
433 
434 static void
435 crypto_remove(struct cryptocap *cap)
436 {
437 
438 	KKASSERT(lockstatus(&crypto_drivers_lock, curthread) != 0);
439 	if (cap->cc_sessions == 0 && cap->cc_koperations == 0)
440 		bzero(cap, sizeof(*cap));
441 }
442 
443 /*
444  * Delete an existing session (or a reserved session on an unregistered
445  * driver).
446  */
447 int
448 crypto_freesession(u_int64_t sid)
449 {
450 	struct cryptocap *cap;
451 	u_int32_t hid;
452 	int err;
453 
454 	CRYPTO_DRIVER_LOCK();
455 
456 	if (crypto_drivers == NULL) {
457 		err = EINVAL;
458 		goto done;
459 	}
460 
461 	/* Determine two IDs. */
462 	hid = CRYPTO_SESID2HID(sid);
463 
464 	if (hid >= crypto_drivers_num) {
465 		err = ENOENT;
466 		goto done;
467 	}
468 	cap = &crypto_drivers[hid];
469 
470 	if (cap->cc_sessions)
471 		cap->cc_sessions--;
472 
473 	/* Call the driver cleanup routine, if available. */
474 	err = CRYPTODEV_FREESESSION(cap->cc_dev, sid);
475 
476 	if (cap->cc_flags & CRYPTOCAP_F_CLEANUP)
477 		crypto_remove(cap);
478 
479 done:
480 	CRYPTO_DRIVER_UNLOCK();
481 	return err;
482 }
483 
484 /*
485  * Return an unused driver id.  Used by drivers prior to registering
486  * support for the algorithms they handle.
487  */
488 int32_t
489 crypto_get_driverid(device_t dev, int flags)
490 {
491 	struct cryptocap *newdrv;
492 	int i;
493 
494 	if ((flags & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
495 		kprintf("%s: no flags specified when registering driver\n",
496 		    device_get_nameunit(dev));
497 		return -1;
498 	}
499 
500 	CRYPTO_DRIVER_LOCK();
501 
502 	for (i = 0; i < crypto_drivers_num; i++) {
503 		if (crypto_drivers[i].cc_dev == NULL &&
504 		    (crypto_drivers[i].cc_flags & CRYPTOCAP_F_CLEANUP) == 0) {
505 			break;
506 		}
507 	}
508 
509 	/* Out of entries, allocate some more. */
510 	if (i == crypto_drivers_num) {
511 		/* Be careful about wrap-around. */
512 		if (2 * crypto_drivers_num <= crypto_drivers_num) {
513 			CRYPTO_DRIVER_UNLOCK();
514 			kprintf("crypto: driver count wraparound!\n");
515 			return -1;
516 		}
517 
518 		newdrv = kmalloc(2 * crypto_drivers_num *
519 				 sizeof(struct cryptocap),
520 				 M_CRYPTO_DATA, M_WAITOK|M_ZERO);
521 
522 		bcopy(crypto_drivers, newdrv,
523 		    crypto_drivers_num * sizeof(struct cryptocap));
524 
525 		crypto_drivers_num *= 2;
526 
527 		kfree(crypto_drivers, M_CRYPTO_DATA);
528 		crypto_drivers = newdrv;
529 	}
530 
531 	/* NB: state is zero'd on free */
532 	crypto_drivers[i].cc_sessions = 1;	/* Mark */
533 	crypto_drivers[i].cc_dev = dev;
534 	crypto_drivers[i].cc_flags = flags;
535 	if (bootverbose)
536 		kprintf("crypto: assign %s driver id %u, flags %u\n",
537 		    device_get_nameunit(dev), i, flags);
538 
539 	CRYPTO_DRIVER_UNLOCK();
540 
541 	return i;
542 }
543 
544 /*
545  * Lookup a driver by name.  We match against the full device
546  * name and unit, and against just the name.  The latter gives
547  * us a simple widlcarding by device name.  On success return the
548  * driver/hardware identifier; otherwise return -1.
549  */
550 int
551 crypto_find_driver(const char *match)
552 {
553 	int i, len = strlen(match);
554 
555 	CRYPTO_DRIVER_LOCK();
556 	for (i = 0; i < crypto_drivers_num; i++) {
557 		device_t dev = crypto_drivers[i].cc_dev;
558 		if (dev == NULL ||
559 		    (crypto_drivers[i].cc_flags & CRYPTOCAP_F_CLEANUP))
560 			continue;
561 		if (strncmp(match, device_get_nameunit(dev), len) == 0 ||
562 		    strncmp(match, device_get_name(dev), len) == 0)
563 			break;
564 	}
565 	CRYPTO_DRIVER_UNLOCK();
566 	return i < crypto_drivers_num ? i : -1;
567 }
568 
569 /*
570  * Return the device_t for the specified driver or NULL
571  * if the driver identifier is invalid.
572  */
573 device_t
574 crypto_find_device_byhid(int hid)
575 {
576 	struct cryptocap *cap = crypto_checkdriver(hid);
577 	return cap != NULL ? cap->cc_dev : NULL;
578 }
579 
580 /*
581  * Return the device/driver capabilities.
582  */
583 int
584 crypto_getcaps(int hid)
585 {
586 	struct cryptocap *cap = crypto_checkdriver(hid);
587 	return cap != NULL ? cap->cc_flags : 0;
588 }
589 
590 /*
591  * Register support for a key-related algorithm.  This routine
592  * is called once for each algorithm supported a driver.
593  */
594 int
595 crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags)
596 {
597 	struct cryptocap *cap;
598 	int err;
599 
600 	CRYPTO_DRIVER_LOCK();
601 
602 	cap = crypto_checkdriver(driverid);
603 	if (cap != NULL &&
604 	    (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
605 		/*
606 		 * XXX Do some performance testing to determine placing.
607 		 * XXX We probably need an auxiliary data structure that
608 		 * XXX describes relative performances.
609 		 */
610 
611 		cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
612 		if (bootverbose)
613 			kprintf("crypto: %s registers key alg %u flags %u\n"
614 				, device_get_nameunit(cap->cc_dev)
615 				, kalg
616 				, flags
617 			);
618 
619 		err = 0;
620 	} else
621 		err = EINVAL;
622 
623 	CRYPTO_DRIVER_UNLOCK();
624 	return err;
625 }
626 
627 /*
628  * Register support for a non-key-related algorithm.  This routine
629  * is called once for each such algorithm supported by a driver.
630  */
631 int
632 crypto_register(u_int32_t driverid, int alg, u_int16_t maxoplen,
633 		u_int32_t flags)
634 {
635 	struct cryptocap *cap;
636 	int err;
637 
638 	CRYPTO_DRIVER_LOCK();
639 
640 	cap = crypto_checkdriver(driverid);
641 	/* NB: algorithms are in the range [1..max] */
642 	if (cap != NULL &&
643 	    (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX)) {
644 		/*
645 		 * XXX Do some performance testing to determine placing.
646 		 * XXX We probably need an auxiliary data structure that
647 		 * XXX describes relative performances.
648 		 */
649 
650 		cap->cc_alg[alg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
651 		cap->cc_max_op_len[alg] = maxoplen;
652 		if (bootverbose)
653 			kprintf("crypto: %s registers alg %u flags %u maxoplen %u\n"
654 				, device_get_nameunit(cap->cc_dev)
655 				, alg
656 				, flags
657 				, maxoplen
658 			);
659 		cap->cc_sessions = 0;		/* Unmark */
660 		err = 0;
661 	} else
662 		err = EINVAL;
663 
664 	CRYPTO_DRIVER_UNLOCK();
665 	return err;
666 }
667 
668 static void
669 driver_finis(struct cryptocap *cap)
670 {
671 	u_int32_t ses, kops;
672 
673 	CRYPTO_DRIVER_ASSERT();
674 
675 	ses = cap->cc_sessions;
676 	kops = cap->cc_koperations;
677 	bzero(cap, sizeof(*cap));
678 	if (ses != 0 || kops != 0) {
679 		/*
680 		 * If there are pending sessions,
681 		 * just mark as invalid.
682 		 */
683 		cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
684 		cap->cc_sessions = ses;
685 		cap->cc_koperations = kops;
686 	}
687 }
688 
689 /*
690  * Unregister a crypto driver. If there are pending sessions using it,
691  * leave enough information around so that subsequent calls using those
692  * sessions will correctly detect the driver has been unregistered and
693  * reroute requests.
694  */
695 int
696 crypto_unregister(u_int32_t driverid, int alg)
697 {
698 	struct cryptocap *cap;
699 	int i, err;
700 
701 	CRYPTO_DRIVER_LOCK();
702 	cap = crypto_checkdriver(driverid);
703 	if (cap != NULL &&
704 	    (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX) &&
705 	    cap->cc_alg[alg] != 0) {
706 		cap->cc_alg[alg] = 0;
707 		cap->cc_max_op_len[alg] = 0;
708 
709 		/* Was this the last algorithm ? */
710 		for (i = 1; i <= CRYPTO_ALGORITHM_MAX; i++) {
711 			if (cap->cc_alg[i] != 0)
712 				break;
713 		}
714 
715 		if (i == CRYPTO_ALGORITHM_MAX + 1)
716 			driver_finis(cap);
717 		err = 0;
718 	} else {
719 		err = EINVAL;
720 	}
721 	CRYPTO_DRIVER_UNLOCK();
722 
723 	return err;
724 }
725 
726 /*
727  * Unregister all algorithms associated with a crypto driver.
728  * If there are pending sessions using it, leave enough information
729  * around so that subsequent calls using those sessions will
730  * correctly detect the driver has been unregistered and reroute
731  * requests.
732  */
733 int
734 crypto_unregister_all(u_int32_t driverid)
735 {
736 	struct cryptocap *cap;
737 	int err;
738 
739 	CRYPTO_DRIVER_LOCK();
740 	cap = crypto_checkdriver(driverid);
741 	if (cap != NULL) {
742 		driver_finis(cap);
743 		err = 0;
744 	} else {
745 		err = EINVAL;
746 	}
747 	CRYPTO_DRIVER_UNLOCK();
748 
749 	return err;
750 }
751 
752 /*
753  * Clear blockage on a driver.  The what parameter indicates whether
754  * the driver is now ready for cryptop's and/or cryptokop's.
755  */
756 int
757 crypto_unblock(u_int32_t driverid, int what)
758 {
759 	crypto_tdinfo_t tdinfo;
760 	struct cryptocap *cap;
761 	int err;
762 	int n;
763 
764 	CRYPTO_DRIVER_LOCK();
765 	cap = crypto_checkdriver(driverid);
766 	if (cap != NULL) {
767 		if (what & CRYPTO_SYMQ)
768 			cap->cc_qblocked = 0;
769 		if (what & CRYPTO_ASYMQ)
770 			cap->cc_kqblocked = 0;
771 		for (n = 0; n < ncpus; ++n) {
772 			tdinfo = &tdinfo_array[n];
773 			CRYPTO_Q_LOCK(tdinfo);
774 			if (tdinfo[n].crp_sleep)
775 				wakeup_one(&tdinfo->crp_q);
776 			CRYPTO_Q_UNLOCK(tdinfo);
777 		}
778 		err = 0;
779 	} else {
780 		err = EINVAL;
781 	}
782 	CRYPTO_DRIVER_UNLOCK();
783 
784 	return err;
785 }
786 
787 static volatile int dispatch_rover;
788 
789 /*
790  * Add a crypto request to a queue, to be processed by the kernel thread.
791  */
792 int
793 crypto_dispatch(struct cryptop *crp)
794 {
795 	crypto_tdinfo_t tdinfo;
796 	struct cryptocap *cap;
797 	u_int32_t hid;
798 	int result;
799 	int n;
800 
801 	cryptostats.cs_ops++;
802 
803 #ifdef CRYPTO_TIMING
804 	if (crypto_timing)
805 		nanouptime(&crp->crp_tstamp);
806 #endif
807 
808 	hid = CRYPTO_SESID2HID(crp->crp_sid);
809 
810 	/*
811 	 * Dispatch the crypto op directly to the driver if the caller
812 	 * marked the request to be processed immediately or this is
813 	 * a synchronous callback chain occuring from within a crypto
814 	 * processing thread.
815 	 *
816 	 * Fall through to queueing the driver is blocked.
817 	 */
818 	if ((crp->crp_flags & CRYPTO_F_BATCH) == 0 ||
819 	    curthread->td_type == TD_TYPE_CRYPTO) {
820 		cap = crypto_checkdriver(hid);
821 		/* Driver cannot disappeared when there is an active session. */
822 		KASSERT(cap != NULL, ("%s: Driver disappeared.", __func__));
823 		if (!cap->cc_qblocked) {
824 			result = crypto_invoke(cap, crp, 0);
825 			if (result != ERESTART)
826 				return (result);
827 			/*
828 			 * The driver ran out of resources, put the request on
829 			 * the queue.
830 			 */
831 		}
832 	}
833 
834 	/*
835 	 * Dispatch to a cpu for action if possible.  Dispatch to a different
836 	 * cpu than the current cpu.
837 	 */
838 	if (CRYPTO_SESID2CAPS(crp->crp_sid) & CRYPTOCAP_F_SMP) {
839 		n = atomic_fetchadd_int(&dispatch_rover, 1) & 255;
840 		if (crypto_altdispatch && mycpu->gd_cpuid == n)
841 			++n;
842 		n = n % ncpus;
843 	} else {
844 		n = 0;
845 	}
846 	tdinfo = &tdinfo_array[n];
847 
848 	CRYPTO_Q_LOCK(tdinfo);
849 	TAILQ_INSERT_TAIL(&tdinfo->crp_q, crp, crp_next);
850 	if (tdinfo->crp_sleep)
851 		wakeup_one(&tdinfo->crp_q);
852 	CRYPTO_Q_UNLOCK(tdinfo);
853 	return 0;
854 }
855 
856 /*
857  * Add an asymetric crypto request to a queue,
858  * to be processed by the kernel thread.
859  */
860 int
861 crypto_kdispatch(struct cryptkop *krp)
862 {
863 	crypto_tdinfo_t tdinfo;
864 	int error;
865 	int n;
866 
867 	cryptostats.cs_kops++;
868 
869 #if 0
870 	/* not sure how to test F_SMP here */
871 	n = atomic_fetchadd_int(&dispatch_rover, 1) & 255;
872 	n = n % ncpus;
873 #endif
874 	n = 0;
875 	tdinfo = &tdinfo_array[n];
876 
877 	error = crypto_kinvoke(krp, krp->krp_crid);
878 
879 	if (error == ERESTART) {
880 		CRYPTO_Q_LOCK(tdinfo);
881 		TAILQ_INSERT_TAIL(&tdinfo->crp_kq, krp, krp_next);
882 		if (tdinfo->crp_sleep)
883 			wakeup_one(&tdinfo->crp_q);
884 		CRYPTO_Q_UNLOCK(tdinfo);
885 		error = 0;
886 	}
887 	return error;
888 }
889 
890 /*
891  * Verify a driver is suitable for the specified operation.
892  */
893 static __inline int
894 kdriver_suitable(const struct cryptocap *cap, const struct cryptkop *krp)
895 {
896 	return (cap->cc_kalg[krp->krp_op] & CRYPTO_ALG_FLAG_SUPPORTED) != 0;
897 }
898 
899 /*
900  * Select a driver for an asym operation.  The driver must
901  * support the necessary algorithm.  The caller can constrain
902  * which device is selected with the flags parameter.  The
903  * algorithm we use here is pretty stupid; just use the first
904  * driver that supports the algorithms we need. If there are
905  * multiple suitable drivers we choose the driver with the
906  * fewest active operations.  We prefer hardware-backed
907  * drivers to software ones when either may be used.
908  */
909 static struct cryptocap *
910 crypto_select_kdriver(const struct cryptkop *krp, int flags)
911 {
912 	struct cryptocap *cap, *best;
913 	int match, hid;
914 
915 	CRYPTO_DRIVER_ASSERT();
916 
917 	/*
918 	 * Look first for hardware crypto devices if permitted.
919 	 */
920 	if (flags & CRYPTOCAP_F_HARDWARE)
921 		match = CRYPTOCAP_F_HARDWARE;
922 	else
923 		match = CRYPTOCAP_F_SOFTWARE;
924 	best = NULL;
925 again:
926 	for (hid = 0; hid < crypto_drivers_num; hid++) {
927 		cap = &crypto_drivers[hid];
928 		/*
929 		 * If it's not initialized, is in the process of
930 		 * going away, or is not appropriate (hardware
931 		 * or software based on match), then skip.
932 		 */
933 		if (cap->cc_dev == NULL ||
934 		    (cap->cc_flags & CRYPTOCAP_F_CLEANUP) ||
935 		    (cap->cc_flags & match) == 0)
936 			continue;
937 
938 		/* verify all the algorithms are supported. */
939 		if (kdriver_suitable(cap, krp)) {
940 			if (best == NULL ||
941 			    cap->cc_koperations < best->cc_koperations)
942 				best = cap;
943 		}
944 	}
945 	if (best != NULL)
946 		return best;
947 	if (match == CRYPTOCAP_F_HARDWARE && (flags & CRYPTOCAP_F_SOFTWARE)) {
948 		/* sort of an Algol 68-style for loop */
949 		match = CRYPTOCAP_F_SOFTWARE;
950 		goto again;
951 	}
952 	return best;
953 }
954 
955 /*
956  * Dispatch an assymetric crypto request.
957  */
958 static int
959 crypto_kinvoke(struct cryptkop *krp, int crid)
960 {
961 	struct cryptocap *cap = NULL;
962 	int error;
963 
964 	KASSERT(krp != NULL, ("%s: krp == NULL", __func__));
965 	KASSERT(krp->krp_callback != NULL,
966 	    ("%s: krp->crp_callback == NULL", __func__));
967 
968 	CRYPTO_DRIVER_LOCK();
969 	if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
970 		cap = crypto_checkdriver(crid);
971 		if (cap != NULL) {
972 			/*
973 			 * Driver present, it must support the necessary
974 			 * algorithm and, if s/w drivers are excluded,
975 			 * it must be registered as hardware-backed.
976 			 */
977 			if (!kdriver_suitable(cap, krp) ||
978 			    (!crypto_devallowsoft &&
979 			     (cap->cc_flags & CRYPTOCAP_F_HARDWARE) == 0))
980 				cap = NULL;
981 		}
982 	} else {
983 		/*
984 		 * No requested driver; select based on crid flags.
985 		 */
986 		if (!crypto_devallowsoft)	/* NB: disallow s/w drivers */
987 			crid &= ~CRYPTOCAP_F_SOFTWARE;
988 		cap = crypto_select_kdriver(krp, crid);
989 	}
990 	if (cap != NULL && !cap->cc_kqblocked) {
991 		krp->krp_hid = cap - crypto_drivers;
992 		cap->cc_koperations++;
993 		CRYPTO_DRIVER_UNLOCK();
994 		error = CRYPTODEV_KPROCESS(cap->cc_dev, krp, 0);
995 		CRYPTO_DRIVER_LOCK();
996 		if (error == ERESTART) {
997 			cap->cc_koperations--;
998 			CRYPTO_DRIVER_UNLOCK();
999 			return (error);
1000 		}
1001 	} else {
1002 		/*
1003 		 * NB: cap is !NULL if device is blocked; in
1004 		 *     that case return ERESTART so the operation
1005 		 *     is resubmitted if possible.
1006 		 */
1007 		error = (cap == NULL) ? ENODEV : ERESTART;
1008 	}
1009 	CRYPTO_DRIVER_UNLOCK();
1010 
1011 	if (error) {
1012 		krp->krp_status = error;
1013 		crypto_kdone(krp);
1014 	}
1015 	return 0;
1016 }
1017 
1018 #ifdef CRYPTO_TIMING
1019 static void
1020 crypto_tstat(struct cryptotstat *ts, struct timespec *tv)
1021 {
1022 	struct timespec now, t;
1023 
1024 	nanouptime(&now);
1025 	t.tv_sec = now.tv_sec - tv->tv_sec;
1026 	t.tv_nsec = now.tv_nsec - tv->tv_nsec;
1027 	if (t.tv_nsec < 0) {
1028 		t.tv_sec--;
1029 		t.tv_nsec += 1000000000;
1030 	}
1031 	timespecadd(&ts->acc, &t);
1032 	if (timespeccmp(&t, &ts->min, <))
1033 		ts->min = t;
1034 	if (timespeccmp(&t, &ts->max, >))
1035 		ts->max = t;
1036 	ts->count++;
1037 
1038 	*tv = now;
1039 }
1040 #endif
1041 
1042 /*
1043  * Dispatch a crypto request to the appropriate crypto devices.
1044  */
1045 static int
1046 crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint)
1047 {
1048 
1049 	KASSERT(crp != NULL, ("%s: crp == NULL", __func__));
1050 	KASSERT(crp->crp_callback != NULL,
1051 	    ("%s: crp->crp_callback == NULL", __func__));
1052 	KASSERT(crp->crp_desc != NULL, ("%s: crp->crp_desc == NULL", __func__));
1053 
1054 #ifdef CRYPTO_TIMING
1055 	if (crypto_timing)
1056 		crypto_tstat(&cryptostats.cs_invoke, &crp->crp_tstamp);
1057 #endif
1058 	if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1059 		struct cryptodesc *crd;
1060 		u_int64_t nid;
1061 
1062 		/*
1063 		 * Driver has unregistered; migrate the session and return
1064 		 * an error to the caller so they'll resubmit the op.
1065 		 *
1066 		 * XXX: What if there are more already queued requests for this
1067 		 *      session?
1068 		 */
1069 		crypto_freesession(crp->crp_sid);
1070 
1071 		for (crd = crp->crp_desc; crd->crd_next; crd = crd->crd_next)
1072 			crd->CRD_INI.cri_next = &(crd->crd_next->CRD_INI);
1073 
1074 		/* XXX propagate flags from initial session? */
1075 		if (crypto_newsession(&nid, &(crp->crp_desc->CRD_INI),
1076 		    CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE) == 0)
1077 			crp->crp_sid = nid;
1078 
1079 		crp->crp_etype = EAGAIN;
1080 		crypto_done(crp);
1081 		return 0;
1082 	} else {
1083 		/*
1084 		 * Invoke the driver to process the request.
1085 		 */
1086 		return CRYPTODEV_PROCESS(cap->cc_dev, crp, hint);
1087 	}
1088 }
1089 
1090 /*
1091  * Release a set of crypto descriptors.
1092  */
1093 void
1094 crypto_freereq(struct cryptop *crp)
1095 {
1096 	struct cryptodesc *crd;
1097 #ifdef DIAGNOSTIC
1098 	crypto_tdinfo_t tdinfo;
1099 	struct cryptop *crp2;
1100 	int n;
1101 #endif
1102 
1103 	if (crp == NULL)
1104 		return;
1105 
1106 #ifdef DIAGNOSTIC
1107 	for (n = 0; n < ncpus; ++n) {
1108 		tdinfo = &tdinfo_array[n];
1109 
1110 		CRYPTO_Q_LOCK(tdinfo);
1111 		TAILQ_FOREACH(crp2, &tdinfo->crp_q, crp_next) {
1112 			KASSERT(crp2 != crp,
1113 			    ("Freeing cryptop from the crypto queue (%p).",
1114 			    crp));
1115 		}
1116 		CRYPTO_Q_UNLOCK(tdinfo);
1117 	}
1118 	CRYPTO_RETQ_LOCK();
1119 	TAILQ_FOREACH(crp2, &crp_ret_q, crp_next) {
1120 		KASSERT(crp2 != crp,
1121 		    ("Freeing cryptop from the return queue (%p).",
1122 		    crp));
1123 	}
1124 	CRYPTO_RETQ_UNLOCK();
1125 #endif
1126 
1127 	while ((crd = crp->crp_desc) != NULL) {
1128 		crp->crp_desc = crd->crd_next;
1129 		objcache_put(cryptodesc_oc, crd);
1130 	}
1131 	objcache_put(cryptop_oc, crp);
1132 }
1133 
1134 /*
1135  * Acquire a set of crypto descriptors.
1136  */
1137 struct cryptop *
1138 crypto_getreq(int num)
1139 {
1140 	struct cryptodesc *crd;
1141 	struct cryptop *crp;
1142 
1143 	crp = objcache_get(cryptop_oc, M_WAITOK);
1144 	if (crp != NULL) {
1145 		bzero(crp, sizeof (*crp));
1146 		while (num--) {
1147 			crd = objcache_get(cryptodesc_oc, M_WAITOK);
1148 			if (crd == NULL) {
1149 				crypto_freereq(crp);
1150 				return NULL;
1151 			}
1152 			bzero(crd, sizeof (*crd));
1153 
1154 			crd->crd_next = crp->crp_desc;
1155 			crp->crp_desc = crd;
1156 		}
1157 	}
1158 	return crp;
1159 }
1160 
1161 /*
1162  * Invoke the callback on behalf of the driver.
1163  */
1164 void
1165 crypto_done(struct cryptop *crp)
1166 {
1167 	KASSERT((crp->crp_flags & CRYPTO_F_DONE) == 0,
1168 		("crypto_done: op already done, flags 0x%x", crp->crp_flags));
1169 	crp->crp_flags |= CRYPTO_F_DONE;
1170 	if (crp->crp_etype != 0)
1171 		cryptostats.cs_errs++;
1172 #ifdef CRYPTO_TIMING
1173 	if (crypto_timing)
1174 		crypto_tstat(&cryptostats.cs_done, &crp->crp_tstamp);
1175 #endif
1176 	/*
1177 	 * CBIMM means unconditionally do the callback immediately;
1178 	 * CBIFSYNC means do the callback immediately only if the
1179 	 * operation was done synchronously.  Both are used to avoid
1180 	 * doing extraneous context switches; the latter is mostly
1181 	 * used with the software crypto driver.
1182 	 */
1183 	if ((crp->crp_flags & CRYPTO_F_CBIMM) ||
1184 	    ((crp->crp_flags & CRYPTO_F_CBIFSYNC) &&
1185 	     (CRYPTO_SESID2CAPS(crp->crp_sid) & CRYPTOCAP_F_SYNC))) {
1186 		/*
1187 		 * Do the callback directly.  This is ok when the
1188 		 * callback routine does very little (e.g. the
1189 		 * /dev/crypto callback method just does a wakeup).
1190 		 */
1191 #ifdef CRYPTO_TIMING
1192 		if (crypto_timing) {
1193 			/*
1194 			 * NB: We must copy the timestamp before
1195 			 * doing the callback as the cryptop is
1196 			 * likely to be reclaimed.
1197 			 */
1198 			struct timespec t = crp->crp_tstamp;
1199 			crypto_tstat(&cryptostats.cs_cb, &t);
1200 			crp->crp_callback(crp);
1201 			crypto_tstat(&cryptostats.cs_finis, &t);
1202 		} else
1203 #endif
1204 			crp->crp_callback(crp);
1205 	} else {
1206 		/*
1207 		 * Normal case; queue the callback for the thread.
1208 		 */
1209 		CRYPTO_RETQ_LOCK();
1210 		if (CRYPTO_RETQ_EMPTY())
1211 			wakeup_one(&crp_ret_q);	/* shared wait channel */
1212 		TAILQ_INSERT_TAIL(&crp_ret_q, crp, crp_next);
1213 		CRYPTO_RETQ_UNLOCK();
1214 	}
1215 }
1216 
1217 /*
1218  * Invoke the callback on behalf of the driver.
1219  */
1220 void
1221 crypto_kdone(struct cryptkop *krp)
1222 {
1223 	struct cryptocap *cap;
1224 
1225 	if (krp->krp_status != 0)
1226 		cryptostats.cs_kerrs++;
1227 	CRYPTO_DRIVER_LOCK();
1228 	/* XXX: What if driver is loaded in the meantime? */
1229 	if (krp->krp_hid < crypto_drivers_num) {
1230 		cap = &crypto_drivers[krp->krp_hid];
1231 		cap->cc_koperations--;
1232 		KASSERT(cap->cc_koperations >= 0, ("cc_koperations < 0"));
1233 		if (cap->cc_flags & CRYPTOCAP_F_CLEANUP)
1234 			crypto_remove(cap);
1235 	}
1236 	CRYPTO_DRIVER_UNLOCK();
1237 	CRYPTO_RETQ_LOCK();
1238 	if (CRYPTO_RETQ_EMPTY())
1239 		wakeup_one(&crp_ret_q);		/* shared wait channel */
1240 	TAILQ_INSERT_TAIL(&crp_ret_kq, krp, krp_next);
1241 	CRYPTO_RETQ_UNLOCK();
1242 }
1243 
1244 int
1245 crypto_getfeat(int *featp)
1246 {
1247 	int hid, kalg, feat = 0;
1248 
1249 	CRYPTO_DRIVER_LOCK();
1250 	for (hid = 0; hid < crypto_drivers_num; hid++) {
1251 		const struct cryptocap *cap = &crypto_drivers[hid];
1252 
1253 		if ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
1254 		    !crypto_devallowsoft) {
1255 			continue;
1256 		}
1257 		for (kalg = 0; kalg <= CRK_ALGORITHM_MAX; kalg++)
1258 			if (cap->cc_kalg[kalg] & CRYPTO_ALG_FLAG_SUPPORTED)
1259 				feat |=  1 << kalg;
1260 	}
1261 	CRYPTO_DRIVER_UNLOCK();
1262 	*featp = feat;
1263 	return (0);
1264 }
1265 
1266 /*
1267  * Terminate a thread at module unload.  The process that
1268  * initiated this is waiting for us to signal that we're gone;
1269  * wake it up and exit.  We use the driver table lock to insure
1270  * we don't do the wakeup before they're waiting.  There is no
1271  * race here because the waiter sleeps on the proc lock for the
1272  * thread so it gets notified at the right time because of an
1273  * extra wakeup that's done in exit1().
1274  */
1275 static void
1276 crypto_finis(void *chan)
1277 {
1278 	CRYPTO_DRIVER_LOCK();
1279 	wakeup_one(chan);
1280 	CRYPTO_DRIVER_UNLOCK();
1281 	kthread_exit();
1282 }
1283 
1284 /*
1285  * Crypto thread, dispatches crypto requests.
1286  *
1287  * MPSAFE
1288  */
1289 static void
1290 crypto_proc(void *arg)
1291 {
1292 	crypto_tdinfo_t tdinfo = arg;
1293 	struct cryptop *crp, *submit;
1294 	struct cryptkop *krp;
1295 	struct cryptocap *cap;
1296 	u_int32_t hid;
1297 	int result, hint;
1298 
1299 	CRYPTO_Q_LOCK(tdinfo);
1300 
1301 	curthread->td_type = TD_TYPE_CRYPTO;
1302 
1303 	for (;;) {
1304 		/*
1305 		 * Find the first element in the queue that can be
1306 		 * processed and look-ahead to see if multiple ops
1307 		 * are ready for the same driver.
1308 		 */
1309 		submit = NULL;
1310 		hint = 0;
1311 		TAILQ_FOREACH(crp, &tdinfo->crp_q, crp_next) {
1312 			hid = CRYPTO_SESID2HID(crp->crp_sid);
1313 			cap = crypto_checkdriver(hid);
1314 			/*
1315 			 * Driver cannot disappeared when there is an active
1316 			 * session.
1317 			 */
1318 			KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1319 			    __func__, __LINE__));
1320 			if (cap == NULL || cap->cc_dev == NULL) {
1321 				/* Op needs to be migrated, process it. */
1322 				if (submit == NULL)
1323 					submit = crp;
1324 				break;
1325 			}
1326 			if (!cap->cc_qblocked) {
1327 				if (submit != NULL) {
1328 					/*
1329 					 * We stop on finding another op,
1330 					 * regardless whether its for the same
1331 					 * driver or not.  We could keep
1332 					 * searching the queue but it might be
1333 					 * better to just use a per-driver
1334 					 * queue instead.
1335 					 */
1336 					if (CRYPTO_SESID2HID(submit->crp_sid) == hid)
1337 						hint = CRYPTO_HINT_MORE;
1338 					break;
1339 				} else {
1340 					submit = crp;
1341 					if ((submit->crp_flags & CRYPTO_F_BATCH) == 0)
1342 						break;
1343 					/* keep scanning for more are q'd */
1344 				}
1345 			}
1346 		}
1347 		if (submit != NULL) {
1348 			TAILQ_REMOVE(&tdinfo->crp_q, submit, crp_next);
1349 			hid = CRYPTO_SESID2HID(submit->crp_sid);
1350 			cap = crypto_checkdriver(hid);
1351 			KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1352 			    __func__, __LINE__));
1353 
1354 			CRYPTO_Q_UNLOCK(tdinfo);
1355 			result = crypto_invoke(cap, submit, hint);
1356 			CRYPTO_Q_LOCK(tdinfo);
1357 
1358 			if (result == ERESTART) {
1359 				/*
1360 				 * The driver ran out of resources, mark the
1361 				 * driver ``blocked'' for cryptop's and put
1362 				 * the request back in the queue.  It would
1363 				 * best to put the request back where we got
1364 				 * it but that's hard so for now we put it
1365 				 * at the front.  This should be ok; putting
1366 				 * it at the end does not work.
1367 				 */
1368 				/* XXX validate sid again? */
1369 				crypto_drivers[CRYPTO_SESID2HID(submit->crp_sid)].cc_qblocked = 1;
1370 				TAILQ_INSERT_HEAD(&tdinfo->crp_q,
1371 						  submit, crp_next);
1372 				cryptostats.cs_blocks++;
1373 			}
1374 		}
1375 
1376 		/* As above, but for key ops */
1377 		TAILQ_FOREACH(krp, &tdinfo->crp_kq, krp_next) {
1378 			cap = crypto_checkdriver(krp->krp_hid);
1379 			if (cap == NULL || cap->cc_dev == NULL) {
1380 				/*
1381 				 * Operation needs to be migrated, invalidate
1382 				 * the assigned device so it will reselect a
1383 				 * new one below.  Propagate the original
1384 				 * crid selection flags if supplied.
1385 				 */
1386 				krp->krp_hid = krp->krp_crid &
1387 				    (CRYPTOCAP_F_SOFTWARE|CRYPTOCAP_F_HARDWARE);
1388 				if (krp->krp_hid == 0)
1389 					krp->krp_hid =
1390 				    CRYPTOCAP_F_SOFTWARE|CRYPTOCAP_F_HARDWARE;
1391 				break;
1392 			}
1393 			if (!cap->cc_kqblocked)
1394 				break;
1395 		}
1396 		if (krp != NULL) {
1397 			TAILQ_REMOVE(&tdinfo->crp_kq, krp, krp_next);
1398 
1399 			CRYPTO_Q_UNLOCK(tdinfo);
1400 			result = crypto_kinvoke(krp, krp->krp_hid);
1401 			CRYPTO_Q_LOCK(tdinfo);
1402 
1403 			if (result == ERESTART) {
1404 				/*
1405 				 * The driver ran out of resources, mark the
1406 				 * driver ``blocked'' for cryptkop's and put
1407 				 * the request back in the queue.  It would
1408 				 * best to put the request back where we got
1409 				 * it but that's hard so for now we put it
1410 				 * at the front.  This should be ok; putting
1411 				 * it at the end does not work.
1412 				 */
1413 				/* XXX validate sid again? */
1414 				crypto_drivers[krp->krp_hid].cc_kqblocked = 1;
1415 				TAILQ_INSERT_HEAD(&tdinfo->crp_kq,
1416 						  krp, krp_next);
1417 				cryptostats.cs_kblocks++;
1418 			}
1419 		}
1420 
1421 		if (submit == NULL && krp == NULL) {
1422 			/*
1423 			 * Nothing more to be processed.  Sleep until we're
1424 			 * woken because there are more ops to process.
1425 			 * This happens either by submission or by a driver
1426 			 * becoming unblocked and notifying us through
1427 			 * crypto_unblock.  Note that when we wakeup we
1428 			 * start processing each queue again from the
1429 			 * front. It's not clear that it's important to
1430 			 * preserve this ordering since ops may finish
1431 			 * out of order if dispatched to different devices
1432 			 * and some become blocked while others do not.
1433 			 */
1434 			tdinfo->crp_sleep = 1;
1435 			lksleep (&tdinfo->crp_q, &tdinfo->crp_lock,
1436 				 0, "crypto_wait", 0);
1437 			tdinfo->crp_sleep = 0;
1438 			if (tdinfo->crp_td == NULL)
1439 				break;
1440 			cryptostats.cs_intrs++;
1441 		}
1442 	}
1443 	CRYPTO_Q_UNLOCK(tdinfo);
1444 
1445 	crypto_finis(&tdinfo->crp_q);
1446 }
1447 
1448 /*
1449  * Crypto returns thread, does callbacks for processed crypto requests.
1450  * Callbacks are done here, rather than in the crypto drivers, because
1451  * callbacks typically are expensive and would slow interrupt handling.
1452  *
1453  * MPSAFE
1454  */
1455 static void
1456 crypto_ret_proc(void *dummy __unused)
1457 {
1458 	struct cryptop *crpt;
1459 	struct cryptkop *krpt;
1460 
1461 	get_mplock();
1462 	CRYPTO_RETQ_LOCK();
1463 	for (;;) {
1464 		/* Harvest return q's for completed ops */
1465 		crpt = TAILQ_FIRST(&crp_ret_q);
1466 		if (crpt != NULL)
1467 			TAILQ_REMOVE(&crp_ret_q, crpt, crp_next);
1468 
1469 		krpt = TAILQ_FIRST(&crp_ret_kq);
1470 		if (krpt != NULL)
1471 			TAILQ_REMOVE(&crp_ret_kq, krpt, krp_next);
1472 
1473 		if (crpt != NULL || krpt != NULL) {
1474 			CRYPTO_RETQ_UNLOCK();
1475 			/*
1476 			 * Run callbacks unlocked.
1477 			 */
1478 			if (crpt != NULL) {
1479 #ifdef CRYPTO_TIMING
1480 				if (crypto_timing) {
1481 					/*
1482 					 * NB: We must copy the timestamp before
1483 					 * doing the callback as the cryptop is
1484 					 * likely to be reclaimed.
1485 					 */
1486 					struct timespec t = crpt->crp_tstamp;
1487 					crypto_tstat(&cryptostats.cs_cb, &t);
1488 					crpt->crp_callback(crpt);
1489 					crypto_tstat(&cryptostats.cs_finis, &t);
1490 				} else
1491 #endif
1492 					crpt->crp_callback(crpt);
1493 			}
1494 			if (krpt != NULL)
1495 				krpt->krp_callback(krpt);
1496 			CRYPTO_RETQ_LOCK();
1497 		} else {
1498 			/*
1499 			 * Nothing more to be processed.  Sleep until we're
1500 			 * woken because there are more returns to process.
1501 			 */
1502 			lksleep (&crp_ret_q, &crypto_ret_q_lock,
1503 				 0, "crypto_ret_wait", 0);
1504 			if (cryptoretthread == NULL)
1505 				break;
1506 			cryptostats.cs_rets++;
1507 		}
1508 	}
1509 	CRYPTO_RETQ_UNLOCK();
1510 
1511 	crypto_finis(&crp_ret_q);
1512 }
1513 
1514 #ifdef DDB
1515 static void
1516 db_show_drivers(void)
1517 {
1518 	int hid;
1519 
1520 	db_printf("%12s %4s %4s %8s %2s %2s\n"
1521 		, "Device"
1522 		, "Ses"
1523 		, "Kops"
1524 		, "Flags"
1525 		, "QB"
1526 		, "KB"
1527 	);
1528 	for (hid = 0; hid < crypto_drivers_num; hid++) {
1529 		const struct cryptocap *cap = &crypto_drivers[hid];
1530 		if (cap->cc_dev == NULL)
1531 			continue;
1532 		db_printf("%-12s %4u %4u %08x %2u %2u\n"
1533 		    , device_get_nameunit(cap->cc_dev)
1534 		    , cap->cc_sessions
1535 		    , cap->cc_koperations
1536 		    , cap->cc_flags
1537 		    , cap->cc_qblocked
1538 		    , cap->cc_kqblocked
1539 		);
1540 	}
1541 }
1542 
1543 DB_SHOW_COMMAND(crypto, db_show_crypto)
1544 {
1545 	crypto_tdinfo_t tdinfo;
1546 	struct cryptop *crp;
1547 	int n;
1548 
1549 	db_show_drivers();
1550 	db_printf("\n");
1551 
1552 	db_printf("%4s %8s %4s %4s %4s %4s %8s %8s\n",
1553 	    "HID", "Caps", "Ilen", "Olen", "Etype", "Flags",
1554 	    "Desc", "Callback");
1555 
1556 	for (n = 0; n < ncpus; ++n) {
1557 		tdinfo = &tdinfo_array[n];
1558 
1559 		TAILQ_FOREACH(crp, &tdinfo->crp_q, crp_next) {
1560 			db_printf("%4u %08x %4u %4u %4u %04x %8p %8p\n"
1561 			    , (int) CRYPTO_SESID2HID(crp->crp_sid)
1562 			    , (int) CRYPTO_SESID2CAPS(crp->crp_sid)
1563 			    , crp->crp_ilen, crp->crp_olen
1564 			    , crp->crp_etype
1565 			    , crp->crp_flags
1566 			    , crp->crp_desc
1567 			    , crp->crp_callback
1568 			);
1569 		}
1570 	}
1571 	if (!TAILQ_EMPTY(&crp_ret_q)) {
1572 		db_printf("\n%4s %4s %4s %8s\n",
1573 		    "HID", "Etype", "Flags", "Callback");
1574 		TAILQ_FOREACH(crp, &crp_ret_q, crp_next) {
1575 			db_printf("%4u %4u %04x %8p\n"
1576 			    , (int) CRYPTO_SESID2HID(crp->crp_sid)
1577 			    , crp->crp_etype
1578 			    , crp->crp_flags
1579 			    , crp->crp_callback
1580 			);
1581 		}
1582 	}
1583 }
1584 
1585 DB_SHOW_COMMAND(kcrypto, db_show_kcrypto)
1586 {
1587 	crypto_tdinfo_t tdinfo;
1588 	struct cryptkop *krp;
1589 	int n;
1590 
1591 	db_show_drivers();
1592 	db_printf("\n");
1593 
1594 	db_printf("%4s %5s %4s %4s %8s %4s %8s\n",
1595 	    "Op", "Status", "#IP", "#OP", "CRID", "HID", "Callback");
1596 
1597 	for (n = 0; n < ncpus; ++n) {
1598 		tdinfo = &tdinfo_array[n];
1599 
1600 		TAILQ_FOREACH(krp, &tdinfo->crp_kq, krp_next) {
1601 			db_printf("%4u %5u %4u %4u %08x %4u %8p\n"
1602 			    , krp->krp_op
1603 			    , krp->krp_status
1604 			    , krp->krp_iparams, krp->krp_oparams
1605 			    , krp->krp_crid, krp->krp_hid
1606 			    , krp->krp_callback
1607 			);
1608 		}
1609 	}
1610 	if (!TAILQ_EMPTY(&crp_ret_q)) {
1611 		db_printf("%4s %5s %8s %4s %8s\n",
1612 		    "Op", "Status", "CRID", "HID", "Callback");
1613 		TAILQ_FOREACH(krp, &crp_ret_kq, krp_next) {
1614 			db_printf("%4u %5u %08x %4u %8p\n"
1615 			    , krp->krp_op
1616 			    , krp->krp_status
1617 			    , krp->krp_crid, krp->krp_hid
1618 			    , krp->krp_callback
1619 			);
1620 		}
1621 	}
1622 }
1623 #endif
1624 
1625 int crypto_modevent(module_t mod, int type, void *unused);
1626 
1627 /*
1628  * Initialization code, both for static and dynamic loading.
1629  * Note this is not invoked with the usual MODULE_DECLARE
1630  * mechanism but instead is listed as a dependency by the
1631  * cryptosoft driver.  This guarantees proper ordering of
1632  * calls on module load/unload.
1633  */
1634 int
1635 crypto_modevent(module_t mod, int type, void *unused)
1636 {
1637 	int error = EINVAL;
1638 
1639 	switch (type) {
1640 	case MOD_LOAD:
1641 		error = crypto_init();
1642 		if (error == 0 && bootverbose)
1643 			kprintf("crypto: <crypto core>\n");
1644 		break;
1645 	case MOD_UNLOAD:
1646 		/*XXX disallow if active sessions */
1647 		error = 0;
1648 		crypto_destroy();
1649 		return 0;
1650 	}
1651 	return error;
1652 }
1653 MODULE_VERSION(crypto, 1);
1654 MODULE_DEPEND(crypto, zlib, 1, 1, 1);
1655