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>
67 #include <sys/module.h>
68 #include <sys/mutex.h>
69 #include <sys/malloc.h>
72 #include <sys/sysctl.h>
77 #include <opencrypto/cryptodev.h>
78 #include <opencrypto/xform.h> /* XXX for M_XDATA */
82 #include "cryptodev_if.h"
84 #if defined(__i386__) || defined(__amd64__)
85 #include <machine/pcb.h>
88 SDT_PROVIDER_DEFINE(opencrypto);
91 * Crypto drivers register themselves by allocating a slot in the
92 * crypto_drivers table with crypto_get_driverid() and then registering
93 * each algorithm they support with crypto_register() and crypto_kregister().
95 static struct mtx crypto_drivers_mtx; /* lock on driver table */
96 #define CRYPTO_DRIVER_LOCK() mtx_lock(&crypto_drivers_mtx)
97 #define CRYPTO_DRIVER_UNLOCK() mtx_unlock(&crypto_drivers_mtx)
98 #define CRYPTO_DRIVER_ASSERT() mtx_assert(&crypto_drivers_mtx, MA_OWNED)
101 * Crypto device/driver capabilities structure.
104 * (d) - protected by CRYPTO_DRIVER_LOCK()
105 * (q) - protected by CRYPTO_Q_LOCK()
106 * Not tagged fields are read-only.
109 device_t cc_dev; /* (d) device/driver */
110 u_int32_t cc_sessions; /* (d) # of sessions */
111 u_int32_t cc_koperations; /* (d) # os asym operations */
113 * Largest possible operator length (in bits) for each type of
114 * encryption algorithm. XXX not used
116 u_int16_t cc_max_op_len[CRYPTO_ALGORITHM_MAX + 1];
117 u_int8_t cc_alg[CRYPTO_ALGORITHM_MAX + 1];
118 u_int8_t cc_kalg[CRK_ALGORITHM_MAX + 1];
120 int cc_flags; /* (d) flags */
121 #define CRYPTOCAP_F_CLEANUP 0x80000000 /* needs resource cleanup */
122 int cc_qblocked; /* (q) symmetric q blocked */
123 int cc_kqblocked; /* (q) asymmetric q blocked */
125 static struct cryptocap *crypto_drivers = NULL;
126 static int crypto_drivers_num = 0;
129 * There are two queues for crypto requests; one for symmetric (e.g.
130 * cipher) operations and one for asymmetric (e.g. MOD)operations.
131 * A single mutex is used to lock access to both queues. We could
132 * have one per-queue but having one simplifies handling of block/unblock
135 static int crp_sleep = 0;
136 static TAILQ_HEAD(,cryptop) crp_q; /* request queues */
137 static TAILQ_HEAD(,cryptkop) crp_kq;
138 static struct mtx crypto_q_mtx;
139 #define CRYPTO_Q_LOCK() mtx_lock(&crypto_q_mtx)
140 #define CRYPTO_Q_UNLOCK() mtx_unlock(&crypto_q_mtx)
143 * There are two queues for processing completed crypto requests; one
144 * for the symmetric and one for the asymmetric ops. We only need one
145 * but have two to avoid type futzing (cryptop vs. cryptkop). A single
146 * mutex is used to lock access to both queues. Note that this lock
147 * must be separate from the lock on request queues to insure driver
148 * callbacks don't generate lock order reversals.
150 static TAILQ_HEAD(,cryptop) crp_ret_q; /* callback queues */
151 static TAILQ_HEAD(,cryptkop) crp_ret_kq;
152 static struct mtx crypto_ret_q_mtx;
153 #define CRYPTO_RETQ_LOCK() mtx_lock(&crypto_ret_q_mtx)
154 #define CRYPTO_RETQ_UNLOCK() mtx_unlock(&crypto_ret_q_mtx)
155 #define CRYPTO_RETQ_EMPTY() (TAILQ_EMPTY(&crp_ret_q) && TAILQ_EMPTY(&crp_ret_kq))
157 static uma_zone_t cryptop_zone;
158 static uma_zone_t cryptodesc_zone;
160 int crypto_userasymcrypto = 1; /* userland may do asym crypto reqs */
161 SYSCTL_INT(_kern, OID_AUTO, userasymcrypto, CTLFLAG_RW,
162 &crypto_userasymcrypto, 0,
163 "Enable/disable user-mode access to asymmetric crypto support");
164 int crypto_devallowsoft = 0; /* only use hardware crypto for asym */
165 SYSCTL_INT(_kern, OID_AUTO, cryptodevallowsoft, CTLFLAG_RW,
166 &crypto_devallowsoft, 0,
167 "Enable/disable use of software asym crypto support");
169 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
171 static void crypto_proc(void);
172 static struct proc *cryptoproc;
173 static void crypto_ret_proc(void);
174 static struct proc *cryptoretproc;
175 static void crypto_destroy(void);
176 static int crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint);
177 static int crypto_kinvoke(struct cryptkop *krp, int flags);
179 static struct cryptostats cryptostats;
180 SYSCTL_STRUCT(_kern, OID_AUTO, crypto_stats, CTLFLAG_RW, &cryptostats,
181 cryptostats, "Crypto system statistics");
184 static int crypto_timing = 0;
185 SYSCTL_INT(_debug, OID_AUTO, crypto_timing, CTLFLAG_RW,
186 &crypto_timing, 0, "Enable/disable crypto timing support");
194 mtx_init(&crypto_drivers_mtx, "crypto", "crypto driver table",
199 mtx_init(&crypto_q_mtx, "crypto", "crypto op queues", MTX_DEF);
201 TAILQ_INIT(&crp_ret_q);
202 TAILQ_INIT(&crp_ret_kq);
203 mtx_init(&crypto_ret_q_mtx, "crypto", "crypto return queues", MTX_DEF);
205 cryptop_zone = uma_zcreate("cryptop", sizeof (struct cryptop),
207 UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
208 cryptodesc_zone = uma_zcreate("cryptodesc", sizeof (struct cryptodesc),
210 UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
211 if (cryptodesc_zone == NULL || cryptop_zone == NULL) {
212 printf("crypto_init: cannot setup crypto zones\n");
217 crypto_drivers_num = CRYPTO_DRIVERS_INITIAL;
218 crypto_drivers = malloc(crypto_drivers_num *
219 sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT | M_ZERO);
220 if (crypto_drivers == NULL) {
221 printf("crypto_init: cannot setup crypto drivers\n");
226 error = kproc_create((void (*)(void *)) crypto_proc, NULL,
227 &cryptoproc, 0, 0, "crypto");
229 printf("crypto_init: cannot start crypto thread; error %d",
234 error = kproc_create((void (*)(void *)) crypto_ret_proc, NULL,
235 &cryptoretproc, 0, 0, "crypto returns");
237 printf("crypto_init: cannot start cryptoret thread; error %d",
248 * Signal a crypto thread to terminate. We use the driver
249 * table lock to synchronize the sleep/wakeups so that we
250 * are sure the threads have terminated before we release
251 * the data structures they use. See crypto_finis below
252 * for the other half of this song-and-dance.
255 crypto_terminate(struct proc **pp, void *q)
259 mtx_assert(&crypto_drivers_mtx, MA_OWNED);
264 PROC_LOCK(p); /* NB: insure we don't miss wakeup */
265 CRYPTO_DRIVER_UNLOCK(); /* let crypto_finis progress */
266 msleep(p, &p->p_mtx, PWAIT, "crypto_destroy", 0);
268 CRYPTO_DRIVER_LOCK();
276 * Terminate any crypto threads.
278 CRYPTO_DRIVER_LOCK();
279 crypto_terminate(&cryptoproc, &crp_q);
280 crypto_terminate(&cryptoretproc, &crp_ret_q);
281 CRYPTO_DRIVER_UNLOCK();
283 /* XXX flush queues??? */
286 * Reclaim dynamically allocated resources.
288 if (crypto_drivers != NULL)
289 free(crypto_drivers, M_CRYPTO_DATA);
291 if (cryptodesc_zone != NULL)
292 uma_zdestroy(cryptodesc_zone);
293 if (cryptop_zone != NULL)
294 uma_zdestroy(cryptop_zone);
295 mtx_destroy(&crypto_q_mtx);
296 mtx_destroy(&crypto_ret_q_mtx);
297 mtx_destroy(&crypto_drivers_mtx);
300 static struct cryptocap *
301 crypto_checkdriver(u_int32_t hid)
303 if (crypto_drivers == NULL)
305 return (hid >= crypto_drivers_num ? NULL : &crypto_drivers[hid]);
309 * Compare a driver's list of supported algorithms against another
310 * list; return non-zero if all algorithms are supported.
313 driver_suitable(const struct cryptocap *cap, const struct cryptoini *cri)
315 const struct cryptoini *cr;
317 /* See if all the algorithms are supported. */
318 for (cr = cri; cr; cr = cr->cri_next)
319 if (cap->cc_alg[cr->cri_alg] == 0)
325 * Select a driver for a new session that supports the specified
326 * algorithms and, optionally, is constrained according to the flags.
327 * The algorithm we use here is pretty stupid; just use the
328 * first driver that supports all the algorithms we need. If there
329 * are multiple drivers we choose the driver with the fewest active
330 * sessions. We prefer hardware-backed drivers to software ones.
332 * XXX We need more smarts here (in real life too, but that's
333 * XXX another story altogether).
335 static struct cryptocap *
336 crypto_select_driver(const struct cryptoini *cri, int flags)
338 struct cryptocap *cap, *best;
341 CRYPTO_DRIVER_ASSERT();
344 * Look first for hardware crypto devices if permitted.
346 if (flags & CRYPTOCAP_F_HARDWARE)
347 match = CRYPTOCAP_F_HARDWARE;
349 match = CRYPTOCAP_F_SOFTWARE;
352 for (hid = 0; hid < crypto_drivers_num; hid++) {
353 cap = &crypto_drivers[hid];
355 * If it's not initialized, is in the process of
356 * going away, or is not appropriate (hardware
357 * or software based on match), then skip.
359 if (cap->cc_dev == NULL ||
360 (cap->cc_flags & CRYPTOCAP_F_CLEANUP) ||
361 (cap->cc_flags & match) == 0)
364 /* verify all the algorithms are supported. */
365 if (driver_suitable(cap, cri)) {
367 cap->cc_sessions < best->cc_sessions)
373 if (match == CRYPTOCAP_F_HARDWARE && (flags & CRYPTOCAP_F_SOFTWARE)) {
374 /* sort of an Algol 68-style for loop */
375 match = CRYPTOCAP_F_SOFTWARE;
382 * Create a new session. The crid argument specifies a crypto
383 * driver to use or constraints on a driver to select (hardware
384 * only, software only, either). Whatever driver is selected
385 * must be capable of the requested crypto algorithms.
388 crypto_newsession(u_int64_t *sid, struct cryptoini *cri, int crid)
390 struct cryptocap *cap;
394 CRYPTO_DRIVER_LOCK();
395 if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
397 * Use specified driver; verify it is capable.
399 cap = crypto_checkdriver(crid);
400 if (cap != NULL && !driver_suitable(cap, cri))
404 * No requested driver; select based on crid flags.
406 cap = crypto_select_driver(cri, crid);
408 * if NULL then can't do everything in one session.
409 * XXX Fix this. We need to inject a "virtual" session
410 * XXX layer right about here.
414 /* Call the driver initialization routine. */
415 hid = cap - crypto_drivers;
416 lid = hid; /* Pass the driver ID. */
417 err = CRYPTODEV_NEWSESSION(cap->cc_dev, &lid, cri);
419 (*sid) = (cap->cc_flags & 0xff000000)
420 | (hid & 0x00ffffff);
422 (*sid) |= (lid & 0xffffffff);
427 CRYPTO_DRIVER_UNLOCK();
432 crypto_remove(struct cryptocap *cap)
435 mtx_assert(&crypto_drivers_mtx, MA_OWNED);
436 if (cap->cc_sessions == 0 && cap->cc_koperations == 0)
437 bzero(cap, sizeof(*cap));
441 * Delete an existing session (or a reserved session on an unregistered
445 crypto_freesession(u_int64_t sid)
447 struct cryptocap *cap;
451 CRYPTO_DRIVER_LOCK();
453 if (crypto_drivers == NULL) {
458 /* Determine two IDs. */
459 hid = CRYPTO_SESID2HID(sid);
461 if (hid >= crypto_drivers_num) {
465 cap = &crypto_drivers[hid];
467 if (cap->cc_sessions)
470 /* Call the driver cleanup routine, if available. */
471 err = CRYPTODEV_FREESESSION(cap->cc_dev, sid);
473 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP)
477 CRYPTO_DRIVER_UNLOCK();
482 * Return an unused driver id. Used by drivers prior to registering
483 * support for the algorithms they handle.
486 crypto_get_driverid(device_t dev, int flags)
488 struct cryptocap *newdrv;
491 if ((flags & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
492 printf("%s: no flags specified when registering driver\n",
493 device_get_nameunit(dev));
497 CRYPTO_DRIVER_LOCK();
499 for (i = 0; i < crypto_drivers_num; i++) {
500 if (crypto_drivers[i].cc_dev == NULL &&
501 (crypto_drivers[i].cc_flags & CRYPTOCAP_F_CLEANUP) == 0) {
506 /* Out of entries, allocate some more. */
507 if (i == crypto_drivers_num) {
508 /* Be careful about wrap-around. */
509 if (2 * crypto_drivers_num <= crypto_drivers_num) {
510 CRYPTO_DRIVER_UNLOCK();
511 printf("crypto: driver count wraparound!\n");
515 newdrv = malloc(2 * crypto_drivers_num *
516 sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT|M_ZERO);
517 if (newdrv == NULL) {
518 CRYPTO_DRIVER_UNLOCK();
519 printf("crypto: no space to expand driver table!\n");
523 bcopy(crypto_drivers, newdrv,
524 crypto_drivers_num * sizeof(struct cryptocap));
526 crypto_drivers_num *= 2;
528 free(crypto_drivers, M_CRYPTO_DATA);
529 crypto_drivers = newdrv;
532 /* NB: state is zero'd on free */
533 crypto_drivers[i].cc_sessions = 1; /* Mark */
534 crypto_drivers[i].cc_dev = dev;
535 crypto_drivers[i].cc_flags = flags;
537 printf("crypto: assign %s driver id %u, flags %u\n",
538 device_get_nameunit(dev), i, flags);
540 CRYPTO_DRIVER_UNLOCK();
546 * Lookup a driver by name. We match against the full device
547 * name and unit, and against just the name. The latter gives
548 * us a simple widlcarding by device name. On success return the
549 * driver/hardware identifier; otherwise return -1.
552 crypto_find_driver(const char *match)
554 int i, len = strlen(match);
556 CRYPTO_DRIVER_LOCK();
557 for (i = 0; i < crypto_drivers_num; i++) {
558 device_t dev = crypto_drivers[i].cc_dev;
560 (crypto_drivers[i].cc_flags & CRYPTOCAP_F_CLEANUP))
562 if (strncmp(match, device_get_nameunit(dev), len) == 0 ||
563 strncmp(match, device_get_name(dev), len) == 0)
566 CRYPTO_DRIVER_UNLOCK();
567 return i < crypto_drivers_num ? i : -1;
571 * Return the device_t for the specified driver or NULL
572 * if the driver identifier is invalid.
575 crypto_find_device_byhid(int hid)
577 struct cryptocap *cap = crypto_checkdriver(hid);
578 return cap != NULL ? cap->cc_dev : NULL;
582 * Return the device/driver capabilities.
585 crypto_getcaps(int hid)
587 struct cryptocap *cap = crypto_checkdriver(hid);
588 return cap != NULL ? cap->cc_flags : 0;
592 * Register support for a key-related algorithm. This routine
593 * is called once for each algorithm supported a driver.
596 crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags)
598 struct cryptocap *cap;
601 CRYPTO_DRIVER_LOCK();
603 cap = crypto_checkdriver(driverid);
605 (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
607 * XXX Do some performance testing to determine placing.
608 * XXX We probably need an auxiliary data structure that
609 * XXX describes relative performances.
612 cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
614 printf("crypto: %s registers key alg %u flags %u\n"
615 , device_get_nameunit(cap->cc_dev)
623 CRYPTO_DRIVER_UNLOCK();
628 * Register support for a non-key-related algorithm. This routine
629 * is called once for each such algorithm supported by a driver.
632 crypto_register(u_int32_t driverid, int alg, u_int16_t maxoplen,
635 struct cryptocap *cap;
638 CRYPTO_DRIVER_LOCK();
640 cap = crypto_checkdriver(driverid);
641 /* NB: algorithms are in the range [1..max] */
643 (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_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_alg[alg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
651 cap->cc_max_op_len[alg] = maxoplen;
653 printf("crypto: %s registers alg %u flags %u maxoplen %u\n"
654 , device_get_nameunit(cap->cc_dev)
659 cap->cc_sessions = 0; /* Unmark */
664 CRYPTO_DRIVER_UNLOCK();
669 driver_finis(struct cryptocap *cap)
673 CRYPTO_DRIVER_ASSERT();
675 ses = cap->cc_sessions;
676 kops = cap->cc_koperations;
677 bzero(cap, sizeof(*cap));
678 if (ses != 0 || kops != 0) {
680 * If there are pending sessions,
681 * just mark as invalid.
683 cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
684 cap->cc_sessions = ses;
685 cap->cc_koperations = kops;
690 * Unregister a crypto driver. If there are pending sessions using it,
691 * leave enough information around so that subsequent calls using those
692 * sessions will correctly detect the driver has been unregistered and
696 crypto_unregister(u_int32_t driverid, int alg)
698 struct cryptocap *cap;
701 CRYPTO_DRIVER_LOCK();
702 cap = crypto_checkdriver(driverid);
704 (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX) &&
705 cap->cc_alg[alg] != 0) {
706 cap->cc_alg[alg] = 0;
707 cap->cc_max_op_len[alg] = 0;
709 /* Was this the last algorithm ? */
710 for (i = 1; i <= CRYPTO_ALGORITHM_MAX; i++)
711 if (cap->cc_alg[i] != 0)
714 if (i == CRYPTO_ALGORITHM_MAX + 1)
719 CRYPTO_DRIVER_UNLOCK();
725 * Unregister all algorithms associated with a crypto driver.
726 * If there are pending sessions using it, leave enough information
727 * around so that subsequent calls using those sessions will
728 * correctly detect the driver has been unregistered and reroute
732 crypto_unregister_all(u_int32_t driverid)
734 struct cryptocap *cap;
737 CRYPTO_DRIVER_LOCK();
738 cap = crypto_checkdriver(driverid);
744 CRYPTO_DRIVER_UNLOCK();
750 * Clear blockage on a driver. The what parameter indicates whether
751 * the driver is now ready for cryptop's and/or cryptokop's.
754 crypto_unblock(u_int32_t driverid, int what)
756 struct cryptocap *cap;
760 cap = crypto_checkdriver(driverid);
762 if (what & CRYPTO_SYMQ)
763 cap->cc_qblocked = 0;
764 if (what & CRYPTO_ASYMQ)
765 cap->cc_kqblocked = 0;
777 * Add a crypto request to a queue, to be processed by the kernel thread.
780 crypto_dispatch(struct cryptop *crp)
782 struct cryptocap *cap;
786 cryptostats.cs_ops++;
790 binuptime(&crp->crp_tstamp);
793 hid = CRYPTO_SESID2HID(crp->crp_sid);
795 if ((crp->crp_flags & CRYPTO_F_BATCH) == 0) {
797 * Caller marked the request to be processed
798 * immediately; dispatch it directly to the
799 * driver unless the driver is currently blocked.
801 cap = crypto_checkdriver(hid);
802 /* Driver cannot disappeared when there is an active session. */
803 KASSERT(cap != NULL, ("%s: Driver disappeared.", __func__));
804 if (!cap->cc_qblocked) {
805 result = crypto_invoke(cap, crp, 0);
806 if (result != ERESTART)
809 * The driver ran out of resources, put the request on
815 TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
823 * Add an asymetric crypto request to a queue,
824 * to be processed by the kernel thread.
827 crypto_kdispatch(struct cryptkop *krp)
831 cryptostats.cs_kops++;
833 error = crypto_kinvoke(krp, krp->krp_crid);
834 if (error == ERESTART) {
836 TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
846 * Verify a driver is suitable for the specified operation.
849 kdriver_suitable(const struct cryptocap *cap, const struct cryptkop *krp)
851 return (cap->cc_kalg[krp->krp_op] & CRYPTO_ALG_FLAG_SUPPORTED) != 0;
855 * Select a driver for an asym operation. The driver must
856 * support the necessary algorithm. The caller can constrain
857 * which device is selected with the flags parameter. The
858 * algorithm we use here is pretty stupid; just use the first
859 * driver that supports the algorithms we need. If there are
860 * multiple suitable drivers we choose the driver with the
861 * fewest active operations. We prefer hardware-backed
862 * drivers to software ones when either may be used.
864 static struct cryptocap *
865 crypto_select_kdriver(const struct cryptkop *krp, int flags)
867 struct cryptocap *cap, *best, *blocked;
870 CRYPTO_DRIVER_ASSERT();
873 * Look first for hardware crypto devices if permitted.
875 if (flags & CRYPTOCAP_F_HARDWARE)
876 match = CRYPTOCAP_F_HARDWARE;
878 match = CRYPTOCAP_F_SOFTWARE;
882 for (hid = 0; hid < crypto_drivers_num; hid++) {
883 cap = &crypto_drivers[hid];
885 * If it's not initialized, is in the process of
886 * going away, or is not appropriate (hardware
887 * or software based on match), then skip.
889 if (cap->cc_dev == NULL ||
890 (cap->cc_flags & CRYPTOCAP_F_CLEANUP) ||
891 (cap->cc_flags & match) == 0)
894 /* verify all the algorithms are supported. */
895 if (kdriver_suitable(cap, krp)) {
897 cap->cc_koperations < best->cc_koperations)
903 if (match == CRYPTOCAP_F_HARDWARE && (flags & CRYPTOCAP_F_SOFTWARE)) {
904 /* sort of an Algol 68-style for loop */
905 match = CRYPTOCAP_F_SOFTWARE;
912 * Dispatch an assymetric crypto request.
915 crypto_kinvoke(struct cryptkop *krp, int crid)
917 struct cryptocap *cap = NULL;
920 KASSERT(krp != NULL, ("%s: krp == NULL", __func__));
921 KASSERT(krp->krp_callback != NULL,
922 ("%s: krp->crp_callback == NULL", __func__));
924 CRYPTO_DRIVER_LOCK();
925 if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
926 cap = crypto_checkdriver(crid);
929 * Driver present, it must support the necessary
930 * algorithm and, if s/w drivers are excluded,
931 * it must be registered as hardware-backed.
933 if (!kdriver_suitable(cap, krp) ||
934 (!crypto_devallowsoft &&
935 (cap->cc_flags & CRYPTOCAP_F_HARDWARE) == 0))
940 * No requested driver; select based on crid flags.
942 if (!crypto_devallowsoft) /* NB: disallow s/w drivers */
943 crid &= ~CRYPTOCAP_F_SOFTWARE;
944 cap = crypto_select_kdriver(krp, crid);
946 if (cap != NULL && !cap->cc_kqblocked) {
947 krp->krp_hid = cap - crypto_drivers;
948 cap->cc_koperations++;
949 CRYPTO_DRIVER_UNLOCK();
950 error = CRYPTODEV_KPROCESS(cap->cc_dev, krp, 0);
951 CRYPTO_DRIVER_LOCK();
952 if (error == ERESTART) {
953 cap->cc_koperations--;
954 CRYPTO_DRIVER_UNLOCK();
959 * NB: cap is !NULL if device is blocked; in
960 * that case return ERESTART so the operation
961 * is resubmitted if possible.
963 error = (cap == NULL) ? ENODEV : ERESTART;
965 CRYPTO_DRIVER_UNLOCK();
968 krp->krp_status = error;
976 crypto_tstat(struct cryptotstat *ts, struct bintime *bt)
978 struct bintime now, delta;
984 delta.frac = now.frac - bt->frac;
985 delta.sec = now.sec - bt->sec;
988 bintime2timespec(&delta, &t);
989 timespecadd(&ts->acc, &t);
990 if (timespeccmp(&t, &ts->min, <))
992 if (timespeccmp(&t, &ts->max, >))
1001 * Dispatch a crypto request to the appropriate crypto devices.
1004 crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint)
1007 KASSERT(crp != NULL, ("%s: crp == NULL", __func__));
1008 KASSERT(crp->crp_callback != NULL,
1009 ("%s: crp->crp_callback == NULL", __func__));
1010 KASSERT(crp->crp_desc != NULL, ("%s: crp->crp_desc == NULL", __func__));
1012 #ifdef CRYPTO_TIMING
1014 crypto_tstat(&cryptostats.cs_invoke, &crp->crp_tstamp);
1016 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1017 struct cryptodesc *crd;
1021 * Driver has unregistered; migrate the session and return
1022 * an error to the caller so they'll resubmit the op.
1024 * XXX: What if there are more already queued requests for this
1027 crypto_freesession(crp->crp_sid);
1029 for (crd = crp->crp_desc; crd->crd_next; crd = crd->crd_next)
1030 crd->CRD_INI.cri_next = &(crd->crd_next->CRD_INI);
1032 /* XXX propagate flags from initial session? */
1033 if (crypto_newsession(&nid, &(crp->crp_desc->CRD_INI),
1034 CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE) == 0)
1037 crp->crp_etype = EAGAIN;
1042 * Invoke the driver to process the request.
1044 return CRYPTODEV_PROCESS(cap->cc_dev, crp, hint);
1049 * Release a set of crypto descriptors.
1052 crypto_freereq(struct cryptop *crp)
1054 struct cryptodesc *crd;
1061 struct cryptop *crp2;
1064 TAILQ_FOREACH(crp2, &crp_q, crp_next) {
1065 KASSERT(crp2 != crp,
1066 ("Freeing cryptop from the crypto queue (%p).",
1071 TAILQ_FOREACH(crp2, &crp_ret_q, crp_next) {
1072 KASSERT(crp2 != crp,
1073 ("Freeing cryptop from the return queue (%p).",
1076 CRYPTO_RETQ_UNLOCK();
1080 while ((crd = crp->crp_desc) != NULL) {
1081 crp->crp_desc = crd->crd_next;
1082 uma_zfree(cryptodesc_zone, crd);
1084 uma_zfree(cryptop_zone, crp);
1088 * Acquire a set of crypto descriptors.
1091 crypto_getreq(int num)
1093 struct cryptodesc *crd;
1094 struct cryptop *crp;
1096 crp = uma_zalloc(cryptop_zone, M_NOWAIT|M_ZERO);
1099 crd = uma_zalloc(cryptodesc_zone, M_NOWAIT|M_ZERO);
1101 crypto_freereq(crp);
1105 crd->crd_next = crp->crp_desc;
1106 crp->crp_desc = crd;
1113 * Invoke the callback on behalf of the driver.
1116 crypto_done(struct cryptop *crp)
1118 KASSERT((crp->crp_flags & CRYPTO_F_DONE) == 0,
1119 ("crypto_done: op already done, flags 0x%x", crp->crp_flags));
1120 crp->crp_flags |= CRYPTO_F_DONE;
1121 if (crp->crp_etype != 0)
1122 cryptostats.cs_errs++;
1123 #ifdef CRYPTO_TIMING
1125 crypto_tstat(&cryptostats.cs_done, &crp->crp_tstamp);
1128 * CBIMM means unconditionally do the callback immediately;
1129 * CBIFSYNC means do the callback immediately only if the
1130 * operation was done synchronously. Both are used to avoid
1131 * doing extraneous context switches; the latter is mostly
1132 * used with the software crypto driver.
1134 if ((crp->crp_flags & CRYPTO_F_CBIMM) ||
1135 ((crp->crp_flags & CRYPTO_F_CBIFSYNC) &&
1136 (CRYPTO_SESID2CAPS(crp->crp_sid) & CRYPTOCAP_F_SYNC))) {
1138 * Do the callback directly. This is ok when the
1139 * callback routine does very little (e.g. the
1140 * /dev/crypto callback method just does a wakeup).
1142 #ifdef CRYPTO_TIMING
1143 if (crypto_timing) {
1145 * NB: We must copy the timestamp before
1146 * doing the callback as the cryptop is
1147 * likely to be reclaimed.
1149 struct bintime t = crp->crp_tstamp;
1150 crypto_tstat(&cryptostats.cs_cb, &t);
1151 crp->crp_callback(crp);
1152 crypto_tstat(&cryptostats.cs_finis, &t);
1155 crp->crp_callback(crp);
1158 * Normal case; queue the callback for the thread.
1161 if (CRYPTO_RETQ_EMPTY())
1162 wakeup_one(&crp_ret_q); /* shared wait channel */
1163 TAILQ_INSERT_TAIL(&crp_ret_q, crp, crp_next);
1164 CRYPTO_RETQ_UNLOCK();
1169 * Invoke the callback on behalf of the driver.
1172 crypto_kdone(struct cryptkop *krp)
1174 struct cryptocap *cap;
1176 if (krp->krp_status != 0)
1177 cryptostats.cs_kerrs++;
1178 CRYPTO_DRIVER_LOCK();
1179 /* XXX: What if driver is loaded in the meantime? */
1180 if (krp->krp_hid < crypto_drivers_num) {
1181 cap = &crypto_drivers[krp->krp_hid];
1182 cap->cc_koperations--;
1183 KASSERT(cap->cc_koperations >= 0, ("cc_koperations < 0"));
1184 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP)
1187 CRYPTO_DRIVER_UNLOCK();
1189 if (CRYPTO_RETQ_EMPTY())
1190 wakeup_one(&crp_ret_q); /* shared wait channel */
1191 TAILQ_INSERT_TAIL(&crp_ret_kq, krp, krp_next);
1192 CRYPTO_RETQ_UNLOCK();
1196 crypto_getfeat(int *featp)
1198 int hid, kalg, feat = 0;
1200 CRYPTO_DRIVER_LOCK();
1201 for (hid = 0; hid < crypto_drivers_num; hid++) {
1202 const struct cryptocap *cap = &crypto_drivers[hid];
1204 if ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
1205 !crypto_devallowsoft) {
1208 for (kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
1209 if (cap->cc_kalg[kalg] & CRYPTO_ALG_FLAG_SUPPORTED)
1212 CRYPTO_DRIVER_UNLOCK();
1218 * Terminate a thread at module unload. The process that
1219 * initiated this is waiting for us to signal that we're gone;
1220 * wake it up and exit. We use the driver table lock to insure
1221 * we don't do the wakeup before they're waiting. There is no
1222 * race here because the waiter sleeps on the proc lock for the
1223 * thread so it gets notified at the right time because of an
1224 * extra wakeup that's done in exit1().
1227 crypto_finis(void *chan)
1229 CRYPTO_DRIVER_LOCK();
1231 CRYPTO_DRIVER_UNLOCK();
1236 * Crypto thread, dispatches crypto requests.
1241 struct cryptop *crp, *submit;
1242 struct cryptkop *krp;
1243 struct cryptocap *cap;
1247 #if defined(__i386__) || defined(__amd64__)
1248 fpu_kern_thread(FPU_KERN_NORMAL);
1254 * Find the first element in the queue that can be
1255 * processed and look-ahead to see if multiple ops
1256 * are ready for the same driver.
1260 TAILQ_FOREACH(crp, &crp_q, crp_next) {
1261 hid = CRYPTO_SESID2HID(crp->crp_sid);
1262 cap = crypto_checkdriver(hid);
1264 * Driver cannot disappeared when there is an active
1267 KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1268 __func__, __LINE__));
1269 if (cap == NULL || cap->cc_dev == NULL) {
1270 /* Op needs to be migrated, process it. */
1275 if (!cap->cc_qblocked) {
1276 if (submit != NULL) {
1278 * We stop on finding another op,
1279 * regardless whether its for the same
1280 * driver or not. We could keep
1281 * searching the queue but it might be
1282 * better to just use a per-driver
1285 if (CRYPTO_SESID2HID(submit->crp_sid) == hid)
1286 hint = CRYPTO_HINT_MORE;
1290 if ((submit->crp_flags & CRYPTO_F_BATCH) == 0)
1292 /* keep scanning for more are q'd */
1296 if (submit != NULL) {
1297 TAILQ_REMOVE(&crp_q, submit, crp_next);
1298 hid = CRYPTO_SESID2HID(submit->crp_sid);
1299 cap = crypto_checkdriver(hid);
1300 KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1301 __func__, __LINE__));
1302 result = crypto_invoke(cap, submit, hint);
1303 if (result == ERESTART) {
1305 * The driver ran out of resources, mark the
1306 * driver ``blocked'' for cryptop's and put
1307 * the request back in the queue. It would
1308 * best to put the request back where we got
1309 * it but that's hard so for now we put it
1310 * at the front. This should be ok; putting
1311 * it at the end does not work.
1313 /* XXX validate sid again? */
1314 crypto_drivers[CRYPTO_SESID2HID(submit->crp_sid)].cc_qblocked = 1;
1315 TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
1316 cryptostats.cs_blocks++;
1320 /* As above, but for key ops */
1321 TAILQ_FOREACH(krp, &crp_kq, krp_next) {
1322 cap = crypto_checkdriver(krp->krp_hid);
1323 if (cap == NULL || cap->cc_dev == NULL) {
1325 * Operation needs to be migrated, invalidate
1326 * the assigned device so it will reselect a
1327 * new one below. Propagate the original
1328 * crid selection flags if supplied.
1330 krp->krp_hid = krp->krp_crid &
1331 (CRYPTOCAP_F_SOFTWARE|CRYPTOCAP_F_HARDWARE);
1332 if (krp->krp_hid == 0)
1334 CRYPTOCAP_F_SOFTWARE|CRYPTOCAP_F_HARDWARE;
1337 if (!cap->cc_kqblocked)
1341 TAILQ_REMOVE(&crp_kq, krp, krp_next);
1342 result = crypto_kinvoke(krp, krp->krp_hid);
1343 if (result == ERESTART) {
1345 * The driver ran out of resources, mark the
1346 * driver ``blocked'' for cryptkop's and put
1347 * the request back in the queue. It would
1348 * best to put the request back where we got
1349 * it but that's hard so for now we put it
1350 * at the front. This should be ok; putting
1351 * it at the end does not work.
1353 /* XXX validate sid again? */
1354 crypto_drivers[krp->krp_hid].cc_kqblocked = 1;
1355 TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
1356 cryptostats.cs_kblocks++;
1360 if (submit == NULL && krp == NULL) {
1362 * Nothing more to be processed. Sleep until we're
1363 * woken because there are more ops to process.
1364 * This happens either by submission or by a driver
1365 * becoming unblocked and notifying us through
1366 * crypto_unblock. Note that when we wakeup we
1367 * start processing each queue again from the
1368 * front. It's not clear that it's important to
1369 * preserve this ordering since ops may finish
1370 * out of order if dispatched to different devices
1371 * and some become blocked while others do not.
1374 msleep(&crp_q, &crypto_q_mtx, PWAIT, "crypto_wait", 0);
1376 if (cryptoproc == NULL)
1378 cryptostats.cs_intrs++;
1383 crypto_finis(&crp_q);
1387 * Crypto returns thread, does callbacks for processed crypto requests.
1388 * Callbacks are done here, rather than in the crypto drivers, because
1389 * callbacks typically are expensive and would slow interrupt handling.
1392 crypto_ret_proc(void)
1394 struct cryptop *crpt;
1395 struct cryptkop *krpt;
1399 /* Harvest return q's for completed ops */
1400 crpt = TAILQ_FIRST(&crp_ret_q);
1402 TAILQ_REMOVE(&crp_ret_q, crpt, crp_next);
1404 krpt = TAILQ_FIRST(&crp_ret_kq);
1406 TAILQ_REMOVE(&crp_ret_kq, krpt, krp_next);
1408 if (crpt != NULL || krpt != NULL) {
1409 CRYPTO_RETQ_UNLOCK();
1411 * Run callbacks unlocked.
1414 #ifdef CRYPTO_TIMING
1415 if (crypto_timing) {
1417 * NB: We must copy the timestamp before
1418 * doing the callback as the cryptop is
1419 * likely to be reclaimed.
1421 struct bintime t = crpt->crp_tstamp;
1422 crypto_tstat(&cryptostats.cs_cb, &t);
1423 crpt->crp_callback(crpt);
1424 crypto_tstat(&cryptostats.cs_finis, &t);
1427 crpt->crp_callback(crpt);
1430 krpt->krp_callback(krpt);
1434 * Nothing more to be processed. Sleep until we're
1435 * woken because there are more returns to process.
1437 msleep(&crp_ret_q, &crypto_ret_q_mtx, PWAIT,
1438 "crypto_ret_wait", 0);
1439 if (cryptoretproc == NULL)
1441 cryptostats.cs_rets++;
1444 CRYPTO_RETQ_UNLOCK();
1446 crypto_finis(&crp_ret_q);
1451 db_show_drivers(void)
1455 db_printf("%12s %4s %4s %8s %2s %2s\n"
1463 for (hid = 0; hid < crypto_drivers_num; hid++) {
1464 const struct cryptocap *cap = &crypto_drivers[hid];
1465 if (cap->cc_dev == NULL)
1467 db_printf("%-12s %4u %4u %08x %2u %2u\n"
1468 , device_get_nameunit(cap->cc_dev)
1470 , cap->cc_koperations
1478 DB_SHOW_COMMAND(crypto, db_show_crypto)
1480 struct cryptop *crp;
1485 db_printf("%4s %8s %4s %4s %4s %4s %8s %8s\n",
1486 "HID", "Caps", "Ilen", "Olen", "Etype", "Flags",
1487 "Desc", "Callback");
1488 TAILQ_FOREACH(crp, &crp_q, crp_next) {
1489 db_printf("%4u %08x %4u %4u %4u %04x %8p %8p\n"
1490 , (int) CRYPTO_SESID2HID(crp->crp_sid)
1491 , (int) CRYPTO_SESID2CAPS(crp->crp_sid)
1492 , crp->crp_ilen, crp->crp_olen
1499 if (!TAILQ_EMPTY(&crp_ret_q)) {
1500 db_printf("\n%4s %4s %4s %8s\n",
1501 "HID", "Etype", "Flags", "Callback");
1502 TAILQ_FOREACH(crp, &crp_ret_q, crp_next) {
1503 db_printf("%4u %4u %04x %8p\n"
1504 , (int) CRYPTO_SESID2HID(crp->crp_sid)
1513 DB_SHOW_COMMAND(kcrypto, db_show_kcrypto)
1515 struct cryptkop *krp;
1520 db_printf("%4s %5s %4s %4s %8s %4s %8s\n",
1521 "Op", "Status", "#IP", "#OP", "CRID", "HID", "Callback");
1522 TAILQ_FOREACH(krp, &crp_kq, krp_next) {
1523 db_printf("%4u %5u %4u %4u %08x %4u %8p\n"
1526 , krp->krp_iparams, krp->krp_oparams
1527 , krp->krp_crid, krp->krp_hid
1531 if (!TAILQ_EMPTY(&crp_ret_q)) {
1532 db_printf("%4s %5s %8s %4s %8s\n",
1533 "Op", "Status", "CRID", "HID", "Callback");
1534 TAILQ_FOREACH(krp, &crp_ret_kq, krp_next) {
1535 db_printf("%4u %5u %08x %4u %8p\n"
1538 , krp->krp_crid, krp->krp_hid
1546 int crypto_modevent(module_t mod, int type, void *unused);
1549 * Initialization code, both for static and dynamic loading.
1550 * Note this is not invoked with the usual MODULE_DECLARE
1551 * mechanism but instead is listed as a dependency by the
1552 * cryptosoft driver. This guarantees proper ordering of
1553 * calls on module load/unload.
1556 crypto_modevent(module_t mod, int type, void *unused)
1562 error = crypto_init();
1563 if (error == 0 && bootverbose)
1564 printf("crypto: <crypto core>\n");
1567 /*XXX disallow if active sessions */
1574 MODULE_VERSION(crypto, 1);
1575 MODULE_DEPEND(crypto, zlib, 1, 1, 1);