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