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