crypto.c revision 1.90 1 /* $NetBSD: crypto.c,v 1.90 2017/06/15 12:45:10 knakahara 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.90 2017/06/15 12:45:10 knakahara 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 #include <sys/errno.h>
69 #include <sys/module.h>
70
71 #if defined(_KERNEL_OPT)
72 #include "opt_ocf.h"
73 #endif
74
75 #include <opencrypto/cryptodev.h>
76 #include <opencrypto/xform.h> /* XXX for M_XDATA */
77
78 static kmutex_t crypto_q_mtx;
79 static kmutex_t crypto_ret_q_mtx;
80 static kcondvar_t cryptoret_cv;
81
82 /* below are kludges for residual code wrtitten to FreeBSD interfaces */
83 #define SWI_CRYPTO 17
84 #define register_swi(lvl, fn) \
85 softint_establish(SOFTINT_NET|SOFTINT_MPSAFE, (void (*)(void *))fn, NULL)
86 #define unregister_swi(lvl, fn) softint_disestablish(softintr_cookie)
87 #define setsoftcrypto(x) \
88 do{ \
89 kpreempt_disable(); \
90 softint_schedule(x); \
91 kpreempt_enable(); \
92 }while(0)
93
94 int crypto_ret_q_check(struct cryptop *);
95
96 /*
97 * Crypto drivers register themselves by allocating a slot in the
98 * crypto_drivers table with crypto_get_driverid() and then registering
99 * each algorithm they support with crypto_register() and crypto_kregister().
100 */
101 static kmutex_t crypto_drv_mtx;
102 /* Don't directly access crypto_drivers[i], use crypto_checkdriver(i). */
103 static struct cryptocap *crypto_drivers;
104 static int crypto_drivers_num;
105 static void *softintr_cookie;
106 static int crypto_exit_flag;
107
108 /*
109 * There are two queues for crypto requests; one for symmetric (e.g.
110 * cipher) operations and one for asymmetric (e.g. MOD) operations.
111 * See below for how synchronization is handled.
112 */
113 static TAILQ_HEAD(,cryptop) crp_q = /* request queues */
114 TAILQ_HEAD_INITIALIZER(crp_q);
115 static TAILQ_HEAD(,cryptkop) crp_kq =
116 TAILQ_HEAD_INITIALIZER(crp_kq);
117
118 /*
119 * There are two queues for processing completed crypto requests; one
120 * for the symmetric and one for the asymmetric ops. We only need one
121 * but have two to avoid type futzing (cryptop vs. cryptkop). See below
122 * for how synchronization is handled.
123 */
124 static TAILQ_HEAD(crprethead, cryptop) crp_ret_q = /* callback queues */
125 TAILQ_HEAD_INITIALIZER(crp_ret_q);
126 static TAILQ_HEAD(krprethead, cryptkop) crp_ret_kq =
127 TAILQ_HEAD_INITIALIZER(crp_ret_kq);
128
129 #define DEFINIT_CRYPTO_Q_LEN(name) \
130 static int crypto_##name##_len = 0
131
132 #define DEFINIT_CRYPTO_Q_DROPS(name) \
133 static int crypto_##name##_drops = 0
134
135 #define DEFINIT_CRYPTO_Q_MAXLEN(name, defval) \
136 static int crypto_##name##_maxlen = defval
137
138 #define CRYPTO_Q_INC(name) \
139 do { \
140 crypto_##name##_len++; \
141 } while(0);
142
143 #define CRYPTO_Q_DEC(name) \
144 do { \
145 crypto_##name##_len--; \
146 } while(0);
147
148 #define CRYPTO_Q_INC_DROPS(name) \
149 do { \
150 crypto_##name##_drops++; \
151 } while(0);
152
153 #define CRYPTO_Q_IS_FULL(name) \
154 (crypto_##name##_maxlen > 0 \
155 && (crypto_##name##_len > crypto_##name##_maxlen))
156
157 /*
158 * current queue length.
159 */
160 DEFINIT_CRYPTO_Q_LEN(crp_ret_q);
161 DEFINIT_CRYPTO_Q_LEN(crp_ret_kq);
162
163 /*
164 * queue dropped count.
165 */
166 DEFINIT_CRYPTO_Q_DROPS(crp_ret_q);
167 DEFINIT_CRYPTO_Q_DROPS(crp_ret_kq);
168
169 #ifndef CRYPTO_RET_Q_MAXLEN
170 #define CRYPTO_RET_Q_MAXLEN 0
171 #endif
172 #ifndef CRYPTO_RET_KQ_MAXLEN
173 #define CRYPTO_RET_KQ_MAXLEN 0
174 #endif
175 /*
176 * queue length limit.
177 * default value is 0. <=0 means unlimited.
178 */
179 DEFINIT_CRYPTO_Q_MAXLEN(crp_ret_q, CRYPTO_RET_Q_MAXLEN);
180 DEFINIT_CRYPTO_Q_MAXLEN(crp_ret_kq, CRYPTO_RET_KQ_MAXLEN);
181
182 /*
183 * TODO:
184 * make percpu
185 */
186 static int
187 sysctl_opencrypto_q_len(SYSCTLFN_ARGS)
188 {
189 int error;
190
191 error = sysctl_lookup(SYSCTLFN_CALL(rnode));
192 if (error || newp == NULL)
193 return error;
194
195 return 0;
196 }
197
198 /*
199 * TODO:
200 * make percpu
201 */
202 static int
203 sysctl_opencrypto_q_drops(SYSCTLFN_ARGS)
204 {
205 int error;
206
207 error = sysctl_lookup(SYSCTLFN_CALL(rnode));
208 if (error || newp == NULL)
209 return error;
210
211 return 0;
212 }
213
214 /*
215 * need to make percpu?
216 */
217 static int
218 sysctl_opencrypto_q_maxlen(SYSCTLFN_ARGS)
219 {
220 int error;
221
222 error = sysctl_lookup(SYSCTLFN_CALL(rnode));
223 if (error || newp == NULL)
224 return error;
225
226 return 0;
227 }
228
229 /*
230 * Crypto op and desciptor data structures are allocated
231 * from separate private zones(FreeBSD)/pools(netBSD/OpenBSD) .
232 */
233 struct pool cryptop_pool;
234 struct pool cryptodesc_pool;
235 struct pool cryptkop_pool;
236
237 int crypto_usercrypto = 1; /* userland may open /dev/crypto */
238 int crypto_userasymcrypto = 1; /* userland may do asym crypto reqs */
239 /*
240 * cryptodevallowsoft is (intended to be) sysctl'able, controlling
241 * access to hardware versus software transforms as below:
242 *
243 * crypto_devallowsoft < 0: Force userlevel requests to use software
244 * transforms, always
245 * crypto_devallowsoft = 0: Use hardware if present, grant userlevel
246 * requests for non-accelerated transforms
247 * (handling the latter in software)
248 * crypto_devallowsoft > 0: Allow user requests only for transforms which
249 * are hardware-accelerated.
250 */
251 int crypto_devallowsoft = 1; /* only use hardware crypto */
252
253 static void
254 sysctl_opencrypto_setup(struct sysctllog **clog)
255 {
256 const struct sysctlnode *ocnode;
257 const struct sysctlnode *retqnode, *retkqnode;
258
259 sysctl_createv(clog, 0, NULL, NULL,
260 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
261 CTLTYPE_INT, "usercrypto",
262 SYSCTL_DESCR("Enable/disable user-mode access to "
263 "crypto support"),
264 NULL, 0, &crypto_usercrypto, 0,
265 CTL_KERN, CTL_CREATE, CTL_EOL);
266 sysctl_createv(clog, 0, NULL, NULL,
267 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
268 CTLTYPE_INT, "userasymcrypto",
269 SYSCTL_DESCR("Enable/disable user-mode access to "
270 "asymmetric crypto support"),
271 NULL, 0, &crypto_userasymcrypto, 0,
272 CTL_KERN, CTL_CREATE, CTL_EOL);
273 sysctl_createv(clog, 0, NULL, NULL,
274 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
275 CTLTYPE_INT, "cryptodevallowsoft",
276 SYSCTL_DESCR("Enable/disable use of software "
277 "asymmetric crypto support"),
278 NULL, 0, &crypto_devallowsoft, 0,
279 CTL_KERN, CTL_CREATE, CTL_EOL);
280
281 sysctl_createv(clog, 0, NULL, &ocnode,
282 CTLFLAG_PERMANENT,
283 CTLTYPE_NODE, "opencrypto",
284 SYSCTL_DESCR("opencrypto related entries"),
285 NULL, 0, NULL, 0,
286 CTL_CREATE, CTL_EOL);
287
288 sysctl_createv(clog, 0, &ocnode, &retqnode,
289 CTLFLAG_PERMANENT,
290 CTLTYPE_NODE, "crypto_ret_q",
291 SYSCTL_DESCR("crypto_ret_q related entries"),
292 NULL, 0, NULL, 0,
293 CTL_CREATE, CTL_EOL);
294 sysctl_createv(clog, 0, &retqnode, NULL,
295 CTLFLAG_PERMANENT|CTLFLAG_READONLY,
296 CTLTYPE_INT, "len",
297 SYSCTL_DESCR("Current queue length"),
298 sysctl_opencrypto_q_len, 0,
299 (void *)&crypto_crp_ret_q_len, 0,
300 CTL_CREATE, CTL_EOL);
301 sysctl_createv(clog, 0, &retqnode, NULL,
302 CTLFLAG_PERMANENT|CTLFLAG_READONLY,
303 CTLTYPE_INT, "drops",
304 SYSCTL_DESCR("Crypto requests dropped due to full ret queue"),
305 sysctl_opencrypto_q_drops, 0,
306 (void *)&crypto_crp_ret_q_drops, 0,
307 CTL_CREATE, CTL_EOL);
308 sysctl_createv(clog, 0, &retqnode, NULL,
309 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
310 CTLTYPE_INT, "maxlen",
311 SYSCTL_DESCR("Maximum allowed queue length"),
312 sysctl_opencrypto_q_maxlen, 0,
313 (void *)&crypto_crp_ret_q_maxlen, 0,
314 CTL_CREATE, CTL_EOL);
315
316 sysctl_createv(clog, 0, &ocnode, &retkqnode,
317 CTLFLAG_PERMANENT,
318 CTLTYPE_NODE, "crypto_ret_kq",
319 SYSCTL_DESCR("crypto_ret_kq related entries"),
320 NULL, 0, NULL, 0,
321 CTL_CREATE, CTL_EOL);
322 sysctl_createv(clog, 0, &retkqnode, NULL,
323 CTLFLAG_PERMANENT|CTLFLAG_READONLY,
324 CTLTYPE_INT, "len",
325 SYSCTL_DESCR("Current queue length"),
326 sysctl_opencrypto_q_len, 0,
327 (void *)&crypto_crp_ret_kq_len, 0,
328 CTL_CREATE, CTL_EOL);
329 sysctl_createv(clog, 0, &retkqnode, NULL,
330 CTLFLAG_PERMANENT|CTLFLAG_READONLY,
331 CTLTYPE_INT, "drops",
332 SYSCTL_DESCR("Crypto requests dropped due to full ret queue"),
333 sysctl_opencrypto_q_drops, 0,
334 (void *)&crypto_crp_ret_kq_drops, 0,
335 CTL_CREATE, CTL_EOL);
336 sysctl_createv(clog, 0, &retkqnode, NULL,
337 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
338 CTLTYPE_INT, "maxlen",
339 SYSCTL_DESCR("Maximum allowed queue length"),
340 sysctl_opencrypto_q_maxlen, 0,
341 (void *)&crypto_crp_ret_kq_maxlen, 0,
342 CTL_CREATE, CTL_EOL);
343 }
344
345 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
346
347 /*
348 * Synchronization: read carefully, this is non-trivial.
349 *
350 * Crypto requests are submitted via crypto_dispatch. Typically
351 * these come in from network protocols at spl0 (output path) or
352 * spl[,soft]net (input path).
353 *
354 * Requests are typically passed on the driver directly, but they
355 * may also be queued for processing by a software interrupt thread,
356 * cryptointr, that runs at splsoftcrypto. This thread dispatches
357 * the requests to crypto drivers (h/w or s/w) who call crypto_done
358 * when a request is complete. Hardware crypto drivers are assumed
359 * to register their IRQ's as network devices so their interrupt handlers
360 * and subsequent "done callbacks" happen at spl[imp,net].
361 *
362 * Completed crypto ops are queued for a separate kernel thread that
363 * handles the callbacks at spl0. This decoupling insures the crypto
364 * driver interrupt service routine is not delayed while the callback
365 * takes place and that callbacks are delivered after a context switch
366 * (as opposed to a software interrupt that clients must block).
367 *
368 * This scheme is not intended for SMP machines.
369 */
370 static void cryptointr(void); /* swi thread to dispatch ops */
371 static void cryptoret(void); /* kernel thread for callbacks*/
372 static struct lwp *cryptothread;
373 static int crypto_destroy(bool);
374 static int crypto_invoke(struct cryptop *crp, int hint);
375 static int crypto_kinvoke(struct cryptkop *krp, int hint);
376
377 static struct cryptocap *crypto_checkdriver_lock(u_int32_t);
378 static struct cryptocap *crypto_checkdriver_uninit(u_int32_t);
379 static struct cryptocap *crypto_checkdriver(u_int32_t);
380 static void crypto_driver_lock(struct cryptocap *);
381 static void crypto_driver_unlock(struct cryptocap *);
382 static void crypto_driver_clear(struct cryptocap *);
383
384 static struct cryptostats cryptostats;
385 #ifdef CRYPTO_TIMING
386 static int crypto_timing = 0;
387 #endif
388
389 static struct sysctllog *sysctl_opencrypto_clog;
390
391 static int
392 crypto_init0(void)
393 {
394 int error;
395
396 mutex_init(&crypto_drv_mtx, MUTEX_DEFAULT, IPL_NONE);
397 mutex_init(&crypto_q_mtx, MUTEX_DEFAULT, IPL_NONE);
398 mutex_init(&crypto_ret_q_mtx, MUTEX_DEFAULT, IPL_NET);
399 cv_init(&cryptoret_cv, "crypto_w");
400 pool_init(&cryptop_pool, sizeof(struct cryptop), 0, 0,
401 0, "cryptop", NULL, IPL_NET);
402 pool_init(&cryptodesc_pool, sizeof(struct cryptodesc), 0, 0,
403 0, "cryptodesc", NULL, IPL_NET);
404 pool_init(&cryptkop_pool, sizeof(struct cryptkop), 0, 0,
405 0, "cryptkop", NULL, IPL_NET);
406
407 crypto_drivers = malloc(CRYPTO_DRIVERS_INITIAL *
408 sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT | M_ZERO);
409 if (crypto_drivers == NULL) {
410 printf("crypto_init: cannot malloc driver table\n");
411 return ENOMEM;
412 }
413 crypto_drivers_num = CRYPTO_DRIVERS_INITIAL;
414
415 softintr_cookie = register_swi(SWI_CRYPTO, cryptointr);
416 error = kthread_create(PRI_NONE, KTHREAD_MPSAFE, NULL,
417 (void (*)(void *))cryptoret, NULL, &cryptothread, "cryptoret");
418 if (error) {
419 printf("crypto_init: cannot start cryptoret thread; error %d",
420 error);
421 return crypto_destroy(false);
422 }
423
424 sysctl_opencrypto_setup(&sysctl_opencrypto_clog);
425
426 return 0;
427 }
428
429 int
430 crypto_init(void)
431 {
432 static ONCE_DECL(crypto_init_once);
433
434 return RUN_ONCE(&crypto_init_once, crypto_init0);
435 }
436
437 static int
438 crypto_destroy(bool exit_kthread)
439 {
440 int i;
441
442 if (exit_kthread) {
443 struct cryptocap *cap = NULL;
444
445 /* if we have any in-progress requests, don't unload */
446 mutex_enter(&crypto_q_mtx);
447 if (!TAILQ_EMPTY(&crp_q) || !TAILQ_EMPTY(&crp_kq)) {
448 mutex_exit(&crypto_q_mtx);
449 return EBUSY;
450 }
451 mutex_exit(&crypto_q_mtx);
452 /* FIXME:
453 * prohibit enqueue to crp_q and crp_kq after here.
454 */
455
456 mutex_enter(&crypto_drv_mtx);
457 for (i = 0; i < crypto_drivers_num; i++) {
458 cap = crypto_checkdriver(i);
459 if (cap == NULL)
460 continue;
461 if (cap->cc_sessions != 0) {
462 mutex_exit(&crypto_drv_mtx);
463 return EBUSY;
464 }
465 }
466 mutex_exit(&crypto_drv_mtx);
467 /* FIXME:
468 * prohibit touch crypto_drivers[] and each element after here.
469 */
470
471 mutex_spin_enter(&crypto_ret_q_mtx);
472 /* kick the cryptoret thread and wait for it to exit */
473 crypto_exit_flag = 1;
474 cv_signal(&cryptoret_cv);
475
476 while (crypto_exit_flag != 0)
477 cv_wait(&cryptoret_cv, &crypto_ret_q_mtx);
478 mutex_spin_exit(&crypto_ret_q_mtx);
479 }
480
481 if (sysctl_opencrypto_clog != NULL)
482 sysctl_teardown(&sysctl_opencrypto_clog);
483
484 unregister_swi(SWI_CRYPTO, cryptointr);
485
486 mutex_enter(&crypto_drv_mtx);
487 if (crypto_drivers != NULL)
488 free(crypto_drivers, M_CRYPTO_DATA);
489 mutex_exit(&crypto_drv_mtx);
490
491 pool_destroy(&cryptop_pool);
492 pool_destroy(&cryptodesc_pool);
493 pool_destroy(&cryptkop_pool);
494
495 cv_destroy(&cryptoret_cv);
496
497 mutex_destroy(&crypto_ret_q_mtx);
498 mutex_destroy(&crypto_q_mtx);
499 mutex_destroy(&crypto_drv_mtx);
500
501 return 0;
502 }
503
504 static bool
505 crypto_driver_suitable(struct cryptocap *cap, struct cryptoini *cri)
506 {
507 struct cryptoini *cr;
508
509 for (cr = cri; cr; cr = cr->cri_next)
510 if (cap->cc_alg[cr->cri_alg] == 0) {
511 DPRINTF("alg %d not supported\n", cr->cri_alg);
512 return false;
513 }
514
515 return true;
516 }
517
518 #define CRYPTO_ACCEPT_HARDWARE 0x1
519 #define CRYPTO_ACCEPT_SOFTWARE 0x2
520 /*
521 * The algorithm we use here is pretty stupid; just use the
522 * first driver that supports all the algorithms we need.
523 * If there are multiple drivers we choose the driver with
524 * the fewest active sessions. We prefer hardware-backed
525 * drivers to software ones.
526 *
527 * XXX We need more smarts here (in real life too, but that's
528 * XXX another story altogether).
529 */
530 static struct cryptocap *
531 crypto_select_driver_lock(struct cryptoini *cri, int hard)
532 {
533 u_int32_t hid;
534 int accept;
535 struct cryptocap *cap, *best;
536
537 best = NULL;
538 /*
539 * hard == 0 can use both hardware and software drivers.
540 * We use hardware drivers prior to software drivers, so search
541 * hardware drivers at first time.
542 */
543 if (hard >= 0)
544 accept = CRYPTO_ACCEPT_HARDWARE;
545 else
546 accept = CRYPTO_ACCEPT_SOFTWARE;
547 again:
548 for (hid = 0; hid < crypto_drivers_num; hid++) {
549 cap = crypto_checkdriver(hid);
550 if (cap == NULL)
551 continue;
552
553 crypto_driver_lock(cap);
554
555 /*
556 * If it's not initialized or has remaining sessions
557 * referencing it, skip.
558 */
559 if (cap->cc_newsession == NULL ||
560 (cap->cc_flags & CRYPTOCAP_F_CLEANUP)) {
561 crypto_driver_unlock(cap);
562 continue;
563 }
564
565 /* Hardware required -- ignore software drivers. */
566 if ((accept & CRYPTO_ACCEPT_SOFTWARE) == 0
567 && (cap->cc_flags & CRYPTOCAP_F_SOFTWARE)) {
568 crypto_driver_unlock(cap);
569 continue;
570 }
571 /* Software required -- ignore hardware drivers. */
572 if ((accept & CRYPTO_ACCEPT_HARDWARE) == 0
573 && (cap->cc_flags & CRYPTOCAP_F_SOFTWARE) == 0) {
574 crypto_driver_unlock(cap);
575 continue;
576 }
577
578 /* See if all the algorithms are supported. */
579 if (crypto_driver_suitable(cap, cri)) {
580 if (best == NULL) {
581 /* keep holding crypto_driver_lock(cap) */
582 best = cap;
583 continue;
584 } else if (cap->cc_sessions < best->cc_sessions) {
585 crypto_driver_unlock(best);
586 /* keep holding crypto_driver_lock(cap) */
587 best = cap;
588 continue;
589 }
590 }
591
592 crypto_driver_unlock(cap);
593 }
594 if (best == NULL && hard == 0
595 && (accept & CRYPTO_ACCEPT_SOFTWARE) == 0) {
596 accept = CRYPTO_ACCEPT_SOFTWARE;
597 goto again;
598 }
599
600 return best;
601 }
602
603 /*
604 * Create a new session.
605 */
606 int
607 crypto_newsession(u_int64_t *sid, struct cryptoini *cri, int hard)
608 {
609 struct cryptocap *cap;
610 int err = EINVAL;
611
612 mutex_enter(&crypto_drv_mtx);
613
614 cap = crypto_select_driver_lock(cri, hard);
615 if (cap != NULL) {
616 u_int32_t hid, lid;
617
618 hid = cap - crypto_drivers;
619 /*
620 * Can't do everything in one session.
621 *
622 * XXX Fix this. We need to inject a "virtual" session layer right
623 * XXX about here.
624 */
625
626 /* Call the driver initialization routine. */
627 lid = hid; /* Pass the driver ID. */
628 crypto_driver_unlock(cap);
629 err = cap->cc_newsession(cap->cc_arg, &lid, cri);
630 crypto_driver_lock(cap);
631 if (err == 0) {
632 (*sid) = hid;
633 (*sid) <<= 32;
634 (*sid) |= (lid & 0xffffffff);
635 (cap->cc_sessions)++;
636 } else {
637 DPRINTF("crypto_drivers[%d].cc_newsession() failed. error=%d\n",
638 hid, err);
639 }
640 crypto_driver_unlock(cap);
641 }
642
643 mutex_exit(&crypto_drv_mtx);
644
645 return err;
646 }
647
648 /*
649 * Delete an existing session (or a reserved session on an unregistered
650 * driver).
651 */
652 int
653 crypto_freesession(u_int64_t sid)
654 {
655 struct cryptocap *cap;
656 int err = 0;
657
658 /* Determine two IDs. */
659 cap = crypto_checkdriver_lock(CRYPTO_SESID2HID(sid));
660 if (cap == NULL)
661 return ENOENT;
662
663 if (cap->cc_sessions)
664 (cap->cc_sessions)--;
665
666 /* Call the driver cleanup routine, if available. */
667 if (cap->cc_freesession)
668 err = cap->cc_freesession(cap->cc_arg, sid);
669 else
670 err = 0;
671
672 /*
673 * If this was the last session of a driver marked as invalid,
674 * make the entry available for reuse.
675 */
676 if ((cap->cc_flags & CRYPTOCAP_F_CLEANUP) && cap->cc_sessions == 0)
677 crypto_driver_clear(cap);
678
679 crypto_driver_unlock(cap);
680 return err;
681 }
682
683 static bool
684 crypto_checkdriver_initialized(const struct cryptocap *cap)
685 {
686
687 return cap->cc_process != NULL ||
688 (cap->cc_flags & CRYPTOCAP_F_CLEANUP) != 0 ||
689 cap->cc_sessions != 0;
690 }
691
692 /*
693 * Return an unused driver id. Used by drivers prior to registering
694 * support for the algorithms they handle.
695 */
696 int32_t
697 crypto_get_driverid(u_int32_t flags)
698 {
699 struct cryptocap *newdrv;
700 struct cryptocap *cap = NULL;
701 int i;
702
703 (void)crypto_init(); /* XXX oh, this is foul! */
704
705 mutex_enter(&crypto_drv_mtx);
706 for (i = 0; i < crypto_drivers_num; i++) {
707 cap = crypto_checkdriver_uninit(i);
708 if (cap == NULL || crypto_checkdriver_initialized(cap))
709 continue;
710 break;
711 }
712
713 /* Out of entries, allocate some more. */
714 if (cap == NULL) {
715 /* Be careful about wrap-around. */
716 if (2 * crypto_drivers_num <= crypto_drivers_num) {
717 mutex_exit(&crypto_drv_mtx);
718 printf("crypto: driver count wraparound!\n");
719 return -1;
720 }
721
722 newdrv = malloc(2 * crypto_drivers_num *
723 sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT|M_ZERO);
724 if (newdrv == NULL) {
725 mutex_exit(&crypto_drv_mtx);
726 printf("crypto: no space to expand driver table!\n");
727 return -1;
728 }
729
730 memcpy(newdrv, crypto_drivers,
731 crypto_drivers_num * sizeof(struct cryptocap));
732
733 crypto_drivers_num *= 2;
734
735 free(crypto_drivers, M_CRYPTO_DATA);
736 crypto_drivers = newdrv;
737
738 cap = crypto_checkdriver_uninit(i);
739 KASSERT(cap != NULL);
740 }
741
742 /* NB: state is zero'd on free */
743 cap->cc_sessions = 1; /* Mark */
744 cap->cc_flags = flags;
745 mutex_init(&cap->cc_lock, MUTEX_DEFAULT, IPL_NET);
746
747 if (bootverbose)
748 printf("crypto: assign driver %u, flags %u\n", i, flags);
749
750 mutex_exit(&crypto_drv_mtx);
751
752 return i;
753 }
754
755 static struct cryptocap *
756 crypto_checkdriver_lock(u_int32_t hid)
757 {
758 struct cryptocap *cap;
759
760 KASSERT(crypto_drivers != NULL);
761
762 if (hid >= crypto_drivers_num)
763 return NULL;
764
765 cap = &crypto_drivers[hid];
766 mutex_enter(&cap->cc_lock);
767 return cap;
768 }
769
770 /*
771 * Use crypto_checkdriver_uninit() instead of crypto_checkdriver() below two
772 * situations
773 * - crypto_drivers[] may not be allocated
774 * - crypto_drivers[hid] may not be initialized
775 */
776 static struct cryptocap *
777 crypto_checkdriver_uninit(u_int32_t hid)
778 {
779
780 KASSERT(mutex_owned(&crypto_drv_mtx));
781
782 if (crypto_drivers == NULL)
783 return NULL;
784
785 return (hid >= crypto_drivers_num ? NULL : &crypto_drivers[hid]);
786 }
787
788 /*
789 * Use crypto_checkdriver_uninit() instead of crypto_checkdriver() below two
790 * situations
791 * - crypto_drivers[] may not be allocated
792 * - crypto_drivers[hid] may not be initialized
793 */
794 static struct cryptocap *
795 crypto_checkdriver(u_int32_t hid)
796 {
797
798 KASSERT(mutex_owned(&crypto_drv_mtx));
799
800 if (crypto_drivers == NULL || hid >= crypto_drivers_num)
801 return NULL;
802
803 struct cryptocap *cap = &crypto_drivers[hid];
804 return crypto_checkdriver_initialized(cap) ? cap : NULL;
805 }
806
807 static inline void
808 crypto_driver_lock(struct cryptocap *cap)
809 {
810
811 KASSERT(cap != NULL);
812
813 mutex_enter(&cap->cc_lock);
814 }
815
816 static inline void
817 crypto_driver_unlock(struct cryptocap *cap)
818 {
819
820 KASSERT(cap != NULL);
821
822 mutex_exit(&cap->cc_lock);
823 }
824
825 static void
826 crypto_driver_clear(struct cryptocap *cap)
827 {
828
829 if (cap == NULL)
830 return;
831
832 KASSERT(mutex_owned(&cap->cc_lock));
833
834 cap->cc_sessions = 0;
835 memset(&cap->cc_max_op_len, 0, sizeof(cap->cc_max_op_len));
836 memset(&cap->cc_alg, 0, sizeof(cap->cc_alg));
837 memset(&cap->cc_kalg, 0, sizeof(cap->cc_kalg));
838 cap->cc_flags = 0;
839 cap->cc_qblocked = 0;
840 cap->cc_kqblocked = 0;
841
842 cap->cc_arg = NULL;
843 cap->cc_newsession = NULL;
844 cap->cc_process = NULL;
845 cap->cc_freesession = NULL;
846 cap->cc_kprocess = NULL;
847 }
848
849 /*
850 * Register support for a key-related algorithm. This routine
851 * is called once for each algorithm supported a driver.
852 */
853 int
854 crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags,
855 int (*kprocess)(void *, struct cryptkop *, int),
856 void *karg)
857 {
858 struct cryptocap *cap;
859 int err;
860
861 mutex_enter(&crypto_drv_mtx);
862
863 cap = crypto_checkdriver_lock(driverid);
864 if (cap != NULL &&
865 (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
866 /*
867 * XXX Do some performance testing to determine placing.
868 * XXX We probably need an auxiliary data structure that
869 * XXX describes relative performances.
870 */
871
872 cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
873 if (bootverbose) {
874 printf("crypto: driver %u registers key alg %u "
875 " flags %u\n",
876 driverid,
877 kalg,
878 flags
879 );
880 }
881
882 if (cap->cc_kprocess == NULL) {
883 cap->cc_karg = karg;
884 cap->cc_kprocess = kprocess;
885 }
886 err = 0;
887 } else
888 err = EINVAL;
889
890 mutex_exit(&crypto_drv_mtx);
891 return err;
892 }
893
894 /*
895 * Register support for a non-key-related algorithm. This routine
896 * is called once for each such algorithm supported by a driver.
897 */
898 int
899 crypto_register(u_int32_t driverid, int alg, u_int16_t maxoplen,
900 u_int32_t flags,
901 int (*newses)(void *, u_int32_t*, struct cryptoini*),
902 int (*freeses)(void *, u_int64_t),
903 int (*process)(void *, struct cryptop *, int),
904 void *arg)
905 {
906 struct cryptocap *cap;
907 int err;
908
909 cap = crypto_checkdriver_lock(driverid);
910 if (cap == NULL)
911 return EINVAL;
912
913 /* NB: algorithms are in the range [1..max] */
914 if (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX) {
915 /*
916 * XXX Do some performance testing to determine placing.
917 * XXX We probably need an auxiliary data structure that
918 * XXX describes relative performances.
919 */
920
921 cap->cc_alg[alg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
922 cap->cc_max_op_len[alg] = maxoplen;
923 if (bootverbose) {
924 printf("crypto: driver %u registers alg %u "
925 "flags %u maxoplen %u\n",
926 driverid,
927 alg,
928 flags,
929 maxoplen
930 );
931 }
932
933 if (cap->cc_process == NULL) {
934 cap->cc_arg = arg;
935 cap->cc_newsession = newses;
936 cap->cc_process = process;
937 cap->cc_freesession = freeses;
938 cap->cc_sessions = 0; /* Unmark */
939 }
940 err = 0;
941 } else
942 err = EINVAL;
943
944 crypto_driver_unlock(cap);
945
946 return err;
947 }
948
949 static int
950 crypto_unregister_locked(struct cryptocap *cap, int alg, bool all)
951 {
952 int i;
953 u_int32_t ses;
954 bool lastalg = true;
955
956 KASSERT(cap != NULL);
957 KASSERT(mutex_owned(&cap->cc_lock));
958
959 if (alg < CRYPTO_ALGORITHM_MIN || CRYPTO_ALGORITHM_MAX < alg)
960 return EINVAL;
961
962 if (!all && cap->cc_alg[alg] == 0)
963 return EINVAL;
964
965 cap->cc_alg[alg] = 0;
966 cap->cc_max_op_len[alg] = 0;
967
968 if (all) {
969 if (alg != CRYPTO_ALGORITHM_MAX)
970 lastalg = false;
971 } else {
972 /* Was this the last algorithm ? */
973 for (i = CRYPTO_ALGORITHM_MIN; i <= CRYPTO_ALGORITHM_MAX; i++)
974 if (cap->cc_alg[i] != 0) {
975 lastalg = false;
976 break;
977 }
978 }
979 if (lastalg) {
980 ses = cap->cc_sessions;
981 crypto_driver_clear(cap);
982 if (ses != 0) {
983 /*
984 * If there are pending sessions, just mark as invalid.
985 */
986 cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
987 cap->cc_sessions = ses;
988 }
989 }
990
991 return 0;
992 }
993
994 /*
995 * Unregister a crypto driver. If there are pending sessions using it,
996 * leave enough information around so that subsequent calls using those
997 * sessions will correctly detect the driver has been unregistered and
998 * reroute requests.
999 */
1000 int
1001 crypto_unregister(u_int32_t driverid, int alg)
1002 {
1003 int err;
1004 struct cryptocap *cap;
1005
1006 cap = crypto_checkdriver_lock(driverid);
1007 err = crypto_unregister_locked(cap, alg, false);
1008 crypto_driver_unlock(cap);
1009
1010 return err;
1011 }
1012
1013 /*
1014 * Unregister all algorithms associated with a crypto driver.
1015 * If there are pending sessions using it, leave enough information
1016 * around so that subsequent calls using those sessions will
1017 * correctly detect the driver has been unregistered and reroute
1018 * requests.
1019 */
1020 int
1021 crypto_unregister_all(u_int32_t driverid)
1022 {
1023 int err, i;
1024 struct cryptocap *cap;
1025
1026 cap = crypto_checkdriver_lock(driverid);
1027 for (i = CRYPTO_ALGORITHM_MIN; i <= CRYPTO_ALGORITHM_MAX; i++) {
1028 err = crypto_unregister_locked(cap, i, true);
1029 if (err)
1030 break;
1031 }
1032 crypto_driver_unlock(cap);
1033
1034 return err;
1035 }
1036
1037 /*
1038 * Clear blockage on a driver. The what parameter indicates whether
1039 * the driver is now ready for cryptop's and/or cryptokop's.
1040 */
1041 int
1042 crypto_unblock(u_int32_t driverid, int what)
1043 {
1044 struct cryptocap *cap;
1045 int needwakeup = 0;
1046
1047 cap = crypto_checkdriver_lock(driverid);
1048 if (cap == NULL)
1049 return EINVAL;
1050
1051 if (what & CRYPTO_SYMQ) {
1052 needwakeup |= cap->cc_qblocked;
1053 cap->cc_qblocked = 0;
1054 }
1055 if (what & CRYPTO_ASYMQ) {
1056 needwakeup |= cap->cc_kqblocked;
1057 cap->cc_kqblocked = 0;
1058 }
1059 crypto_driver_unlock(cap);
1060 if (needwakeup)
1061 setsoftcrypto(softintr_cookie);
1062
1063 return 0;
1064 }
1065
1066 /*
1067 * Dispatch a crypto request to a driver or queue
1068 * it, to be processed by the kernel thread.
1069 */
1070 int
1071 crypto_dispatch(struct cryptop *crp)
1072 {
1073 int result;
1074 struct cryptocap *cap;
1075
1076 KASSERT(crp != NULL);
1077
1078 DPRINTF("crp %p, alg %d\n", crp, crp->crp_desc->crd_alg);
1079
1080 cryptostats.cs_ops++;
1081
1082 #ifdef CRYPTO_TIMING
1083 if (crypto_timing)
1084 nanouptime(&crp->crp_tstamp);
1085 #endif
1086
1087 if ((crp->crp_flags & CRYPTO_F_BATCH) != 0) {
1088 int wasempty;
1089 /*
1090 * Caller marked the request as ``ok to delay'';
1091 * queue it for the swi thread. This is desirable
1092 * when the operation is low priority and/or suitable
1093 * for batching.
1094 *
1095 * don't care list order in batch job.
1096 */
1097 mutex_enter(&crypto_q_mtx);
1098 wasempty = TAILQ_EMPTY(&crp_q);
1099 TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
1100 mutex_exit(&crypto_q_mtx);
1101 if (wasempty)
1102 setsoftcrypto(softintr_cookie);
1103
1104 return 0;
1105 }
1106
1107 mutex_enter(&crypto_q_mtx);
1108 cap = crypto_checkdriver_lock(CRYPTO_SESID2HID(crp->crp_sid));
1109 /*
1110 * TODO:
1111 * If we can ensure the driver has been valid until the driver is
1112 * done crypto_unregister(), this migrate operation is not required.
1113 */
1114 if (cap == NULL) {
1115 /*
1116 * The driver must be detached, so this request will migrate
1117 * to other drivers in cryptointr() later.
1118 */
1119 TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
1120 mutex_exit(&crypto_q_mtx);
1121 return 0;
1122 }
1123
1124 if (cap->cc_qblocked != 0) {
1125 crypto_driver_unlock(cap);
1126 /*
1127 * The driver is blocked, just queue the op until
1128 * it unblocks and the swi thread gets kicked.
1129 */
1130 TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
1131 mutex_exit(&crypto_q_mtx);
1132 return 0;
1133 }
1134
1135 /*
1136 * Caller marked the request to be processed
1137 * immediately; dispatch it directly to the
1138 * driver unless the driver is currently blocked.
1139 */
1140 crypto_driver_unlock(cap);
1141 result = crypto_invoke(crp, 0);
1142 if (result == ERESTART) {
1143 /*
1144 * The driver ran out of resources, mark the
1145 * driver ``blocked'' for cryptop's and put
1146 * the op on the queue.
1147 */
1148 crypto_driver_lock(cap);
1149 cap->cc_qblocked = 1;
1150 crypto_driver_unlock(cap);
1151 TAILQ_INSERT_HEAD(&crp_q, crp, crp_next);
1152 cryptostats.cs_blocks++;
1153
1154 /*
1155 * The crp is enqueued to crp_q, that is,
1156 * no error occurs. So, this function should
1157 * not return error.
1158 */
1159 result = 0;
1160 }
1161
1162 mutex_exit(&crypto_q_mtx);
1163 return result;
1164 }
1165
1166 /*
1167 * Add an asymetric crypto request to a queue,
1168 * to be processed by the kernel thread.
1169 */
1170 int
1171 crypto_kdispatch(struct cryptkop *krp)
1172 {
1173 struct cryptocap *cap;
1174 int result;
1175
1176 KASSERT(krp != NULL);
1177
1178 cryptostats.cs_kops++;
1179
1180 mutex_enter(&crypto_q_mtx);
1181 cap = crypto_checkdriver_lock(krp->krp_hid);
1182 /*
1183 * TODO:
1184 * If we can ensure the driver has been valid until the driver is
1185 * done crypto_unregister(), this migrate operation is not required.
1186 */
1187 if (cap == NULL) {
1188 TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
1189 mutex_exit(&crypto_q_mtx);
1190 return 0;
1191 }
1192
1193 if (cap->cc_kqblocked != 0) {
1194 crypto_driver_unlock(cap);
1195 /*
1196 * The driver is blocked, just queue the op until
1197 * it unblocks and the swi thread gets kicked.
1198 */
1199 TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
1200 mutex_exit(&crypto_q_mtx);
1201 return 0;
1202 }
1203
1204 crypto_driver_unlock(cap);
1205 result = crypto_kinvoke(krp, 0);
1206 if (result == ERESTART) {
1207 /*
1208 * The driver ran out of resources, mark the
1209 * driver ``blocked'' for cryptop's and put
1210 * the op on the queue.
1211 */
1212 crypto_driver_lock(cap);
1213 cap->cc_kqblocked = 1;
1214 crypto_driver_unlock(cap);
1215 TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
1216 cryptostats.cs_kblocks++;
1217 mutex_exit(&crypto_q_mtx);
1218
1219 /*
1220 * The krp is enqueued to crp_kq, that is,
1221 * no error occurs. So, this function should
1222 * not return error.
1223 */
1224 result = 0;
1225 }
1226
1227 return result;
1228 }
1229
1230 /*
1231 * Dispatch an assymetric crypto request to the appropriate crypto devices.
1232 */
1233 static int
1234 crypto_kinvoke(struct cryptkop *krp, int hint)
1235 {
1236 struct cryptocap *cap = NULL;
1237 u_int32_t hid;
1238 int error;
1239
1240 KASSERT(krp != NULL);
1241
1242 /* Sanity checks. */
1243 if (krp->krp_callback == NULL) {
1244 cv_destroy(&krp->krp_cv);
1245 crypto_kfreereq(krp);
1246 return EINVAL;
1247 }
1248
1249 mutex_enter(&crypto_drv_mtx);
1250 for (hid = 0; hid < crypto_drivers_num; hid++) {
1251 cap = crypto_checkdriver(hid);
1252 if (cap == NULL)
1253 continue;
1254 crypto_driver_lock(cap);
1255 if ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
1256 crypto_devallowsoft == 0) {
1257 crypto_driver_unlock(cap);
1258 continue;
1259 }
1260 if (cap->cc_kprocess == NULL) {
1261 crypto_driver_unlock(cap);
1262 continue;
1263 }
1264 if ((cap->cc_kalg[krp->krp_op] &
1265 CRYPTO_ALG_FLAG_SUPPORTED) == 0) {
1266 crypto_driver_unlock(cap);
1267 continue;
1268 }
1269 break;
1270 }
1271 mutex_exit(&crypto_drv_mtx);
1272 if (cap != NULL) {
1273 int (*process)(void *, struct cryptkop *, int);
1274 void *arg;
1275
1276 process = cap->cc_kprocess;
1277 arg = cap->cc_karg;
1278 krp->krp_hid = hid;
1279 crypto_driver_unlock(cap);
1280 error = (*process)(arg, krp, hint);
1281 } else {
1282 error = ENODEV;
1283 }
1284
1285 if (error) {
1286 krp->krp_status = error;
1287 crypto_kdone(krp);
1288 }
1289 return 0;
1290 }
1291
1292 #ifdef CRYPTO_TIMING
1293 static void
1294 crypto_tstat(struct cryptotstat *ts, struct timespec *tv)
1295 {
1296 struct timespec now, t;
1297
1298 nanouptime(&now);
1299 t.tv_sec = now.tv_sec - tv->tv_sec;
1300 t.tv_nsec = now.tv_nsec - tv->tv_nsec;
1301 if (t.tv_nsec < 0) {
1302 t.tv_sec--;
1303 t.tv_nsec += 1000000000;
1304 }
1305 timespecadd(&ts->acc, &t, &t);
1306 if (timespeccmp(&t, &ts->min, <))
1307 ts->min = t;
1308 if (timespeccmp(&t, &ts->max, >))
1309 ts->max = t;
1310 ts->count++;
1311
1312 *tv = now;
1313 }
1314 #endif
1315
1316 /*
1317 * Dispatch a crypto request to the appropriate crypto devices.
1318 */
1319 static int
1320 crypto_invoke(struct cryptop *crp, int hint)
1321 {
1322 struct cryptocap *cap;
1323
1324 KASSERT(crp != NULL);
1325
1326 #ifdef CRYPTO_TIMING
1327 if (crypto_timing)
1328 crypto_tstat(&cryptostats.cs_invoke, &crp->crp_tstamp);
1329 #endif
1330 /* Sanity checks. */
1331 if (crp->crp_callback == NULL) {
1332 return EINVAL;
1333 }
1334 if (crp->crp_desc == NULL) {
1335 crp->crp_etype = EINVAL;
1336 crypto_done(crp);
1337 return 0;
1338 }
1339
1340 cap = crypto_checkdriver_lock(CRYPTO_SESID2HID(crp->crp_sid));
1341 if (cap != NULL && (cap->cc_flags & CRYPTOCAP_F_CLEANUP) == 0) {
1342 int (*process)(void *, struct cryptop *, int);
1343 void *arg;
1344
1345 process = cap->cc_process;
1346 arg = cap->cc_arg;
1347
1348 /*
1349 * Invoke the driver to process the request.
1350 */
1351 DPRINTF("calling process for %p\n", crp);
1352 crypto_driver_unlock(cap);
1353 return (*process)(arg, crp, hint);
1354 } else {
1355 struct cryptodesc *crd;
1356 u_int64_t nid = 0;
1357
1358 if (cap != NULL)
1359 crypto_driver_unlock(cap);
1360
1361 /*
1362 * Driver has unregistered; migrate the session and return
1363 * an error to the caller so they'll resubmit the op.
1364 */
1365 crypto_freesession(crp->crp_sid);
1366
1367 for (crd = crp->crp_desc; crd->crd_next; crd = crd->crd_next)
1368 crd->CRD_INI.cri_next = &(crd->crd_next->CRD_INI);
1369
1370 if (crypto_newsession(&nid, &(crp->crp_desc->CRD_INI), 0) == 0)
1371 crp->crp_sid = nid;
1372
1373 crp->crp_etype = EAGAIN;
1374
1375 crypto_done(crp);
1376 return 0;
1377 }
1378 }
1379
1380 /*
1381 * Release a set of crypto descriptors.
1382 */
1383 void
1384 crypto_freereq(struct cryptop *crp)
1385 {
1386 struct cryptodesc *crd;
1387
1388 if (crp == NULL)
1389 return;
1390 DPRINTF("lid[%u]: crp %p\n", CRYPTO_SESID2LID(crp->crp_sid), crp);
1391
1392 /* sanity check */
1393 if (crp->crp_flags & CRYPTO_F_ONRETQ) {
1394 panic("crypto_freereq() freeing crp on RETQ\n");
1395 }
1396
1397 while ((crd = crp->crp_desc) != NULL) {
1398 crp->crp_desc = crd->crd_next;
1399 pool_put(&cryptodesc_pool, crd);
1400 }
1401 pool_put(&cryptop_pool, crp);
1402 }
1403
1404 /*
1405 * Acquire a set of crypto descriptors.
1406 */
1407 struct cryptop *
1408 crypto_getreq(int num)
1409 {
1410 struct cryptodesc *crd;
1411 struct cryptop *crp;
1412
1413 /*
1414 * When crp_ret_q is full, we restrict here to avoid crp_ret_q overflow
1415 * by error callback.
1416 */
1417 if (CRYPTO_Q_IS_FULL(crp_ret_q)) {
1418 CRYPTO_Q_INC_DROPS(crp_ret_q);
1419 return NULL;
1420 }
1421
1422 crp = pool_get(&cryptop_pool, 0);
1423 if (crp == NULL) {
1424 return NULL;
1425 }
1426 memset(crp, 0, sizeof(struct cryptop));
1427
1428 while (num--) {
1429 crd = pool_get(&cryptodesc_pool, 0);
1430 if (crd == NULL) {
1431 crypto_freereq(crp);
1432 return NULL;
1433 }
1434
1435 memset(crd, 0, sizeof(struct cryptodesc));
1436 crd->crd_next = crp->crp_desc;
1437 crp->crp_desc = crd;
1438 }
1439
1440 return crp;
1441 }
1442
1443 /*
1444 * Release a set of asymmetric crypto descriptors.
1445 * Currently, support one descriptor only.
1446 */
1447 void
1448 crypto_kfreereq(struct cryptkop *krp)
1449 {
1450
1451 if (krp == NULL)
1452 return;
1453
1454 DPRINTF("krp %p\n", krp);
1455
1456 /* sanity check */
1457 if (krp->krp_flags & CRYPTO_F_ONRETQ) {
1458 panic("crypto_kfreereq() freeing krp on RETQ\n");
1459 }
1460
1461 pool_put(&cryptkop_pool, krp);
1462 }
1463
1464 /*
1465 * Acquire a set of asymmetric crypto descriptors.
1466 * Currently, support one descriptor only.
1467 */
1468 struct cryptkop *
1469 crypto_kgetreq(int num __unused, int prflags)
1470 {
1471 struct cryptkop *krp;
1472
1473 /*
1474 * When crp_ret_kq is full, we restrict here to avoid crp_ret_kq
1475 * overflow by error callback.
1476 */
1477 if (CRYPTO_Q_IS_FULL(crp_ret_kq)) {
1478 CRYPTO_Q_INC_DROPS(crp_ret_kq);
1479 return NULL;
1480 }
1481
1482 krp = pool_get(&cryptkop_pool, prflags);
1483 if (krp == NULL) {
1484 return NULL;
1485 }
1486 memset(krp, 0, sizeof(struct cryptkop));
1487
1488 return krp;
1489 }
1490
1491 /*
1492 * Invoke the callback on behalf of the driver.
1493 */
1494 void
1495 crypto_done(struct cryptop *crp)
1496 {
1497
1498 KASSERT(crp != NULL);
1499
1500 if (crp->crp_etype != 0)
1501 cryptostats.cs_errs++;
1502 #ifdef CRYPTO_TIMING
1503 if (crypto_timing)
1504 crypto_tstat(&cryptostats.cs_done, &crp->crp_tstamp);
1505 #endif
1506 DPRINTF("lid[%u]: crp %p\n", CRYPTO_SESID2LID(crp->crp_sid), crp);
1507
1508 /*
1509 * Normal case; queue the callback for the thread.
1510 *
1511 * The return queue is manipulated by the swi thread
1512 * and, potentially, by crypto device drivers calling
1513 * back to mark operations completed. Thus we need
1514 * to mask both while manipulating the return queue.
1515 */
1516 if (crp->crp_flags & CRYPTO_F_CBIMM) {
1517 /*
1518 * Do the callback directly. This is ok when the
1519 * callback routine does very little (e.g. the
1520 * /dev/crypto callback method just does a wakeup).
1521 */
1522 crp->crp_flags |= CRYPTO_F_DONE;
1523
1524 #ifdef CRYPTO_TIMING
1525 if (crypto_timing) {
1526 /*
1527 * NB: We must copy the timestamp before
1528 * doing the callback as the cryptop is
1529 * likely to be reclaimed.
1530 */
1531 struct timespec t = crp->crp_tstamp;
1532 crypto_tstat(&cryptostats.cs_cb, &t);
1533 crp->crp_callback(crp);
1534 crypto_tstat(&cryptostats.cs_finis, &t);
1535 } else
1536 #endif
1537 crp->crp_callback(crp);
1538 } else {
1539 crp->crp_flags |= CRYPTO_F_DONE;
1540 #if 0
1541 if (crp->crp_flags & CRYPTO_F_USER) {
1542 /*
1543 * TODO:
1544 * If crp->crp_flags & CRYPTO_F_USER and the used
1545 * encryption driver does all the processing in
1546 * the same context, we can skip enqueueing crp_ret_q
1547 * and cv_signal(&cryptoret_cv).
1548 */
1549 DPRINTF("lid[%u]: crp %p CRYPTO_F_USER\n",
1550 CRYPTO_SESID2LID(crp->crp_sid), crp);
1551 } else
1552 #endif
1553 {
1554 int wasempty;
1555
1556 mutex_spin_enter(&crypto_ret_q_mtx);
1557 wasempty = TAILQ_EMPTY(&crp_ret_q);
1558 DPRINTF("lid[%u]: queueing %p\n",
1559 CRYPTO_SESID2LID(crp->crp_sid), crp);
1560 crp->crp_flags |= CRYPTO_F_ONRETQ;
1561 TAILQ_INSERT_TAIL(&crp_ret_q, crp, crp_next);
1562 CRYPTO_Q_INC(crp_ret_q);
1563 if (wasempty) {
1564 DPRINTF("lid[%u]: waking cryptoret, "
1565 "crp %p hit empty queue\n.",
1566 CRYPTO_SESID2LID(crp->crp_sid), crp);
1567 cv_signal(&cryptoret_cv);
1568 }
1569 mutex_spin_exit(&crypto_ret_q_mtx);
1570 }
1571 }
1572 }
1573
1574 /*
1575 * Invoke the callback on behalf of the driver.
1576 */
1577 void
1578 crypto_kdone(struct cryptkop *krp)
1579 {
1580
1581 KASSERT(krp != NULL);
1582
1583 if (krp->krp_status != 0)
1584 cryptostats.cs_kerrs++;
1585
1586 krp->krp_flags |= CRYPTO_F_DONE;
1587
1588 /*
1589 * The return queue is manipulated by the swi thread
1590 * and, potentially, by crypto device drivers calling
1591 * back to mark operations completed. Thus we need
1592 * to mask both while manipulating the return queue.
1593 */
1594 if (krp->krp_flags & CRYPTO_F_CBIMM) {
1595 krp->krp_callback(krp);
1596 } else {
1597 int wasempty;
1598
1599 mutex_spin_enter(&crypto_ret_q_mtx);
1600 wasempty = TAILQ_EMPTY(&crp_ret_kq);
1601 krp->krp_flags |= CRYPTO_F_ONRETQ;
1602 TAILQ_INSERT_TAIL(&crp_ret_kq, krp, krp_next);
1603 CRYPTO_Q_INC(crp_ret_kq);
1604 if (wasempty)
1605 cv_signal(&cryptoret_cv);
1606 mutex_spin_exit(&crypto_ret_q_mtx);
1607 }
1608 }
1609
1610 int
1611 crypto_getfeat(int *featp)
1612 {
1613
1614 if (crypto_userasymcrypto == 0) {
1615 *featp = 0;
1616 return 0;
1617 }
1618
1619 mutex_enter(&crypto_drv_mtx);
1620
1621 int feat = 0;
1622 for (int hid = 0; hid < crypto_drivers_num; hid++) {
1623 struct cryptocap *cap;
1624 cap = crypto_checkdriver(hid);
1625 if (cap == NULL)
1626 continue;
1627
1628 crypto_driver_lock(cap);
1629
1630 if ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
1631 crypto_devallowsoft == 0)
1632 goto unlock;
1633
1634 if (cap->cc_kprocess == NULL)
1635 goto unlock;
1636
1637 for (int kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
1638 if ((cap->cc_kalg[kalg] &
1639 CRYPTO_ALG_FLAG_SUPPORTED) != 0)
1640 feat |= 1 << kalg;
1641
1642 unlock: crypto_driver_unlock(cap);
1643 }
1644
1645 mutex_exit(&crypto_drv_mtx);
1646 *featp = feat;
1647 return (0);
1648 }
1649
1650 /*
1651 * Software interrupt thread to dispatch crypto requests.
1652 */
1653 static void
1654 cryptointr(void)
1655 {
1656 struct cryptop *crp, *submit, *cnext;
1657 struct cryptkop *krp, *knext;
1658 struct cryptocap *cap;
1659 int result, hint;
1660
1661 cryptostats.cs_intrs++;
1662 mutex_enter(&crypto_q_mtx);
1663 do {
1664 /*
1665 * Find the first element in the queue that can be
1666 * processed and look-ahead to see if multiple ops
1667 * are ready for the same driver.
1668 */
1669 submit = NULL;
1670 hint = 0;
1671 TAILQ_FOREACH_SAFE(crp, &crp_q, crp_next, cnext) {
1672 u_int32_t hid = CRYPTO_SESID2HID(crp->crp_sid);
1673 cap = crypto_checkdriver_lock(hid);
1674 if (cap == NULL || cap->cc_process == NULL) {
1675 if (cap != NULL)
1676 crypto_driver_unlock(cap);
1677 /* Op needs to be migrated, process it. */
1678 submit = crp;
1679 break;
1680 }
1681
1682 /*
1683 * skip blocked crp regardless of CRYPTO_F_BATCH
1684 */
1685 if (cap->cc_qblocked != 0) {
1686 crypto_driver_unlock(cap);
1687 continue;
1688 }
1689 crypto_driver_unlock(cap);
1690
1691 /*
1692 * skip batch crp until the end of crp_q
1693 */
1694 if ((crp->crp_flags & CRYPTO_F_BATCH) != 0) {
1695 if (submit == NULL) {
1696 submit = crp;
1697 } else {
1698 if (CRYPTO_SESID2HID(submit->crp_sid)
1699 == hid)
1700 hint = CRYPTO_HINT_MORE;
1701 }
1702
1703 continue;
1704 }
1705
1706 /*
1707 * found first crp which is neither blocked nor batch.
1708 */
1709 submit = crp;
1710 /*
1711 * batch crp can be processed much later, so clear hint.
1712 */
1713 hint = 0;
1714 break;
1715 }
1716 if (submit != NULL) {
1717 TAILQ_REMOVE(&crp_q, submit, crp_next);
1718 result = crypto_invoke(submit, hint);
1719 /* we must take here as the TAILQ op or kinvoke
1720 may need this mutex below. sigh. */
1721 if (result == ERESTART) {
1722 /*
1723 * The driver ran out of resources, mark the
1724 * driver ``blocked'' for cryptop's and put
1725 * the request back in the queue. It would
1726 * best to put the request back where we got
1727 * it but that's hard so for now we put it
1728 * at the front. This should be ok; putting
1729 * it at the end does not work.
1730 */
1731 /* validate sid again */
1732 cap = crypto_checkdriver_lock(CRYPTO_SESID2HID(submit->crp_sid));
1733 if (cap == NULL) {
1734 /* migrate again, sigh... */
1735 TAILQ_INSERT_TAIL(&crp_q, submit, crp_next);
1736 } else {
1737 cap->cc_qblocked = 1;
1738 crypto_driver_unlock(cap);
1739 TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
1740 cryptostats.cs_blocks++;
1741 }
1742 }
1743 }
1744
1745 /* As above, but for key ops */
1746 TAILQ_FOREACH_SAFE(krp, &crp_kq, krp_next, knext) {
1747 cap = crypto_checkdriver_lock(krp->krp_hid);
1748 if (cap == NULL || cap->cc_kprocess == NULL) {
1749 if (cap != NULL)
1750 crypto_driver_unlock(cap);
1751 /* Op needs to be migrated, process it. */
1752 break;
1753 }
1754 if (!cap->cc_kqblocked) {
1755 crypto_driver_unlock(cap);
1756 break;
1757 }
1758 crypto_driver_unlock(cap);
1759 }
1760 if (krp != NULL) {
1761 TAILQ_REMOVE(&crp_kq, krp, krp_next);
1762 result = crypto_kinvoke(krp, 0);
1763 /* the next iteration will want the mutex. :-/ */
1764 if (result == ERESTART) {
1765 /*
1766 * The driver ran out of resources, mark the
1767 * driver ``blocked'' for cryptkop's and put
1768 * the request back in the queue. It would
1769 * best to put the request back where we got
1770 * it but that's hard so for now we put it
1771 * at the front. This should be ok; putting
1772 * it at the end does not work.
1773 */
1774 /* validate sid again */
1775 cap = crypto_checkdriver_lock(krp->krp_hid);
1776 if (cap == NULL) {
1777 /* migrate again, sigh... */
1778 TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
1779 } else {
1780 cap->cc_kqblocked = 1;
1781 crypto_driver_unlock(cap);
1782 TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
1783 cryptostats.cs_kblocks++;
1784 }
1785 }
1786 }
1787 } while (submit != NULL || krp != NULL);
1788 mutex_exit(&crypto_q_mtx);
1789 }
1790
1791 /*
1792 * Kernel thread to do callbacks.
1793 */
1794 static void
1795 cryptoret(void)
1796 {
1797 struct cryptop *crp;
1798 struct cryptkop *krp;
1799
1800 mutex_spin_enter(&crypto_ret_q_mtx);
1801 for (;;) {
1802 crp = TAILQ_FIRST(&crp_ret_q);
1803 if (crp != NULL) {
1804 TAILQ_REMOVE(&crp_ret_q, crp, crp_next);
1805 CRYPTO_Q_DEC(crp_ret_q);
1806 crp->crp_flags &= ~CRYPTO_F_ONRETQ;
1807 }
1808 krp = TAILQ_FIRST(&crp_ret_kq);
1809 if (krp != NULL) {
1810 TAILQ_REMOVE(&crp_ret_kq, krp, krp_next);
1811 CRYPTO_Q_DEC(crp_ret_kq);
1812 krp->krp_flags &= ~CRYPTO_F_ONRETQ;
1813 }
1814
1815 /* drop before calling any callbacks. */
1816 if (crp == NULL && krp == NULL) {
1817
1818 /* Check for the exit condition. */
1819 if (crypto_exit_flag != 0) {
1820
1821 /* Time to die. */
1822 crypto_exit_flag = 0;
1823 cv_broadcast(&cryptoret_cv);
1824 mutex_spin_exit(&crypto_ret_q_mtx);
1825 kthread_exit(0);
1826 }
1827
1828 cryptostats.cs_rets++;
1829 cv_wait(&cryptoret_cv, &crypto_ret_q_mtx);
1830 continue;
1831 }
1832
1833 mutex_spin_exit(&crypto_ret_q_mtx);
1834
1835 if (crp != NULL) {
1836 #ifdef CRYPTO_TIMING
1837 if (crypto_timing) {
1838 /*
1839 * NB: We must copy the timestamp before
1840 * doing the callback as the cryptop is
1841 * likely to be reclaimed.
1842 */
1843 struct timespec t = crp->crp_tstamp;
1844 crypto_tstat(&cryptostats.cs_cb, &t);
1845 crp->crp_callback(crp);
1846 crypto_tstat(&cryptostats.cs_finis, &t);
1847 } else
1848 #endif
1849 {
1850 crp->crp_callback(crp);
1851 }
1852 }
1853 if (krp != NULL)
1854 krp->krp_callback(krp);
1855
1856 mutex_spin_enter(&crypto_ret_q_mtx);
1857 }
1858 }
1859
1860 /* NetBSD module interface */
1861
1862 MODULE(MODULE_CLASS_MISC, opencrypto, NULL);
1863
1864 static int
1865 opencrypto_modcmd(modcmd_t cmd, void *opaque)
1866 {
1867 int error = 0;
1868
1869 switch (cmd) {
1870 case MODULE_CMD_INIT:
1871 #ifdef _MODULE
1872 error = crypto_init();
1873 #endif
1874 break;
1875 case MODULE_CMD_FINI:
1876 #ifdef _MODULE
1877 error = crypto_destroy(true);
1878 #endif
1879 break;
1880 default:
1881 error = ENOTTY;
1882 }
1883 return error;
1884 }
1885