2 * Copyright (c) 2002-2006 Sam Leffler. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 #include <sys/cdefs.h>
26 __FBSDID("$FreeBSD$");
29 * Cryptographic Subsystem.
31 * This code is derived from the Openbsd Cryptographic Framework (OCF)
32 * that has the copyright shown below. Very little of the original
37 * The author of this code is Angelos D. Keromytis (angelos@cis.upenn.edu)
39 * This code was written by Angelos D. Keromytis in Athens, Greece, in
40 * February 2000. Network Security Technologies Inc. (NSTI) kindly
41 * supported the development of this code.
43 * Copyright (c) 2000, 2001 Angelos D. Keromytis
45 * Permission to use, copy, and modify this software with or without fee
46 * is hereby granted, provided that this entire notice is included in
47 * all source code copies of any software which is or includes a copy or
48 * modification of this software.
50 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
51 * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
52 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
53 * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
57 #define CRYPTO_TIMING /* enable timing support */
61 #include <sys/param.h>
62 #include <sys/systm.h>
63 #include <sys/eventhandler.h>
64 #include <sys/kernel.h>
65 #include <sys/kthread.h>
66 #include <sys/linker.h>
68 #include <sys/module.h>
69 #include <sys/mutex.h>
70 #include <sys/malloc.h>
73 #include <sys/sysctl.h>
78 #include <crypto/intake.h>
79 #include <opencrypto/cryptodev.h>
80 #include <opencrypto/xform.h> /* XXX for M_XDATA */
84 #include "cryptodev_if.h"
86 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
87 #include <machine/pcb.h>
90 SDT_PROVIDER_DEFINE(opencrypto);
93 * Crypto drivers register themselves by allocating a slot in the
94 * crypto_drivers table with crypto_get_driverid() and then registering
95 * each algorithm they support with crypto_register() and crypto_kregister().
97 static struct mtx crypto_drivers_mtx; /* lock on driver table */
98 #define CRYPTO_DRIVER_LOCK() mtx_lock(&crypto_drivers_mtx)
99 #define CRYPTO_DRIVER_UNLOCK() mtx_unlock(&crypto_drivers_mtx)
100 #define CRYPTO_DRIVER_ASSERT() mtx_assert(&crypto_drivers_mtx, MA_OWNED)
103 * Crypto device/driver capabilities structure.
106 * (d) - protected by CRYPTO_DRIVER_LOCK()
107 * (q) - protected by CRYPTO_Q_LOCK()
108 * Not tagged fields are read-only.
111 device_t cc_dev; /* (d) device/driver */
112 u_int32_t cc_sessions; /* (d) # of sessions */
113 u_int32_t cc_koperations; /* (d) # os asym operations */
115 * Largest possible operator length (in bits) for each type of
116 * encryption algorithm. XXX not used
118 u_int16_t cc_max_op_len[CRYPTO_ALGORITHM_MAX + 1];
119 u_int8_t cc_alg[CRYPTO_ALGORITHM_MAX + 1];
120 u_int8_t cc_kalg[CRK_ALGORITHM_MAX + 1];
122 int cc_flags; /* (d) flags */
123 #define CRYPTOCAP_F_CLEANUP 0x80000000 /* needs resource cleanup */
124 int cc_qblocked; /* (q) symmetric q blocked */
125 int cc_kqblocked; /* (q) asymmetric q blocked */
127 static struct cryptocap *crypto_drivers = NULL;
128 static int crypto_drivers_num = 0;
131 * There are two queues for crypto requests; one for symmetric (e.g.
132 * cipher) operations and one for asymmetric (e.g. MOD)operations.
133 * A single mutex is used to lock access to both queues. We could
134 * have one per-queue but having one simplifies handling of block/unblock
137 static int crp_sleep = 0;
138 static TAILQ_HEAD(,cryptop) crp_q; /* request queues */
139 static TAILQ_HEAD(,cryptkop) crp_kq;
140 static struct mtx crypto_q_mtx;
141 #define CRYPTO_Q_LOCK() mtx_lock(&crypto_q_mtx)
142 #define CRYPTO_Q_UNLOCK() mtx_unlock(&crypto_q_mtx)
145 * There are two queues for processing completed crypto requests; one
146 * for the symmetric and one for the asymmetric ops. We only need one
147 * but have two to avoid type futzing (cryptop vs. cryptkop). A single
148 * mutex is used to lock access to both queues. Note that this lock
149 * must be separate from the lock on request queues to insure driver
150 * callbacks don't generate lock order reversals.
152 static TAILQ_HEAD(,cryptop) crp_ret_q; /* callback queues */
153 static TAILQ_HEAD(,cryptkop) crp_ret_kq;
154 static struct mtx crypto_ret_q_mtx;
155 #define CRYPTO_RETQ_LOCK() mtx_lock(&crypto_ret_q_mtx)
156 #define CRYPTO_RETQ_UNLOCK() mtx_unlock(&crypto_ret_q_mtx)
157 #define CRYPTO_RETQ_EMPTY() (TAILQ_EMPTY(&crp_ret_q) && TAILQ_EMPTY(&crp_ret_kq))
159 static uma_zone_t cryptop_zone;
160 static uma_zone_t cryptodesc_zone;
162 int crypto_userasymcrypto = 1; /* userland may do asym crypto reqs */
163 SYSCTL_INT(_kern, OID_AUTO, userasymcrypto, CTLFLAG_RW,
164 &crypto_userasymcrypto, 0,
165 "Enable/disable user-mode access to asymmetric crypto support");
166 int crypto_devallowsoft = 0; /* only use hardware crypto */
167 SYSCTL_INT(_kern, OID_AUTO, cryptodevallowsoft, CTLFLAG_RW,
168 &crypto_devallowsoft, 0,
169 "Enable/disable use of software crypto by /dev/crypto");
171 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
173 static void crypto_proc(void);
174 static struct proc *cryptoproc;
175 static void crypto_ret_proc(void);
176 static struct proc *cryptoretproc;
177 static void crypto_destroy(void);
178 static int crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint);
179 static int crypto_kinvoke(struct cryptkop *krp, int flags);
181 static struct cryptostats cryptostats;
182 SYSCTL_STRUCT(_kern, OID_AUTO, crypto_stats, CTLFLAG_RW, &cryptostats,
183 cryptostats, "Crypto system statistics");
186 static int crypto_timing = 0;
187 SYSCTL_INT(_debug, OID_AUTO, crypto_timing, CTLFLAG_RW,
188 &crypto_timing, 0, "Enable/disable crypto timing support");
191 /* Try to avoid directly exposing the key buffer as a symbol */
192 static struct keybuf *keybuf;
194 static struct keybuf empty_keybuf = {
198 /* Obtain the key buffer from boot metadata */
204 kmdp = preload_search_by_type("elf kernel");
207 kmdp = preload_search_by_type("elf64 kernel");
209 keybuf = (struct keybuf *)preload_search_info(kmdp,
210 MODINFO_METADATA | MODINFOMD_KEYBUF);
213 keybuf = &empty_keybuf;
216 /* It'd be nice if we could store these in some kind of secure memory... */
217 struct keybuf * get_keybuf(void) {
227 mtx_init(&crypto_drivers_mtx, "crypto", "crypto driver table",
232 mtx_init(&crypto_q_mtx, "crypto", "crypto op queues", MTX_DEF);
234 TAILQ_INIT(&crp_ret_q);
235 TAILQ_INIT(&crp_ret_kq);
236 mtx_init(&crypto_ret_q_mtx, "crypto", "crypto return queues", MTX_DEF);
238 cryptop_zone = uma_zcreate("cryptop", sizeof (struct cryptop),
240 UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
241 cryptodesc_zone = uma_zcreate("cryptodesc", sizeof (struct cryptodesc),
243 UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
244 if (cryptodesc_zone == NULL || cryptop_zone == NULL) {
245 printf("crypto_init: cannot setup crypto zones\n");
250 crypto_drivers_num = CRYPTO_DRIVERS_INITIAL;
251 crypto_drivers = malloc(crypto_drivers_num *
252 sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT | M_ZERO);
253 if (crypto_drivers == NULL) {
254 printf("crypto_init: cannot setup crypto drivers\n");
259 error = kproc_create((void (*)(void *)) crypto_proc, NULL,
260 &cryptoproc, 0, 0, "crypto");
262 printf("crypto_init: cannot start crypto thread; error %d",
267 error = kproc_create((void (*)(void *)) crypto_ret_proc, NULL,
268 &cryptoretproc, 0, 0, "crypto returns");
270 printf("crypto_init: cannot start cryptoret thread; error %d",
284 * Signal a crypto thread to terminate. We use the driver
285 * table lock to synchronize the sleep/wakeups so that we
286 * are sure the threads have terminated before we release
287 * the data structures they use. See crypto_finis below
288 * for the other half of this song-and-dance.
291 crypto_terminate(struct proc **pp, void *q)
295 mtx_assert(&crypto_drivers_mtx, MA_OWNED);
300 PROC_LOCK(p); /* NB: insure we don't miss wakeup */
301 CRYPTO_DRIVER_UNLOCK(); /* let crypto_finis progress */
302 msleep(p, &p->p_mtx, PWAIT, "crypto_destroy", 0);
304 CRYPTO_DRIVER_LOCK();
312 * Terminate any crypto threads.
314 CRYPTO_DRIVER_LOCK();
315 crypto_terminate(&cryptoproc, &crp_q);
316 crypto_terminate(&cryptoretproc, &crp_ret_q);
317 CRYPTO_DRIVER_UNLOCK();
319 /* XXX flush queues??? */
322 * Reclaim dynamically allocated resources.
324 if (crypto_drivers != NULL)
325 free(crypto_drivers, M_CRYPTO_DATA);
327 if (cryptodesc_zone != NULL)
328 uma_zdestroy(cryptodesc_zone);
329 if (cryptop_zone != NULL)
330 uma_zdestroy(cryptop_zone);
331 mtx_destroy(&crypto_q_mtx);
332 mtx_destroy(&crypto_ret_q_mtx);
333 mtx_destroy(&crypto_drivers_mtx);
336 static struct cryptocap *
337 crypto_checkdriver(u_int32_t hid)
339 if (crypto_drivers == NULL)
341 return (hid >= crypto_drivers_num ? NULL : &crypto_drivers[hid]);
345 * Compare a driver's list of supported algorithms against another
346 * list; return non-zero if all algorithms are supported.
349 driver_suitable(const struct cryptocap *cap, const struct cryptoini *cri)
351 const struct cryptoini *cr;
353 /* See if all the algorithms are supported. */
354 for (cr = cri; cr; cr = cr->cri_next)
355 if (cap->cc_alg[cr->cri_alg] == 0)
361 * Select a driver for a new session that supports the specified
362 * algorithms and, optionally, is constrained according to the flags.
363 * The algorithm we use here is pretty stupid; just use the
364 * first driver that supports all the algorithms we need. If there
365 * are multiple drivers we choose the driver with the fewest active
366 * sessions. We prefer hardware-backed drivers to software ones.
368 * XXX We need more smarts here (in real life too, but that's
369 * XXX another story altogether).
371 static struct cryptocap *
372 crypto_select_driver(const struct cryptoini *cri, int flags)
374 struct cryptocap *cap, *best;
377 CRYPTO_DRIVER_ASSERT();
380 * Look first for hardware crypto devices if permitted.
382 if (flags & CRYPTOCAP_F_HARDWARE)
383 match = CRYPTOCAP_F_HARDWARE;
385 match = CRYPTOCAP_F_SOFTWARE;
388 for (hid = 0; hid < crypto_drivers_num; hid++) {
389 cap = &crypto_drivers[hid];
391 * If it's not initialized, is in the process of
392 * going away, or is not appropriate (hardware
393 * or software based on match), then skip.
395 if (cap->cc_dev == NULL ||
396 (cap->cc_flags & CRYPTOCAP_F_CLEANUP) ||
397 (cap->cc_flags & match) == 0)
400 /* verify all the algorithms are supported. */
401 if (driver_suitable(cap, cri)) {
403 cap->cc_sessions < best->cc_sessions)
407 if (best == NULL && match == CRYPTOCAP_F_HARDWARE &&
408 (flags & CRYPTOCAP_F_SOFTWARE)) {
409 /* sort of an Algol 68-style for loop */
410 match = CRYPTOCAP_F_SOFTWARE;
417 * Create a new session. The crid argument specifies a crypto
418 * driver to use or constraints on a driver to select (hardware
419 * only, software only, either). Whatever driver is selected
420 * must be capable of the requested crypto algorithms.
423 crypto_newsession(u_int64_t *sid, struct cryptoini *cri, int crid)
425 struct cryptocap *cap;
429 CRYPTO_DRIVER_LOCK();
430 if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
432 * Use specified driver; verify it is capable.
434 cap = crypto_checkdriver(crid);
435 if (cap != NULL && !driver_suitable(cap, cri))
439 * No requested driver; select based on crid flags.
441 cap = crypto_select_driver(cri, crid);
443 * if NULL then can't do everything in one session.
444 * XXX Fix this. We need to inject a "virtual" session
445 * XXX layer right about here.
449 /* Call the driver initialization routine. */
450 hid = cap - crypto_drivers;
451 lid = hid; /* Pass the driver ID. */
452 err = CRYPTODEV_NEWSESSION(cap->cc_dev, &lid, cri);
454 (*sid) = (cap->cc_flags & 0xff000000)
455 | (hid & 0x00ffffff);
457 (*sid) |= (lid & 0xffffffff);
460 CRYPTDEB("dev newsession failed");
462 CRYPTDEB("no driver");
465 CRYPTO_DRIVER_UNLOCK();
470 crypto_remove(struct cryptocap *cap)
473 mtx_assert(&crypto_drivers_mtx, MA_OWNED);
474 if (cap->cc_sessions == 0 && cap->cc_koperations == 0)
475 bzero(cap, sizeof(*cap));
479 * Delete an existing session (or a reserved session on an unregistered
483 crypto_freesession(u_int64_t sid)
485 struct cryptocap *cap;
489 CRYPTO_DRIVER_LOCK();
491 if (crypto_drivers == NULL) {
496 /* Determine two IDs. */
497 hid = CRYPTO_SESID2HID(sid);
499 if (hid >= crypto_drivers_num) {
503 cap = &crypto_drivers[hid];
505 if (cap->cc_sessions)
508 /* Call the driver cleanup routine, if available. */
509 err = CRYPTODEV_FREESESSION(cap->cc_dev, sid);
511 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP)
515 CRYPTO_DRIVER_UNLOCK();
520 * Return an unused driver id. Used by drivers prior to registering
521 * support for the algorithms they handle.
524 crypto_get_driverid(device_t dev, int flags)
526 struct cryptocap *newdrv;
529 if ((flags & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
530 printf("%s: no flags specified when registering driver\n",
531 device_get_nameunit(dev));
535 CRYPTO_DRIVER_LOCK();
537 for (i = 0; i < crypto_drivers_num; i++) {
538 if (crypto_drivers[i].cc_dev == NULL &&
539 (crypto_drivers[i].cc_flags & CRYPTOCAP_F_CLEANUP) == 0) {
544 /* Out of entries, allocate some more. */
545 if (i == crypto_drivers_num) {
546 /* Be careful about wrap-around. */
547 if (2 * crypto_drivers_num <= crypto_drivers_num) {
548 CRYPTO_DRIVER_UNLOCK();
549 printf("crypto: driver count wraparound!\n");
553 newdrv = malloc(2 * crypto_drivers_num *
554 sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT|M_ZERO);
555 if (newdrv == NULL) {
556 CRYPTO_DRIVER_UNLOCK();
557 printf("crypto: no space to expand driver table!\n");
561 bcopy(crypto_drivers, newdrv,
562 crypto_drivers_num * sizeof(struct cryptocap));
564 crypto_drivers_num *= 2;
566 free(crypto_drivers, M_CRYPTO_DATA);
567 crypto_drivers = newdrv;
570 /* NB: state is zero'd on free */
571 crypto_drivers[i].cc_sessions = 1; /* Mark */
572 crypto_drivers[i].cc_dev = dev;
573 crypto_drivers[i].cc_flags = flags;
575 printf("crypto: assign %s driver id %u, flags %u\n",
576 device_get_nameunit(dev), i, flags);
578 CRYPTO_DRIVER_UNLOCK();
584 * Lookup a driver by name. We match against the full device
585 * name and unit, and against just the name. The latter gives
586 * us a simple widlcarding by device name. On success return the
587 * driver/hardware identifier; otherwise return -1.
590 crypto_find_driver(const char *match)
592 int i, len = strlen(match);
594 CRYPTO_DRIVER_LOCK();
595 for (i = 0; i < crypto_drivers_num; i++) {
596 device_t dev = crypto_drivers[i].cc_dev;
598 (crypto_drivers[i].cc_flags & CRYPTOCAP_F_CLEANUP))
600 if (strncmp(match, device_get_nameunit(dev), len) == 0 ||
601 strncmp(match, device_get_name(dev), len) == 0)
604 CRYPTO_DRIVER_UNLOCK();
605 return i < crypto_drivers_num ? i : -1;
609 * Return the device_t for the specified driver or NULL
610 * if the driver identifier is invalid.
613 crypto_find_device_byhid(int hid)
615 struct cryptocap *cap = crypto_checkdriver(hid);
616 return cap != NULL ? cap->cc_dev : NULL;
620 * Return the device/driver capabilities.
623 crypto_getcaps(int hid)
625 struct cryptocap *cap = crypto_checkdriver(hid);
626 return cap != NULL ? cap->cc_flags : 0;
630 * Register support for a key-related algorithm. This routine
631 * is called once for each algorithm supported a driver.
634 crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags)
636 struct cryptocap *cap;
639 CRYPTO_DRIVER_LOCK();
641 cap = crypto_checkdriver(driverid);
643 (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
645 * XXX Do some performance testing to determine placing.
646 * XXX We probably need an auxiliary data structure that
647 * XXX describes relative performances.
650 cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
652 printf("crypto: %s registers key alg %u flags %u\n"
653 , device_get_nameunit(cap->cc_dev)
661 CRYPTO_DRIVER_UNLOCK();
666 * Register support for a non-key-related algorithm. This routine
667 * is called once for each such algorithm supported by a driver.
670 crypto_register(u_int32_t driverid, int alg, u_int16_t maxoplen,
673 struct cryptocap *cap;
676 CRYPTO_DRIVER_LOCK();
678 cap = crypto_checkdriver(driverid);
679 /* NB: algorithms are in the range [1..max] */
681 (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX)) {
683 * XXX Do some performance testing to determine placing.
684 * XXX We probably need an auxiliary data structure that
685 * XXX describes relative performances.
688 cap->cc_alg[alg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
689 cap->cc_max_op_len[alg] = maxoplen;
691 printf("crypto: %s registers alg %u flags %u maxoplen %u\n"
692 , device_get_nameunit(cap->cc_dev)
697 cap->cc_sessions = 0; /* Unmark */
702 CRYPTO_DRIVER_UNLOCK();
707 driver_finis(struct cryptocap *cap)
711 CRYPTO_DRIVER_ASSERT();
713 ses = cap->cc_sessions;
714 kops = cap->cc_koperations;
715 bzero(cap, sizeof(*cap));
716 if (ses != 0 || kops != 0) {
718 * If there are pending sessions,
719 * just mark as invalid.
721 cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
722 cap->cc_sessions = ses;
723 cap->cc_koperations = kops;
728 * Unregister a crypto driver. If there are pending sessions using it,
729 * leave enough information around so that subsequent calls using those
730 * sessions will correctly detect the driver has been unregistered and
734 crypto_unregister(u_int32_t driverid, int alg)
736 struct cryptocap *cap;
739 CRYPTO_DRIVER_LOCK();
740 cap = crypto_checkdriver(driverid);
742 (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX) &&
743 cap->cc_alg[alg] != 0) {
744 cap->cc_alg[alg] = 0;
745 cap->cc_max_op_len[alg] = 0;
747 /* Was this the last algorithm ? */
748 for (i = 1; i <= CRYPTO_ALGORITHM_MAX; i++)
749 if (cap->cc_alg[i] != 0)
752 if (i == CRYPTO_ALGORITHM_MAX + 1)
757 CRYPTO_DRIVER_UNLOCK();
763 * Unregister all algorithms associated with a crypto driver.
764 * If there are pending sessions using it, leave enough information
765 * around so that subsequent calls using those sessions will
766 * correctly detect the driver has been unregistered and reroute
770 crypto_unregister_all(u_int32_t driverid)
772 struct cryptocap *cap;
775 CRYPTO_DRIVER_LOCK();
776 cap = crypto_checkdriver(driverid);
782 CRYPTO_DRIVER_UNLOCK();
788 * Clear blockage on a driver. The what parameter indicates whether
789 * the driver is now ready for cryptop's and/or cryptokop's.
792 crypto_unblock(u_int32_t driverid, int what)
794 struct cryptocap *cap;
798 cap = crypto_checkdriver(driverid);
800 if (what & CRYPTO_SYMQ)
801 cap->cc_qblocked = 0;
802 if (what & CRYPTO_ASYMQ)
803 cap->cc_kqblocked = 0;
815 * Add a crypto request to a queue, to be processed by the kernel thread.
818 crypto_dispatch(struct cryptop *crp)
820 struct cryptocap *cap;
824 cryptostats.cs_ops++;
828 binuptime(&crp->crp_tstamp);
831 hid = CRYPTO_SESID2HID(crp->crp_sid);
833 if ((crp->crp_flags & CRYPTO_F_BATCH) == 0) {
835 * Caller marked the request to be processed
836 * immediately; dispatch it directly to the
837 * driver unless the driver is currently blocked.
839 cap = crypto_checkdriver(hid);
840 /* Driver cannot disappeared when there is an active session. */
841 KASSERT(cap != NULL, ("%s: Driver disappeared.", __func__));
842 if (!cap->cc_qblocked) {
843 result = crypto_invoke(cap, crp, 0);
844 if (result != ERESTART)
847 * The driver ran out of resources, put the request on
853 TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
861 * Add an asymetric crypto request to a queue,
862 * to be processed by the kernel thread.
865 crypto_kdispatch(struct cryptkop *krp)
869 cryptostats.cs_kops++;
871 error = crypto_kinvoke(krp, krp->krp_crid);
872 if (error == ERESTART) {
874 TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
884 * Verify a driver is suitable for the specified operation.
887 kdriver_suitable(const struct cryptocap *cap, const struct cryptkop *krp)
889 return (cap->cc_kalg[krp->krp_op] & CRYPTO_ALG_FLAG_SUPPORTED) != 0;
893 * Select a driver for an asym operation. The driver must
894 * support the necessary algorithm. The caller can constrain
895 * which device is selected with the flags parameter. The
896 * algorithm we use here is pretty stupid; just use the first
897 * driver that supports the algorithms we need. If there are
898 * multiple suitable drivers we choose the driver with the
899 * fewest active operations. We prefer hardware-backed
900 * drivers to software ones when either may be used.
902 static struct cryptocap *
903 crypto_select_kdriver(const struct cryptkop *krp, int flags)
905 struct cryptocap *cap, *best, *blocked;
908 CRYPTO_DRIVER_ASSERT();
911 * Look first for hardware crypto devices if permitted.
913 if (flags & CRYPTOCAP_F_HARDWARE)
914 match = CRYPTOCAP_F_HARDWARE;
916 match = CRYPTOCAP_F_SOFTWARE;
920 for (hid = 0; hid < crypto_drivers_num; hid++) {
921 cap = &crypto_drivers[hid];
923 * If it's not initialized, is in the process of
924 * going away, or is not appropriate (hardware
925 * or software based on match), then skip.
927 if (cap->cc_dev == NULL ||
928 (cap->cc_flags & CRYPTOCAP_F_CLEANUP) ||
929 (cap->cc_flags & match) == 0)
932 /* verify all the algorithms are supported. */
933 if (kdriver_suitable(cap, krp)) {
935 cap->cc_koperations < best->cc_koperations)
941 if (match == CRYPTOCAP_F_HARDWARE && (flags & CRYPTOCAP_F_SOFTWARE)) {
942 /* sort of an Algol 68-style for loop */
943 match = CRYPTOCAP_F_SOFTWARE;
950 * Dispatch an asymmetric crypto request.
953 crypto_kinvoke(struct cryptkop *krp, int crid)
955 struct cryptocap *cap = NULL;
958 KASSERT(krp != NULL, ("%s: krp == NULL", __func__));
959 KASSERT(krp->krp_callback != NULL,
960 ("%s: krp->crp_callback == NULL", __func__));
962 CRYPTO_DRIVER_LOCK();
963 if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
964 cap = crypto_checkdriver(crid);
967 * Driver present, it must support the necessary
968 * algorithm and, if s/w drivers are excluded,
969 * it must be registered as hardware-backed.
971 if (!kdriver_suitable(cap, krp) ||
972 (!crypto_devallowsoft &&
973 (cap->cc_flags & CRYPTOCAP_F_HARDWARE) == 0))
978 * No requested driver; select based on crid flags.
980 if (!crypto_devallowsoft) /* NB: disallow s/w drivers */
981 crid &= ~CRYPTOCAP_F_SOFTWARE;
982 cap = crypto_select_kdriver(krp, crid);
984 if (cap != NULL && !cap->cc_kqblocked) {
985 krp->krp_hid = cap - crypto_drivers;
986 cap->cc_koperations++;
987 CRYPTO_DRIVER_UNLOCK();
988 error = CRYPTODEV_KPROCESS(cap->cc_dev, krp, 0);
989 CRYPTO_DRIVER_LOCK();
990 if (error == ERESTART) {
991 cap->cc_koperations--;
992 CRYPTO_DRIVER_UNLOCK();
997 * NB: cap is !NULL if device is blocked; in
998 * that case return ERESTART so the operation
999 * is resubmitted if possible.
1001 error = (cap == NULL) ? ENODEV : ERESTART;
1003 CRYPTO_DRIVER_UNLOCK();
1006 krp->krp_status = error;
1012 #ifdef CRYPTO_TIMING
1014 crypto_tstat(struct cryptotstat *ts, struct bintime *bt)
1016 struct bintime now, delta;
1022 delta.frac = now.frac - bt->frac;
1023 delta.sec = now.sec - bt->sec;
1026 bintime2timespec(&delta, &t);
1027 timespecadd(&ts->acc, &t);
1028 if (timespeccmp(&t, &ts->min, <))
1030 if (timespeccmp(&t, &ts->max, >))
1039 * Dispatch a crypto request to the appropriate crypto devices.
1042 crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint)
1045 KASSERT(crp != NULL, ("%s: crp == NULL", __func__));
1046 KASSERT(crp->crp_callback != NULL,
1047 ("%s: crp->crp_callback == NULL", __func__));
1048 KASSERT(crp->crp_desc != NULL, ("%s: crp->crp_desc == NULL", __func__));
1050 #ifdef CRYPTO_TIMING
1052 crypto_tstat(&cryptostats.cs_invoke, &crp->crp_tstamp);
1054 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1055 struct cryptodesc *crd;
1059 * Driver has unregistered; migrate the session and return
1060 * an error to the caller so they'll resubmit the op.
1062 * XXX: What if there are more already queued requests for this
1065 crypto_freesession(crp->crp_sid);
1067 for (crd = crp->crp_desc; crd->crd_next; crd = crd->crd_next)
1068 crd->CRD_INI.cri_next = &(crd->crd_next->CRD_INI);
1070 /* XXX propagate flags from initial session? */
1071 if (crypto_newsession(&nid, &(crp->crp_desc->CRD_INI),
1072 CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE) == 0)
1075 crp->crp_etype = EAGAIN;
1080 * Invoke the driver to process the request.
1082 return CRYPTODEV_PROCESS(cap->cc_dev, crp, hint);
1087 * Release a set of crypto descriptors.
1090 crypto_freereq(struct cryptop *crp)
1092 struct cryptodesc *crd;
1099 struct cryptop *crp2;
1102 TAILQ_FOREACH(crp2, &crp_q, crp_next) {
1103 KASSERT(crp2 != crp,
1104 ("Freeing cryptop from the crypto queue (%p).",
1109 TAILQ_FOREACH(crp2, &crp_ret_q, crp_next) {
1110 KASSERT(crp2 != crp,
1111 ("Freeing cryptop from the return queue (%p).",
1114 CRYPTO_RETQ_UNLOCK();
1118 while ((crd = crp->crp_desc) != NULL) {
1119 crp->crp_desc = crd->crd_next;
1120 uma_zfree(cryptodesc_zone, crd);
1122 uma_zfree(cryptop_zone, crp);
1126 * Acquire a set of crypto descriptors.
1129 crypto_getreq(int num)
1131 struct cryptodesc *crd;
1132 struct cryptop *crp;
1134 crp = uma_zalloc(cryptop_zone, M_NOWAIT|M_ZERO);
1137 crd = uma_zalloc(cryptodesc_zone, M_NOWAIT|M_ZERO);
1139 crypto_freereq(crp);
1143 crd->crd_next = crp->crp_desc;
1144 crp->crp_desc = crd;
1151 * Invoke the callback on behalf of the driver.
1154 crypto_done(struct cryptop *crp)
1156 KASSERT((crp->crp_flags & CRYPTO_F_DONE) == 0,
1157 ("crypto_done: op already done, flags 0x%x", crp->crp_flags));
1158 crp->crp_flags |= CRYPTO_F_DONE;
1159 if (crp->crp_etype != 0)
1160 cryptostats.cs_errs++;
1161 #ifdef CRYPTO_TIMING
1163 crypto_tstat(&cryptostats.cs_done, &crp->crp_tstamp);
1166 * CBIMM means unconditionally do the callback immediately;
1167 * CBIFSYNC means do the callback immediately only if the
1168 * operation was done synchronously. Both are used to avoid
1169 * doing extraneous context switches; the latter is mostly
1170 * used with the software crypto driver.
1172 if ((crp->crp_flags & CRYPTO_F_CBIMM) ||
1173 ((crp->crp_flags & CRYPTO_F_CBIFSYNC) &&
1174 (CRYPTO_SESID2CAPS(crp->crp_sid) & CRYPTOCAP_F_SYNC))) {
1176 * Do the callback directly. This is ok when the
1177 * callback routine does very little (e.g. the
1178 * /dev/crypto callback method just does a wakeup).
1180 #ifdef CRYPTO_TIMING
1181 if (crypto_timing) {
1183 * NB: We must copy the timestamp before
1184 * doing the callback as the cryptop is
1185 * likely to be reclaimed.
1187 struct bintime t = crp->crp_tstamp;
1188 crypto_tstat(&cryptostats.cs_cb, &t);
1189 crp->crp_callback(crp);
1190 crypto_tstat(&cryptostats.cs_finis, &t);
1193 crp->crp_callback(crp);
1196 * Normal case; queue the callback for the thread.
1199 if (CRYPTO_RETQ_EMPTY())
1200 wakeup_one(&crp_ret_q); /* shared wait channel */
1201 TAILQ_INSERT_TAIL(&crp_ret_q, crp, crp_next);
1202 CRYPTO_RETQ_UNLOCK();
1207 * Invoke the callback on behalf of the driver.
1210 crypto_kdone(struct cryptkop *krp)
1212 struct cryptocap *cap;
1214 if (krp->krp_status != 0)
1215 cryptostats.cs_kerrs++;
1216 CRYPTO_DRIVER_LOCK();
1217 /* XXX: What if driver is loaded in the meantime? */
1218 if (krp->krp_hid < crypto_drivers_num) {
1219 cap = &crypto_drivers[krp->krp_hid];
1220 KASSERT(cap->cc_koperations > 0, ("cc_koperations == 0"));
1221 cap->cc_koperations--;
1222 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP)
1225 CRYPTO_DRIVER_UNLOCK();
1227 if (CRYPTO_RETQ_EMPTY())
1228 wakeup_one(&crp_ret_q); /* shared wait channel */
1229 TAILQ_INSERT_TAIL(&crp_ret_kq, krp, krp_next);
1230 CRYPTO_RETQ_UNLOCK();
1234 crypto_getfeat(int *featp)
1236 int hid, kalg, feat = 0;
1238 CRYPTO_DRIVER_LOCK();
1239 for (hid = 0; hid < crypto_drivers_num; hid++) {
1240 const struct cryptocap *cap = &crypto_drivers[hid];
1242 if ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
1243 !crypto_devallowsoft) {
1246 for (kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
1247 if (cap->cc_kalg[kalg] & CRYPTO_ALG_FLAG_SUPPORTED)
1250 CRYPTO_DRIVER_UNLOCK();
1256 * Terminate a thread at module unload. The process that
1257 * initiated this is waiting for us to signal that we're gone;
1258 * wake it up and exit. We use the driver table lock to insure
1259 * we don't do the wakeup before they're waiting. There is no
1260 * race here because the waiter sleeps on the proc lock for the
1261 * thread so it gets notified at the right time because of an
1262 * extra wakeup that's done in exit1().
1265 crypto_finis(void *chan)
1267 CRYPTO_DRIVER_LOCK();
1269 CRYPTO_DRIVER_UNLOCK();
1274 * Crypto thread, dispatches crypto requests.
1279 struct cryptop *crp, *submit;
1280 struct cryptkop *krp;
1281 struct cryptocap *cap;
1285 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
1286 fpu_kern_thread(FPU_KERN_NORMAL);
1292 * Find the first element in the queue that can be
1293 * processed and look-ahead to see if multiple ops
1294 * are ready for the same driver.
1298 TAILQ_FOREACH(crp, &crp_q, crp_next) {
1299 hid = CRYPTO_SESID2HID(crp->crp_sid);
1300 cap = crypto_checkdriver(hid);
1302 * Driver cannot disappeared when there is an active
1305 KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1306 __func__, __LINE__));
1307 if (cap == NULL || cap->cc_dev == NULL) {
1308 /* Op needs to be migrated, process it. */
1313 if (!cap->cc_qblocked) {
1314 if (submit != NULL) {
1316 * We stop on finding another op,
1317 * regardless whether its for the same
1318 * driver or not. We could keep
1319 * searching the queue but it might be
1320 * better to just use a per-driver
1323 if (CRYPTO_SESID2HID(submit->crp_sid) == hid)
1324 hint = CRYPTO_HINT_MORE;
1328 if ((submit->crp_flags & CRYPTO_F_BATCH) == 0)
1330 /* keep scanning for more are q'd */
1334 if (submit != NULL) {
1335 TAILQ_REMOVE(&crp_q, submit, crp_next);
1336 hid = CRYPTO_SESID2HID(submit->crp_sid);
1337 cap = crypto_checkdriver(hid);
1338 KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1339 __func__, __LINE__));
1340 result = crypto_invoke(cap, submit, hint);
1341 if (result == ERESTART) {
1343 * The driver ran out of resources, mark the
1344 * driver ``blocked'' for cryptop's and put
1345 * the request back in the queue. It would
1346 * best to put the request back where we got
1347 * it but that's hard so for now we put it
1348 * at the front. This should be ok; putting
1349 * it at the end does not work.
1351 /* XXX validate sid again? */
1352 crypto_drivers[CRYPTO_SESID2HID(submit->crp_sid)].cc_qblocked = 1;
1353 TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
1354 cryptostats.cs_blocks++;
1358 /* As above, but for key ops */
1359 TAILQ_FOREACH(krp, &crp_kq, krp_next) {
1360 cap = crypto_checkdriver(krp->krp_hid);
1361 if (cap == NULL || cap->cc_dev == NULL) {
1363 * Operation needs to be migrated, invalidate
1364 * the assigned device so it will reselect a
1365 * new one below. Propagate the original
1366 * crid selection flags if supplied.
1368 krp->krp_hid = krp->krp_crid &
1369 (CRYPTOCAP_F_SOFTWARE|CRYPTOCAP_F_HARDWARE);
1370 if (krp->krp_hid == 0)
1372 CRYPTOCAP_F_SOFTWARE|CRYPTOCAP_F_HARDWARE;
1375 if (!cap->cc_kqblocked)
1379 TAILQ_REMOVE(&crp_kq, krp, krp_next);
1380 result = crypto_kinvoke(krp, krp->krp_hid);
1381 if (result == ERESTART) {
1383 * The driver ran out of resources, mark the
1384 * driver ``blocked'' for cryptkop's and put
1385 * the request back in the queue. It would
1386 * best to put the request back where we got
1387 * it but that's hard so for now we put it
1388 * at the front. This should be ok; putting
1389 * it at the end does not work.
1391 /* XXX validate sid again? */
1392 crypto_drivers[krp->krp_hid].cc_kqblocked = 1;
1393 TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
1394 cryptostats.cs_kblocks++;
1398 if (submit == NULL && krp == NULL) {
1400 * Nothing more to be processed. Sleep until we're
1401 * woken because there are more ops to process.
1402 * This happens either by submission or by a driver
1403 * becoming unblocked and notifying us through
1404 * crypto_unblock. Note that when we wakeup we
1405 * start processing each queue again from the
1406 * front. It's not clear that it's important to
1407 * preserve this ordering since ops may finish
1408 * out of order if dispatched to different devices
1409 * and some become blocked while others do not.
1412 msleep(&crp_q, &crypto_q_mtx, PWAIT, "crypto_wait", 0);
1414 if (cryptoproc == NULL)
1416 cryptostats.cs_intrs++;
1421 crypto_finis(&crp_q);
1425 * Crypto returns thread, does callbacks for processed crypto requests.
1426 * Callbacks are done here, rather than in the crypto drivers, because
1427 * callbacks typically are expensive and would slow interrupt handling.
1430 crypto_ret_proc(void)
1432 struct cryptop *crpt;
1433 struct cryptkop *krpt;
1437 /* Harvest return q's for completed ops */
1438 crpt = TAILQ_FIRST(&crp_ret_q);
1440 TAILQ_REMOVE(&crp_ret_q, crpt, crp_next);
1442 krpt = TAILQ_FIRST(&crp_ret_kq);
1444 TAILQ_REMOVE(&crp_ret_kq, krpt, krp_next);
1446 if (crpt != NULL || krpt != NULL) {
1447 CRYPTO_RETQ_UNLOCK();
1449 * Run callbacks unlocked.
1452 #ifdef CRYPTO_TIMING
1453 if (crypto_timing) {
1455 * NB: We must copy the timestamp before
1456 * doing the callback as the cryptop is
1457 * likely to be reclaimed.
1459 struct bintime t = crpt->crp_tstamp;
1460 crypto_tstat(&cryptostats.cs_cb, &t);
1461 crpt->crp_callback(crpt);
1462 crypto_tstat(&cryptostats.cs_finis, &t);
1465 crpt->crp_callback(crpt);
1468 krpt->krp_callback(krpt);
1472 * Nothing more to be processed. Sleep until we're
1473 * woken because there are more returns to process.
1475 msleep(&crp_ret_q, &crypto_ret_q_mtx, PWAIT,
1476 "crypto_ret_wait", 0);
1477 if (cryptoretproc == NULL)
1479 cryptostats.cs_rets++;
1482 CRYPTO_RETQ_UNLOCK();
1484 crypto_finis(&crp_ret_q);
1489 db_show_drivers(void)
1493 db_printf("%12s %4s %4s %8s %2s %2s\n"
1501 for (hid = 0; hid < crypto_drivers_num; hid++) {
1502 const struct cryptocap *cap = &crypto_drivers[hid];
1503 if (cap->cc_dev == NULL)
1505 db_printf("%-12s %4u %4u %08x %2u %2u\n"
1506 , device_get_nameunit(cap->cc_dev)
1508 , cap->cc_koperations
1516 DB_SHOW_COMMAND(crypto, db_show_crypto)
1518 struct cryptop *crp;
1523 db_printf("%4s %8s %4s %4s %4s %4s %8s %8s\n",
1524 "HID", "Caps", "Ilen", "Olen", "Etype", "Flags",
1525 "Desc", "Callback");
1526 TAILQ_FOREACH(crp, &crp_q, crp_next) {
1527 db_printf("%4u %08x %4u %4u %4u %04x %8p %8p\n"
1528 , (int) CRYPTO_SESID2HID(crp->crp_sid)
1529 , (int) CRYPTO_SESID2CAPS(crp->crp_sid)
1530 , crp->crp_ilen, crp->crp_olen
1537 if (!TAILQ_EMPTY(&crp_ret_q)) {
1538 db_printf("\n%4s %4s %4s %8s\n",
1539 "HID", "Etype", "Flags", "Callback");
1540 TAILQ_FOREACH(crp, &crp_ret_q, crp_next) {
1541 db_printf("%4u %4u %04x %8p\n"
1542 , (int) CRYPTO_SESID2HID(crp->crp_sid)
1551 DB_SHOW_COMMAND(kcrypto, db_show_kcrypto)
1553 struct cryptkop *krp;
1558 db_printf("%4s %5s %4s %4s %8s %4s %8s\n",
1559 "Op", "Status", "#IP", "#OP", "CRID", "HID", "Callback");
1560 TAILQ_FOREACH(krp, &crp_kq, krp_next) {
1561 db_printf("%4u %5u %4u %4u %08x %4u %8p\n"
1564 , krp->krp_iparams, krp->krp_oparams
1565 , krp->krp_crid, krp->krp_hid
1569 if (!TAILQ_EMPTY(&crp_ret_q)) {
1570 db_printf("%4s %5s %8s %4s %8s\n",
1571 "Op", "Status", "CRID", "HID", "Callback");
1572 TAILQ_FOREACH(krp, &crp_ret_kq, krp_next) {
1573 db_printf("%4u %5u %08x %4u %8p\n"
1576 , krp->krp_crid, krp->krp_hid
1584 int crypto_modevent(module_t mod, int type, void *unused);
1587 * Initialization code, both for static and dynamic loading.
1588 * Note this is not invoked with the usual MODULE_DECLARE
1589 * mechanism but instead is listed as a dependency by the
1590 * cryptosoft driver. This guarantees proper ordering of
1591 * calls on module load/unload.
1594 crypto_modevent(module_t mod, int type, void *unused)
1600 error = crypto_init();
1601 if (error == 0 && bootverbose)
1602 printf("crypto: <crypto core>\n");
1605 /*XXX disallow if active sessions */
1612 MODULE_VERSION(crypto, 1);
1613 MODULE_DEPEND(crypto, zlib, 1, 1, 1);