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