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