crypto.c revision 104628
1/*	$FreeBSD: head/sys/opencrypto/crypto.c 104628 2002-10-07 18:46:38Z sam $	*/
2/*	$OpenBSD: crypto.c,v 1.38 2002/06/11 11:14:29 beck Exp $	*/
3/*
4 * The author of this code is Angelos D. Keromytis (angelos@cis.upenn.edu)
5 *
6 * This code was written by Angelos D. Keromytis in Athens, Greece, in
7 * February 2000. Network Security Technologies Inc. (NSTI) kindly
8 * supported the development of this code.
9 *
10 * Copyright (c) 2000, 2001 Angelos D. Keromytis
11 *
12 * Permission to use, copy, and modify this software with or without fee
13 * is hereby granted, provided that this entire notice is included in
14 * all source code copies of any software which is or includes a copy or
15 * modification of this software.
16 *
17 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
18 * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
19 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
20 * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
21 * PURPOSE.
22 */
23
24#include <sys/param.h>
25#include <sys/systm.h>
26#include <sys/eventhandler.h>
27#include <sys/kernel.h>
28#include <sys/kthread.h>
29#include <sys/lock.h>
30#include <sys/mutex.h>
31#include <sys/malloc.h>
32#include <sys/proc.h>
33#include <sys/sysctl.h>
34
35#include <vm/uma.h>
36#include <opencrypto/cryptodev.h>
37#include <opencrypto/xform.h>			/* XXX for M_XDATA */
38
39#define	SESID2HID(sid)	(((sid) >> 32) & 0xffffffff)
40
41/*
42 * Crypto drivers register themselves by allocating a slot in the
43 * crypto_drivers table with crypto_get_driverid() and then registering
44 * each algorithm they support with crypto_register() and crypto_kregister().
45 */
46static	struct mtx crypto_drivers_mtx;		/* lock on driver table */
47#define	CRYPTO_DRIVER_LOCK()	mtx_lock(&crypto_drivers_mtx)
48#define	CRYPTO_DRIVER_UNLOCK()	mtx_unlock(&crypto_drivers_mtx)
49static	struct cryptocap *crypto_drivers = NULL;
50static	int crypto_drivers_num = 0;
51
52/*
53 * There are two queues for crypto requests; one for symmetric (e.g.
54 * cipher) operations and one for asymmetric (e.g. MOD)operations.
55 * A single mutex is used to lock access to both queues.  We could
56 * have one per-queue but having one simplifies handling of block/unblock
57 * operations.
58 */
59static	TAILQ_HEAD(,cryptop) crp_q;		/* request queues */
60static	TAILQ_HEAD(,cryptkop) crp_kq;
61static	struct mtx crypto_q_mtx;
62#define	CRYPTO_Q_LOCK()		mtx_lock(&crypto_q_mtx)
63#define	CRYPTO_Q_UNLOCK()	mtx_unlock(&crypto_q_mtx)
64
65/*
66 * There are two queues for processing completed crypto requests; one
67 * for the symmetric and one for the asymmetric ops.  We only need one
68 * but have two to avoid type futzing (cryptop vs. cryptkop).  A single
69 * mutex is used to lock access to both queues.  Note that this lock
70 * must be separate from the lock on request queues to insure driver
71 * callbacks don't generate lock order reversals.
72 */
73static	TAILQ_HEAD(,cryptop) crp_ret_q;		/* callback queues */
74static	TAILQ_HEAD(,cryptkop) crp_ret_kq;
75static	struct mtx crypto_ret_q_mtx;
76#define	CRYPTO_RETQ_LOCK()	mtx_lock(&crypto_ret_q_mtx)
77#define	CRYPTO_RETQ_UNLOCK()	mtx_unlock(&crypto_ret_q_mtx)
78
79static	uma_zone_t cryptop_zone;
80static	uma_zone_t cryptodesc_zone;
81
82int	crypto_usercrypto = 1;		/* userland may open /dev/crypto */
83SYSCTL_INT(_kern, OID_AUTO, usercrypto, CTLFLAG_RW,
84	   &crypto_usercrypto, 0,
85	   "Enable/disable user-mode access to crypto support");
86int	crypto_userasymcrypto = 1;	/* userland may do asym crypto reqs */
87SYSCTL_INT(_kern, OID_AUTO, userasymcrypto, CTLFLAG_RW,
88	   &crypto_userasymcrypto, 0,
89	   "Enable/disable user-mode access to asymmetric crypto support");
90int	crypto_devallowsoft = 0;	/* only use hardware crypto for asym */
91SYSCTL_INT(_kern, OID_AUTO, cryptodevallowsoft, CTLFLAG_RW,
92	   &crypto_devallowsoft, 0,
93	   "Enable/disable use of software asym crypto support");
94
95MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
96
97static void
98crypto_init(void)
99{
100	cryptop_zone = uma_zcreate("cryptop", sizeof (struct cryptop),
101				    0, 0, 0, 0,
102				    UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
103	cryptodesc_zone = uma_zcreate("cryptodesc", sizeof (struct cryptodesc),
104				    0, 0, 0, 0,
105				    UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
106	if (cryptodesc_zone == NULL || cryptop_zone == NULL)
107		panic("cannot setup crypto zones");
108
109	mtx_init(&crypto_drivers_mtx, "crypto driver table",
110		NULL, MTX_DEF|MTX_QUIET);
111
112	crypto_drivers_num = CRYPTO_DRIVERS_INITIAL;
113	crypto_drivers = malloc(crypto_drivers_num *
114	    sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT | M_ZERO);
115	if (crypto_drivers == NULL)
116		panic("cannot setup crypto drivers");
117
118	TAILQ_INIT(&crp_q);
119	TAILQ_INIT(&crp_kq);
120	mtx_init(&crypto_q_mtx, "crypto op queues", NULL, MTX_DEF);
121
122	TAILQ_INIT(&crp_ret_q);
123	TAILQ_INIT(&crp_ret_kq);
124	mtx_init(&crypto_ret_q_mtx, "crypto return queues", NULL, MTX_DEF);
125}
126SYSINIT(crypto_init, SI_SUB_DRIVERS, SI_ORDER_FIRST, crypto_init, NULL)
127
128/*
129 * Create a new session.
130 */
131int
132crypto_newsession(u_int64_t *sid, struct cryptoini *cri, int hard)
133{
134	struct cryptoini *cr;
135	u_int32_t hid, lid;
136	int err = EINVAL;
137
138	CRYPTO_DRIVER_LOCK();
139
140	if (crypto_drivers == NULL)
141		goto done;
142
143	/*
144	 * The algorithm we use here is pretty stupid; just use the
145	 * first driver that supports all the algorithms we need.
146	 *
147	 * XXX We need more smarts here (in real life too, but that's
148	 * XXX another story altogether).
149	 */
150
151	for (hid = 0; hid < crypto_drivers_num; hid++) {
152		/*
153		 * If it's not initialized or has remaining sessions
154		 * referencing it, skip.
155		 */
156		if (crypto_drivers[hid].cc_newsession == NULL ||
157		    (crypto_drivers[hid].cc_flags & CRYPTOCAP_F_CLEANUP))
158			continue;
159
160		/* Hardware required -- ignore software drivers. */
161		if (hard > 0 &&
162		    (crypto_drivers[hid].cc_flags & CRYPTOCAP_F_SOFTWARE))
163			continue;
164		/* Software required -- ignore hardware drivers. */
165		if (hard < 0 &&
166		    (crypto_drivers[hid].cc_flags & CRYPTOCAP_F_SOFTWARE) == 0)
167			continue;
168
169		/* See if all the algorithms are supported. */
170		for (cr = cri; cr; cr = cr->cri_next)
171			if (crypto_drivers[hid].cc_alg[cr->cri_alg] == 0)
172				break;
173
174		if (cr == NULL) {
175			/* Ok, all algorithms are supported. */
176
177			/*
178			 * Can't do everything in one session.
179			 *
180			 * XXX Fix this. We need to inject a "virtual" session layer right
181			 * XXX about here.
182			 */
183
184			/* Call the driver initialization routine. */
185			lid = hid;		/* Pass the driver ID. */
186			err = crypto_drivers[hid].cc_newsession(
187					crypto_drivers[hid].cc_arg, &lid, cri);
188			if (err == 0) {
189				(*sid) = hid;
190				(*sid) <<= 32;
191				(*sid) |= (lid & 0xffffffff);
192				crypto_drivers[hid].cc_sessions++;
193			}
194			break;
195		}
196	}
197done:
198	CRYPTO_DRIVER_UNLOCK();
199	return err;
200}
201
202/*
203 * Delete an existing session (or a reserved session on an unregistered
204 * driver).
205 */
206int
207crypto_freesession(u_int64_t sid)
208{
209	u_int32_t hid;
210	int err;
211
212	CRYPTO_DRIVER_LOCK();
213
214	if (crypto_drivers == NULL) {
215		err = EINVAL;
216		goto done;
217	}
218
219	/* Determine two IDs. */
220	hid = SESID2HID(sid);
221
222	if (hid >= crypto_drivers_num) {
223		err = ENOENT;
224		goto done;
225	}
226
227	if (crypto_drivers[hid].cc_sessions)
228		crypto_drivers[hid].cc_sessions--;
229
230	/* Call the driver cleanup routine, if available. */
231	if (crypto_drivers[hid].cc_freesession)
232		err = crypto_drivers[hid].cc_freesession(
233				crypto_drivers[hid].cc_arg, sid);
234	else
235		err = 0;
236
237	/*
238	 * If this was the last session of a driver marked as invalid,
239	 * make the entry available for reuse.
240	 */
241	if ((crypto_drivers[hid].cc_flags & CRYPTOCAP_F_CLEANUP) &&
242	    crypto_drivers[hid].cc_sessions == 0)
243		bzero(&crypto_drivers[hid], sizeof(struct cryptocap));
244
245done:
246	CRYPTO_DRIVER_UNLOCK();
247	return err;
248}
249
250/*
251 * Return an unused driver id.  Used by drivers prior to registering
252 * support for the algorithms they handle.
253 */
254int32_t
255crypto_get_driverid(u_int32_t flags)
256{
257	struct cryptocap *newdrv;
258	int i;
259
260	CRYPTO_DRIVER_LOCK();
261
262	for (i = 0; i < crypto_drivers_num; i++)
263		if (crypto_drivers[i].cc_process == NULL &&
264		    (crypto_drivers[i].cc_flags & CRYPTOCAP_F_CLEANUP) == 0 &&
265		    crypto_drivers[i].cc_sessions == 0)
266			break;
267
268	/* Out of entries, allocate some more. */
269	if (i == crypto_drivers_num) {
270		/* Be careful about wrap-around. */
271		if (2 * crypto_drivers_num <= crypto_drivers_num) {
272			CRYPTO_DRIVER_UNLOCK();
273			printf("crypto: driver count wraparound!\n");
274			return -1;
275		}
276
277		newdrv = malloc(2 * crypto_drivers_num *
278		    sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT|M_ZERO);
279		if (newdrv == NULL) {
280			CRYPTO_DRIVER_UNLOCK();
281			printf("crypto: no space to expand driver table!\n");
282			return -1;
283		}
284
285		bcopy(crypto_drivers, newdrv,
286		    crypto_drivers_num * sizeof(struct cryptocap));
287
288		crypto_drivers_num *= 2;
289
290		free(crypto_drivers, M_CRYPTO_DATA);
291		crypto_drivers = newdrv;
292	}
293
294	/* NB: state is zero'd on free */
295	crypto_drivers[i].cc_sessions = 1;	/* Mark */
296	crypto_drivers[i].cc_flags = flags;
297	if (bootverbose)
298		printf("crypto: assign driver %u, flags %u\n", i, flags);
299
300	CRYPTO_DRIVER_UNLOCK();
301
302	return i;
303}
304
305static struct cryptocap *
306crypto_checkdriver(u_int32_t hid)
307{
308	if (crypto_drivers == NULL)
309		return NULL;
310	return (hid >= crypto_drivers_num ? NULL : &crypto_drivers[hid]);
311}
312
313/*
314 * Register support for a key-related algorithm.  This routine
315 * is called once for each algorithm supported a driver.
316 */
317int
318crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags,
319    int (*kprocess)(void*, struct cryptkop *, int),
320    void *karg)
321{
322	struct cryptocap *cap;
323	int err;
324
325	CRYPTO_DRIVER_LOCK();
326
327	cap = crypto_checkdriver(driverid);
328	if (cap != NULL &&
329	    (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
330		/*
331		 * XXX Do some performance testing to determine placing.
332		 * XXX We probably need an auxiliary data structure that
333		 * XXX describes relative performances.
334		 */
335
336		cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
337		if (bootverbose)
338			printf("crypto: driver %u registers key alg %u flags %u\n"
339				, driverid
340				, kalg
341				, flags
342			);
343
344		if (cap->cc_kprocess == NULL) {
345			cap->cc_karg = karg;
346			cap->cc_kprocess = kprocess;
347		}
348		err = 0;
349	} else
350		err = EINVAL;
351
352	CRYPTO_DRIVER_UNLOCK();
353	return err;
354}
355
356/*
357 * Register support for a non-key-related algorithm.  This routine
358 * is called once for each such algorithm supported by a driver.
359 */
360int
361crypto_register(u_int32_t driverid, int alg, u_int16_t maxoplen,
362    u_int32_t flags,
363    int (*newses)(void*, u_int32_t*, struct cryptoini*),
364    int (*freeses)(void*, u_int64_t),
365    int (*process)(void*, struct cryptop *, int),
366    void *arg)
367{
368	struct cryptocap *cap;
369	int err;
370
371	CRYPTO_DRIVER_LOCK();
372
373	cap = crypto_checkdriver(driverid);
374	/* NB: algorithms are in the range [1..max] */
375	if (cap != NULL &&
376	    (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX)) {
377		/*
378		 * XXX Do some performance testing to determine placing.
379		 * XXX We probably need an auxiliary data structure that
380		 * XXX describes relative performances.
381		 */
382
383		cap->cc_alg[alg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
384		cap->cc_max_op_len[alg] = maxoplen;
385		if (bootverbose)
386			printf("crypto: driver %u registers alg %u flags %u maxoplen %u\n"
387				, driverid
388				, alg
389				, flags
390				, maxoplen
391			);
392
393		if (cap->cc_process == NULL) {
394			cap->cc_arg = arg;
395			cap->cc_newsession = newses;
396			cap->cc_process = process;
397			cap->cc_freesession = freeses;
398			cap->cc_sessions = 0;		/* Unmark */
399		}
400		err = 0;
401	} else
402		err = EINVAL;
403
404	CRYPTO_DRIVER_UNLOCK();
405	return err;
406}
407
408/*
409 * Unregister a crypto driver. If there are pending sessions using it,
410 * leave enough information around so that subsequent calls using those
411 * sessions will correctly detect the driver has been unregistered and
412 * reroute requests.
413 */
414int
415crypto_unregister(u_int32_t driverid, int alg)
416{
417	int i, err;
418	u_int32_t ses;
419	struct cryptocap *cap;
420
421	CRYPTO_DRIVER_LOCK();
422
423	cap = crypto_checkdriver(driverid);
424	if (cap != NULL &&
425	    (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX) &&
426	    cap->cc_alg[alg] != 0) {
427		cap->cc_alg[alg] = 0;
428		cap->cc_max_op_len[alg] = 0;
429
430		/* Was this the last algorithm ? */
431		for (i = 1; i <= CRYPTO_ALGORITHM_MAX; i++)
432			if (cap->cc_alg[i] != 0)
433				break;
434
435		if (i == CRYPTO_ALGORITHM_MAX + 1) {
436			ses = cap->cc_sessions;
437			bzero(cap, sizeof(struct cryptocap));
438			if (ses != 0) {
439				/*
440				 * If there are pending sessions, just mark as invalid.
441				 */
442				cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
443				cap->cc_sessions = ses;
444			}
445		}
446		err = 0;
447	} else
448		err = EINVAL;
449
450	CRYPTO_DRIVER_UNLOCK();
451	return err;
452}
453
454/*
455 * Unregister all algorithms associated with a crypto driver.
456 * If there are pending sessions using it, leave enough information
457 * around so that subsequent calls using those sessions will
458 * correctly detect the driver has been unregistered and reroute
459 * requests.
460 */
461int
462crypto_unregister_all(u_int32_t driverid)
463{
464	int i, err;
465	u_int32_t ses;
466	struct cryptocap *cap;
467
468	CRYPTO_DRIVER_LOCK();
469
470	cap = crypto_checkdriver(driverid);
471	if (cap != NULL) {
472		for (i = CRYPTO_ALGORITHM_MIN; i <= CRYPTO_ALGORITHM_MAX; i++) {
473			cap->cc_alg[i] = 0;
474			cap->cc_max_op_len[i] = 0;
475		}
476		ses = cap->cc_sessions;
477		bzero(cap, sizeof(struct cryptocap));
478		if (ses != 0) {
479			/*
480			 * If there are pending sessions, just mark as invalid.
481			 */
482			cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
483			cap->cc_sessions = ses;
484		}
485		err = 0;
486	} else
487		err = EINVAL;
488
489	CRYPTO_DRIVER_UNLOCK();
490	return err;
491}
492
493/*
494 * Clear blockage on a driver.  The what parameter indicates whether
495 * the driver is now ready for cryptop's and/or cryptokop's.
496 */
497int
498crypto_unblock(u_int32_t driverid, int what)
499{
500	struct cryptocap *cap;
501	int needwakeup, err;
502
503	CRYPTO_Q_LOCK();
504	cap = crypto_checkdriver(driverid);
505	if (cap != NULL) {
506		needwakeup = 0;
507		if (what & CRYPTO_SYMQ) {
508			needwakeup |= cap->cc_qblocked;
509			cap->cc_qblocked = 0;
510		}
511		if (what & CRYPTO_ASYMQ) {
512			needwakeup |= cap->cc_kqblocked;
513			cap->cc_kqblocked = 0;
514		}
515		if (needwakeup)
516			wakeup_one(&crp_q);
517		err = 0;
518	} else
519		err = EINVAL;
520	CRYPTO_Q_UNLOCK();
521
522	return err;
523}
524
525/*
526 * Add a crypto request to a queue, to be processed by the kernel thread.
527 */
528int
529crypto_dispatch(struct cryptop *crp)
530{
531	struct cryptocap *cap;
532	int wasempty;
533
534	CRYPTO_Q_LOCK();
535	wasempty = TAILQ_EMPTY(&crp_q);
536	TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
537
538	/*
539	 * Wakeup processing thread if driver is not blocked.
540	 */
541	cap = crypto_checkdriver(SESID2HID(crp->crp_sid));
542	if (cap && !cap->cc_qblocked && wasempty)
543		wakeup_one(&crp_q);
544	CRYPTO_Q_UNLOCK();
545
546	return 0;
547}
548
549/*
550 * Add an asymetric crypto request to a queue,
551 * to be processed by the kernel thread.
552 */
553int
554crypto_kdispatch(struct cryptkop *krp)
555{
556	struct cryptocap *cap;
557	int wasempty;
558
559	CRYPTO_Q_LOCK();
560	wasempty = TAILQ_EMPTY(&crp_kq);
561	TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
562
563	/*
564	 * Wakeup processing thread if driver is not blocked.
565	 */
566	cap = crypto_checkdriver(krp->krp_hid);
567	if (cap && !cap->cc_kqblocked && wasempty)
568		wakeup_one(&crp_q);	/* NB: shared wait channel */
569	CRYPTO_Q_UNLOCK();
570
571	return 0;
572}
573
574/*
575 * Dispatch an assymetric crypto request to the appropriate crypto devices.
576 */
577static int
578crypto_kinvoke(struct cryptkop *krp, int hint)
579{
580	u_int32_t hid;
581	int error;
582
583	mtx_assert(&crypto_q_mtx, MA_OWNED);
584
585	/* Sanity checks. */
586	if (krp == NULL)
587		return EINVAL;
588	if (krp->krp_callback == NULL) {
589		free(krp, M_XDATA);		/* XXX allocated in cryptodev */
590		return EINVAL;
591	}
592
593	for (hid = 0; hid < crypto_drivers_num; hid++) {
594		if ((crypto_drivers[hid].cc_flags & CRYPTOCAP_F_SOFTWARE) &&
595		    !crypto_devallowsoft)
596			continue;
597		if (crypto_drivers[hid].cc_kprocess == NULL)
598			continue;
599		if ((crypto_drivers[hid].cc_kalg[krp->krp_op] &
600		    CRYPTO_ALG_FLAG_SUPPORTED) == 0)
601			continue;
602		break;
603	}
604	if (hid < crypto_drivers_num) {
605		krp->krp_hid = hid;
606		error = crypto_drivers[hid].cc_kprocess(
607				crypto_drivers[hid].cc_karg, krp, hint);
608	} else
609		error = ENODEV;
610
611	if (error) {
612		krp->krp_status = error;
613		crypto_kdone(krp);
614	}
615	return 0;
616}
617
618/*
619 * Dispatch a crypto request to the appropriate crypto devices.
620 */
621static int
622crypto_invoke(struct cryptop *crp, int hint)
623{
624	u_int32_t hid;
625	int (*process)(void*, struct cryptop *, int);
626
627	mtx_assert(&crypto_q_mtx, MA_OWNED);
628
629	/* Sanity checks. */
630	if (crp == NULL)
631		return EINVAL;
632	if (crp->crp_callback == NULL) {
633		crypto_freereq(crp);
634		return EINVAL;
635	}
636	if (crp->crp_desc == NULL) {
637		crp->crp_etype = EINVAL;
638		crypto_done(crp);
639		return 0;
640	}
641
642	hid = SESID2HID(crp->crp_sid);
643	if (hid < crypto_drivers_num) {
644		if (crypto_drivers[hid].cc_flags & CRYPTOCAP_F_CLEANUP)
645			crypto_freesession(crp->crp_sid);
646		process = crypto_drivers[hid].cc_process;
647	} else {
648		process = NULL;
649	}
650
651	if (process == NULL) {
652		struct cryptodesc *crd;
653		u_int64_t nid;
654
655		/*
656		 * Driver has unregistered; migrate the session and return
657		 * an error to the caller so they'll resubmit the op.
658		 */
659		for (crd = crp->crp_desc; crd->crd_next; crd = crd->crd_next)
660			crd->CRD_INI.cri_next = &(crd->crd_next->CRD_INI);
661
662		if (crypto_newsession(&nid, &(crp->crp_desc->CRD_INI), 0) == 0)
663			crp->crp_sid = nid;
664
665		crp->crp_etype = EAGAIN;
666		crypto_done(crp);
667		return 0;
668	} else {
669		/*
670		 * Invoke the driver to process the request.
671		 */
672		return (*process)(crypto_drivers[hid].cc_arg, crp, hint);
673	}
674}
675
676/*
677 * Release a set of crypto descriptors.
678 */
679void
680crypto_freereq(struct cryptop *crp)
681{
682	struct cryptodesc *crd;
683
684	if (crp == NULL)
685		return;
686
687	while ((crd = crp->crp_desc) != NULL) {
688		crp->crp_desc = crd->crd_next;
689		uma_zfree(cryptodesc_zone, crd);
690	}
691
692	uma_zfree(cryptop_zone, crp);
693}
694
695/*
696 * Acquire a set of crypto descriptors.
697 */
698struct cryptop *
699crypto_getreq(int num)
700{
701	struct cryptodesc *crd;
702	struct cryptop *crp;
703
704	crp = uma_zalloc(cryptop_zone, 0);
705	if (crp != NULL) {
706		while (num--) {
707			crd = uma_zalloc(cryptodesc_zone, 0);
708			if (crd == NULL) {
709				crypto_freereq(crp);
710				return NULL;
711			}
712
713			crd->crd_next = crp->crp_desc;
714			crp->crp_desc = crd;
715		}
716	}
717	return crp;
718}
719
720/*
721 * Invoke the callback on behalf of the driver.
722 */
723void
724crypto_done(struct cryptop *crp)
725{
726	int wasempty;
727
728	CRYPTO_RETQ_LOCK();
729	wasempty = TAILQ_EMPTY(&crp_ret_q);
730	TAILQ_INSERT_TAIL(&crp_ret_q, crp, crp_next);
731
732	if (wasempty)
733		wakeup_one(&crp_ret_q);		/* shared wait channel */
734	CRYPTO_RETQ_UNLOCK();
735}
736
737/*
738 * Invoke the callback on behalf of the driver.
739 */
740void
741crypto_kdone(struct cryptkop *krp)
742{
743	int wasempty;
744
745	CRYPTO_RETQ_LOCK();
746	wasempty = TAILQ_EMPTY(&crp_ret_kq);
747	TAILQ_INSERT_TAIL(&crp_ret_kq, krp, krp_next);
748
749	if (wasempty)
750		wakeup_one(&crp_ret_q);		/* shared wait channel */
751	CRYPTO_RETQ_UNLOCK();
752}
753
754int
755crypto_getfeat(int *featp)
756{
757	int hid, kalg, feat = 0;
758
759	if (!crypto_userasymcrypto)
760		goto out;
761
762	CRYPTO_DRIVER_LOCK();
763	for (hid = 0; hid < crypto_drivers_num; hid++) {
764		if ((crypto_drivers[hid].cc_flags & CRYPTOCAP_F_SOFTWARE) &&
765		    !crypto_devallowsoft) {
766			continue;
767		}
768		if (crypto_drivers[hid].cc_kprocess == NULL)
769			continue;
770		for (kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
771			if ((crypto_drivers[hid].cc_kalg[kalg] &
772			    CRYPTO_ALG_FLAG_SUPPORTED) != 0)
773				feat |=  1 << kalg;
774	}
775	CRYPTO_DRIVER_UNLOCK();
776out:
777	*featp = feat;
778	return (0);
779}
780
781static struct proc *cryptoproc;
782
783static void
784crypto_shutdown(void *arg, int howto)
785{
786	/* XXX flush queues */
787}
788
789/*
790 * Crypto thread, dispatches crypto requests.
791 */
792static void
793crypto_proc(void)
794{
795	struct cryptop *crp, *submit;
796	struct cryptkop *krp;
797	struct cryptocap *cap;
798	int result, hint;
799
800	EVENTHANDLER_REGISTER(shutdown_pre_sync, crypto_shutdown, NULL,
801			      SHUTDOWN_PRI_FIRST);
802
803	CRYPTO_Q_LOCK();
804
805	for (;;) {
806		/*
807		 * Find the first element in the queue that can be
808		 * processed and look-ahead to see if multiple ops
809		 * are ready for the same driver.
810		 */
811		submit = NULL;
812		hint = 0;
813		TAILQ_FOREACH(crp, &crp_q, crp_next) {
814			u_int32_t hid = SESID2HID(crp->crp_sid);
815			cap = crypto_checkdriver(hid);
816			if (cap == NULL || cap->cc_process == NULL) {
817				/* Op needs to be migrated, process it. */
818				if (submit == NULL)
819					submit = crp;
820				break;
821			}
822			if (!cap->cc_qblocked) {
823				if (submit != NULL) {
824					/*
825					 * We stop on finding another op,
826					 * regardless whether its for the same
827					 * driver or not.  We could keep
828					 * searching the queue but it might be
829					 * better to just use a per-driver
830					 * queue instead.
831					 */
832					if (SESID2HID(submit->crp_sid) == hid)
833						hint = CRYPTO_HINT_MORE;
834					break;
835				} else {
836					submit = crp;
837					if (submit->crp_flags & CRYPTO_F_NODELAY)
838						break;
839					/* keep scanning for more are q'd */
840				}
841			}
842		}
843		if (submit != NULL) {
844			TAILQ_REMOVE(&crp_q, submit, crp_next);
845			result = crypto_invoke(submit, hint);
846			if (result == ERESTART) {
847				/*
848				 * The driver ran out of resources, mark the
849				 * driver ``blocked'' for cryptop's and put
850				 * the request back in the queue.  It would
851				 * best to put the request back where we got
852				 * it but that's hard so for now we put it
853				 * at the front.  This should be ok; putting
854				 * it at the end does not work.
855				 */
856				/* XXX validate sid again? */
857				crypto_drivers[SESID2HID(submit->crp_sid)].cc_qblocked = 1;
858				TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
859			}
860		}
861
862		/* As above, but for key ops */
863		TAILQ_FOREACH(krp, &crp_kq, krp_next) {
864			cap = crypto_checkdriver(krp->krp_hid);
865			if (cap == NULL || cap->cc_kprocess == NULL) {
866				/* Op needs to be migrated, process it. */
867				break;
868			}
869			if (!cap->cc_kqblocked)
870				break;
871		}
872		if (krp != NULL) {
873			TAILQ_REMOVE(&crp_kq, krp, krp_next);
874			result = crypto_kinvoke(krp, 0);
875			if (result == ERESTART) {
876				/*
877				 * The driver ran out of resources, mark the
878				 * driver ``blocked'' for cryptkop's and put
879				 * the request back in the queue.  It would
880				 * best to put the request back where we got
881				 * it but that's hard so for now we put it
882				 * at the front.  This should be ok; putting
883				 * it at the end does not work.
884				 */
885				/* XXX validate sid again? */
886				crypto_drivers[krp->krp_hid].cc_kqblocked = 1;
887				TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
888			}
889		}
890
891		if (submit == NULL && krp == NULL) {
892			/*
893			 * Nothing more to be processed.  Sleep until we're
894			 * woken because there are more ops to process.
895			 * This happens either by submission or by a driver
896			 * becoming unblocked and notifying us through
897			 * crypto_unblock.  Note that when we wakeup we
898			 * start processing each queue again from the
899			 * front. It's not clear that it's important to
900			 * preserve this ordering since ops may finish
901			 * out of order if dispatched to different devices
902			 * and some become blocked while others do not.
903			 */
904			msleep(&crp_q, &crypto_q_mtx, PWAIT, "crypto_wait", 0);
905		}
906	}
907}
908static struct kproc_desc crypto_kp = {
909	"crypto",
910	crypto_proc,
911	&cryptoproc
912};
913SYSINIT(crypto_proc, SI_SUB_KTHREAD_IDLE, SI_ORDER_ANY,
914	kproc_start, &crypto_kp)
915
916static struct proc *cryptoretproc;
917
918static void
919crypto_ret_shutdown(void *arg, int howto)
920{
921	/* XXX flush queues */
922}
923
924/*
925 * Crypto returns thread, does callbacks for processed crypto requests.
926 * Callbacks are done here, rather than in the crypto drivers, because
927 * callbacks typically are expensive and would slow interrupt handling.
928 */
929static void
930crypto_ret_proc(void)
931{
932	struct cryptop *crpt;
933	struct cryptkop *krpt;
934
935	EVENTHANDLER_REGISTER(shutdown_pre_sync, crypto_ret_shutdown, NULL,
936			      SHUTDOWN_PRI_FIRST);
937
938	CRYPTO_RETQ_LOCK();
939
940	for (;;) {
941		/* Harvest return q's for completed ops */
942		crpt = TAILQ_FIRST(&crp_ret_q);
943		if (crpt != NULL)
944			TAILQ_REMOVE(&crp_ret_q, crpt, crp_next);
945
946		krpt = TAILQ_FIRST(&crp_ret_kq);
947		if (krpt != NULL)
948			TAILQ_REMOVE(&crp_ret_kq, krpt, krp_next);
949
950		if (crpt != NULL || krpt != NULL) {
951			CRYPTO_RETQ_UNLOCK();
952			/*
953			 * Run callbacks unlocked.
954			 */
955			if (crpt != NULL)
956				crpt->crp_callback(crpt);
957			if (krpt != NULL)
958				krpt->krp_callback(krpt);
959			CRYPTO_RETQ_LOCK();
960		} else {
961			/*
962			 * Nothing more to be processed.  Sleep until we're
963			 * woken because there are more returns to process.
964			 */
965			msleep(&crp_ret_q, &crypto_ret_q_mtx, PWAIT,
966				"crypto_ret_wait", 0);
967		}
968	}
969}
970static struct kproc_desc crypto_ret_kp = {
971	"crypto returns",
972	crypto_ret_proc,
973	&cryptoretproc
974};
975SYSINIT(crypto_ret_proc, SI_SUB_KTHREAD_IDLE, SI_ORDER_ANY,
976	kproc_start, &crypto_ret_kp)
977