crypto.c revision 1.40 1 /* $NetBSD: crypto.c,v 1.40 2011/05/16 10:27:49 drochner 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.40 2011/05/16 10:27:49 drochner 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 kmutex_t crypto_q_mtx;
74 kmutex_t crypto_ret_q_mtx;
75 kcondvar_t cryptoret_cv;
76 kmutex_t crypto_mtx;
77
78 /* below are kludges for residual code wrtitten to FreeBSD interfaces */
79 #define SWI_CRYPTO 17
80 #define register_swi(lvl, fn) \
81 softint_establish(SOFTINT_NET|SOFTINT_MPSAFE, (void (*)(void *))fn, NULL)
82 #define unregister_swi(lvl, fn) softint_disestablish(softintr_cookie)
83 #define setsoftcrypto(x) softint_schedule(x)
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_NONE);
253 mutex_init(&crypto_q_mtx, MUTEX_DEFAULT, IPL_NET);
254 mutex_init(&crypto_ret_q_mtx, MUTEX_DEFAULT, IPL_NET);
255 cv_init(&cryptoret_cv, "crypto_w");
256 pool_init(&cryptop_pool, sizeof(struct cryptop), 0, 0,
257 0, "cryptop", NULL, IPL_NET);
258 pool_init(&cryptodesc_pool, sizeof(struct cryptodesc), 0, 0,
259 0, "cryptodesc", NULL, IPL_NET);
260 pool_init(&cryptkop_pool, sizeof(struct cryptkop), 0, 0,
261 0, "cryptkop", NULL, IPL_NET);
262
263 crypto_drivers = malloc(CRYPTO_DRIVERS_INITIAL *
264 sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT | M_ZERO);
265 if (crypto_drivers == NULL) {
266 printf("crypto_init: cannot malloc driver table\n");
267 return 0;
268 }
269 crypto_drivers_num = CRYPTO_DRIVERS_INITIAL;
270
271 softintr_cookie = register_swi(SWI_CRYPTO, cryptointr);
272 error = kthread_create(PRI_NONE, KTHREAD_MPSAFE, NULL,
273 (void (*)(void *))cryptoret, NULL, &cryptothread, "cryptoret");
274 if (error) {
275 printf("crypto_init: cannot start cryptoret thread; error %d",
276 error);
277 crypto_destroy();
278 }
279
280 return 0;
281 }
282
283 void
284 crypto_init(void)
285 {
286 static ONCE_DECL(crypto_init_once);
287
288 RUN_ONCE(&crypto_init_once, crypto_init0);
289 }
290
291 static void
292 crypto_destroy(void)
293 {
294 /* XXX no wait to reclaim zones */
295 if (crypto_drivers != NULL)
296 free(crypto_drivers, M_CRYPTO_DATA);
297 unregister_swi(SWI_CRYPTO, cryptointr);
298 }
299
300 /*
301 * Create a new session. Must be called with crypto_mtx held.
302 */
303 int
304 crypto_newsession(u_int64_t *sid, struct cryptoini *cri, int hard)
305 {
306 struct cryptoini *cr;
307 u_int32_t hid, lid;
308 int err = EINVAL;
309
310 mutex_enter(&crypto_mtx);
311
312 if (crypto_drivers == NULL)
313 goto done;
314
315 /*
316 * The algorithm we use here is pretty stupid; just use the
317 * first driver that supports all the algorithms we need.
318 *
319 * XXX We need more smarts here (in real life too, but that's
320 * XXX another story altogether).
321 */
322
323 for (hid = 0; hid < crypto_drivers_num; hid++) {
324 /*
325 * If it's not initialized or has remaining sessions
326 * referencing it, skip.
327 */
328 if (crypto_drivers[hid].cc_newsession == NULL ||
329 (crypto_drivers[hid].cc_flags & CRYPTOCAP_F_CLEANUP))
330 continue;
331
332 /* Hardware required -- ignore software drivers. */
333 if (hard > 0 &&
334 (crypto_drivers[hid].cc_flags & CRYPTOCAP_F_SOFTWARE))
335 continue;
336 /* Software required -- ignore hardware drivers. */
337 if (hard < 0 &&
338 (crypto_drivers[hid].cc_flags & CRYPTOCAP_F_SOFTWARE) == 0)
339 continue;
340
341 /* See if all the algorithms are supported. */
342 for (cr = cri; cr; cr = cr->cri_next)
343 if (crypto_drivers[hid].cc_alg[cr->cri_alg] == 0) {
344 DPRINTF(("crypto_newsession: alg %d not supported\n", cr->cri_alg));
345 break;
346 }
347
348 if (cr == NULL) {
349 /* Ok, all algorithms are supported. */
350
351 /*
352 * Can't do everything in one session.
353 *
354 * XXX Fix this. We need to inject a "virtual" session layer right
355 * XXX about here.
356 */
357
358 /* Call the driver initialization routine. */
359 lid = hid; /* Pass the driver ID. */
360 err = crypto_drivers[hid].cc_newsession(
361 crypto_drivers[hid].cc_arg, &lid, cri);
362 if (err == 0) {
363 (*sid) = hid;
364 (*sid) <<= 32;
365 (*sid) |= (lid & 0xffffffff);
366 crypto_drivers[hid].cc_sessions++;
367 }
368 goto done;
369 /*break;*/
370 }
371 }
372 done:
373 mutex_exit(&crypto_mtx);
374 return err;
375 }
376
377 /*
378 * Delete an existing session (or a reserved session on an unregistered
379 * driver). Must be called with crypto_mtx mutex held.
380 */
381 int
382 crypto_freesession(u_int64_t sid)
383 {
384 u_int32_t hid;
385 int err = 0;
386
387 mutex_enter(&crypto_mtx);
388
389 if (crypto_drivers == NULL) {
390 err = EINVAL;
391 goto done;
392 }
393
394 /* Determine two IDs. */
395 hid = CRYPTO_SESID2HID(sid);
396
397 if (hid >= crypto_drivers_num) {
398 err = ENOENT;
399 goto done;
400 }
401
402 if (crypto_drivers[hid].cc_sessions)
403 crypto_drivers[hid].cc_sessions--;
404
405 /* Call the driver cleanup routine, if available. */
406 if (crypto_drivers[hid].cc_freesession) {
407 err = crypto_drivers[hid].cc_freesession(
408 crypto_drivers[hid].cc_arg, sid);
409 }
410 else
411 err = 0;
412
413 /*
414 * If this was the last session of a driver marked as invalid,
415 * make the entry available for reuse.
416 */
417 if ((crypto_drivers[hid].cc_flags & CRYPTOCAP_F_CLEANUP) &&
418 crypto_drivers[hid].cc_sessions == 0)
419 memset(&crypto_drivers[hid], 0, sizeof(struct cryptocap));
420
421 done:
422 mutex_exit(&crypto_mtx);
423 return err;
424 }
425
426 /*
427 * Return an unused driver id. Used by drivers prior to registering
428 * support for the algorithms they handle.
429 */
430 int32_t
431 crypto_get_driverid(u_int32_t flags)
432 {
433 struct cryptocap *newdrv;
434 int i;
435
436 crypto_init(); /* XXX oh, this is foul! */
437
438 mutex_enter(&crypto_mtx);
439 for (i = 0; i < crypto_drivers_num; i++)
440 if (crypto_drivers[i].cc_process == NULL &&
441 (crypto_drivers[i].cc_flags & CRYPTOCAP_F_CLEANUP) == 0 &&
442 crypto_drivers[i].cc_sessions == 0)
443 break;
444
445 /* Out of entries, allocate some more. */
446 if (i == crypto_drivers_num) {
447 /* Be careful about wrap-around. */
448 if (2 * crypto_drivers_num <= crypto_drivers_num) {
449 mutex_exit(&crypto_mtx);
450 printf("crypto: driver count wraparound!\n");
451 return -1;
452 }
453
454 newdrv = malloc(2 * crypto_drivers_num *
455 sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT|M_ZERO);
456 if (newdrv == NULL) {
457 mutex_exit(&crypto_mtx);
458 printf("crypto: no space to expand driver table!\n");
459 return -1;
460 }
461
462 memcpy(newdrv, crypto_drivers,
463 crypto_drivers_num * sizeof(struct cryptocap));
464
465 crypto_drivers_num *= 2;
466
467 free(crypto_drivers, M_CRYPTO_DATA);
468 crypto_drivers = newdrv;
469 }
470
471 /* NB: state is zero'd on free */
472 crypto_drivers[i].cc_sessions = 1; /* Mark */
473 crypto_drivers[i].cc_flags = flags;
474
475 if (bootverbose)
476 printf("crypto: assign driver %u, flags %u\n", i, flags);
477
478 mutex_exit(&crypto_mtx);
479
480 return i;
481 }
482
483 static struct cryptocap *
484 crypto_checkdriver(u_int32_t hid)
485 {
486 if (crypto_drivers == NULL)
487 return NULL;
488 return (hid >= crypto_drivers_num ? NULL : &crypto_drivers[hid]);
489 }
490
491 /*
492 * Register support for a key-related algorithm. This routine
493 * is called once for each algorithm supported a driver.
494 */
495 int
496 crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags,
497 int (*kprocess)(void *, struct cryptkop *, int),
498 void *karg)
499 {
500 struct cryptocap *cap;
501 int err;
502
503 mutex_enter(&crypto_mtx);
504
505 cap = crypto_checkdriver(driverid);
506 if (cap != NULL &&
507 (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
508 /*
509 * XXX Do some performance testing to determine placing.
510 * XXX We probably need an auxiliary data structure that
511 * XXX describes relative performances.
512 */
513
514 cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
515 if (bootverbose) {
516 printf("crypto: driver %u registers key alg %u "
517 " flags %u\n",
518 driverid,
519 kalg,
520 flags
521 );
522 }
523
524 if (cap->cc_kprocess == NULL) {
525 cap->cc_karg = karg;
526 cap->cc_kprocess = kprocess;
527 }
528 err = 0;
529 } else
530 err = EINVAL;
531
532 mutex_exit(&crypto_mtx);
533 return err;
534 }
535
536 /*
537 * Register support for a non-key-related algorithm. This routine
538 * is called once for each such algorithm supported by a driver.
539 */
540 int
541 crypto_register(u_int32_t driverid, int alg, u_int16_t maxoplen,
542 u_int32_t flags,
543 int (*newses)(void *, u_int32_t*, struct cryptoini*),
544 int (*freeses)(void *, u_int64_t),
545 int (*process)(void *, struct cryptop *, int),
546 void *arg)
547 {
548 struct cryptocap *cap;
549 int err;
550
551 mutex_enter(&crypto_mtx);
552
553 cap = crypto_checkdriver(driverid);
554 /* NB: algorithms are in the range [1..max] */
555 if (cap != NULL &&
556 (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX)) {
557 /*
558 * XXX Do some performance testing to determine placing.
559 * XXX We probably need an auxiliary data structure that
560 * XXX describes relative performances.
561 */
562
563 cap->cc_alg[alg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
564 cap->cc_max_op_len[alg] = maxoplen;
565 if (bootverbose) {
566 printf("crypto: driver %u registers alg %u "
567 "flags %u maxoplen %u\n",
568 driverid,
569 alg,
570 flags,
571 maxoplen
572 );
573 }
574
575 if (cap->cc_process == NULL) {
576 cap->cc_arg = arg;
577 cap->cc_newsession = newses;
578 cap->cc_process = process;
579 cap->cc_freesession = freeses;
580 cap->cc_sessions = 0; /* Unmark */
581 }
582 err = 0;
583 } else
584 err = EINVAL;
585
586 mutex_exit(&crypto_mtx);
587 return err;
588 }
589
590 /*
591 * Unregister a crypto driver. If there are pending sessions using it,
592 * leave enough information around so that subsequent calls using those
593 * sessions will correctly detect the driver has been unregistered and
594 * reroute requests.
595 */
596 int
597 crypto_unregister(u_int32_t driverid, int alg)
598 {
599 int i, err;
600 u_int32_t ses;
601 struct cryptocap *cap;
602
603 mutex_enter(&crypto_mtx);
604
605 cap = crypto_checkdriver(driverid);
606 if (cap != NULL &&
607 (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX) &&
608 cap->cc_alg[alg] != 0) {
609 cap->cc_alg[alg] = 0;
610 cap->cc_max_op_len[alg] = 0;
611
612 /* Was this the last algorithm ? */
613 for (i = 1; i <= CRYPTO_ALGORITHM_MAX; i++)
614 if (cap->cc_alg[i] != 0)
615 break;
616
617 if (i == CRYPTO_ALGORITHM_MAX + 1) {
618 ses = cap->cc_sessions;
619 memset(cap, 0, sizeof(struct cryptocap));
620 if (ses != 0) {
621 /*
622 * If there are pending sessions, just mark as invalid.
623 */
624 cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
625 cap->cc_sessions = ses;
626 }
627 }
628 err = 0;
629 } else
630 err = EINVAL;
631
632 mutex_exit(&crypto_mtx);
633 return err;
634 }
635
636 /*
637 * Unregister all algorithms associated with a crypto driver.
638 * If there are pending sessions using it, leave enough information
639 * around so that subsequent calls using those sessions will
640 * correctly detect the driver has been unregistered and reroute
641 * requests.
642 *
643 * XXX careful. Don't change this to call crypto_unregister() for each
644 * XXX registered algorithm unless you drop the mutex across the calls;
645 * XXX you can't take it recursively.
646 */
647 int
648 crypto_unregister_all(u_int32_t driverid)
649 {
650 int i, err;
651 u_int32_t ses;
652 struct cryptocap *cap;
653
654 mutex_enter(&crypto_mtx);
655 cap = crypto_checkdriver(driverid);
656 if (cap != NULL) {
657 for (i = CRYPTO_ALGORITHM_MIN; i <= CRYPTO_ALGORITHM_MAX; i++) {
658 cap->cc_alg[i] = 0;
659 cap->cc_max_op_len[i] = 0;
660 }
661 ses = cap->cc_sessions;
662 memset(cap, 0, sizeof(struct cryptocap));
663 if (ses != 0) {
664 /*
665 * If there are pending sessions, just mark as invalid.
666 */
667 cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
668 cap->cc_sessions = ses;
669 }
670 err = 0;
671 } else
672 err = EINVAL;
673
674 mutex_exit(&crypto_mtx);
675 return err;
676 }
677
678 /*
679 * Clear blockage on a driver. The what parameter indicates whether
680 * the driver is now ready for cryptop's and/or cryptokop's.
681 */
682 int
683 crypto_unblock(u_int32_t driverid, int what)
684 {
685 struct cryptocap *cap;
686 int needwakeup, err;
687
688 mutex_spin_enter(&crypto_q_mtx);
689 cap = crypto_checkdriver(driverid);
690 if (cap != NULL) {
691 needwakeup = 0;
692 if (what & CRYPTO_SYMQ) {
693 needwakeup |= cap->cc_qblocked;
694 cap->cc_qblocked = 0;
695 }
696 if (what & CRYPTO_ASYMQ) {
697 needwakeup |= cap->cc_kqblocked;
698 cap->cc_kqblocked = 0;
699 }
700 err = 0;
701 if (needwakeup)
702 setsoftcrypto(softintr_cookie);
703 mutex_spin_exit(&crypto_q_mtx);
704 } else {
705 err = EINVAL;
706 mutex_spin_exit(&crypto_q_mtx);
707 }
708
709 return err;
710 }
711
712 /*
713 * Dispatch a crypto request to a driver or queue
714 * it, to be processed by the kernel thread.
715 */
716 int
717 crypto_dispatch(struct cryptop *crp)
718 {
719 u_int32_t hid = CRYPTO_SESID2HID(crp->crp_sid);
720 int result;
721
722 mutex_spin_enter(&crypto_q_mtx);
723 DPRINTF(("crypto_dispatch: crp %p, reqid 0x%x, alg %d\n",
724 crp, crp->crp_reqid, crp->crp_desc->crd_alg));
725
726 cryptostats.cs_ops++;
727
728 #ifdef CRYPTO_TIMING
729 if (crypto_timing)
730 nanouptime(&crp->crp_tstamp);
731 #endif
732 if ((crp->crp_flags & CRYPTO_F_BATCH) == 0) {
733 struct cryptocap *cap;
734 /*
735 * Caller marked the request to be processed
736 * immediately; dispatch it directly to the
737 * driver unless the driver is currently blocked.
738 */
739 cap = crypto_checkdriver(hid);
740 if (cap && !cap->cc_qblocked) {
741 mutex_spin_exit(&crypto_q_mtx);
742 result = crypto_invoke(crp, 0);
743 if (result == ERESTART) {
744 /*
745 * The driver ran out of resources, mark the
746 * driver ``blocked'' for cryptop's and put
747 * the op on the queue.
748 */
749 mutex_spin_enter(&crypto_q_mtx);
750 crypto_drivers[hid].cc_qblocked = 1;
751 TAILQ_INSERT_HEAD(&crp_q, crp, crp_next);
752 cryptostats.cs_blocks++;
753 mutex_spin_exit(&crypto_q_mtx);
754 }
755 goto out_released;
756 } else {
757 /*
758 * The driver is blocked, just queue the op until
759 * it unblocks and the swi thread gets kicked.
760 */
761 TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
762 result = 0;
763 }
764 } else {
765 int wasempty = TAILQ_EMPTY(&crp_q);
766 /*
767 * Caller marked the request as ``ok to delay'';
768 * queue it for the swi thread. This is desirable
769 * when the operation is low priority and/or suitable
770 * for batching.
771 */
772 TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
773 if (wasempty) {
774 setsoftcrypto(softintr_cookie);
775 mutex_spin_exit(&crypto_q_mtx);
776 result = 0;
777 goto out_released;
778 }
779
780 result = 0;
781 }
782
783 mutex_spin_exit(&crypto_q_mtx);
784 out_released:
785 return result;
786 }
787
788 /*
789 * Add an asymetric crypto request to a queue,
790 * to be processed by the kernel thread.
791 */
792 int
793 crypto_kdispatch(struct cryptkop *krp)
794 {
795 struct cryptocap *cap;
796 int result;
797
798 mutex_spin_enter(&crypto_q_mtx);
799 cryptostats.cs_kops++;
800
801 cap = crypto_checkdriver(krp->krp_hid);
802 if (cap && !cap->cc_kqblocked) {
803 mutex_spin_exit(&crypto_q_mtx);
804 result = crypto_kinvoke(krp, 0);
805 if (result == ERESTART) {
806 /*
807 * The driver ran out of resources, mark the
808 * driver ``blocked'' for cryptop's and put
809 * the op on the queue.
810 */
811 mutex_spin_enter(&crypto_q_mtx);
812 crypto_drivers[krp->krp_hid].cc_kqblocked = 1;
813 TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
814 cryptostats.cs_kblocks++;
815 mutex_spin_exit(&crypto_q_mtx);
816 }
817 } else {
818 /*
819 * The driver is blocked, just queue the op until
820 * it unblocks and the swi thread gets kicked.
821 */
822 TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
823 result = 0;
824 mutex_spin_exit(&crypto_q_mtx);
825 }
826
827 return result;
828 }
829
830 /*
831 * Dispatch an assymetric crypto request to the appropriate crypto devices.
832 */
833 static int
834 crypto_kinvoke(struct cryptkop *krp, int hint)
835 {
836 u_int32_t hid;
837 int error;
838
839 /* Sanity checks. */
840 if (krp == NULL)
841 return EINVAL;
842 if (krp->krp_callback == NULL) {
843 cv_destroy(&krp->krp_cv);
844 pool_put(&cryptkop_pool, krp);
845 return EINVAL;
846 }
847
848 mutex_enter(&crypto_mtx);
849 for (hid = 0; hid < crypto_drivers_num; hid++) {
850 if ((crypto_drivers[hid].cc_flags & CRYPTOCAP_F_SOFTWARE) &&
851 crypto_devallowsoft == 0)
852 continue;
853 if (crypto_drivers[hid].cc_kprocess == NULL)
854 continue;
855 if ((crypto_drivers[hid].cc_kalg[krp->krp_op] &
856 CRYPTO_ALG_FLAG_SUPPORTED) == 0)
857 continue;
858 break;
859 }
860 if (hid < crypto_drivers_num) {
861 int (*process)(void *, struct cryptkop *, int);
862 void *arg;
863
864 process = crypto_drivers[hid].cc_kprocess;
865 arg = crypto_drivers[hid].cc_karg;
866 mutex_exit(&crypto_mtx);
867 krp->krp_hid = hid;
868 error = (*process)(arg, krp, hint);
869 } else {
870 mutex_exit(&crypto_mtx);
871 error = ENODEV;
872 }
873
874 if (error) {
875 krp->krp_status = error;
876 crypto_kdone(krp);
877 }
878 return 0;
879 }
880
881 #ifdef CRYPTO_TIMING
882 static void
883 crypto_tstat(struct cryptotstat *ts, struct timespec *tv)
884 {
885 struct timespec now, t;
886
887 nanouptime(&now);
888 t.tv_sec = now.tv_sec - tv->tv_sec;
889 t.tv_nsec = now.tv_nsec - tv->tv_nsec;
890 if (t.tv_nsec < 0) {
891 t.tv_sec--;
892 t.tv_nsec += 1000000000;
893 }
894 timespecadd(&ts->acc, &t, &t);
895 if (timespeccmp(&t, &ts->min, <))
896 ts->min = t;
897 if (timespeccmp(&t, &ts->max, >))
898 ts->max = t;
899 ts->count++;
900
901 *tv = now;
902 }
903 #endif
904
905 /*
906 * Dispatch a crypto request to the appropriate crypto devices.
907 */
908 static int
909 crypto_invoke(struct cryptop *crp, int hint)
910 {
911 u_int32_t hid;
912
913 #ifdef CRYPTO_TIMING
914 if (crypto_timing)
915 crypto_tstat(&cryptostats.cs_invoke, &crp->crp_tstamp);
916 #endif
917 /* Sanity checks. */
918 if (crp == NULL)
919 return EINVAL;
920 if (crp->crp_callback == NULL) {
921 return EINVAL;
922 }
923 if (crp->crp_desc == NULL) {
924 crp->crp_etype = EINVAL;
925 crypto_done(crp);
926 return 0;
927 }
928
929 hid = CRYPTO_SESID2HID(crp->crp_sid);
930
931 mutex_enter(&crypto_mtx);
932 if (hid < crypto_drivers_num) {
933 int (*process)(void *, struct cryptop *, int);
934 void *arg;
935
936 if (crypto_drivers[hid].cc_flags & CRYPTOCAP_F_CLEANUP) {
937 mutex_exit(&crypto_mtx);
938 crypto_freesession(crp->crp_sid);
939 mutex_enter(&crypto_mtx);
940 }
941 process = crypto_drivers[hid].cc_process;
942 arg = crypto_drivers[hid].cc_arg;
943 mutex_exit(&crypto_mtx);
944
945 /*
946 * Invoke the driver to process the request.
947 */
948 DPRINTF(("calling process for %p\n", crp));
949 return (*process)(arg, crp, hint);
950 } else {
951 struct cryptodesc *crd;
952 u_int64_t nid = 0;
953
954 /*
955 * Driver has unregistered; migrate the session and return
956 * an error to the caller so they'll resubmit the op.
957 */
958 for (crd = crp->crp_desc; crd->crd_next; crd = crd->crd_next)
959 crd->CRD_INI.cri_next = &(crd->crd_next->CRD_INI);
960
961 mutex_exit(&crypto_mtx);
962
963 if (crypto_newsession(&nid, &(crp->crp_desc->CRD_INI), 0) == 0)
964 crp->crp_sid = nid;
965
966 crp->crp_etype = EAGAIN;
967
968 crypto_done(crp);
969 return 0;
970 }
971 }
972
973 /*
974 * Release a set of crypto descriptors.
975 */
976 void
977 crypto_freereq(struct cryptop *crp)
978 {
979 struct cryptodesc *crd;
980
981 if (crp == NULL)
982 return;
983 DPRINTF(("crypto_freereq[%u]: crp %p\n",
984 CRYPTO_SESID2LID(crp->crp_sid), crp));
985
986 /* sanity check */
987 if (crp->crp_flags & CRYPTO_F_ONRETQ) {
988 panic("crypto_freereq() freeing crp on RETQ\n");
989 }
990
991 while ((crd = crp->crp_desc) != NULL) {
992 crp->crp_desc = crd->crd_next;
993 pool_put(&cryptodesc_pool, crd);
994 }
995 cv_destroy(&crp->crp_cv);
996 pool_put(&cryptop_pool, crp);
997 }
998
999 /*
1000 * Acquire a set of crypto descriptors.
1001 */
1002 struct cryptop *
1003 crypto_getreq(int num)
1004 {
1005 struct cryptodesc *crd;
1006 struct cryptop *crp;
1007
1008 crp = pool_get(&cryptop_pool, 0);
1009 if (crp == NULL) {
1010 return NULL;
1011 }
1012 memset(crp, 0, sizeof(struct cryptop));
1013 cv_init(&crp->crp_cv, "crydev");
1014
1015 while (num--) {
1016 crd = pool_get(&cryptodesc_pool, 0);
1017 if (crd == NULL) {
1018 crypto_freereq(crp);
1019 return NULL;
1020 }
1021
1022 memset(crd, 0, sizeof(struct cryptodesc));
1023 crd->crd_next = crp->crp_desc;
1024 crp->crp_desc = crd;
1025 }
1026
1027 return crp;
1028 }
1029
1030 /*
1031 * Invoke the callback on behalf of the driver.
1032 */
1033 void
1034 crypto_done(struct cryptop *crp)
1035 {
1036 int wasempty;
1037
1038 if (crp->crp_etype != 0)
1039 cryptostats.cs_errs++;
1040 #ifdef CRYPTO_TIMING
1041 if (crypto_timing)
1042 crypto_tstat(&cryptostats.cs_done, &crp->crp_tstamp);
1043 #endif
1044 DPRINTF(("crypto_done[%u]: crp %p\n",
1045 CRYPTO_SESID2LID(crp->crp_sid), crp));
1046
1047 /*
1048 * Normal case; queue the callback for the thread.
1049 *
1050 * The return queue is manipulated by the swi thread
1051 * and, potentially, by crypto device drivers calling
1052 * back to mark operations completed. Thus we need
1053 * to mask both while manipulating the return queue.
1054 */
1055 if (crp->crp_flags & CRYPTO_F_CBIMM) {
1056 /*
1057 * Do the callback directly. This is ok when the
1058 * callback routine does very little (e.g. the
1059 * /dev/crypto callback method just does a wakeup).
1060 */
1061 mutex_spin_enter(&crypto_ret_q_mtx);
1062 crp->crp_flags |= CRYPTO_F_DONE;
1063 mutex_spin_exit(&crypto_ret_q_mtx);
1064
1065 #ifdef CRYPTO_TIMING
1066 if (crypto_timing) {
1067 /*
1068 * NB: We must copy the timestamp before
1069 * doing the callback as the cryptop is
1070 * likely to be reclaimed.
1071 */
1072 struct timespec t = crp->crp_tstamp;
1073 crypto_tstat(&cryptostats.cs_cb, &t);
1074 crp->crp_callback(crp);
1075 crypto_tstat(&cryptostats.cs_finis, &t);
1076 } else
1077 #endif
1078 crp->crp_callback(crp);
1079 } else {
1080 mutex_spin_enter(&crypto_ret_q_mtx);
1081 crp->crp_flags |= CRYPTO_F_DONE;
1082
1083 if (crp->crp_flags & CRYPTO_F_USER) {
1084 /* the request has completed while
1085 * running in the user context
1086 * so don't queue it - the user
1087 * thread won't sleep when it sees
1088 * the CRYPTO_F_DONE flag.
1089 * This is an optimization to avoid
1090 * unecessary context switches.
1091 */
1092 DPRINTF(("crypto_done[%u]: crp %p CRYPTO_F_USER\n",
1093 CRYPTO_SESID2LID(crp->crp_sid), crp));
1094 } else {
1095 wasempty = TAILQ_EMPTY(&crp_ret_q);
1096 DPRINTF(("crypto_done[%u]: queueing %p\n",
1097 CRYPTO_SESID2LID(crp->crp_sid), crp));
1098 crp->crp_flags |= CRYPTO_F_ONRETQ;
1099 TAILQ_INSERT_TAIL(&crp_ret_q, crp, crp_next);
1100 if (wasempty) {
1101 DPRINTF(("crypto_done[%u]: waking cryptoret, "
1102 "crp %p hit empty queue\n.",
1103 CRYPTO_SESID2LID(crp->crp_sid), crp));
1104 cv_signal(&cryptoret_cv);
1105 }
1106 }
1107 mutex_spin_exit(&crypto_ret_q_mtx);
1108 }
1109 }
1110
1111 /*
1112 * Invoke the callback on behalf of the driver.
1113 */
1114 void
1115 crypto_kdone(struct cryptkop *krp)
1116 {
1117 int wasempty;
1118
1119 if (krp->krp_status != 0)
1120 cryptostats.cs_kerrs++;
1121
1122 krp->krp_flags |= CRYPTO_F_DONE;
1123
1124 /*
1125 * The return queue is manipulated by the swi thread
1126 * and, potentially, by crypto device drivers calling
1127 * back to mark operations completed. Thus we need
1128 * to mask both while manipulating the return queue.
1129 */
1130 if (krp->krp_flags & CRYPTO_F_CBIMM) {
1131 krp->krp_callback(krp);
1132 } else {
1133 mutex_spin_enter(&crypto_ret_q_mtx);
1134 wasempty = TAILQ_EMPTY(&crp_ret_kq);
1135 krp->krp_flags |= CRYPTO_F_ONRETQ;
1136 TAILQ_INSERT_TAIL(&crp_ret_kq, krp, krp_next);
1137 if (wasempty)
1138 cv_signal(&cryptoret_cv);
1139 mutex_spin_exit(&crypto_ret_q_mtx);
1140 }
1141 }
1142
1143 int
1144 crypto_getfeat(int *featp)
1145 {
1146 int hid, kalg, feat = 0;
1147
1148 mutex_enter(&crypto_mtx);
1149
1150 if (crypto_userasymcrypto == 0)
1151 goto out;
1152
1153 for (hid = 0; hid < crypto_drivers_num; hid++) {
1154 if ((crypto_drivers[hid].cc_flags & CRYPTOCAP_F_SOFTWARE) &&
1155 crypto_devallowsoft == 0) {
1156 continue;
1157 }
1158 if (crypto_drivers[hid].cc_kprocess == NULL)
1159 continue;
1160 for (kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
1161 if ((crypto_drivers[hid].cc_kalg[kalg] &
1162 CRYPTO_ALG_FLAG_SUPPORTED) != 0)
1163 feat |= 1 << kalg;
1164 }
1165 out:
1166 mutex_exit(&crypto_mtx);
1167 *featp = feat;
1168 return (0);
1169 }
1170
1171 /*
1172 * Software interrupt thread to dispatch crypto requests.
1173 */
1174 static void
1175 cryptointr(void)
1176 {
1177 struct cryptop *crp, *submit, *cnext;
1178 struct cryptkop *krp, *knext;
1179 struct cryptocap *cap;
1180 int result, hint;
1181
1182 cryptostats.cs_intrs++;
1183 mutex_spin_enter(&crypto_q_mtx);
1184 do {
1185 /*
1186 * Find the first element in the queue that can be
1187 * processed and look-ahead to see if multiple ops
1188 * are ready for the same driver.
1189 */
1190 submit = NULL;
1191 hint = 0;
1192 TAILQ_FOREACH_SAFE(crp, &crp_q, crp_next, cnext) {
1193 u_int32_t hid = CRYPTO_SESID2HID(crp->crp_sid);
1194 cap = crypto_checkdriver(hid);
1195 if (cap == NULL || cap->cc_process == NULL) {
1196 /* Op needs to be migrated, process it. */
1197 if (submit == NULL)
1198 submit = crp;
1199 break;
1200 }
1201 if (!cap->cc_qblocked) {
1202 if (submit != NULL) {
1203 /*
1204 * We stop on finding another op,
1205 * regardless whether its for the same
1206 * driver or not. We could keep
1207 * searching the queue but it might be
1208 * better to just use a per-driver
1209 * queue instead.
1210 */
1211 if (CRYPTO_SESID2HID(submit->crp_sid)
1212 == hid)
1213 hint = CRYPTO_HINT_MORE;
1214 break;
1215 } else {
1216 submit = crp;
1217 if ((submit->crp_flags & CRYPTO_F_BATCH) == 0)
1218 break;
1219 /* keep scanning for more are q'd */
1220 }
1221 }
1222 }
1223 if (submit != NULL) {
1224 TAILQ_REMOVE(&crp_q, submit, crp_next);
1225 mutex_spin_exit(&crypto_q_mtx);
1226 result = crypto_invoke(submit, hint);
1227 /* we must take here as the TAILQ op or kinvoke
1228 may need this mutex below. sigh. */
1229 mutex_spin_enter(&crypto_q_mtx);
1230 if (result == ERESTART) {
1231 /*
1232 * The driver ran out of resources, mark the
1233 * driver ``blocked'' for cryptop's and put
1234 * the request back in the queue. It would
1235 * best to put the request back where we got
1236 * it but that's hard so for now we put it
1237 * at the front. This should be ok; putting
1238 * it at the end does not work.
1239 */
1240 /* XXX validate sid again? */
1241 crypto_drivers[CRYPTO_SESID2HID(submit->crp_sid)].cc_qblocked = 1;
1242 TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
1243 cryptostats.cs_blocks++;
1244 }
1245 }
1246
1247 /* As above, but for key ops */
1248 TAILQ_FOREACH_SAFE(krp, &crp_kq, krp_next, knext) {
1249 cap = crypto_checkdriver(krp->krp_hid);
1250 if (cap == NULL || cap->cc_kprocess == NULL) {
1251 /* Op needs to be migrated, process it. */
1252 break;
1253 }
1254 if (!cap->cc_kqblocked)
1255 break;
1256 }
1257 if (krp != NULL) {
1258 TAILQ_REMOVE(&crp_kq, krp, krp_next);
1259 mutex_spin_exit(&crypto_q_mtx);
1260 result = crypto_kinvoke(krp, 0);
1261 /* the next iteration will want the mutex. :-/ */
1262 mutex_spin_enter(&crypto_q_mtx);
1263 if (result == ERESTART) {
1264 /*
1265 * The driver ran out of resources, mark the
1266 * driver ``blocked'' for cryptkop's and put
1267 * the request back in the queue. It would
1268 * best to put the request back where we got
1269 * it but that's hard so for now we put it
1270 * at the front. This should be ok; putting
1271 * it at the end does not work.
1272 */
1273 /* XXX validate sid again? */
1274 crypto_drivers[krp->krp_hid].cc_kqblocked = 1;
1275 TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
1276 cryptostats.cs_kblocks++;
1277 }
1278 }
1279 } while (submit != NULL || krp != NULL);
1280 mutex_spin_exit(&crypto_q_mtx);
1281 }
1282
1283 /*
1284 * Kernel thread to do callbacks.
1285 */
1286 static void
1287 cryptoret(void)
1288 {
1289 struct cryptop *crp;
1290 struct cryptkop *krp;
1291
1292 mutex_spin_enter(&crypto_ret_q_mtx);
1293 for (;;) {
1294 crp = TAILQ_FIRST(&crp_ret_q);
1295 if (crp != NULL) {
1296 TAILQ_REMOVE(&crp_ret_q, crp, crp_next);
1297 crp->crp_flags &= ~CRYPTO_F_ONRETQ;
1298 }
1299 krp = TAILQ_FIRST(&crp_ret_kq);
1300 if (krp != NULL) {
1301 TAILQ_REMOVE(&crp_ret_kq, krp, krp_next);
1302 krp->krp_flags &= ~CRYPTO_F_ONRETQ;
1303 }
1304
1305 /* drop before calling any callbacks. */
1306 if (crp == NULL && krp == NULL) {
1307 cryptostats.cs_rets++;
1308 cv_wait(&cryptoret_cv, &crypto_ret_q_mtx);
1309 continue;
1310 }
1311
1312 mutex_spin_exit(&crypto_ret_q_mtx);
1313
1314 if (crp != NULL) {
1315 #ifdef CRYPTO_TIMING
1316 if (crypto_timing) {
1317 /*
1318 * NB: We must copy the timestamp before
1319 * doing the callback as the cryptop is
1320 * likely to be reclaimed.
1321 */
1322 struct timespec t = crp->crp_tstamp;
1323 crypto_tstat(&cryptostats.cs_cb, &t);
1324 crp->crp_callback(crp);
1325 crypto_tstat(&cryptostats.cs_finis, &t);
1326 } else
1327 #endif
1328 {
1329 crp->crp_callback(crp);
1330 }
1331 }
1332 if (krp != NULL)
1333 krp->krp_callback(krp);
1334
1335 mutex_spin_enter(&crypto_ret_q_mtx);
1336 }
1337 }
1338