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