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