1 /* $FreeBSD: src/sys/opencrypto/crypto.c,v 1.28 2007/10/20 23:23:22 julian Exp $ */
3 * Copyright (c) 2002-2006 Sam Leffler. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 * Cryptographic Subsystem.
29 * This code is derived from the Openbsd Cryptographic Framework (OCF)
30 * that has the copyright shown below. Very little of the original
35 * The author of this code is Angelos D. Keromytis (angelos@cis.upenn.edu)
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.
41 * Copyright (c) 2000, 2001 Angelos D. Keromytis
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.
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
55 #define CRYPTO_TIMING /* enable timing support */
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/eventhandler.h>
62 #include <sys/kernel.h>
63 #include <sys/kthread.h>
65 #include <sys/module.h>
66 #include <sys/malloc.h>
68 #include <sys/sysctl.h>
69 #include <sys/thread2.h>
71 #include <vm/vm_zone.h>
75 #include <opencrypto/cryptodev.h>
76 #include <opencrypto/xform.h> /* XXX for M_XDATA */
80 #include "cryptodev_if.h"
83 * Crypto drivers register themselves by allocating a slot in the
84 * crypto_drivers table with crypto_get_driverid() and then registering
85 * each algorithm they support with crypto_register() and crypto_kregister().
87 static struct lock crypto_drivers_lock; /* lock on driver table */
88 #define CRYPTO_DRIVER_LOCK() lockmgr(&crypto_drivers_lock, LK_EXCLUSIVE)
89 #define CRYPTO_DRIVER_UNLOCK() lockmgr(&crypto_drivers_lock, LK_RELEASE)
90 #define CRYPTO_DRIVER_ASSERT() KKASSERT(lockstatus(&crypto_drivers_lock, curthread) != 0)
93 * Crypto device/driver capabilities structure.
96 * (d) - protected by CRYPTO_DRIVER_LOCK()
97 * (q) - protected by CRYPTO_Q_LOCK()
98 * Not tagged fields are read-only.
101 device_t cc_dev; /* (d) device/driver */
102 u_int32_t cc_sessions; /* (d) # of sessions */
103 u_int32_t cc_koperations; /* (d) # os asym operations */
105 * Largest possible operator length (in bits) for each type of
106 * encryption algorithm. XXX not used
108 u_int16_t cc_max_op_len[CRYPTO_ALGORITHM_MAX + 1];
109 u_int8_t cc_alg[CRYPTO_ALGORITHM_MAX + 1];
110 u_int8_t cc_kalg[CRK_ALGORITHM_MAX + 1];
112 int cc_flags; /* (d) flags */
113 #define CRYPTOCAP_F_CLEANUP 0x80000000 /* needs resource cleanup */
114 int cc_qblocked; /* (q) symmetric q blocked */
115 int cc_kqblocked; /* (q) asymmetric q blocked */
117 static struct cryptocap *crypto_drivers = NULL;
118 static int crypto_drivers_num = 0;
121 * There are two queues for crypto requests; one for symmetric (e.g.
122 * cipher) operations and one for asymmetric (e.g. MOD) operations.
123 * See below for how synchronization is handled.
124 * A single lock is used to lock access to both queues. We could
125 * have one per-queue but having one simplifies handling of block/unblock
128 static int crp_sleep = 0;
129 static TAILQ_HEAD(,cryptop) crp_q; /* request queues */
130 static TAILQ_HEAD(,cryptkop) crp_kq;
131 static struct lock crypto_q_lock;
132 #define CRYPTO_Q_LOCK() lockmgr(&crypto_q_lock, LK_EXCLUSIVE)
133 #define CRYPTO_Q_UNLOCK() lockmgr(&crypto_q_lock, LK_RELEASE)
136 * There are two queues for processing completed crypto requests; one
137 * for the symmetric and one for the asymmetric ops. We only need one
138 * but have two to avoid type futzing (cryptop vs. cryptkop). A single
139 * lock is used to lock access to both queues. Note that this lock
140 * must be separate from the lock on request queues to insure driver
141 * callbacks don't generate lock order reversals.
143 static TAILQ_HEAD(,cryptop) crp_ret_q; /* callback queues */
144 static TAILQ_HEAD(,cryptkop) crp_ret_kq;
145 static struct lock crypto_ret_q_lock;
146 #define CRYPTO_RETQ_LOCK() lockmgr(&crypto_ret_q_lock, LK_EXCLUSIVE)
147 #define CRYPTO_RETQ_UNLOCK() lockmgr(&crypto_ret_q_lock, LK_RELEASE)
148 #define CRYPTO_RETQ_EMPTY() (TAILQ_EMPTY(&crp_ret_q) && TAILQ_EMPTY(&crp_ret_kq))
151 * Crypto op and desciptor data structures are allocated
152 * from separate private zones.
154 static vm_zone_t cryptop_zone;
155 static vm_zone_t cryptodesc_zone;
157 int crypto_userasymcrypto = 1; /* userland may do asym crypto reqs */
158 SYSCTL_INT(_kern, OID_AUTO, userasymcrypto, CTLFLAG_RW,
159 &crypto_userasymcrypto, 0,
160 "Enable/disable user-mode access to asymmetric crypto support");
161 int crypto_devallowsoft = 0; /* only use hardware crypto for asym */
162 SYSCTL_INT(_kern, OID_AUTO, cryptodevallowsoft, CTLFLAG_RW,
163 &crypto_devallowsoft, 0,
164 "Enable/disable use of software asym crypto support");
166 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
168 static void crypto_proc(void);
169 static struct thread *cryptothread;
170 static void crypto_ret_proc(void);
171 static struct thread *cryptoretthread;
172 static void crypto_destroy(void);
173 static int crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint);
174 static int crypto_kinvoke(struct cryptkop *krp, int flags);
176 static struct cryptostats cryptostats;
177 SYSCTL_STRUCT(_kern, OID_AUTO, crypto_stats, CTLFLAG_RW, &cryptostats,
178 cryptostats, "Crypto system statistics");
181 static int crypto_timing = 0;
182 SYSCTL_INT(_debug, OID_AUTO, crypto_timing, CTLFLAG_RW,
183 &crypto_timing, 0, "Enable/disable crypto timing support");
191 lockinit(&crypto_drivers_lock, "crypto driver table", 0, LK_CANRECURSE);
195 lockinit(&crypto_q_lock, "crypto op queues", 0, LK_CANRECURSE);
197 TAILQ_INIT(&crp_ret_q);
198 TAILQ_INIT(&crp_ret_kq);
199 lockinit(&crypto_ret_q_lock, "crypto return queues", 0, LK_CANRECURSE);
201 cryptop_zone = zinit("cryptop", sizeof (struct cryptop), 0, 0, 1);
202 cryptodesc_zone = zinit("cryptodesc", sizeof (struct cryptodesc),
204 if (cryptodesc_zone == NULL || cryptop_zone == NULL) {
205 kprintf("crypto_init: cannot setup crypto zones\n");
210 crypto_drivers_num = CRYPTO_DRIVERS_INITIAL;
211 crypto_drivers = kmalloc(crypto_drivers_num *
212 sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT | M_ZERO);
213 if (crypto_drivers == NULL) {
214 kprintf("crypto_init: cannot malloc driver table\n");
219 error = kthread_create((void (*)(void *)) crypto_proc, NULL,
220 &cryptothread, "crypto");
222 kprintf("crypto_init: cannot start crypto thread; error %d",
227 error = kthread_create((void (*)(void *)) crypto_ret_proc, NULL,
228 &cryptoretthread, "crypto returns");
230 kprintf("crypto_init: cannot start cryptoret thread; error %d",
241 * Signal a crypto thread to terminate. We use the driver
242 * table lock to synchronize the sleep/wakeups so that we
243 * are sure the threads have terminated before we release
244 * the data structures they use. See crypto_finis below
245 * for the other half of this song-and-dance.
248 crypto_terminate(struct thread **tp, void *q)
252 KKASSERT(lockstatus(&crypto_drivers_lock, curthread) != 0);
258 tsleep_interlock(t, 0);
259 CRYPTO_DRIVER_UNLOCK(); /* let crypto_finis progress */
260 tsleep(t, 0, "crypto_destroy", 0);
262 CRYPTO_DRIVER_LOCK();
270 * Terminate any crypto threads.
272 CRYPTO_DRIVER_LOCK();
273 crypto_terminate(&cryptoproc, &crp_q);
274 crypto_terminate(&cryptoretproc, &crp_ret_q);
275 CRYPTO_DRIVER_UNLOCK();
277 /* XXX flush queues??? */
280 * Reclaim dynamically allocated resources.
282 if (crypto_drivers != NULL)
283 kfree(crypto_drivers, M_CRYPTO_DATA);
285 if (cryptodesc_zone != NULL)
286 zdestroy(cryptodesc_zone);
287 if (cryptop_zone != NULL)
288 zdestroy(cryptop_zone);
289 lockuninit(&crypto_q_mtx);
290 lockuninit(&crypto_ret_q_mtx);
291 lockuninit(&crypto_drivers_mtx);
294 static struct cryptocap *
295 crypto_checkdriver(u_int32_t hid)
297 if (crypto_drivers == NULL)
299 return (hid >= crypto_drivers_num ? NULL : &crypto_drivers[hid]);
303 * Compare a driver's list of supported algorithms against another
304 * list; return non-zero if all algorithms are supported.
307 driver_suitable(const struct cryptocap *cap, const struct cryptoini *cri)
309 const struct cryptoini *cr;
311 /* See if all the algorithms are supported. */
312 for (cr = cri; cr; cr = cr->cri_next)
313 if (cap->cc_alg[cr->cri_alg] == 0)
319 * Select a driver for a new session that supports the specified
320 * algorithms and, optionally, is constrained according to the flags.
321 * The algorithm we use here is pretty stupid; just use the
322 * first driver that supports all the algorithms we need. If there
323 * are multiple drivers we choose the driver with the fewest active
324 * sessions. We prefer hardware-backed drivers to software ones.
326 * XXX We need more smarts here (in real life too, but that's
327 * XXX another story altogether).
329 static struct cryptocap *
330 crypto_select_driver(const struct cryptoini *cri, int flags)
332 struct cryptocap *cap, *best;
335 CRYPTO_DRIVER_ASSERT();
338 * Look first for hardware crypto devices if permitted.
340 if (flags & CRYPTOCAP_F_HARDWARE)
341 match = CRYPTOCAP_F_HARDWARE;
343 match = CRYPTOCAP_F_SOFTWARE;
346 for (hid = 0; hid < crypto_drivers_num; hid++) {
347 cap = &crypto_drivers[hid];
349 * If it's not initialized, is in the process of
350 * going away, or is not appropriate (hardware
351 * or software based on match), then skip.
353 if (cap->cc_dev == NULL ||
354 (cap->cc_flags & CRYPTOCAP_F_CLEANUP) ||
355 (cap->cc_flags & match) == 0)
358 /* verify all the algorithms are supported. */
359 if (driver_suitable(cap, cri)) {
361 cap->cc_sessions < best->cc_sessions)
367 if (match == CRYPTOCAP_F_HARDWARE && (flags & CRYPTOCAP_F_SOFTWARE)) {
368 /* sort of an Algol 68-style for loop */
369 match = CRYPTOCAP_F_SOFTWARE;
376 * Create a new session. The crid argument specifies a crypto
377 * driver to use or constraints on a driver to select (hardware
378 * only, software only, either). Whatever driver is selected
379 * must be capable of the requested crypto algorithms.
382 crypto_newsession(u_int64_t *sid, struct cryptoini *cri, int crid)
384 struct cryptocap *cap;
388 CRYPTO_DRIVER_LOCK();
389 if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
391 * Use specified driver; verify it is capable.
393 cap = crypto_checkdriver(crid);
394 if (cap != NULL && !driver_suitable(cap, cri))
398 * No requested driver; select based on crid flags.
400 cap = crypto_select_driver(cri, crid);
402 * if NULL then can't do everything in one session.
403 * XXX Fix this. We need to inject a "virtual" session
404 * XXX layer right about here.
408 /* Call the driver initialization routine. */
409 hid = cap - crypto_drivers;
410 lid = hid; /* Pass the driver ID. */
411 err = CRYPTODEV_NEWSESSION(cap->cc_dev, &lid, cri);
413 (*sid) = (cap->cc_flags & 0xff000000)
414 | (hid & 0x00ffffff);
416 (*sid) |= (lid & 0xffffffff);
421 CRYPTO_DRIVER_UNLOCK();
426 crypto_remove(struct cryptocap *cap)
429 KKASSERT(lockstatus(&crypto_drivers_lock, curthread) != 0);
430 if (cap->cc_sessions == 0 && cap->cc_koperations == 0)
431 bzero(cap, sizeof(*cap));
435 * Delete an existing session (or a reserved session on an unregistered
439 crypto_freesession(u_int64_t sid)
441 struct cryptocap *cap;
445 CRYPTO_DRIVER_LOCK();
447 if (crypto_drivers == NULL) {
452 /* Determine two IDs. */
453 hid = CRYPTO_SESID2HID(sid);
455 if (hid >= crypto_drivers_num) {
459 cap = &crypto_drivers[hid];
461 if (cap->cc_sessions)
464 /* Call the driver cleanup routine, if available. */
465 err = CRYPTODEV_FREESESSION(cap->cc_dev, sid);
467 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP)
471 CRYPTO_DRIVER_UNLOCK();
476 * Return an unused driver id. Used by drivers prior to registering
477 * support for the algorithms they handle.
480 crypto_get_driverid(device_t dev, int flags)
482 struct cryptocap *newdrv;
485 if ((flags & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
486 kprintf("%s: no flags specified when registering driver\n",
487 device_get_nameunit(dev));
491 CRYPTO_DRIVER_LOCK();
493 for (i = 0; i < crypto_drivers_num; i++) {
494 if (crypto_drivers[i].cc_dev == NULL &&
495 (crypto_drivers[i].cc_flags & CRYPTOCAP_F_CLEANUP) == 0) {
500 /* Out of entries, allocate some more. */
501 if (i == crypto_drivers_num) {
502 /* Be careful about wrap-around. */
503 if (2 * crypto_drivers_num <= crypto_drivers_num) {
504 CRYPTO_DRIVER_UNLOCK();
505 kprintf("crypto: driver count wraparound!\n");
509 newdrv = kmalloc(2 * crypto_drivers_num *
510 sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT|M_ZERO);
511 if (newdrv == NULL) {
512 CRYPTO_DRIVER_UNLOCK();
513 kprintf("crypto: no space to expand driver table!\n");
517 bcopy(crypto_drivers, newdrv,
518 crypto_drivers_num * sizeof(struct cryptocap));
520 crypto_drivers_num *= 2;
522 kfree(crypto_drivers, M_CRYPTO_DATA);
523 crypto_drivers = newdrv;
526 /* NB: state is zero'd on free */
527 crypto_drivers[i].cc_sessions = 1; /* Mark */
528 crypto_drivers[i].cc_dev = dev;
529 crypto_drivers[i].cc_flags = flags;
531 kprintf("crypto: assign %s driver id %u, flags %u\n",
532 device_get_nameunit(dev), i, flags);
534 CRYPTO_DRIVER_UNLOCK();
540 * Lookup a driver by name. We match against the full device
541 * name and unit, and against just the name. The latter gives
542 * us a simple widlcarding by device name. On success return the
543 * driver/hardware identifier; otherwise return -1.
546 crypto_find_driver(const char *match)
548 int i, len = strlen(match);
550 CRYPTO_DRIVER_LOCK();
551 for (i = 0; i < crypto_drivers_num; i++) {
552 device_t dev = crypto_drivers[i].cc_dev;
554 (crypto_drivers[i].cc_flags & CRYPTOCAP_F_CLEANUP))
556 if (strncmp(match, device_get_nameunit(dev), len) == 0 ||
557 strncmp(match, device_get_name(dev), len) == 0)
560 CRYPTO_DRIVER_UNLOCK();
561 return i < crypto_drivers_num ? i : -1;
565 * Return the device_t for the specified driver or NULL
566 * if the driver identifier is invalid.
569 crypto_find_device_byhid(int hid)
571 struct cryptocap *cap = crypto_checkdriver(hid);
572 return cap != NULL ? cap->cc_dev : NULL;
576 * Return the device/driver capabilities.
579 crypto_getcaps(int hid)
581 struct cryptocap *cap = crypto_checkdriver(hid);
582 return cap != NULL ? cap->cc_flags : 0;
586 * Register support for a key-related algorithm. This routine
587 * is called once for each algorithm supported a driver.
590 crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags)
592 struct cryptocap *cap;
595 CRYPTO_DRIVER_LOCK();
597 cap = crypto_checkdriver(driverid);
599 (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
601 * XXX Do some performance testing to determine placing.
602 * XXX We probably need an auxiliary data structure that
603 * XXX describes relative performances.
606 cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
608 kprintf("crypto: %s registers key alg %u flags %u\n"
609 , device_get_nameunit(cap->cc_dev)
618 CRYPTO_DRIVER_UNLOCK();
623 * Register support for a non-key-related algorithm. This routine
624 * is called once for each such algorithm supported by a driver.
627 crypto_register(u_int32_t driverid, int alg, u_int16_t maxoplen,
630 struct cryptocap *cap;
633 CRYPTO_DRIVER_LOCK();
635 cap = crypto_checkdriver(driverid);
636 /* NB: algorithms are in the range [1..max] */
638 (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX)) {
640 * XXX Do some performance testing to determine placing.
641 * XXX We probably need an auxiliary data structure that
642 * XXX describes relative performances.
645 cap->cc_alg[alg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
646 cap->cc_max_op_len[alg] = maxoplen;
648 kprintf("crypto: %s registers alg %u flags %u maxoplen %u\n"
649 , device_get_nameunit(cap->cc_dev)
654 cap->cc_sessions = 0; /* Unmark */
659 CRYPTO_DRIVER_UNLOCK();
664 driver_finis(struct cryptocap *cap)
668 CRYPTO_DRIVER_ASSERT();
670 ses = cap->cc_sessions;
671 kops = cap->cc_koperations;
672 bzero(cap, sizeof(*cap));
673 if (ses != 0 || kops != 0) {
675 * If there are pending sessions,
676 * just mark as invalid.
678 cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
679 cap->cc_sessions = ses;
680 cap->cc_koperations = kops;
685 * Unregister a crypto driver. If there are pending sessions using it,
686 * leave enough information around so that subsequent calls using those
687 * sessions will correctly detect the driver has been unregistered and
691 crypto_unregister(u_int32_t driverid, int alg)
693 struct cryptocap *cap;
696 CRYPTO_DRIVER_LOCK();
697 cap = crypto_checkdriver(driverid);
699 (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX) &&
700 cap->cc_alg[alg] != 0) {
701 cap->cc_alg[alg] = 0;
702 cap->cc_max_op_len[alg] = 0;
704 /* Was this the last algorithm ? */
705 for (i = 1; i <= CRYPTO_ALGORITHM_MAX; i++)
706 if (cap->cc_alg[i] != 0)
709 if (i == CRYPTO_ALGORITHM_MAX + 1)
714 CRYPTO_DRIVER_UNLOCK();
720 * Unregister all algorithms associated with a crypto driver.
721 * If there are pending sessions using it, leave enough information
722 * around so that subsequent calls using those sessions will
723 * correctly detect the driver has been unregistered and reroute
727 crypto_unregister_all(u_int32_t driverid)
729 struct cryptocap *cap;
732 CRYPTO_DRIVER_LOCK();
733 cap = crypto_checkdriver(driverid);
739 CRYPTO_DRIVER_UNLOCK();
745 * Clear blockage on a driver. The what parameter indicates whether
746 * the driver is now ready for cryptop's and/or cryptokop's.
749 crypto_unblock(u_int32_t driverid, int what)
751 struct cryptocap *cap;
755 cap = crypto_checkdriver(driverid);
757 if (what & CRYPTO_SYMQ)
758 cap->cc_qblocked = 0;
759 if (what & CRYPTO_ASYMQ)
760 cap->cc_kqblocked = 0;
772 * Add a crypto request to a queue, to be processed by the kernel thread.
775 crypto_dispatch(struct cryptop *crp)
777 struct cryptocap *cap;
781 cryptostats.cs_ops++;
785 nanouptime(&crp->crp_tstamp);
788 hid = CRYPTO_SESID2HID(crp->crp_sid);
790 if ((crp->crp_flags & CRYPTO_F_BATCH) == 0) {
792 * Caller marked the request to be processed
793 * immediately; dispatch it directly to the
794 * driver unless the driver is currently blocked.
796 cap = crypto_checkdriver(hid);
797 /* Driver cannot disappeared when there is an active session. */
798 KASSERT(cap != NULL, ("%s: Driver disappeared.", __func__));
799 if (!cap->cc_qblocked) {
800 result = crypto_invoke(cap, crp, 0);
801 if (result != ERESTART)
804 * The driver ran out of resources, put the request on
810 TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
818 * Add an asymetric crypto request to a queue,
819 * to be processed by the kernel thread.
822 crypto_kdispatch(struct cryptkop *krp)
826 cryptostats.cs_kops++;
828 error = crypto_kinvoke(krp, krp->krp_crid);
829 if (error == ERESTART) {
831 TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
841 * Verify a driver is suitable for the specified operation.
844 kdriver_suitable(const struct cryptocap *cap, const struct cryptkop *krp)
846 return (cap->cc_kalg[krp->krp_op] & CRYPTO_ALG_FLAG_SUPPORTED) != 0;
850 * Select a driver for an asym operation. The driver must
851 * support the necessary algorithm. The caller can constrain
852 * which device is selected with the flags parameter. The
853 * algorithm we use here is pretty stupid; just use the first
854 * driver that supports the algorithms we need. If there are
855 * multiple suitable drivers we choose the driver with the
856 * fewest active operations. We prefer hardware-backed
857 * drivers to software ones when either may be used.
859 static struct cryptocap *
860 crypto_select_kdriver(const struct cryptkop *krp, int flags)
862 struct cryptocap *cap, *best, *blocked;
865 CRYPTO_DRIVER_ASSERT();
868 * Look first for hardware crypto devices if permitted.
870 if (flags & CRYPTOCAP_F_HARDWARE)
871 match = CRYPTOCAP_F_HARDWARE;
873 match = CRYPTOCAP_F_SOFTWARE;
877 for (hid = 0; hid < crypto_drivers_num; hid++) {
878 cap = &crypto_drivers[hid];
880 * If it's not initialized, is in the process of
881 * going away, or is not appropriate (hardware
882 * or software based on match), then skip.
884 if (cap->cc_dev == NULL ||
885 (cap->cc_flags & CRYPTOCAP_F_CLEANUP) ||
886 (cap->cc_flags & match) == 0)
889 /* verify all the algorithms are supported. */
890 if (kdriver_suitable(cap, krp)) {
892 cap->cc_koperations < best->cc_koperations)
898 if (match == CRYPTOCAP_F_HARDWARE && (flags & CRYPTOCAP_F_SOFTWARE)) {
899 /* sort of an Algol 68-style for loop */
900 match = CRYPTOCAP_F_SOFTWARE;
907 * Dispatch an assymetric crypto request.
910 crypto_kinvoke(struct cryptkop *krp, int crid)
912 struct cryptocap *cap = NULL;
915 KASSERT(krp != NULL, ("%s: krp == NULL", __func__));
916 KASSERT(krp->krp_callback != NULL,
917 ("%s: krp->crp_callback == NULL", __func__));
919 CRYPTO_DRIVER_LOCK();
920 if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
921 cap = crypto_checkdriver(crid);
924 * Driver present, it must support the necessary
925 * algorithm and, if s/w drivers are excluded,
926 * it must be registered as hardware-backed.
928 if (!kdriver_suitable(cap, krp) ||
929 (!crypto_devallowsoft &&
930 (cap->cc_flags & CRYPTOCAP_F_HARDWARE) == 0))
935 * No requested driver; select based on crid flags.
937 if (!crypto_devallowsoft) /* NB: disallow s/w drivers */
938 crid &= ~CRYPTOCAP_F_SOFTWARE;
939 cap = crypto_select_kdriver(krp, crid);
941 if (cap != NULL && !cap->cc_kqblocked) {
942 krp->krp_hid = cap - crypto_drivers;
943 cap->cc_koperations++;
944 CRYPTO_DRIVER_UNLOCK();
945 error = CRYPTODEV_KPROCESS(cap->cc_dev, krp, 0);
946 CRYPTO_DRIVER_LOCK();
947 if (error == ERESTART) {
948 cap->cc_koperations--;
949 CRYPTO_DRIVER_UNLOCK();
954 * NB: cap is !NULL if device is blocked; in
955 * that case return ERESTART so the operation
956 * is resubmitted if possible.
958 error = (cap == NULL) ? ENODEV : ERESTART;
960 CRYPTO_DRIVER_UNLOCK();
963 krp->krp_status = error;
971 crypto_tstat(struct cryptotstat *ts, struct timespec *tv)
973 struct timespec now, t;
976 t.tv_sec = now.tv_sec - tv->tv_sec;
977 t.tv_nsec = now.tv_nsec - tv->tv_nsec;
980 t.tv_nsec += 1000000000;
982 timespecadd(&ts->acc, &t);
983 if (timespeccmp(&t, &ts->min, <))
985 if (timespeccmp(&t, &ts->max, >))
994 * Dispatch a crypto request to the appropriate crypto devices.
997 crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint)
1000 KASSERT(crp != NULL, ("%s: crp == NULL", __func__));
1001 KASSERT(crp->crp_callback != NULL,
1002 ("%s: crp->crp_callback == NULL", __func__));
1003 KASSERT(crp->crp_desc != NULL, ("%s: crp->crp_desc == NULL", __func__));
1005 #ifdef CRYPTO_TIMING
1007 crypto_tstat(&cryptostats.cs_invoke, &crp->crp_tstamp);
1009 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1010 struct cryptodesc *crd;
1014 * Driver has unregistered; migrate the session and return
1015 * an error to the caller so they'll resubmit the op.
1017 * XXX: What if there are more already queued requests for this
1020 crypto_freesession(crp->crp_sid);
1022 for (crd = crp->crp_desc; crd->crd_next; crd = crd->crd_next)
1023 crd->CRD_INI.cri_next = &(crd->crd_next->CRD_INI);
1025 /* XXX propagate flags from initial session? */
1026 if (crypto_newsession(&nid, &(crp->crp_desc->CRD_INI),
1027 CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE) == 0)
1030 crp->crp_etype = EAGAIN;
1035 * Invoke the driver to process the request.
1037 return CRYPTODEV_PROCESS(cap->cc_dev, crp, hint);
1042 * Release a set of crypto descriptors.
1045 crypto_freereq(struct cryptop *crp)
1047 struct cryptodesc *crd;
1054 struct cryptop *crp2;
1057 TAILQ_FOREACH(crp2, &crp_q, crp_next) {
1058 KASSERT(crp2 != crp,
1059 ("Freeing cryptop from the crypto queue (%p).",
1064 TAILQ_FOREACH(crp2, &crp_ret_q, crp_next) {
1065 KASSERT(crp2 != crp,
1066 ("Freeing cryptop from the return queue (%p).",
1069 CRYPTO_RETQ_UNLOCK();
1073 while ((crd = crp->crp_desc) != NULL) {
1074 crp->crp_desc = crd->crd_next;
1075 zfree(cryptodesc_zone, crd);
1077 zfree(cryptop_zone, crp);
1081 * Acquire a set of crypto descriptors.
1084 crypto_getreq(int num)
1086 struct cryptodesc *crd;
1087 struct cryptop *crp;
1089 crp = zalloc(cryptop_zone);
1091 bzero(crp, sizeof (*crp));
1093 crd = zalloc(cryptodesc_zone);
1095 crypto_freereq(crp);
1098 bzero(crd, sizeof (*crd));
1100 crd->crd_next = crp->crp_desc;
1101 crp->crp_desc = crd;
1108 * Invoke the callback on behalf of the driver.
1111 crypto_done(struct cryptop *crp)
1113 KASSERT((crp->crp_flags & CRYPTO_F_DONE) == 0,
1114 ("crypto_done: op already done, flags 0x%x", crp->crp_flags));
1115 crp->crp_flags |= CRYPTO_F_DONE;
1116 if (crp->crp_etype != 0)
1117 cryptostats.cs_errs++;
1118 #ifdef CRYPTO_TIMING
1120 crypto_tstat(&cryptostats.cs_done, &crp->crp_tstamp);
1123 * CBIMM means unconditionally do the callback immediately;
1124 * CBIFSYNC means do the callback immediately only if the
1125 * operation was done synchronously. Both are used to avoid
1126 * doing extraneous context switches; the latter is mostly
1127 * used with the software crypto driver.
1129 if ((crp->crp_flags & CRYPTO_F_CBIMM) ||
1130 ((crp->crp_flags & CRYPTO_F_CBIFSYNC) &&
1131 (CRYPTO_SESID2CAPS(crp->crp_sid) & CRYPTOCAP_F_SYNC))) {
1133 * Do the callback directly. This is ok when the
1134 * callback routine does very little (e.g. the
1135 * /dev/crypto callback method just does a wakeup).
1137 #ifdef CRYPTO_TIMING
1138 if (crypto_timing) {
1140 * NB: We must copy the timestamp before
1141 * doing the callback as the cryptop is
1142 * likely to be reclaimed.
1144 struct timespec t = crp->crp_tstamp;
1145 crypto_tstat(&cryptostats.cs_cb, &t);
1146 crp->crp_callback(crp);
1147 crypto_tstat(&cryptostats.cs_finis, &t);
1150 crp->crp_callback(crp);
1153 * Normal case; queue the callback for the thread.
1156 if (CRYPTO_RETQ_EMPTY())
1157 wakeup_one(&crp_ret_q); /* shared wait channel */
1158 TAILQ_INSERT_TAIL(&crp_ret_q, crp, crp_next);
1159 CRYPTO_RETQ_UNLOCK();
1164 * Invoke the callback on behalf of the driver.
1167 crypto_kdone(struct cryptkop *krp)
1169 struct cryptocap *cap;
1171 if (krp->krp_status != 0)
1172 cryptostats.cs_kerrs++;
1173 CRYPTO_DRIVER_LOCK();
1174 /* XXX: What if driver is loaded in the meantime? */
1175 if (krp->krp_hid < crypto_drivers_num) {
1176 cap = &crypto_drivers[krp->krp_hid];
1177 cap->cc_koperations--;
1178 KASSERT(cap->cc_koperations >= 0, ("cc_koperations < 0"));
1179 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP)
1182 CRYPTO_DRIVER_UNLOCK();
1184 if (CRYPTO_RETQ_EMPTY())
1185 wakeup_one(&crp_ret_q); /* shared wait channel */
1186 TAILQ_INSERT_TAIL(&crp_ret_kq, krp, krp_next);
1187 CRYPTO_RETQ_UNLOCK();
1191 crypto_getfeat(int *featp)
1193 int hid, kalg, feat = 0;
1195 CRYPTO_DRIVER_LOCK();
1196 for (hid = 0; hid < crypto_drivers_num; hid++) {
1197 const struct cryptocap *cap = &crypto_drivers[hid];
1199 if ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
1200 !crypto_devallowsoft) {
1203 for (kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
1204 if (cap->cc_kalg[kalg] & CRYPTO_ALG_FLAG_SUPPORTED)
1207 CRYPTO_DRIVER_UNLOCK();
1213 * Terminate a thread at module unload. The process that
1214 * initiated this is waiting for us to signal that we're gone;
1215 * wake it up and exit. We use the driver table lock to insure
1216 * we don't do the wakeup before they're waiting. There is no
1217 * race here because the waiter sleeps on the proc lock for the
1218 * thread so it gets notified at the right time because of an
1219 * extra wakeup that's done in exit1().
1222 crypto_finis(void *chan)
1224 CRYPTO_DRIVER_LOCK();
1226 CRYPTO_DRIVER_UNLOCK();
1231 * Crypto thread, dispatches crypto requests.
1236 struct cryptop *crp, *submit;
1237 struct cryptkop *krp;
1238 struct cryptocap *cap;
1245 * Find the first element in the queue that can be
1246 * processed and look-ahead to see if multiple ops
1247 * are ready for the same driver.
1251 TAILQ_FOREACH(crp, &crp_q, crp_next) {
1252 hid = CRYPTO_SESID2HID(crp->crp_sid);
1253 cap = crypto_checkdriver(hid);
1255 * Driver cannot disappeared when there is an active
1258 KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1259 __func__, __LINE__));
1260 if (cap == NULL || cap->cc_dev == NULL) {
1261 /* Op needs to be migrated, process it. */
1266 if (!cap->cc_qblocked) {
1267 if (submit != NULL) {
1269 * We stop on finding another op,
1270 * regardless whether its for the same
1271 * driver or not. We could keep
1272 * searching the queue but it might be
1273 * better to just use a per-driver
1276 if (CRYPTO_SESID2HID(submit->crp_sid) == hid)
1277 hint = CRYPTO_HINT_MORE;
1281 if ((submit->crp_flags & CRYPTO_F_BATCH) == 0)
1283 /* keep scanning for more are q'd */
1287 if (submit != NULL) {
1288 TAILQ_REMOVE(&crp_q, submit, crp_next);
1289 hid = CRYPTO_SESID2HID(submit->crp_sid);
1290 cap = crypto_checkdriver(hid);
1291 KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1292 __func__, __LINE__));
1293 result = crypto_invoke(cap, submit, hint);
1294 if (result == ERESTART) {
1296 * The driver ran out of resources, mark the
1297 * driver ``blocked'' for cryptop's and put
1298 * the request back in the queue. It would
1299 * best to put the request back where we got
1300 * it but that's hard so for now we put it
1301 * at the front. This should be ok; putting
1302 * it at the end does not work.
1304 /* XXX validate sid again? */
1305 crypto_drivers[CRYPTO_SESID2HID(submit->crp_sid)].cc_qblocked = 1;
1306 TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
1307 cryptostats.cs_blocks++;
1311 /* As above, but for key ops */
1312 TAILQ_FOREACH(krp, &crp_kq, krp_next) {
1313 cap = crypto_checkdriver(krp->krp_hid);
1314 if (cap == NULL || cap->cc_dev == NULL) {
1316 * Operation needs to be migrated, invalidate
1317 * the assigned device so it will reselect a
1318 * new one below. Propagate the original
1319 * crid selection flags if supplied.
1321 krp->krp_hid = krp->krp_crid &
1322 (CRYPTOCAP_F_SOFTWARE|CRYPTOCAP_F_HARDWARE);
1323 if (krp->krp_hid == 0)
1325 CRYPTOCAP_F_SOFTWARE|CRYPTOCAP_F_HARDWARE;
1328 if (!cap->cc_kqblocked)
1332 TAILQ_REMOVE(&crp_kq, krp, krp_next);
1333 result = crypto_kinvoke(krp, krp->krp_hid);
1334 if (result == ERESTART) {
1336 * The driver ran out of resources, mark the
1337 * driver ``blocked'' for cryptkop's and put
1338 * the request back in the queue. It would
1339 * best to put the request back where we got
1340 * it but that's hard so for now we put it
1341 * at the front. This should be ok; putting
1342 * it at the end does not work.
1344 /* XXX validate sid again? */
1345 crypto_drivers[krp->krp_hid].cc_kqblocked = 1;
1346 TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
1347 cryptostats.cs_kblocks++;
1351 if (submit == NULL && krp == NULL) {
1353 * Nothing more to be processed. Sleep until we're
1354 * woken because there are more ops to process.
1355 * This happens either by submission or by a driver
1356 * becoming unblocked and notifying us through
1357 * crypto_unblock. Note that when we wakeup we
1358 * start processing each queue again from the
1359 * front. It's not clear that it's important to
1360 * preserve this ordering since ops may finish
1361 * out of order if dispatched to different devices
1362 * and some become blocked while others do not.
1365 tsleep(&crp_q, 0, "crypto_wait", 0);
1367 if (cryptoproc == NULL)
1369 cryptostats.cs_intrs++;
1374 crypto_finis(&crp_q);
1378 * Crypto returns thread, does callbacks for processed crypto requests.
1379 * Callbacks are done here, rather than in the crypto drivers, because
1380 * callbacks typically are expensive and would slow interrupt handling.
1383 crypto_ret_proc(void)
1385 struct cryptop *crpt;
1386 struct cryptkop *krpt;
1390 /* Harvest return q's for completed ops */
1391 crpt = TAILQ_FIRST(&crp_ret_q);
1393 TAILQ_REMOVE(&crp_ret_q, crpt, crp_next);
1395 krpt = TAILQ_FIRST(&crp_ret_kq);
1397 TAILQ_REMOVE(&crp_ret_kq, krpt, krp_next);
1399 if (crpt != NULL || krpt != NULL) {
1400 CRYPTO_RETQ_UNLOCK();
1402 * Run callbacks unlocked.
1405 #ifdef CRYPTO_TIMING
1406 if (crypto_timing) {
1408 * NB: We must copy the timestamp before
1409 * doing the callback as the cryptop is
1410 * likely to be reclaimed.
1412 struct timespec t = crp->crp_tstamp;
1413 crypto_tstat(&cryptostats.cs_cb, &t);
1414 crpt->crp_callback(crpt);
1415 crypto_tstat(&cryptostats.cs_finis, &t);
1418 crpt->crp_callback(crpt);
1421 krpt->krp_callback(krpt);
1425 * Nothing more to be processed. Sleep until we're
1426 * woken because there are more returns to process.
1428 tsleep(&crp_ret_q, 0, "crypto_ret_wait", 0);
1429 if (cryptoretproc == NULL)
1431 cryptostats.cs_rets++;
1434 CRYPTO_RETQ_UNLOCK();
1436 crypto_finis(&crp_ret_q);
1441 db_show_drivers(void)
1445 db_printf("%12s %4s %4s %8s %2s %2s\n"
1453 for (hid = 0; hid < crypto_drivers_num; hid++) {
1454 const struct cryptocap *cap = &crypto_drivers[hid];
1455 if (cap->cc_dev == NULL)
1457 db_printf("%-12s %4u %4u %08x %2u %2u\n"
1458 , device_get_nameunit(cap->cc_dev)
1460 , cap->cc_koperations
1468 DB_SHOW_COMMAND(crypto, db_show_crypto)
1470 struct cryptop *crp;
1475 db_printf("%4s %8s %4s %4s %4s %4s %8s %8s\n",
1476 "HID", "Caps", "Ilen", "Olen", "Etype", "Flags",
1477 "Desc", "Callback");
1478 TAILQ_FOREACH(crp, &crp_q, crp_next) {
1479 db_printf("%4u %08x %4u %4u %4u %04x %8p %8p\n"
1480 , (int) CRYPTO_SESID2HID(crp->crp_sid)
1481 , (int) CRYPTO_SESID2CAPS(crp->crp_sid)
1482 , crp->crp_ilen, crp->crp_olen
1489 if (!TAILQ_EMPTY(&crp_ret_q)) {
1490 db_printf("\n%4s %4s %4s %8s\n",
1491 "HID", "Etype", "Flags", "Callback");
1492 TAILQ_FOREACH(crp, &crp_ret_q, crp_next) {
1493 db_printf("%4u %4u %04x %8p\n"
1494 , (int) CRYPTO_SESID2HID(crp->crp_sid)
1503 DB_SHOW_COMMAND(kcrypto, db_show_kcrypto)
1505 struct cryptkop *krp;
1510 db_printf("%4s %5s %4s %4s %8s %4s %8s\n",
1511 "Op", "Status", "#IP", "#OP", "CRID", "HID", "Callback");
1512 TAILQ_FOREACH(krp, &crp_kq, krp_next) {
1513 db_printf("%4u %5u %4u %4u %08x %4u %8p\n"
1516 , krp->krp_iparams, krp->krp_oparams
1517 , krp->krp_crid, krp->krp_hid
1521 if (!TAILQ_EMPTY(&crp_ret_q)) {
1522 db_printf("%4s %5s %8s %4s %8s\n",
1523 "Op", "Status", "CRID", "HID", "Callback");
1524 TAILQ_FOREACH(krp, &crp_ret_kq, krp_next) {
1525 db_printf("%4u %5u %08x %4u %8p\n"
1528 , krp->krp_crid, krp->krp_hid
1536 int crypto_modevent(module_t mod, int type, void *unused);
1539 * Initialization code, both for static and dynamic loading.
1540 * Note this is not invoked with the usual MODULE_DECLARE
1541 * mechanism but instead is listed as a dependency by the
1542 * cryptosoft driver. This guarantees proper ordering of
1543 * calls on module load/unload.
1546 crypto_modevent(module_t mod, int type, void *unused)
1552 error = crypto_init();
1553 if (error == 0 && bootverbose)
1554 printf("crypto: <crypto core>\n");
1557 /*XXX disallow if active sessions */
1564 MODULE_VERSION(crypto, 1);
1565 MODULE_DEPEND(crypto, zlib, 1, 1, 1);