kernel - opencrypto - optimize chained synchronous callbacks for soft crypto
[dragonfly.git] / sys / opencrypto / crypto.c
1 /*      $FreeBSD: src/sys/opencrypto/crypto.c,v 1.28 2007/10/20 23:23:22 julian Exp $   */
2 /*-
3  * Copyright (c) 2002-2006 Sam Leffler.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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.
13  *
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.
24  */
25
26 /*
27  * Cryptographic Subsystem.
28  *
29  * This code is derived from the Openbsd Cryptographic Framework (OCF)
30  * that has the copyright shown below.  Very little of the original
31  * code remains.
32  */
33
34 /*-
35  * The author of this code is Angelos D. Keromytis (angelos@cis.upenn.edu)
36  *
37  * This code was written by Angelos D. Keromytis in Athens, Greece, in
38  * February 2000. Network Security Technologies Inc. (NSTI) kindly
39  * supported the development of this code.
40  *
41  * Copyright (c) 2000, 2001 Angelos D. Keromytis
42  *
43  * Permission to use, copy, and modify this software with or without fee
44  * is hereby granted, provided that this entire notice is included in
45  * all source code copies of any software which is or includes a copy or
46  * modification of this software.
47  *
48  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
49  * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
50  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
51  * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
52  * PURPOSE.
53  */
54
55 #define CRYPTO_TIMING                           /* enable timing support */
56
57 #include "opt_ddb.h"
58
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>
64 #include <sys/lock.h>
65 #include <sys/module.h>
66 #include <sys/malloc.h>
67 #include <sys/proc.h>
68 #include <sys/sysctl.h>
69 #include <sys/thread2.h>
70 #include <sys/mplock2.h>
71
72 #include <vm/vm_zone.h>
73
74 #include <ddb/ddb.h>
75
76 #include <opencrypto/cryptodev.h>
77 #include <opencrypto/xform.h>                   /* XXX for M_XDATA */
78
79 #include <sys/kobj.h>
80 #include <sys/bus.h>
81 #include "cryptodev_if.h"
82
83 /*
84  * Crypto drivers register themselves by allocating a slot in the
85  * crypto_drivers table with crypto_get_driverid() and then registering
86  * each algorithm they support with crypto_register() and crypto_kregister().
87  */
88 static  struct lock crypto_drivers_lock;        /* lock on driver table */
89 #define CRYPTO_DRIVER_LOCK()    lockmgr(&crypto_drivers_lock, LK_EXCLUSIVE)
90 #define CRYPTO_DRIVER_UNLOCK()  lockmgr(&crypto_drivers_lock, LK_RELEASE)
91 #define CRYPTO_DRIVER_ASSERT()  KKASSERT(lockstatus(&crypto_drivers_lock, curthread) != 0)
92
93 /*
94  * Crypto device/driver capabilities structure.
95  *
96  * Synchronization:
97  * (d) - protected by CRYPTO_DRIVER_LOCK()
98  * (q) - protected by CRYPTO_Q_LOCK()
99  * Not tagged fields are read-only.
100  */
101 struct cryptocap {
102         device_t        cc_dev;                 /* (d) device/driver */
103         u_int32_t       cc_sessions;            /* (d) # of sessions */
104         u_int32_t       cc_koperations;         /* (d) # os asym operations */
105         /*
106          * Largest possible operator length (in bits) for each type of
107          * encryption algorithm. XXX not used
108          */
109         u_int16_t       cc_max_op_len[CRYPTO_ALGORITHM_MAX + 1];
110         u_int8_t        cc_alg[CRYPTO_ALGORITHM_MAX + 1];
111         u_int8_t        cc_kalg[CRK_ALGORITHM_MAX + 1];
112
113         int             cc_flags;               /* (d) flags */
114 #define CRYPTOCAP_F_CLEANUP     0x80000000      /* needs resource cleanup */
115         int             cc_qblocked;            /* (q) symmetric q blocked */
116         int             cc_kqblocked;           /* (q) asymmetric q blocked */
117 };
118 static  struct cryptocap *crypto_drivers = NULL;
119 static  int crypto_drivers_num = 0;
120
121 typedef struct crypto_tdinfo {
122         TAILQ_HEAD(,cryptop)    crp_q;          /* request queues */
123         TAILQ_HEAD(,cryptkop)   crp_kq;
124         thread_t                crp_td;
125         struct lock             crp_lock;
126         int                     crp_sleep;
127 } *crypto_tdinfo_t;
128
129 /*
130  * There are two queues for crypto requests; one for symmetric (e.g.
131  * cipher) operations and one for asymmetric (e.g. MOD) operations.
132  * See below for how synchronization is handled.
133  * A single lock is used to lock access to both queues.  We could
134  * have one per-queue but having one simplifies handling of block/unblock
135  * operations.
136  */
137 static  struct crypto_tdinfo tdinfo_array[MAXCPU];
138
139 #define CRYPTO_Q_LOCK(tdinfo)   lockmgr(&tdinfo->crp_lock, LK_EXCLUSIVE)
140 #define CRYPTO_Q_UNLOCK(tdinfo) lockmgr(&tdinfo->crp_lock, LK_RELEASE)
141
142 /*
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  * lock 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.
149  */
150 static  TAILQ_HEAD(,cryptop) crp_ret_q;         /* callback queues */
151 static  TAILQ_HEAD(,cryptkop) crp_ret_kq;
152 static  struct lock crypto_ret_q_lock;
153 #define CRYPTO_RETQ_LOCK()      lockmgr(&crypto_ret_q_lock, LK_EXCLUSIVE)
154 #define CRYPTO_RETQ_UNLOCK()    lockmgr(&crypto_ret_q_lock, LK_RELEASE)
155 #define CRYPTO_RETQ_EMPTY()     (TAILQ_EMPTY(&crp_ret_q) && TAILQ_EMPTY(&crp_ret_kq))
156
157 /*
158  * Crypto op and desciptor data structures are allocated
159  * from separate private zones.
160  */
161 static  vm_zone_t cryptop_zone;
162 static  vm_zone_t cryptodesc_zone;
163
164 int     crypto_userasymcrypto = 1;      /* userland may do asym crypto reqs */
165 SYSCTL_INT(_kern, OID_AUTO, userasymcrypto, CTLFLAG_RW,
166            &crypto_userasymcrypto, 0,
167            "Enable/disable user-mode access to asymmetric crypto support");
168 int     crypto_devallowsoft = 0;        /* only use hardware crypto for asym */
169 SYSCTL_INT(_kern, OID_AUTO, cryptodevallowsoft, CTLFLAG_RW,
170            &crypto_devallowsoft, 0,
171            "Enable/disable use of software asym crypto support");
172 int     crypto_altdispatch = 0;         /* dispatch to alternative cpu */
173 SYSCTL_INT(_kern, OID_AUTO, cryptoaltdispatch, CTLFLAG_RW,
174            &crypto_altdispatch, 0,
175            "Do not queue crypto op on current cpu");
176
177 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
178
179 static  void crypto_proc(void *dummy);
180 static  void crypto_ret_proc(void *dummy);
181 static  struct thread *cryptoretthread;
182 static  void crypto_destroy(void);
183 static  int crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint);
184 static  int crypto_kinvoke(struct cryptkop *krp, int flags);
185
186 static struct cryptostats cryptostats;
187 SYSCTL_STRUCT(_kern, OID_AUTO, crypto_stats, CTLFLAG_RW, &cryptostats,
188             cryptostats, "Crypto system statistics");
189
190 #ifdef CRYPTO_TIMING
191 static  int crypto_timing = 0;
192 SYSCTL_INT(_debug, OID_AUTO, crypto_timing, CTLFLAG_RW,
193            &crypto_timing, 0, "Enable/disable crypto timing support");
194 #endif
195
196 static int
197 crypto_init(void)
198 {
199         crypto_tdinfo_t tdinfo;
200         int error;
201         int n;
202
203         lockinit(&crypto_drivers_lock, "crypto driver table", 0, LK_CANRECURSE);
204
205         TAILQ_INIT(&crp_ret_q);
206         TAILQ_INIT(&crp_ret_kq);
207         lockinit(&crypto_ret_q_lock, "crypto return queues", 0, LK_CANRECURSE);
208
209         cryptop_zone = zinit("cryptop", sizeof (struct cryptop), 0, 0, 1);
210         cryptodesc_zone = zinit("cryptodesc", sizeof (struct cryptodesc),
211                                 0, 0, 1);
212         if (cryptodesc_zone == NULL || cryptop_zone == NULL) {
213                 kprintf("crypto_init: cannot setup crypto zones\n");
214                 error = ENOMEM;
215                 goto bad;
216         }
217
218         crypto_drivers_num = CRYPTO_DRIVERS_INITIAL;
219         crypto_drivers = kmalloc(crypto_drivers_num * sizeof(struct cryptocap),
220                                  M_CRYPTO_DATA, M_WAITOK | M_ZERO);
221         if (crypto_drivers == NULL) {
222                 kprintf("crypto_init: cannot malloc driver table\n");
223                 error = ENOMEM;
224                 goto bad;
225         }
226
227         for (n = 0; n < ncpus; ++n) {
228                 tdinfo = &tdinfo_array[n];
229                 TAILQ_INIT(&tdinfo->crp_q);
230                 TAILQ_INIT(&tdinfo->crp_kq);
231                 lockinit(&tdinfo->crp_lock, "crypto op queues",
232                          0, LK_CANRECURSE);
233                 kthread_create_cpu(crypto_proc, tdinfo, &tdinfo->crp_td,
234                                    n, "crypto %d", n);
235         }
236         kthread_create(crypto_ret_proc, NULL,
237                        &cryptoretthread, "crypto returns");
238         return 0;
239 bad:
240         crypto_destroy();
241         return error;
242 }
243
244 /*
245  * Signal a crypto thread to terminate.  We use the driver
246  * table lock to synchronize the sleep/wakeups so that we
247  * are sure the threads have terminated before we release
248  * the data structures they use.  See crypto_finis below
249  * for the other half of this song-and-dance.
250  */
251 static void
252 crypto_terminate(struct thread **tp, void *q)
253 {
254         struct thread *t;
255
256         KKASSERT(lockstatus(&crypto_drivers_lock, curthread) != 0);
257         t = *tp;
258         *tp = NULL;
259         if (t) {
260                 kprintf("crypto_terminate: start\n");
261                 wakeup_one(q);
262                 crit_enter();
263                 tsleep_interlock(t, 0);
264                 CRYPTO_DRIVER_UNLOCK(); /* let crypto_finis progress */
265                 crit_exit();
266                 tsleep(t, PINTERLOCKED, "crypto_destroy", 0);
267                 CRYPTO_DRIVER_LOCK();
268                 kprintf("crypto_terminate: end\n");
269         }
270 }
271
272 static void
273 crypto_destroy(void)
274 {
275         crypto_tdinfo_t tdinfo;
276         int n;
277
278         /*
279          * Terminate any crypto threads.
280          */
281         CRYPTO_DRIVER_LOCK();
282         for (n = 0; n < ncpus; ++n) {
283                 tdinfo = &tdinfo_array[n];
284                 crypto_terminate(&tdinfo->crp_td, &tdinfo->crp_q);
285                 lockuninit(&tdinfo->crp_lock);
286         }
287         crypto_terminate(&cryptoretthread, &crp_ret_q);
288         CRYPTO_DRIVER_UNLOCK();
289
290         /* XXX flush queues??? */
291
292         /*
293          * Reclaim dynamically allocated resources.
294          */
295         if (crypto_drivers != NULL)
296                 kfree(crypto_drivers, M_CRYPTO_DATA);
297
298         if (cryptodesc_zone != NULL)
299                 zdestroy(cryptodesc_zone);
300         if (cryptop_zone != NULL)
301                 zdestroy(cryptop_zone);
302         lockuninit(&crypto_ret_q_lock);
303         lockuninit(&crypto_drivers_lock);
304 }
305
306 static struct cryptocap *
307 crypto_checkdriver(u_int32_t hid)
308 {
309         if (crypto_drivers == NULL)
310                 return NULL;
311         return (hid >= crypto_drivers_num ? NULL : &crypto_drivers[hid]);
312 }
313
314 /*
315  * Compare a driver's list of supported algorithms against another
316  * list; return non-zero if all algorithms are supported.
317  */
318 static int
319 driver_suitable(const struct cryptocap *cap, const struct cryptoini *cri)
320 {
321         const struct cryptoini *cr;
322
323         /* See if all the algorithms are supported. */
324         for (cr = cri; cr; cr = cr->cri_next)
325                 if (cap->cc_alg[cr->cri_alg] == 0)
326                         return 0;
327         return 1;
328 }
329
330 /*
331  * Select a driver for a new session that supports the specified
332  * algorithms and, optionally, is constrained according to the flags.
333  * The algorithm we use here is pretty stupid; just use the
334  * first driver that supports all the algorithms we need. If there
335  * are multiple drivers we choose the driver with the fewest active
336  * sessions.  We prefer hardware-backed drivers to software ones.
337  *
338  * XXX We need more smarts here (in real life too, but that's
339  * XXX another story altogether).
340  */
341 static struct cryptocap *
342 crypto_select_driver(const struct cryptoini *cri, int flags)
343 {
344         struct cryptocap *cap, *best;
345         int match, hid;
346
347         CRYPTO_DRIVER_ASSERT();
348
349         /*
350          * Look first for hardware crypto devices if permitted.
351          */
352         if (flags & CRYPTOCAP_F_HARDWARE)
353                 match = CRYPTOCAP_F_HARDWARE;
354         else
355                 match = CRYPTOCAP_F_SOFTWARE;
356         best = NULL;
357 again:
358         for (hid = 0; hid < crypto_drivers_num; hid++) {
359                 cap = &crypto_drivers[hid];
360                 /*
361                  * If it's not initialized, is in the process of
362                  * going away, or is not appropriate (hardware
363                  * or software based on match), then skip.
364                  */
365                 if (cap->cc_dev == NULL ||
366                     (cap->cc_flags & CRYPTOCAP_F_CLEANUP) ||
367                     (cap->cc_flags & match) == 0)
368                         continue;
369
370                 /* verify all the algorithms are supported. */
371                 if (driver_suitable(cap, cri)) {
372                         if (best == NULL ||
373                             cap->cc_sessions < best->cc_sessions)
374                                 best = cap;
375                 }
376         }
377         if (best != NULL)
378                 return best;
379         if (match == CRYPTOCAP_F_HARDWARE && (flags & CRYPTOCAP_F_SOFTWARE)) {
380                 /* sort of an Algol 68-style for loop */
381                 match = CRYPTOCAP_F_SOFTWARE;
382                 goto again;
383         }
384         return best;
385 }
386
387 /*
388  * Create a new session.  The crid argument specifies a crypto
389  * driver to use or constraints on a driver to select (hardware
390  * only, software only, either).  Whatever driver is selected
391  * must be capable of the requested crypto algorithms.
392  */
393 int
394 crypto_newsession(u_int64_t *sid, struct cryptoini *cri, int crid)
395 {
396         struct cryptocap *cap;
397         u_int32_t hid, lid;
398         int err;
399
400         CRYPTO_DRIVER_LOCK();
401         if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
402                 /*
403                  * Use specified driver; verify it is capable.
404                  */
405                 cap = crypto_checkdriver(crid);
406                 if (cap != NULL && !driver_suitable(cap, cri))
407                         cap = NULL;
408         } else {
409                 /*
410                  * No requested driver; select based on crid flags.
411                  */
412                 cap = crypto_select_driver(cri, crid);
413                 /*
414                  * if NULL then can't do everything in one session.
415                  * XXX Fix this. We need to inject a "virtual" session
416                  * XXX layer right about here.
417                  */
418         }
419         if (cap != NULL) {
420                 /* Call the driver initialization routine. */
421                 hid = cap - crypto_drivers;
422                 lid = hid;              /* Pass the driver ID. */
423                 err = CRYPTODEV_NEWSESSION(cap->cc_dev, &lid, cri);
424                 if (err == 0) {
425                         (*sid) = (cap->cc_flags & 0xff000000)
426                                | (hid & 0x00ffffff);
427                         (*sid) <<= 32;
428                         (*sid) |= (lid & 0xffffffff);
429                         cap->cc_sessions++;
430                 }
431         } else
432                 err = EINVAL;
433         CRYPTO_DRIVER_UNLOCK();
434         return err;
435 }
436
437 static void
438 crypto_remove(struct cryptocap *cap)
439 {
440
441         KKASSERT(lockstatus(&crypto_drivers_lock, curthread) != 0);
442         if (cap->cc_sessions == 0 && cap->cc_koperations == 0)
443                 bzero(cap, sizeof(*cap));
444 }
445
446 /*
447  * Delete an existing session (or a reserved session on an unregistered
448  * driver).
449  */
450 int
451 crypto_freesession(u_int64_t sid)
452 {
453         struct cryptocap *cap;
454         u_int32_t hid;
455         int err;
456
457         CRYPTO_DRIVER_LOCK();
458
459         if (crypto_drivers == NULL) {
460                 err = EINVAL;
461                 goto done;
462         }
463
464         /* Determine two IDs. */
465         hid = CRYPTO_SESID2HID(sid);
466
467         if (hid >= crypto_drivers_num) {
468                 err = ENOENT;
469                 goto done;
470         }
471         cap = &crypto_drivers[hid];
472
473         if (cap->cc_sessions)
474                 cap->cc_sessions--;
475
476         /* Call the driver cleanup routine, if available. */
477         err = CRYPTODEV_FREESESSION(cap->cc_dev, sid);
478
479         if (cap->cc_flags & CRYPTOCAP_F_CLEANUP)
480                 crypto_remove(cap);
481
482 done:
483         CRYPTO_DRIVER_UNLOCK();
484         return err;
485 }
486
487 /*
488  * Return an unused driver id.  Used by drivers prior to registering
489  * support for the algorithms they handle.
490  */
491 int32_t
492 crypto_get_driverid(device_t dev, int flags)
493 {
494         struct cryptocap *newdrv;
495         int i;
496
497         if ((flags & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
498                 kprintf("%s: no flags specified when registering driver\n",
499                     device_get_nameunit(dev));
500                 return -1;
501         }
502
503         CRYPTO_DRIVER_LOCK();
504
505         for (i = 0; i < crypto_drivers_num; i++) {
506                 if (crypto_drivers[i].cc_dev == NULL &&
507                     (crypto_drivers[i].cc_flags & CRYPTOCAP_F_CLEANUP) == 0) {
508                         break;
509                 }
510         }
511
512         /* Out of entries, allocate some more. */
513         if (i == crypto_drivers_num) {
514                 /* Be careful about wrap-around. */
515                 if (2 * crypto_drivers_num <= crypto_drivers_num) {
516                         CRYPTO_DRIVER_UNLOCK();
517                         kprintf("crypto: driver count wraparound!\n");
518                         return -1;
519                 }
520
521                 newdrv = kmalloc(2 * crypto_drivers_num *
522                                  sizeof(struct cryptocap),
523                                  M_CRYPTO_DATA, M_WAITOK|M_ZERO);
524                 if (newdrv == NULL) {
525                         CRYPTO_DRIVER_UNLOCK();
526                         kprintf("crypto: no space to expand driver table!\n");
527                         return -1;
528                 }
529
530                 bcopy(crypto_drivers, newdrv,
531                     crypto_drivers_num * sizeof(struct cryptocap));
532
533                 crypto_drivers_num *= 2;
534
535                 kfree(crypto_drivers, M_CRYPTO_DATA);
536                 crypto_drivers = newdrv;
537         }
538
539         /* NB: state is zero'd on free */
540         crypto_drivers[i].cc_sessions = 1;      /* Mark */
541         crypto_drivers[i].cc_dev = dev;
542         crypto_drivers[i].cc_flags = flags;
543         if (bootverbose)
544                 kprintf("crypto: assign %s driver id %u, flags %u\n",
545                     device_get_nameunit(dev), i, flags);
546
547         CRYPTO_DRIVER_UNLOCK();
548
549         return i;
550 }
551
552 /*
553  * Lookup a driver by name.  We match against the full device
554  * name and unit, and against just the name.  The latter gives
555  * us a simple widlcarding by device name.  On success return the
556  * driver/hardware identifier; otherwise return -1.
557  */
558 int
559 crypto_find_driver(const char *match)
560 {
561         int i, len = strlen(match);
562
563         CRYPTO_DRIVER_LOCK();
564         for (i = 0; i < crypto_drivers_num; i++) {
565                 device_t dev = crypto_drivers[i].cc_dev;
566                 if (dev == NULL ||
567                     (crypto_drivers[i].cc_flags & CRYPTOCAP_F_CLEANUP))
568                         continue;
569                 if (strncmp(match, device_get_nameunit(dev), len) == 0 ||
570                     strncmp(match, device_get_name(dev), len) == 0)
571                         break;
572         }
573         CRYPTO_DRIVER_UNLOCK();
574         return i < crypto_drivers_num ? i : -1;
575 }
576
577 /*
578  * Return the device_t for the specified driver or NULL
579  * if the driver identifier is invalid.
580  */
581 device_t
582 crypto_find_device_byhid(int hid)
583 {
584         struct cryptocap *cap = crypto_checkdriver(hid);
585         return cap != NULL ? cap->cc_dev : NULL;
586 }
587
588 /*
589  * Return the device/driver capabilities.
590  */
591 int
592 crypto_getcaps(int hid)
593 {
594         struct cryptocap *cap = crypto_checkdriver(hid);
595         return cap != NULL ? cap->cc_flags : 0;
596 }
597
598 /*
599  * Register support for a key-related algorithm.  This routine
600  * is called once for each algorithm supported a driver.
601  */
602 int
603 crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags)
604 {
605         struct cryptocap *cap;
606         int err;
607
608         CRYPTO_DRIVER_LOCK();
609
610         cap = crypto_checkdriver(driverid);
611         if (cap != NULL &&
612             (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
613                 /*
614                  * XXX Do some performance testing to determine placing.
615                  * XXX We probably need an auxiliary data structure that
616                  * XXX describes relative performances.
617                  */
618
619                 cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
620                 if (bootverbose)
621                         kprintf("crypto: %s registers key alg %u flags %u\n"
622                                 , device_get_nameunit(cap->cc_dev)
623                                 , kalg
624                                 , flags
625                         );
626
627                 err = 0;
628         } else
629                 err = EINVAL;
630
631         CRYPTO_DRIVER_UNLOCK();
632         return err;
633 }
634
635 /*
636  * Register support for a non-key-related algorithm.  This routine
637  * is called once for each such algorithm supported by a driver.
638  */
639 int
640 crypto_register(u_int32_t driverid, int alg, u_int16_t maxoplen,
641                 u_int32_t flags)
642 {
643         struct cryptocap *cap;
644         int err;
645
646         CRYPTO_DRIVER_LOCK();
647
648         cap = crypto_checkdriver(driverid);
649         /* NB: algorithms are in the range [1..max] */
650         if (cap != NULL &&
651             (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX)) {
652                 /*
653                  * XXX Do some performance testing to determine placing.
654                  * XXX We probably need an auxiliary data structure that
655                  * XXX describes relative performances.
656                  */
657
658                 cap->cc_alg[alg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
659                 cap->cc_max_op_len[alg] = maxoplen;
660                 if (bootverbose)
661                         kprintf("crypto: %s registers alg %u flags %u maxoplen %u\n"
662                                 , device_get_nameunit(cap->cc_dev)
663                                 , alg
664                                 , flags
665                                 , maxoplen
666                         );
667                 cap->cc_sessions = 0;           /* Unmark */
668                 err = 0;
669         } else
670                 err = EINVAL;
671
672         CRYPTO_DRIVER_UNLOCK();
673         return err;
674 }
675
676 static void
677 driver_finis(struct cryptocap *cap)
678 {
679         u_int32_t ses, kops;
680
681         CRYPTO_DRIVER_ASSERT();
682
683         ses = cap->cc_sessions;
684         kops = cap->cc_koperations;
685         bzero(cap, sizeof(*cap));
686         if (ses != 0 || kops != 0) {
687                 /*
688                  * If there are pending sessions,
689                  * just mark as invalid.
690                  */
691                 cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
692                 cap->cc_sessions = ses;
693                 cap->cc_koperations = kops;
694         }
695 }
696
697 /*
698  * Unregister a crypto driver. If there are pending sessions using it,
699  * leave enough information around so that subsequent calls using those
700  * sessions will correctly detect the driver has been unregistered and
701  * reroute requests.
702  */
703 int
704 crypto_unregister(u_int32_t driverid, int alg)
705 {
706         struct cryptocap *cap;
707         int i, err;
708
709         CRYPTO_DRIVER_LOCK();
710         cap = crypto_checkdriver(driverid);
711         if (cap != NULL &&
712             (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX) &&
713             cap->cc_alg[alg] != 0) {
714                 cap->cc_alg[alg] = 0;
715                 cap->cc_max_op_len[alg] = 0;
716
717                 /* Was this the last algorithm ? */
718                 for (i = 1; i <= CRYPTO_ALGORITHM_MAX; i++) {
719                         if (cap->cc_alg[i] != 0)
720                                 break;
721                 }
722
723                 if (i == CRYPTO_ALGORITHM_MAX + 1)
724                         driver_finis(cap);
725                 err = 0;
726         } else {
727                 err = EINVAL;
728         }
729         CRYPTO_DRIVER_UNLOCK();
730
731         return err;
732 }
733
734 /*
735  * Unregister all algorithms associated with a crypto driver.
736  * If there are pending sessions using it, leave enough information
737  * around so that subsequent calls using those sessions will
738  * correctly detect the driver has been unregistered and reroute
739  * requests.
740  */
741 int
742 crypto_unregister_all(u_int32_t driverid)
743 {
744         struct cryptocap *cap;
745         int err;
746
747         CRYPTO_DRIVER_LOCK();
748         cap = crypto_checkdriver(driverid);
749         if (cap != NULL) {
750                 driver_finis(cap);
751                 err = 0;
752         } else {
753                 err = EINVAL;
754         }
755         CRYPTO_DRIVER_UNLOCK();
756
757         return err;
758 }
759
760 /*
761  * Clear blockage on a driver.  The what parameter indicates whether
762  * the driver is now ready for cryptop's and/or cryptokop's.
763  */
764 int
765 crypto_unblock(u_int32_t driverid, int what)
766 {
767         crypto_tdinfo_t tdinfo;
768         struct cryptocap *cap;
769         int err;
770         int n;
771
772         CRYPTO_DRIVER_LOCK();
773         cap = crypto_checkdriver(driverid);
774         if (cap != NULL) {
775                 if (what & CRYPTO_SYMQ)
776                         cap->cc_qblocked = 0;
777                 if (what & CRYPTO_ASYMQ)
778                         cap->cc_kqblocked = 0;
779                 for (n = 0; n < ncpus; ++n) {
780                         tdinfo = &tdinfo_array[n];
781                         CRYPTO_Q_LOCK(tdinfo);
782                         if (tdinfo[n].crp_sleep)
783                                 wakeup_one(&tdinfo->crp_q);
784                         CRYPTO_Q_UNLOCK(tdinfo);
785                 }
786                 err = 0;
787         } else {
788                 err = EINVAL;
789         }
790         CRYPTO_DRIVER_UNLOCK();
791
792         return err;
793 }
794
795 static volatile int dispatch_rover;
796
797 /*
798  * Add a crypto request to a queue, to be processed by the kernel thread.
799  */
800 int
801 crypto_dispatch(struct cryptop *crp)
802 {
803         crypto_tdinfo_t tdinfo;
804         struct cryptocap *cap;
805         u_int32_t hid;
806         int result;
807         int n;
808
809         cryptostats.cs_ops++;
810
811 #ifdef CRYPTO_TIMING
812         if (crypto_timing)
813                 nanouptime(&crp->crp_tstamp);
814 #endif
815
816         hid = CRYPTO_SESID2HID(crp->crp_sid);
817
818         /*
819          * Dispatch the crypto op directly to the driver if the caller
820          * marked the request to be processed immediately or this is
821          * a synchronous callback chain occuring from within a crypto
822          * processing thread.
823          *
824          * Fall through to queueing the driver is blocked.
825          */
826         if ((crp->crp_flags & CRYPTO_F_BATCH) == 0 ||
827             (curthread->td_flags & TDF_CRYPTO)) {
828                 cap = crypto_checkdriver(hid);
829                 /* Driver cannot disappeared when there is an active session. */
830                 KASSERT(cap != NULL, ("%s: Driver disappeared.", __func__));
831                 if (!cap->cc_qblocked) {
832                         result = crypto_invoke(cap, crp, 0);
833                         if (result != ERESTART)
834                                 return (result);
835                         /*
836                          * The driver ran out of resources, put the request on
837                          * the queue.
838                          */
839                 }
840         }
841
842         /*
843          * Dispatch to a cpu for action if possible.  Dispatch to a different
844          * cpu than the current cpu.
845          */
846         if (CRYPTO_SESID2CAPS(crp->crp_sid) & CRYPTOCAP_F_SMP) {
847                 n = atomic_fetchadd_int(&dispatch_rover, 1) & 255;
848                 if (crypto_altdispatch && mycpu->gd_cpuid == n)
849                         ++n;
850                 n = n % ncpus;
851         } else {
852                 n = 0;
853         }
854         tdinfo = &tdinfo_array[n];
855
856         CRYPTO_Q_LOCK(tdinfo);
857         TAILQ_INSERT_TAIL(&tdinfo->crp_q, crp, crp_next);
858         if (tdinfo->crp_sleep)
859                 wakeup_one(&tdinfo->crp_q);
860         CRYPTO_Q_UNLOCK(tdinfo);
861         return 0;
862 }
863
864 /*
865  * Add an asymetric crypto request to a queue,
866  * to be processed by the kernel thread.
867  */
868 int
869 crypto_kdispatch(struct cryptkop *krp)
870 {
871         crypto_tdinfo_t tdinfo;
872         int error;
873         int n;
874
875         cryptostats.cs_kops++;
876
877 #if 0
878         /* not sure how to test F_SMP here */
879         n = atomic_fetchadd_int(&dispatch_rover, 1) & 255;
880         n = n % ncpus;
881 #endif
882         n = 0;
883         tdinfo = &tdinfo_array[n];
884
885         error = crypto_kinvoke(krp, krp->krp_crid);
886
887         if (error == ERESTART) {
888                 CRYPTO_Q_LOCK(tdinfo);
889                 TAILQ_INSERT_TAIL(&tdinfo->crp_kq, krp, krp_next);
890                 if (tdinfo->crp_sleep)
891                         wakeup_one(&tdinfo->crp_q);
892                 CRYPTO_Q_UNLOCK(tdinfo);
893                 error = 0;
894         }
895         return error;
896 }
897
898 /*
899  * Verify a driver is suitable for the specified operation.
900  */
901 static __inline int
902 kdriver_suitable(const struct cryptocap *cap, const struct cryptkop *krp)
903 {
904         return (cap->cc_kalg[krp->krp_op] & CRYPTO_ALG_FLAG_SUPPORTED) != 0;
905 }
906
907 /*
908  * Select a driver for an asym operation.  The driver must
909  * support the necessary algorithm.  The caller can constrain
910  * which device is selected with the flags parameter.  The
911  * algorithm we use here is pretty stupid; just use the first
912  * driver that supports the algorithms we need. If there are
913  * multiple suitable drivers we choose the driver with the
914  * fewest active operations.  We prefer hardware-backed
915  * drivers to software ones when either may be used.
916  */
917 static struct cryptocap *
918 crypto_select_kdriver(const struct cryptkop *krp, int flags)
919 {
920         struct cryptocap *cap, *best, *blocked;
921         int match, hid;
922
923         CRYPTO_DRIVER_ASSERT();
924
925         /*
926          * Look first for hardware crypto devices if permitted.
927          */
928         if (flags & CRYPTOCAP_F_HARDWARE)
929                 match = CRYPTOCAP_F_HARDWARE;
930         else
931                 match = CRYPTOCAP_F_SOFTWARE;
932         best = NULL;
933         blocked = NULL;
934 again:
935         for (hid = 0; hid < crypto_drivers_num; hid++) {
936                 cap = &crypto_drivers[hid];
937                 /*
938                  * If it's not initialized, is in the process of
939                  * going away, or is not appropriate (hardware
940                  * or software based on match), then skip.
941                  */
942                 if (cap->cc_dev == NULL ||
943                     (cap->cc_flags & CRYPTOCAP_F_CLEANUP) ||
944                     (cap->cc_flags & match) == 0)
945                         continue;
946
947                 /* verify all the algorithms are supported. */
948                 if (kdriver_suitable(cap, krp)) {
949                         if (best == NULL ||
950                             cap->cc_koperations < best->cc_koperations)
951                                 best = cap;
952                 }
953         }
954         if (best != NULL)
955                 return best;
956         if (match == CRYPTOCAP_F_HARDWARE && (flags & CRYPTOCAP_F_SOFTWARE)) {
957                 /* sort of an Algol 68-style for loop */
958                 match = CRYPTOCAP_F_SOFTWARE;
959                 goto again;
960         }
961         return best;
962 }
963
964 /*
965  * Dispatch an assymetric crypto request.
966  */
967 static int
968 crypto_kinvoke(struct cryptkop *krp, int crid)
969 {
970         struct cryptocap *cap = NULL;
971         int error;
972
973         KASSERT(krp != NULL, ("%s: krp == NULL", __func__));
974         KASSERT(krp->krp_callback != NULL,
975             ("%s: krp->crp_callback == NULL", __func__));
976
977         CRYPTO_DRIVER_LOCK();
978         if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
979                 cap = crypto_checkdriver(crid);
980                 if (cap != NULL) {
981                         /*
982                          * Driver present, it must support the necessary
983                          * algorithm and, if s/w drivers are excluded,
984                          * it must be registered as hardware-backed.
985                          */
986                         if (!kdriver_suitable(cap, krp) ||
987                             (!crypto_devallowsoft &&
988                              (cap->cc_flags & CRYPTOCAP_F_HARDWARE) == 0))
989                                 cap = NULL;
990                 }
991         } else {
992                 /*
993                  * No requested driver; select based on crid flags.
994                  */
995                 if (!crypto_devallowsoft)       /* NB: disallow s/w drivers */
996                         crid &= ~CRYPTOCAP_F_SOFTWARE;
997                 cap = crypto_select_kdriver(krp, crid);
998         }
999         if (cap != NULL && !cap->cc_kqblocked) {
1000                 krp->krp_hid = cap - crypto_drivers;
1001                 cap->cc_koperations++;
1002                 CRYPTO_DRIVER_UNLOCK();
1003                 error = CRYPTODEV_KPROCESS(cap->cc_dev, krp, 0);
1004                 CRYPTO_DRIVER_LOCK();
1005                 if (error == ERESTART) {
1006                         cap->cc_koperations--;
1007                         CRYPTO_DRIVER_UNLOCK();
1008                         return (error);
1009                 }
1010         } else {
1011                 /*
1012                  * NB: cap is !NULL if device is blocked; in
1013                  *     that case return ERESTART so the operation
1014                  *     is resubmitted if possible.
1015                  */
1016                 error = (cap == NULL) ? ENODEV : ERESTART;
1017         }
1018         CRYPTO_DRIVER_UNLOCK();
1019
1020         if (error) {
1021                 krp->krp_status = error;
1022                 crypto_kdone(krp);
1023         }
1024         return 0;
1025 }
1026
1027 #ifdef CRYPTO_TIMING
1028 static void
1029 crypto_tstat(struct cryptotstat *ts, struct timespec *tv)
1030 {
1031         struct timespec now, t;
1032
1033         nanouptime(&now);
1034         t.tv_sec = now.tv_sec - tv->tv_sec;
1035         t.tv_nsec = now.tv_nsec - tv->tv_nsec;
1036         if (t.tv_nsec < 0) {
1037                 t.tv_sec--;
1038                 t.tv_nsec += 1000000000;
1039         }
1040         timespecadd(&ts->acc, &t);
1041         if (timespeccmp(&t, &ts->min, <))
1042                 ts->min = t;
1043         if (timespeccmp(&t, &ts->max, >))
1044                 ts->max = t;
1045         ts->count++;
1046
1047         *tv = now;
1048 }
1049 #endif
1050
1051 /*
1052  * Dispatch a crypto request to the appropriate crypto devices.
1053  */
1054 static int
1055 crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint)
1056 {
1057
1058         KASSERT(crp != NULL, ("%s: crp == NULL", __func__));
1059         KASSERT(crp->crp_callback != NULL,
1060             ("%s: crp->crp_callback == NULL", __func__));
1061         KASSERT(crp->crp_desc != NULL, ("%s: crp->crp_desc == NULL", __func__));
1062
1063 #ifdef CRYPTO_TIMING
1064         if (crypto_timing)
1065                 crypto_tstat(&cryptostats.cs_invoke, &crp->crp_tstamp);
1066 #endif
1067         if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1068                 struct cryptodesc *crd;
1069                 u_int64_t nid;
1070
1071                 /*
1072                  * Driver has unregistered; migrate the session and return
1073                  * an error to the caller so they'll resubmit the op.
1074                  *
1075                  * XXX: What if there are more already queued requests for this
1076                  *      session?
1077                  */
1078                 crypto_freesession(crp->crp_sid);
1079
1080                 for (crd = crp->crp_desc; crd->crd_next; crd = crd->crd_next)
1081                         crd->CRD_INI.cri_next = &(crd->crd_next->CRD_INI);
1082
1083                 /* XXX propagate flags from initial session? */
1084                 if (crypto_newsession(&nid, &(crp->crp_desc->CRD_INI),
1085                     CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE) == 0)
1086                         crp->crp_sid = nid;
1087
1088                 crp->crp_etype = EAGAIN;
1089                 crypto_done(crp);
1090                 return 0;
1091         } else {
1092                 /*
1093                  * Invoke the driver to process the request.
1094                  */
1095                 return CRYPTODEV_PROCESS(cap->cc_dev, crp, hint);
1096         }
1097 }
1098
1099 /*
1100  * Release a set of crypto descriptors.
1101  */
1102 void
1103 crypto_freereq(struct cryptop *crp)
1104 {
1105         struct cryptodesc *crd;
1106 #ifdef DIAGNOSTIC
1107         crypto_tdinfo_t tdinfo;
1108         struct cryptop *crp2;
1109         int n;
1110 #endif
1111
1112         if (crp == NULL)
1113                 return;
1114
1115 #ifdef DIAGNOSTIC
1116         for (n = 0; n < ncpus; ++n) {
1117                 tdinfo = &tdinfo_array[n];
1118
1119                 CRYPTO_Q_LOCK(tdinfo);
1120                 TAILQ_FOREACH(crp2, &tdinfo->crp_q, crp_next) {
1121                         KASSERT(crp2 != crp,
1122                             ("Freeing cryptop from the crypto queue (%p).",
1123                             crp));
1124                 }
1125                 CRYPTO_Q_UNLOCK(tdinfo);
1126         }
1127         CRYPTO_RETQ_LOCK();
1128         TAILQ_FOREACH(crp2, &crp_ret_q, crp_next) {
1129                 KASSERT(crp2 != crp,
1130                     ("Freeing cryptop from the return queue (%p).",
1131                     crp));
1132         }
1133         CRYPTO_RETQ_UNLOCK();
1134 #endif
1135
1136         while ((crd = crp->crp_desc) != NULL) {
1137                 crp->crp_desc = crd->crd_next;
1138                 zfree(cryptodesc_zone, crd);
1139         }
1140         zfree(cryptop_zone, crp);
1141 }
1142
1143 /*
1144  * Acquire a set of crypto descriptors.
1145  */
1146 struct cryptop *
1147 crypto_getreq(int num)
1148 {
1149         struct cryptodesc *crd;
1150         struct cryptop *crp;
1151
1152         crp = zalloc(cryptop_zone);
1153         if (crp != NULL) {
1154                 bzero(crp, sizeof (*crp));
1155                 while (num--) {
1156                         crd = zalloc(cryptodesc_zone);
1157                         if (crd == NULL) {
1158                                 crypto_freereq(crp);
1159                                 return NULL;
1160                         }
1161                         bzero(crd, sizeof (*crd));
1162
1163                         crd->crd_next = crp->crp_desc;
1164                         crp->crp_desc = crd;
1165                 }
1166         }
1167         return crp;
1168 }
1169
1170 /*
1171  * Invoke the callback on behalf of the driver.
1172  */
1173 void
1174 crypto_done(struct cryptop *crp)
1175 {
1176         KASSERT((crp->crp_flags & CRYPTO_F_DONE) == 0,
1177                 ("crypto_done: op already done, flags 0x%x", crp->crp_flags));
1178         crp->crp_flags |= CRYPTO_F_DONE;
1179         if (crp->crp_etype != 0)
1180                 cryptostats.cs_errs++;
1181 #ifdef CRYPTO_TIMING
1182         if (crypto_timing)
1183                 crypto_tstat(&cryptostats.cs_done, &crp->crp_tstamp);
1184 #endif
1185         /*
1186          * CBIMM means unconditionally do the callback immediately;
1187          * CBIFSYNC means do the callback immediately only if the
1188          * operation was done synchronously.  Both are used to avoid
1189          * doing extraneous context switches; the latter is mostly
1190          * used with the software crypto driver.
1191          */
1192         if ((crp->crp_flags & CRYPTO_F_CBIMM) ||
1193             ((crp->crp_flags & CRYPTO_F_CBIFSYNC) &&
1194              (CRYPTO_SESID2CAPS(crp->crp_sid) & CRYPTOCAP_F_SYNC))) {
1195                 /*
1196                  * Do the callback directly.  This is ok when the
1197                  * callback routine does very little (e.g. the
1198                  * /dev/crypto callback method just does a wakeup).
1199                  */
1200 #ifdef CRYPTO_TIMING
1201                 if (crypto_timing) {
1202                         /*
1203                          * NB: We must copy the timestamp before
1204                          * doing the callback as the cryptop is
1205                          * likely to be reclaimed.
1206                          */
1207                         struct timespec t = crp->crp_tstamp;
1208                         crypto_tstat(&cryptostats.cs_cb, &t);
1209                         crp->crp_callback(crp);
1210                         crypto_tstat(&cryptostats.cs_finis, &t);
1211                 } else
1212 #endif
1213                         crp->crp_callback(crp);
1214         } else {
1215                 /*
1216                  * Normal case; queue the callback for the thread.
1217                  */
1218                 CRYPTO_RETQ_LOCK();
1219                 if (CRYPTO_RETQ_EMPTY())
1220                         wakeup_one(&crp_ret_q); /* shared wait channel */
1221                 TAILQ_INSERT_TAIL(&crp_ret_q, crp, crp_next);
1222                 CRYPTO_RETQ_UNLOCK();
1223         }
1224 }
1225
1226 /*
1227  * Invoke the callback on behalf of the driver.
1228  */
1229 void
1230 crypto_kdone(struct cryptkop *krp)
1231 {
1232         struct cryptocap *cap;
1233
1234         if (krp->krp_status != 0)
1235                 cryptostats.cs_kerrs++;
1236         CRYPTO_DRIVER_LOCK();
1237         /* XXX: What if driver is loaded in the meantime? */
1238         if (krp->krp_hid < crypto_drivers_num) {
1239                 cap = &crypto_drivers[krp->krp_hid];
1240                 cap->cc_koperations--;
1241                 KASSERT(cap->cc_koperations >= 0, ("cc_koperations < 0"));
1242                 if (cap->cc_flags & CRYPTOCAP_F_CLEANUP)
1243                         crypto_remove(cap);
1244         }
1245         CRYPTO_DRIVER_UNLOCK();
1246         CRYPTO_RETQ_LOCK();
1247         if (CRYPTO_RETQ_EMPTY())
1248                 wakeup_one(&crp_ret_q);         /* shared wait channel */
1249         TAILQ_INSERT_TAIL(&crp_ret_kq, krp, krp_next);
1250         CRYPTO_RETQ_UNLOCK();
1251 }
1252
1253 int
1254 crypto_getfeat(int *featp)
1255 {
1256         int hid, kalg, feat = 0;
1257
1258         CRYPTO_DRIVER_LOCK();
1259         for (hid = 0; hid < crypto_drivers_num; hid++) {
1260                 const struct cryptocap *cap = &crypto_drivers[hid];
1261
1262                 if ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
1263                     !crypto_devallowsoft) {
1264                         continue;
1265                 }
1266                 for (kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
1267                         if (cap->cc_kalg[kalg] & CRYPTO_ALG_FLAG_SUPPORTED)
1268                                 feat |=  1 << kalg;
1269         }
1270         CRYPTO_DRIVER_UNLOCK();
1271         *featp = feat;
1272         return (0);
1273 }
1274
1275 /*
1276  * Terminate a thread at module unload.  The process that
1277  * initiated this is waiting for us to signal that we're gone;
1278  * wake it up and exit.  We use the driver table lock to insure
1279  * we don't do the wakeup before they're waiting.  There is no
1280  * race here because the waiter sleeps on the proc lock for the
1281  * thread so it gets notified at the right time because of an
1282  * extra wakeup that's done in exit1().
1283  */
1284 static void
1285 crypto_finis(void *chan)
1286 {
1287         CRYPTO_DRIVER_LOCK();
1288         wakeup_one(chan);
1289         CRYPTO_DRIVER_UNLOCK();
1290         kthread_exit();
1291 }
1292
1293 /*
1294  * Crypto thread, dispatches crypto requests.
1295  */
1296 static void
1297 crypto_proc(void *arg)
1298 {
1299         crypto_tdinfo_t tdinfo = arg;
1300         struct cryptop *crp, *submit;
1301         struct cryptkop *krp;
1302         struct cryptocap *cap;
1303         u_int32_t hid;
1304         int result, hint;
1305
1306         rel_mplock();           /* release the mplock held on startup */
1307
1308         CRYPTO_Q_LOCK(tdinfo);
1309
1310         curthread->td_flags |= TDF_CRYPTO;
1311
1312         for (;;) {
1313                 /*
1314                  * Find the first element in the queue that can be
1315                  * processed and look-ahead to see if multiple ops
1316                  * are ready for the same driver.
1317                  */
1318                 submit = NULL;
1319                 hint = 0;
1320                 TAILQ_FOREACH(crp, &tdinfo->crp_q, crp_next) {
1321                         hid = CRYPTO_SESID2HID(crp->crp_sid);
1322                         cap = crypto_checkdriver(hid);
1323                         /*
1324                          * Driver cannot disappeared when there is an active
1325                          * session.
1326                          */
1327                         KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1328                             __func__, __LINE__));
1329                         if (cap == NULL || cap->cc_dev == NULL) {
1330                                 /* Op needs to be migrated, process it. */
1331                                 if (submit == NULL)
1332                                         submit = crp;
1333                                 break;
1334                         }
1335                         if (!cap->cc_qblocked) {
1336                                 if (submit != NULL) {
1337                                         /*
1338                                          * We stop on finding another op,
1339                                          * regardless whether its for the same
1340                                          * driver or not.  We could keep
1341                                          * searching the queue but it might be
1342                                          * better to just use a per-driver
1343                                          * queue instead.
1344                                          */
1345                                         if (CRYPTO_SESID2HID(submit->crp_sid) == hid)
1346                                                 hint = CRYPTO_HINT_MORE;
1347                                         break;
1348                                 } else {
1349                                         submit = crp;
1350                                         if ((submit->crp_flags & CRYPTO_F_BATCH) == 0)
1351                                                 break;
1352                                         /* keep scanning for more are q'd */
1353                                 }
1354                         }
1355                 }
1356                 if (submit != NULL) {
1357                         TAILQ_REMOVE(&tdinfo->crp_q, submit, crp_next);
1358                         hid = CRYPTO_SESID2HID(submit->crp_sid);
1359                         cap = crypto_checkdriver(hid);
1360                         KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1361                             __func__, __LINE__));
1362
1363                         CRYPTO_Q_UNLOCK(tdinfo);
1364                         result = crypto_invoke(cap, submit, hint);
1365                         CRYPTO_Q_LOCK(tdinfo);
1366
1367                         if (result == ERESTART) {
1368                                 /*
1369                                  * The driver ran out of resources, mark the
1370                                  * driver ``blocked'' for cryptop's and put
1371                                  * the request back in the queue.  It would
1372                                  * best to put the request back where we got
1373                                  * it but that's hard so for now we put it
1374                                  * at the front.  This should be ok; putting
1375                                  * it at the end does not work.
1376                                  */
1377                                 /* XXX validate sid again? */
1378                                 crypto_drivers[CRYPTO_SESID2HID(submit->crp_sid)].cc_qblocked = 1;
1379                                 TAILQ_INSERT_HEAD(&tdinfo->crp_q,
1380                                                   submit, crp_next);
1381                                 cryptostats.cs_blocks++;
1382                         }
1383                 }
1384
1385                 /* As above, but for key ops */
1386                 TAILQ_FOREACH(krp, &tdinfo->crp_kq, krp_next) {
1387                         cap = crypto_checkdriver(krp->krp_hid);
1388                         if (cap == NULL || cap->cc_dev == NULL) {
1389                                 /*
1390                                  * Operation needs to be migrated, invalidate
1391                                  * the assigned device so it will reselect a
1392                                  * new one below.  Propagate the original
1393                                  * crid selection flags if supplied.
1394                                  */
1395                                 krp->krp_hid = krp->krp_crid &
1396                                     (CRYPTOCAP_F_SOFTWARE|CRYPTOCAP_F_HARDWARE);
1397                                 if (krp->krp_hid == 0)
1398                                         krp->krp_hid =
1399                                     CRYPTOCAP_F_SOFTWARE|CRYPTOCAP_F_HARDWARE;
1400                                 break;
1401                         }
1402                         if (!cap->cc_kqblocked)
1403                                 break;
1404                 }
1405                 if (krp != NULL) {
1406                         TAILQ_REMOVE(&tdinfo->crp_kq, krp, krp_next);
1407
1408                         CRYPTO_Q_UNLOCK(tdinfo);
1409                         result = crypto_kinvoke(krp, krp->krp_hid);
1410                         CRYPTO_Q_LOCK(tdinfo);
1411
1412                         if (result == ERESTART) {
1413                                 /*
1414                                  * The driver ran out of resources, mark the
1415                                  * driver ``blocked'' for cryptkop's and put
1416                                  * the request back in the queue.  It would
1417                                  * best to put the request back where we got
1418                                  * it but that's hard so for now we put it
1419                                  * at the front.  This should be ok; putting
1420                                  * it at the end does not work.
1421                                  */
1422                                 /* XXX validate sid again? */
1423                                 crypto_drivers[krp->krp_hid].cc_kqblocked = 1;
1424                                 TAILQ_INSERT_HEAD(&tdinfo->crp_kq,
1425                                                   krp, krp_next);
1426                                 cryptostats.cs_kblocks++;
1427                         }
1428                 }
1429
1430                 if (submit == NULL && krp == NULL) {
1431                         /*
1432                          * Nothing more to be processed.  Sleep until we're
1433                          * woken because there are more ops to process.
1434                          * This happens either by submission or by a driver
1435                          * becoming unblocked and notifying us through
1436                          * crypto_unblock.  Note that when we wakeup we
1437                          * start processing each queue again from the
1438                          * front. It's not clear that it's important to
1439                          * preserve this ordering since ops may finish
1440                          * out of order if dispatched to different devices
1441                          * and some become blocked while others do not.
1442                          */
1443                         tdinfo->crp_sleep = 1;
1444                         lksleep (&tdinfo->crp_q, &tdinfo->crp_lock,
1445                                  0, "crypto_wait", 0);
1446                         tdinfo->crp_sleep = 0;
1447                         if (tdinfo->crp_td == NULL)
1448                                 break;
1449                         cryptostats.cs_intrs++;
1450                 }
1451         }
1452         CRYPTO_Q_UNLOCK(tdinfo);
1453
1454         crypto_finis(&tdinfo->crp_q);
1455 }
1456
1457 /*
1458  * Crypto returns thread, does callbacks for processed crypto requests.
1459  * Callbacks are done here, rather than in the crypto drivers, because
1460  * callbacks typically are expensive and would slow interrupt handling.
1461  */
1462 static void
1463 crypto_ret_proc(void *dummy __unused)
1464 {
1465         struct cryptop *crpt;
1466         struct cryptkop *krpt;
1467
1468         CRYPTO_RETQ_LOCK();
1469         for (;;) {
1470                 /* Harvest return q's for completed ops */
1471                 crpt = TAILQ_FIRST(&crp_ret_q);
1472                 if (crpt != NULL)
1473                         TAILQ_REMOVE(&crp_ret_q, crpt, crp_next);
1474
1475                 krpt = TAILQ_FIRST(&crp_ret_kq);
1476                 if (krpt != NULL)
1477                         TAILQ_REMOVE(&crp_ret_kq, krpt, krp_next);
1478
1479                 if (crpt != NULL || krpt != NULL) {
1480                         CRYPTO_RETQ_UNLOCK();
1481                         /*
1482                          * Run callbacks unlocked.
1483                          */
1484                         if (crpt != NULL) {
1485 #ifdef CRYPTO_TIMING
1486                                 if (crypto_timing) {
1487                                         /*
1488                                          * NB: We must copy the timestamp before
1489                                          * doing the callback as the cryptop is
1490                                          * likely to be reclaimed.
1491                                          */
1492                                         struct timespec t = crpt->crp_tstamp;
1493                                         crypto_tstat(&cryptostats.cs_cb, &t);
1494                                         crpt->crp_callback(crpt);
1495                                         crypto_tstat(&cryptostats.cs_finis, &t);
1496                                 } else
1497 #endif
1498                                         crpt->crp_callback(crpt);
1499                         }
1500                         if (krpt != NULL)
1501                                 krpt->krp_callback(krpt);
1502                         CRYPTO_RETQ_LOCK();
1503                 } else {
1504                         /*
1505                          * Nothing more to be processed.  Sleep until we're
1506                          * woken because there are more returns to process.
1507                          */
1508                         lksleep (&crp_ret_q, &crypto_ret_q_lock,
1509                                  0, "crypto_ret_wait", 0);
1510                         if (cryptoretthread == NULL)
1511                                 break;
1512                         cryptostats.cs_rets++;
1513                 }
1514         }
1515         CRYPTO_RETQ_UNLOCK();
1516
1517         crypto_finis(&crp_ret_q);
1518 }
1519
1520 #ifdef DDB
1521 static void
1522 db_show_drivers(void)
1523 {
1524         int hid;
1525
1526         db_printf("%12s %4s %4s %8s %2s %2s\n"
1527                 , "Device"
1528                 , "Ses"
1529                 , "Kops"
1530                 , "Flags"
1531                 , "QB"
1532                 , "KB"
1533         );
1534         for (hid = 0; hid < crypto_drivers_num; hid++) {
1535                 const struct cryptocap *cap = &crypto_drivers[hid];
1536                 if (cap->cc_dev == NULL)
1537                         continue;
1538                 db_printf("%-12s %4u %4u %08x %2u %2u\n"
1539                     , device_get_nameunit(cap->cc_dev)
1540                     , cap->cc_sessions
1541                     , cap->cc_koperations
1542                     , cap->cc_flags
1543                     , cap->cc_qblocked
1544                     , cap->cc_kqblocked
1545                 );
1546         }
1547 }
1548
1549 DB_SHOW_COMMAND(crypto, db_show_crypto)
1550 {
1551         crypto_tdinfo_t tdinfo;
1552         struct cryptop *crp;
1553         int n;
1554
1555         db_show_drivers();
1556         db_printf("\n");
1557
1558         db_printf("%4s %8s %4s %4s %4s %4s %8s %8s\n",
1559             "HID", "Caps", "Ilen", "Olen", "Etype", "Flags",
1560             "Desc", "Callback");
1561
1562         for (n = 0; n < ncpus; ++n) {
1563                 tdinfo = &tdinfo_array[n];
1564
1565                 TAILQ_FOREACH(crp, &tdinfo->crp_q, crp_next) {
1566                         db_printf("%4u %08x %4u %4u %4u %04x %8p %8p\n"
1567                             , (int) CRYPTO_SESID2HID(crp->crp_sid)
1568                             , (int) CRYPTO_SESID2CAPS(crp->crp_sid)
1569                             , crp->crp_ilen, crp->crp_olen
1570                             , crp->crp_etype
1571                             , crp->crp_flags
1572                             , crp->crp_desc
1573                             , crp->crp_callback
1574                         );
1575                 }
1576         }
1577         if (!TAILQ_EMPTY(&crp_ret_q)) {
1578                 db_printf("\n%4s %4s %4s %8s\n",
1579                     "HID", "Etype", "Flags", "Callback");
1580                 TAILQ_FOREACH(crp, &crp_ret_q, crp_next) {
1581                         db_printf("%4u %4u %04x %8p\n"
1582                             , (int) CRYPTO_SESID2HID(crp->crp_sid)
1583                             , crp->crp_etype
1584                             , crp->crp_flags
1585                             , crp->crp_callback
1586                         );
1587                 }
1588         }
1589 }
1590
1591 DB_SHOW_COMMAND(kcrypto, db_show_kcrypto)
1592 {
1593         crypto_tdinfo_t tdinfo;
1594         struct cryptkop *krp;
1595         int n;
1596
1597         db_show_drivers();
1598         db_printf("\n");
1599
1600         db_printf("%4s %5s %4s %4s %8s %4s %8s\n",
1601             "Op", "Status", "#IP", "#OP", "CRID", "HID", "Callback");
1602
1603         for (n = 0; n < ncpus; ++n) {
1604                 tdinfo = &tdinfo_array[n];
1605
1606                 TAILQ_FOREACH(krp, &tdinfo->crp_kq, krp_next) {
1607                         db_printf("%4u %5u %4u %4u %08x %4u %8p\n"
1608                             , krp->krp_op
1609                             , krp->krp_status
1610                             , krp->krp_iparams, krp->krp_oparams
1611                             , krp->krp_crid, krp->krp_hid
1612                             , krp->krp_callback
1613                         );
1614                 }
1615         }
1616         if (!TAILQ_EMPTY(&crp_ret_q)) {
1617                 db_printf("%4s %5s %8s %4s %8s\n",
1618                     "Op", "Status", "CRID", "HID", "Callback");
1619                 TAILQ_FOREACH(krp, &crp_ret_kq, krp_next) {
1620                         db_printf("%4u %5u %08x %4u %8p\n"
1621                             , krp->krp_op
1622                             , krp->krp_status
1623                             , krp->krp_crid, krp->krp_hid
1624                             , krp->krp_callback
1625                         );
1626                 }
1627         }
1628 }
1629 #endif
1630
1631 int crypto_modevent(module_t mod, int type, void *unused);
1632
1633 /*
1634  * Initialization code, both for static and dynamic loading.
1635  * Note this is not invoked with the usual MODULE_DECLARE
1636  * mechanism but instead is listed as a dependency by the
1637  * cryptosoft driver.  This guarantees proper ordering of
1638  * calls on module load/unload.
1639  */
1640 int
1641 crypto_modevent(module_t mod, int type, void *unused)
1642 {
1643         int error = EINVAL;
1644
1645         switch (type) {
1646         case MOD_LOAD:
1647                 error = crypto_init();
1648                 if (error == 0 && bootverbose)
1649                         kprintf("crypto: <crypto core>\n");
1650                 break;
1651         case MOD_UNLOAD:
1652                 /*XXX disallow if active sessions */
1653                 error = 0;
1654                 crypto_destroy();
1655                 return 0;
1656         }
1657         return error;
1658 }
1659 MODULE_VERSION(crypto, 1);
1660 MODULE_DEPEND(crypto, zlib, 1, 1, 1);