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