]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/opencrypto/crypto.c
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / sys / opencrypto / crypto.c
1 /*-
2  * Copyright (c) 2002-2006 Sam Leffler.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23  */
24
25 #include <sys/cdefs.h>
26 __FBSDID("$FreeBSD$");
27
28 /*
29  * Cryptographic Subsystem.
30  *
31  * This code is derived from the Openbsd Cryptographic Framework (OCF)
32  * that has the copyright shown below.  Very little of the original
33  * code remains.
34  */
35
36 /*-
37  * The author of this code is Angelos D. Keromytis (angelos@cis.upenn.edu)
38  *
39  * This code was written by Angelos D. Keromytis in Athens, Greece, in
40  * February 2000. Network Security Technologies Inc. (NSTI) kindly
41  * supported the development of this code.
42  *
43  * Copyright (c) 2000, 2001 Angelos D. Keromytis
44  *
45  * Permission to use, copy, and modify this software with or without fee
46  * is hereby granted, provided that this entire notice is included in
47  * all source code copies of any software which is or includes a copy or
48  * modification of this software.
49  *
50  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
51  * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
52  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
53  * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
54  * PURPOSE.
55  */
56
57 #define CRYPTO_TIMING                           /* enable timing support */
58
59 #include "opt_compat.h"
60 #include "opt_ddb.h"
61
62 #include <sys/param.h>
63 #include <sys/systm.h>
64 #include <sys/eventhandler.h>
65 #include <sys/kernel.h>
66 #include <sys/kthread.h>
67 #include <sys/linker.h>
68 #include <sys/lock.h>
69 #include <sys/module.h>
70 #include <sys/mutex.h>
71 #include <sys/malloc.h>
72 #include <sys/mbuf.h>
73 #include <sys/proc.h>
74 #include <sys/refcount.h>
75 #include <sys/sdt.h>
76 #include <sys/smp.h>
77 #include <sys/sysctl.h>
78 #include <sys/taskqueue.h>
79 #include <sys/uio.h>
80
81 #include <ddb/ddb.h>
82
83 #include <vm/uma.h>
84 #include <crypto/intake.h>
85 #include <opencrypto/cryptodev.h>
86 #include <opencrypto/xform_auth.h>
87 #include <opencrypto/xform_enc.h>
88
89 #include <sys/kobj.h>
90 #include <sys/bus.h>
91 #include "cryptodev_if.h"
92
93 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
94 #include <machine/pcb.h>
95 #endif
96
97 SDT_PROVIDER_DEFINE(opencrypto);
98
99 /*
100  * Crypto drivers register themselves by allocating a slot in the
101  * crypto_drivers table with crypto_get_driverid() and then registering
102  * each asym algorithm they support with crypto_kregister().
103  */
104 static  struct mtx crypto_drivers_mtx;          /* lock on driver table */
105 #define CRYPTO_DRIVER_LOCK()    mtx_lock(&crypto_drivers_mtx)
106 #define CRYPTO_DRIVER_UNLOCK()  mtx_unlock(&crypto_drivers_mtx)
107 #define CRYPTO_DRIVER_ASSERT()  mtx_assert(&crypto_drivers_mtx, MA_OWNED)
108
109 /*
110  * Crypto device/driver capabilities structure.
111  *
112  * Synchronization:
113  * (d) - protected by CRYPTO_DRIVER_LOCK()
114  * (q) - protected by CRYPTO_Q_LOCK()
115  * Not tagged fields are read-only.
116  */
117 struct cryptocap {
118         device_t        cc_dev;
119         uint32_t        cc_hid;
120         u_int32_t       cc_sessions;            /* (d) # of sessions */
121         u_int32_t       cc_koperations;         /* (d) # os asym operations */
122         u_int8_t        cc_kalg[CRK_ALGORITHM_MAX + 1];
123
124         int             cc_flags;               /* (d) flags */
125 #define CRYPTOCAP_F_CLEANUP     0x80000000      /* needs resource cleanup */
126         int             cc_qblocked;            /* (q) symmetric q blocked */
127         int             cc_kqblocked;           /* (q) asymmetric q blocked */
128         size_t          cc_session_size;
129         volatile int    cc_refs;
130 };
131
132 static  struct cryptocap **crypto_drivers = NULL;
133 static  int crypto_drivers_size = 0;
134
135 struct crypto_session {
136         struct cryptocap *cap;
137         void *softc;
138         struct crypto_session_params csp;
139 };
140
141 /*
142  * There are two queues for crypto requests; one for symmetric (e.g.
143  * cipher) operations and one for asymmetric (e.g. MOD)operations.
144  * A single mutex is used to lock access to both queues.  We could
145  * have one per-queue but having one simplifies handling of block/unblock
146  * operations.
147  */
148 static  int crp_sleep = 0;
149 static  TAILQ_HEAD(cryptop_q ,cryptop) crp_q;           /* request queues */
150 static  TAILQ_HEAD(,cryptkop) crp_kq;
151 static  struct mtx crypto_q_mtx;
152 #define CRYPTO_Q_LOCK()         mtx_lock(&crypto_q_mtx)
153 #define CRYPTO_Q_UNLOCK()       mtx_unlock(&crypto_q_mtx)
154
155 SYSCTL_NODE(_kern, OID_AUTO, crypto, CTLFLAG_RW, 0,
156     "In-kernel cryptography");
157
158 /*
159  * Taskqueue used to dispatch the crypto requests
160  * that have the CRYPTO_F_ASYNC flag
161  */
162 static struct taskqueue *crypto_tq;
163
164 /*
165  * Crypto seq numbers are operated on with modular arithmetic
166  */
167 #define CRYPTO_SEQ_GT(a,b)      ((int)((a)-(b)) > 0)
168
169 struct crypto_ret_worker {
170         struct mtx crypto_ret_mtx;
171
172         TAILQ_HEAD(,cryptop) crp_ordered_ret_q; /* ordered callback queue for symetric jobs */
173         TAILQ_HEAD(,cryptop) crp_ret_q;         /* callback queue for symetric jobs */
174         TAILQ_HEAD(,cryptkop) crp_ret_kq;       /* callback queue for asym jobs */
175
176         u_int32_t reorder_ops;          /* total ordered sym jobs received */
177         u_int32_t reorder_cur_seq;      /* current sym job dispatched */
178
179         struct proc *cryptoretproc;
180 };
181 static struct crypto_ret_worker *crypto_ret_workers = NULL;
182
183 #define CRYPTO_RETW(i)          (&crypto_ret_workers[i])
184 #define CRYPTO_RETW_ID(w)       ((w) - crypto_ret_workers)
185 #define FOREACH_CRYPTO_RETW(w) \
186         for (w = crypto_ret_workers; w < crypto_ret_workers + crypto_workers_num; ++w)
187
188 #define CRYPTO_RETW_LOCK(w)     mtx_lock(&w->crypto_ret_mtx)
189 #define CRYPTO_RETW_UNLOCK(w)   mtx_unlock(&w->crypto_ret_mtx)
190 #define CRYPTO_RETW_EMPTY(w) \
191         (TAILQ_EMPTY(&w->crp_ret_q) && TAILQ_EMPTY(&w->crp_ret_kq) && TAILQ_EMPTY(&w->crp_ordered_ret_q))
192
193 static int crypto_workers_num = 0;
194 SYSCTL_INT(_kern_crypto, OID_AUTO, num_workers, CTLFLAG_RDTUN,
195            &crypto_workers_num, 0,
196            "Number of crypto workers used to dispatch crypto jobs");
197 #ifdef COMPAT_FREEBSD12
198 SYSCTL_INT(_kern, OID_AUTO, crypto_workers_num, CTLFLAG_RDTUN,
199            &crypto_workers_num, 0,
200            "Number of crypto workers used to dispatch crypto jobs");
201 #endif
202
203 static  uma_zone_t cryptop_zone;
204 static  uma_zone_t cryptoses_zone;
205
206 int     crypto_userasymcrypto = 1;
207 SYSCTL_INT(_kern_crypto, OID_AUTO, asym_enable, CTLFLAG_RW,
208            &crypto_userasymcrypto, 0,
209            "Enable user-mode access to asymmetric crypto support");
210 #ifdef COMPAT_FREEBSD12
211 SYSCTL_INT(_kern, OID_AUTO, userasymcrypto, CTLFLAG_RW,
212            &crypto_userasymcrypto, 0,
213            "Enable/disable user-mode access to asymmetric crypto support");
214 #endif
215
216 int     crypto_devallowsoft = 0;
217 SYSCTL_INT(_kern_crypto, OID_AUTO, allow_soft, CTLFLAG_RW,
218            &crypto_devallowsoft, 0,
219            "Enable use of software crypto by /dev/crypto");
220 #ifdef COMPAT_FREEBSD12
221 SYSCTL_INT(_kern, OID_AUTO, cryptodevallowsoft, CTLFLAG_RW,
222            &crypto_devallowsoft, 0,
223            "Enable/disable use of software crypto by /dev/crypto");
224 #endif
225
226 MALLOC_DEFINE(M_CRYPTO_DATA, "crypto", "crypto session records");
227
228 static  void crypto_proc(void);
229 static  struct proc *cryptoproc;
230 static  void crypto_ret_proc(struct crypto_ret_worker *ret_worker);
231 static  void crypto_destroy(void);
232 static  int crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint);
233 static  int crypto_kinvoke(struct cryptkop *krp);
234 static  void crypto_task_invoke(void *ctx, int pending);
235 static void crypto_batch_enqueue(struct cryptop *crp);
236
237 static  struct cryptostats cryptostats;
238 SYSCTL_STRUCT(_kern_crypto, OID_AUTO, stats, CTLFLAG_RW, &cryptostats,
239             cryptostats, "Crypto system statistics");
240
241 #ifdef CRYPTO_TIMING
242 static  int crypto_timing = 0;
243 SYSCTL_INT(_debug, OID_AUTO, crypto_timing, CTLFLAG_RW,
244            &crypto_timing, 0, "Enable/disable crypto timing support");
245 #endif
246
247 /* Try to avoid directly exposing the key buffer as a symbol */
248 static struct keybuf *keybuf;
249
250 static struct keybuf empty_keybuf = {
251         .kb_nents = 0
252 };
253
254 /* Obtain the key buffer from boot metadata */
255 static void
256 keybuf_init(void)
257 {
258         caddr_t kmdp;
259
260         kmdp = preload_search_by_type("elf kernel");
261
262         if (kmdp == NULL)
263                 kmdp = preload_search_by_type("elf64 kernel");
264
265         keybuf = (struct keybuf *)preload_search_info(kmdp,
266             MODINFO_METADATA | MODINFOMD_KEYBUF);
267
268         if (keybuf == NULL)
269                 keybuf = &empty_keybuf;
270 }
271
272 /* It'd be nice if we could store these in some kind of secure memory... */
273 struct keybuf * get_keybuf(void) {
274
275         return (keybuf);
276 }
277
278 static struct cryptocap *
279 cap_ref(struct cryptocap *cap)
280 {
281
282         refcount_acquire(&cap->cc_refs);
283         return (cap);
284 }
285
286 static void
287 cap_rele(struct cryptocap *cap)
288 {
289
290         if (refcount_release(&cap->cc_refs) == 0)
291                 return;
292
293         KASSERT(cap->cc_sessions == 0,
294             ("freeing crypto driver with active sessions"));
295         KASSERT(cap->cc_koperations == 0,
296             ("freeing crypto driver with active key operations"));
297
298         free(cap, M_CRYPTO_DATA);
299 }
300
301 static int
302 crypto_init(void)
303 {
304         struct crypto_ret_worker *ret_worker;
305         int error;
306
307         mtx_init(&crypto_drivers_mtx, "crypto", "crypto driver table",
308                 MTX_DEF|MTX_QUIET);
309
310         TAILQ_INIT(&crp_q);
311         TAILQ_INIT(&crp_kq);
312         mtx_init(&crypto_q_mtx, "crypto", "crypto op queues", MTX_DEF);
313
314         cryptop_zone = uma_zcreate("cryptop", sizeof (struct cryptop),
315                                     0, 0, 0, 0,
316                                     UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
317         cryptoses_zone = uma_zcreate("crypto_session",
318             sizeof(struct crypto_session), NULL, NULL, NULL, NULL,
319             UMA_ALIGN_PTR, UMA_ZONE_ZINIT);
320
321         if (cryptop_zone == NULL || cryptoses_zone == NULL) {
322                 printf("crypto_init: cannot setup crypto zones\n");
323                 error = ENOMEM;
324                 goto bad;
325         }
326
327         crypto_drivers_size = CRYPTO_DRIVERS_INITIAL;
328         crypto_drivers = malloc(crypto_drivers_size *
329             sizeof(struct cryptocap), M_CRYPTO_DATA, M_NOWAIT | M_ZERO);
330         if (crypto_drivers == NULL) {
331                 printf("crypto_init: cannot setup crypto drivers\n");
332                 error = ENOMEM;
333                 goto bad;
334         }
335
336         if (crypto_workers_num < 1 || crypto_workers_num > mp_ncpus)
337                 crypto_workers_num = mp_ncpus;
338
339         crypto_tq = taskqueue_create("crypto", M_WAITOK|M_ZERO,
340                                 taskqueue_thread_enqueue, &crypto_tq);
341         if (crypto_tq == NULL) {
342                 printf("crypto init: cannot setup crypto taskqueue\n");
343                 error = ENOMEM;
344                 goto bad;
345         }
346
347         taskqueue_start_threads(&crypto_tq, crypto_workers_num, PRI_MIN_KERN,
348                 "crypto");
349
350         error = kproc_create((void (*)(void *)) crypto_proc, NULL,
351                     &cryptoproc, 0, 0, "crypto");
352         if (error) {
353                 printf("crypto_init: cannot start crypto thread; error %d",
354                         error);
355                 goto bad;
356         }
357
358         crypto_ret_workers = malloc(crypto_workers_num * sizeof(struct crypto_ret_worker),
359                         M_CRYPTO_DATA, M_NOWAIT|M_ZERO);
360         if (crypto_ret_workers == NULL) {
361                 error = ENOMEM;
362                 printf("crypto_init: cannot allocate ret workers\n");
363                 goto bad;
364         }
365
366
367         FOREACH_CRYPTO_RETW(ret_worker) {
368                 TAILQ_INIT(&ret_worker->crp_ordered_ret_q);
369                 TAILQ_INIT(&ret_worker->crp_ret_q);
370                 TAILQ_INIT(&ret_worker->crp_ret_kq);
371
372                 ret_worker->reorder_ops = 0;
373                 ret_worker->reorder_cur_seq = 0;
374
375                 mtx_init(&ret_worker->crypto_ret_mtx, "crypto", "crypto return queues", MTX_DEF);
376
377                 error = kproc_create((void (*)(void *)) crypto_ret_proc, ret_worker,
378                                 &ret_worker->cryptoretproc, 0, 0, "crypto returns %td", CRYPTO_RETW_ID(ret_worker));
379                 if (error) {
380                         printf("crypto_init: cannot start cryptoret thread; error %d",
381                                 error);
382                         goto bad;
383                 }
384         }
385
386         keybuf_init();
387
388         return 0;
389 bad:
390         crypto_destroy();
391         return error;
392 }
393
394 /*
395  * Signal a crypto thread to terminate.  We use the driver
396  * table lock to synchronize the sleep/wakeups so that we
397  * are sure the threads have terminated before we release
398  * the data structures they use.  See crypto_finis below
399  * for the other half of this song-and-dance.
400  */
401 static void
402 crypto_terminate(struct proc **pp, void *q)
403 {
404         struct proc *p;
405
406         mtx_assert(&crypto_drivers_mtx, MA_OWNED);
407         p = *pp;
408         *pp = NULL;
409         if (p) {
410                 wakeup_one(q);
411                 PROC_LOCK(p);           /* NB: insure we don't miss wakeup */
412                 CRYPTO_DRIVER_UNLOCK(); /* let crypto_finis progress */
413                 msleep(p, &p->p_mtx, PWAIT, "crypto_destroy", 0);
414                 PROC_UNLOCK(p);
415                 CRYPTO_DRIVER_LOCK();
416         }
417 }
418
419 static void
420 hmac_init_pad(struct auth_hash *axf, const char *key, int klen, void *auth_ctx,
421     uint8_t padval)
422 {
423         uint8_t hmac_key[HMAC_MAX_BLOCK_LEN];
424         u_int i;
425
426         KASSERT(axf->blocksize <= sizeof(hmac_key),
427             ("Invalid HMAC block size %d", axf->blocksize));
428
429         /*
430          * If the key is larger than the block size, use the digest of
431          * the key as the key instead.
432          */
433         memset(hmac_key, 0, sizeof(hmac_key));
434         if (klen > axf->blocksize) {
435                 axf->Init(auth_ctx);
436                 axf->Update(auth_ctx, key, klen);
437                 axf->Final(hmac_key, auth_ctx);
438                 klen = axf->hashsize;
439         } else
440                 memcpy(hmac_key, key, klen);
441
442         for (i = 0; i < axf->blocksize; i++)
443                 hmac_key[i] ^= padval;
444
445         axf->Init(auth_ctx);
446         axf->Update(auth_ctx, hmac_key, axf->blocksize);
447         explicit_bzero(hmac_key, sizeof(hmac_key));
448 }
449
450 void
451 hmac_init_ipad(struct auth_hash *axf, const char *key, int klen,
452     void *auth_ctx)
453 {
454
455         hmac_init_pad(axf, key, klen, auth_ctx, HMAC_IPAD_VAL);
456 }
457
458 void
459 hmac_init_opad(struct auth_hash *axf, const char *key, int klen,
460     void *auth_ctx)
461 {
462
463         hmac_init_pad(axf, key, klen, auth_ctx, HMAC_OPAD_VAL);
464 }
465
466 static void
467 crypto_destroy(void)
468 {
469         struct crypto_ret_worker *ret_worker;
470         int i;
471
472         /*
473          * Terminate any crypto threads.
474          */
475         if (crypto_tq != NULL)
476                 taskqueue_drain_all(crypto_tq);
477         CRYPTO_DRIVER_LOCK();
478         crypto_terminate(&cryptoproc, &crp_q);
479         FOREACH_CRYPTO_RETW(ret_worker)
480                 crypto_terminate(&ret_worker->cryptoretproc, &ret_worker->crp_ret_q);
481         CRYPTO_DRIVER_UNLOCK();
482
483         /* XXX flush queues??? */
484
485         /*
486          * Reclaim dynamically allocated resources.
487          */
488         for (i = 0; i < crypto_drivers_size; i++) {
489                 if (crypto_drivers[i] != NULL)
490                         cap_rele(crypto_drivers[i]);
491         }
492         free(crypto_drivers, M_CRYPTO_DATA);
493
494         if (cryptoses_zone != NULL)
495                 uma_zdestroy(cryptoses_zone);
496         if (cryptop_zone != NULL)
497                 uma_zdestroy(cryptop_zone);
498         mtx_destroy(&crypto_q_mtx);
499         FOREACH_CRYPTO_RETW(ret_worker)
500                 mtx_destroy(&ret_worker->crypto_ret_mtx);
501         free(crypto_ret_workers, M_CRYPTO_DATA);
502         if (crypto_tq != NULL)
503                 taskqueue_free(crypto_tq);
504         mtx_destroy(&crypto_drivers_mtx);
505 }
506
507 uint32_t
508 crypto_ses2hid(crypto_session_t crypto_session)
509 {
510         return (crypto_session->cap->cc_hid);
511 }
512
513 uint32_t
514 crypto_ses2caps(crypto_session_t crypto_session)
515 {
516         return (crypto_session->cap->cc_flags & 0xff000000);
517 }
518
519 void *
520 crypto_get_driver_session(crypto_session_t crypto_session)
521 {
522         return (crypto_session->softc);
523 }
524
525 const struct crypto_session_params *
526 crypto_get_params(crypto_session_t crypto_session)
527 {
528         return (&crypto_session->csp);
529 }
530
531 struct auth_hash *
532 crypto_auth_hash(const struct crypto_session_params *csp)
533 {
534
535         switch (csp->csp_auth_alg) {
536         case CRYPTO_SHA1_HMAC:
537                 return (&auth_hash_hmac_sha1);
538         case CRYPTO_SHA2_224_HMAC:
539                 return (&auth_hash_hmac_sha2_224);
540         case CRYPTO_SHA2_256_HMAC:
541                 return (&auth_hash_hmac_sha2_256);
542         case CRYPTO_SHA2_384_HMAC:
543                 return (&auth_hash_hmac_sha2_384);
544         case CRYPTO_SHA2_512_HMAC:
545                 return (&auth_hash_hmac_sha2_512);
546         case CRYPTO_NULL_HMAC:
547                 return (&auth_hash_null);
548         case CRYPTO_RIPEMD160_HMAC:
549                 return (&auth_hash_hmac_ripemd_160);
550         case CRYPTO_SHA1:
551                 return (&auth_hash_sha1);
552         case CRYPTO_SHA2_224:
553                 return (&auth_hash_sha2_224);
554         case CRYPTO_SHA2_256:
555                 return (&auth_hash_sha2_256);
556         case CRYPTO_SHA2_384:
557                 return (&auth_hash_sha2_384);
558         case CRYPTO_SHA2_512:
559                 return (&auth_hash_sha2_512);
560         case CRYPTO_AES_NIST_GMAC:
561                 switch (csp->csp_auth_klen) {
562                 case 128 / 8:
563                         return (&auth_hash_nist_gmac_aes_128);
564                 case 192 / 8:
565                         return (&auth_hash_nist_gmac_aes_192);
566                 case 256 / 8:
567                         return (&auth_hash_nist_gmac_aes_256);
568                 default:
569                         return (NULL);
570                 }
571         case CRYPTO_BLAKE2B:
572                 return (&auth_hash_blake2b);
573         case CRYPTO_BLAKE2S:
574                 return (&auth_hash_blake2s);
575         case CRYPTO_POLY1305:
576                 return (&auth_hash_poly1305);
577         case CRYPTO_AES_CCM_CBC_MAC:
578                 switch (csp->csp_auth_klen) {
579                 case 128 / 8:
580                         return (&auth_hash_ccm_cbc_mac_128);
581                 case 192 / 8:
582                         return (&auth_hash_ccm_cbc_mac_192);
583                 case 256 / 8:
584                         return (&auth_hash_ccm_cbc_mac_256);
585                 default:
586                         return (NULL);
587                 }
588         default:
589                 return (NULL);
590         }
591 }
592
593 struct enc_xform *
594 crypto_cipher(const struct crypto_session_params *csp)
595 {
596
597         switch (csp->csp_cipher_alg) {
598         case CRYPTO_RIJNDAEL128_CBC:
599                 return (&enc_xform_rijndael128);
600         case CRYPTO_AES_XTS:
601                 return (&enc_xform_aes_xts);
602         case CRYPTO_AES_ICM:
603                 return (&enc_xform_aes_icm);
604         case CRYPTO_AES_NIST_GCM_16:
605                 return (&enc_xform_aes_nist_gcm);
606         case CRYPTO_CAMELLIA_CBC:
607                 return (&enc_xform_camellia);
608         case CRYPTO_NULL_CBC:
609                 return (&enc_xform_null);
610         case CRYPTO_CHACHA20:
611                 return (&enc_xform_chacha20);
612         case CRYPTO_AES_CCM_16:
613                 return (&enc_xform_ccm);
614         default:
615                 return (NULL);
616         }
617 }
618
619 static struct cryptocap *
620 crypto_checkdriver(u_int32_t hid)
621 {
622
623         return (hid >= crypto_drivers_size ? NULL : crypto_drivers[hid]);
624 }
625
626 /*
627  * Select a driver for a new session that supports the specified
628  * algorithms and, optionally, is constrained according to the flags.
629  */
630 static struct cryptocap *
631 crypto_select_driver(const struct crypto_session_params *csp, int flags)
632 {
633         struct cryptocap *cap, *best;
634         int best_match, error, hid;
635
636         CRYPTO_DRIVER_ASSERT();
637
638         best = NULL;
639         for (hid = 0; hid < crypto_drivers_size; hid++) {
640                 /*
641                  * If there is no driver for this slot, or the driver
642                  * is not appropriate (hardware or software based on
643                  * match), then skip.
644                  */
645                 cap = crypto_drivers[hid];
646                 if (cap == NULL ||
647                     (cap->cc_flags & flags) == 0)
648                         continue;
649
650                 error = CRYPTODEV_PROBESESSION(cap->cc_dev, csp);
651                 if (error >= 0)
652                         continue;
653
654                 /*
655                  * Use the driver with the highest probe value.
656                  * Hardware drivers use a higher probe value than
657                  * software.  In case of a tie, prefer the driver with
658                  * the fewest active sessions.
659                  */
660                 if (best == NULL || error > best_match ||
661                     (error == best_match &&
662                     cap->cc_sessions < best->cc_sessions)) {
663                         best = cap;
664                         best_match = error;
665                 }
666         }
667         return best;
668 }
669
670 static enum alg_type {
671         ALG_NONE = 0,
672         ALG_CIPHER,
673         ALG_DIGEST,
674         ALG_KEYED_DIGEST,
675         ALG_COMPRESSION,
676         ALG_AEAD
677 } alg_types[] = {
678         [CRYPTO_SHA1_HMAC] = ALG_KEYED_DIGEST,
679         [CRYPTO_RIPEMD160_HMAC] = ALG_KEYED_DIGEST,
680         [CRYPTO_AES_CBC] = ALG_CIPHER,
681         [CRYPTO_SHA1] = ALG_DIGEST,
682         [CRYPTO_NULL_HMAC] = ALG_DIGEST,
683         [CRYPTO_NULL_CBC] = ALG_CIPHER,
684         [CRYPTO_DEFLATE_COMP] = ALG_COMPRESSION,
685         [CRYPTO_SHA2_256_HMAC] = ALG_KEYED_DIGEST,
686         [CRYPTO_SHA2_384_HMAC] = ALG_KEYED_DIGEST,
687         [CRYPTO_SHA2_512_HMAC] = ALG_KEYED_DIGEST,
688         [CRYPTO_CAMELLIA_CBC] = ALG_CIPHER,
689         [CRYPTO_AES_XTS] = ALG_CIPHER,
690         [CRYPTO_AES_ICM] = ALG_CIPHER,
691         [CRYPTO_AES_NIST_GMAC] = ALG_KEYED_DIGEST,
692         [CRYPTO_AES_NIST_GCM_16] = ALG_AEAD,
693         [CRYPTO_BLAKE2B] = ALG_KEYED_DIGEST,
694         [CRYPTO_BLAKE2S] = ALG_KEYED_DIGEST,
695         [CRYPTO_CHACHA20] = ALG_CIPHER,
696         [CRYPTO_SHA2_224_HMAC] = ALG_KEYED_DIGEST,
697         [CRYPTO_RIPEMD160] = ALG_DIGEST,
698         [CRYPTO_SHA2_224] = ALG_DIGEST,
699         [CRYPTO_SHA2_256] = ALG_DIGEST,
700         [CRYPTO_SHA2_384] = ALG_DIGEST,
701         [CRYPTO_SHA2_512] = ALG_DIGEST,
702         [CRYPTO_POLY1305] = ALG_KEYED_DIGEST,
703         [CRYPTO_AES_CCM_CBC_MAC] = ALG_KEYED_DIGEST,
704         [CRYPTO_AES_CCM_16] = ALG_AEAD,
705 };
706
707 static enum alg_type
708 alg_type(int alg)
709 {
710
711         if (alg < nitems(alg_types))
712                 return (alg_types[alg]);
713         return (ALG_NONE);
714 }
715
716 static bool
717 alg_is_compression(int alg)
718 {
719
720         return (alg_type(alg) == ALG_COMPRESSION);
721 }
722
723 static bool
724 alg_is_cipher(int alg)
725 {
726
727         return (alg_type(alg) == ALG_CIPHER);
728 }
729
730 static bool
731 alg_is_digest(int alg)
732 {
733
734         return (alg_type(alg) == ALG_DIGEST ||
735             alg_type(alg) == ALG_KEYED_DIGEST);
736 }
737
738 static bool
739 alg_is_keyed_digest(int alg)
740 {
741
742         return (alg_type(alg) == ALG_KEYED_DIGEST);
743 }
744
745 static bool
746 alg_is_aead(int alg)
747 {
748
749         return (alg_type(alg) == ALG_AEAD);
750 }
751
752 /* Various sanity checks on crypto session parameters. */
753 static bool
754 check_csp(const struct crypto_session_params *csp)
755 {
756         struct auth_hash *axf;
757
758         /* Mode-independent checks. */
759         if ((csp->csp_flags & ~(CSP_F_SEPARATE_OUTPUT | CSP_F_SEPARATE_AAD)) !=
760             0)
761                 return (false);
762         if (csp->csp_ivlen < 0 || csp->csp_cipher_klen < 0 ||
763             csp->csp_auth_klen < 0 || csp->csp_auth_mlen < 0)
764                 return (false);
765         if (csp->csp_auth_key != NULL && csp->csp_auth_klen == 0)
766                 return (false);
767         if (csp->csp_cipher_key != NULL && csp->csp_cipher_klen == 0)
768                 return (false);
769
770         switch (csp->csp_mode) {
771         case CSP_MODE_COMPRESS:
772                 if (!alg_is_compression(csp->csp_cipher_alg))
773                         return (false);
774                 if (csp->csp_flags & CSP_F_SEPARATE_OUTPUT)
775                         return (false);
776                 if (csp->csp_flags & CSP_F_SEPARATE_AAD)
777                         return (false);
778                 if (csp->csp_cipher_klen != 0 || csp->csp_ivlen != 0 ||
779                     csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0 ||
780                     csp->csp_auth_mlen != 0)
781                         return (false);
782                 break;
783         case CSP_MODE_CIPHER:
784                 if (!alg_is_cipher(csp->csp_cipher_alg))
785                         return (false);
786                 if (csp->csp_flags & CSP_F_SEPARATE_AAD)
787                         return (false);
788                 if (csp->csp_cipher_alg != CRYPTO_NULL_CBC) {
789                         if (csp->csp_cipher_klen == 0)
790                                 return (false);
791                         if (csp->csp_ivlen == 0)
792                                 return (false);
793                 }
794                 if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
795                         return (false);
796                 if (csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0 ||
797                     csp->csp_auth_mlen != 0)
798                         return (false);
799                 break;
800         case CSP_MODE_DIGEST:
801                 if (csp->csp_cipher_alg != 0 || csp->csp_cipher_klen != 0)
802                         return (false);
803
804                 if (csp->csp_flags & CSP_F_SEPARATE_AAD)
805                         return (false);
806
807                 /* IV is optional for digests (e.g. GMAC). */
808                 if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
809                         return (false);
810                 if (!alg_is_digest(csp->csp_auth_alg))
811                         return (false);
812
813                 /* Key is optional for BLAKE2 digests. */
814                 if (csp->csp_auth_alg == CRYPTO_BLAKE2B ||
815                     csp->csp_auth_alg == CRYPTO_BLAKE2S)
816                         ;
817                 else if (alg_is_keyed_digest(csp->csp_auth_alg)) {
818                         if (csp->csp_auth_klen == 0)
819                                 return (false);
820                 } else {
821                         if (csp->csp_auth_klen != 0)
822                                 return (false);
823                 }
824                 if (csp->csp_auth_mlen != 0) {
825                         axf = crypto_auth_hash(csp);
826                         if (axf == NULL || csp->csp_auth_mlen > axf->hashsize)
827                                 return (false);
828                 }
829                 break;
830         case CSP_MODE_AEAD:
831                 if (!alg_is_aead(csp->csp_cipher_alg))
832                         return (false);
833                 if (csp->csp_cipher_klen == 0)
834                         return (false);
835                 if (csp->csp_ivlen == 0 ||
836                     csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
837                         return (false);
838                 if (csp->csp_auth_alg != 0 || csp->csp_auth_klen != 0)
839                         return (false);
840
841                 /*
842                  * XXX: Would be nice to have a better way to get this
843                  * value.
844                  */
845                 switch (csp->csp_cipher_alg) {
846                 case CRYPTO_AES_NIST_GCM_16:
847                 case CRYPTO_AES_CCM_16:
848                         if (csp->csp_auth_mlen > 16)
849                                 return (false);
850                         break;
851                 }
852                 break;
853         case CSP_MODE_ETA:
854                 if (!alg_is_cipher(csp->csp_cipher_alg))
855                         return (false);
856                 if (csp->csp_cipher_alg != CRYPTO_NULL_CBC) {
857                         if (csp->csp_cipher_klen == 0)
858                                 return (false);
859                         if (csp->csp_ivlen == 0)
860                                 return (false);
861                 }
862                 if (csp->csp_ivlen >= EALG_MAX_BLOCK_LEN)
863                         return (false);
864                 if (!alg_is_digest(csp->csp_auth_alg))
865                         return (false);
866
867                 /* Key is optional for BLAKE2 digests. */
868                 if (csp->csp_auth_alg == CRYPTO_BLAKE2B ||
869                     csp->csp_auth_alg == CRYPTO_BLAKE2S)
870                         ;
871                 else if (alg_is_keyed_digest(csp->csp_auth_alg)) {
872                         if (csp->csp_auth_klen == 0)
873                                 return (false);
874                 } else {
875                         if (csp->csp_auth_klen != 0)
876                                 return (false);
877                 }
878                 if (csp->csp_auth_mlen != 0) {
879                         axf = crypto_auth_hash(csp);
880                         if (axf == NULL || csp->csp_auth_mlen > axf->hashsize)
881                                 return (false);
882                 }
883                 break;
884         default:
885                 return (false);
886         }
887
888         return (true);
889 }
890
891 /*
892  * Delete a session after it has been detached from its driver.
893  */
894 static void
895 crypto_deletesession(crypto_session_t cses)
896 {
897         struct cryptocap *cap;
898
899         cap = cses->cap;
900
901         zfree(cses->softc, M_CRYPTO_DATA);
902         uma_zfree(cryptoses_zone, cses);
903
904         CRYPTO_DRIVER_LOCK();
905         cap->cc_sessions--;
906         if (cap->cc_sessions == 0 && cap->cc_flags & CRYPTOCAP_F_CLEANUP)
907                 wakeup(cap);
908         CRYPTO_DRIVER_UNLOCK();
909         cap_rele(cap);
910 }
911
912 /*
913  * Create a new session.  The crid argument specifies a crypto
914  * driver to use or constraints on a driver to select (hardware
915  * only, software only, either).  Whatever driver is selected
916  * must be capable of the requested crypto algorithms.
917  */
918 int
919 crypto_newsession(crypto_session_t *cses,
920     const struct crypto_session_params *csp, int crid)
921 {
922         crypto_session_t res;
923         struct cryptocap *cap;
924         int err;
925
926         if (!check_csp(csp))
927                 return (EINVAL);
928
929         res = NULL;
930
931         CRYPTO_DRIVER_LOCK();
932         if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
933                 /*
934                  * Use specified driver; verify it is capable.
935                  */
936                 cap = crypto_checkdriver(crid);
937                 if (cap != NULL && CRYPTODEV_PROBESESSION(cap->cc_dev, csp) > 0)
938                         cap = NULL;
939         } else {
940                 /*
941                  * No requested driver; select based on crid flags.
942                  */
943                 cap = crypto_select_driver(csp, crid);
944         }
945         if (cap == NULL) {
946                 CRYPTO_DRIVER_UNLOCK();
947                 CRYPTDEB("no driver");
948                 return (EOPNOTSUPP);
949         }
950         cap_ref(cap);
951         cap->cc_sessions++;
952         CRYPTO_DRIVER_UNLOCK();
953
954         res = uma_zalloc(cryptoses_zone, M_WAITOK | M_ZERO);
955         res->cap = cap;
956         res->softc = malloc(cap->cc_session_size, M_CRYPTO_DATA, M_WAITOK |
957             M_ZERO);
958         res->csp = *csp;
959
960         /* Call the driver initialization routine. */
961         err = CRYPTODEV_NEWSESSION(cap->cc_dev, res, csp);
962         if (err != 0) {
963                 CRYPTDEB("dev newsession failed: %d", err);
964                 crypto_deletesession(res);
965                 return (err);
966         }
967
968         *cses = res;
969         return (0);
970 }
971
972 /*
973  * Delete an existing session (or a reserved session on an unregistered
974  * driver).
975  */
976 void
977 crypto_freesession(crypto_session_t cses)
978 {
979         struct cryptocap *cap;
980
981         if (cses == NULL)
982                 return;
983
984         cap = cses->cap;
985
986         /* Call the driver cleanup routine, if available. */
987         CRYPTODEV_FREESESSION(cap->cc_dev, cses);
988
989         crypto_deletesession(cses);
990 }
991
992 /*
993  * Return a new driver id.  Registers a driver with the system so that
994  * it can be probed by subsequent sessions.
995  */
996 int32_t
997 crypto_get_driverid(device_t dev, size_t sessionsize, int flags)
998 {
999         struct cryptocap *cap, **newdrv;
1000         int i;
1001
1002         if ((flags & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
1003                 device_printf(dev,
1004                     "no flags specified when registering driver\n");
1005                 return -1;
1006         }
1007
1008         cap = malloc(sizeof(*cap), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
1009         cap->cc_dev = dev;
1010         cap->cc_session_size = sessionsize;
1011         cap->cc_flags = flags;
1012         refcount_init(&cap->cc_refs, 1);
1013
1014         CRYPTO_DRIVER_LOCK();
1015         for (;;) {
1016                 for (i = 0; i < crypto_drivers_size; i++) {
1017                         if (crypto_drivers[i] == NULL)
1018                                 break;
1019                 }
1020
1021                 if (i < crypto_drivers_size)
1022                         break;
1023
1024                 /* Out of entries, allocate some more. */
1025
1026                 if (2 * crypto_drivers_size <= crypto_drivers_size) {
1027                         CRYPTO_DRIVER_UNLOCK();
1028                         printf("crypto: driver count wraparound!\n");
1029                         cap_rele(cap);
1030                         return (-1);
1031                 }
1032                 CRYPTO_DRIVER_UNLOCK();
1033
1034                 newdrv = malloc(2 * crypto_drivers_size *
1035                     sizeof(*crypto_drivers), M_CRYPTO_DATA, M_WAITOK | M_ZERO);
1036
1037                 CRYPTO_DRIVER_LOCK();
1038                 memcpy(newdrv, crypto_drivers,
1039                     crypto_drivers_size * sizeof(*crypto_drivers));
1040
1041                 crypto_drivers_size *= 2;
1042
1043                 free(crypto_drivers, M_CRYPTO_DATA);
1044                 crypto_drivers = newdrv;
1045         }
1046
1047         cap->cc_hid = i;
1048         crypto_drivers[i] = cap;
1049         CRYPTO_DRIVER_UNLOCK();
1050
1051         if (bootverbose)
1052                 printf("crypto: assign %s driver id %u, flags 0x%x\n",
1053                     device_get_nameunit(dev), i, flags);
1054
1055         return i;
1056 }
1057
1058 /*
1059  * Lookup a driver by name.  We match against the full device
1060  * name and unit, and against just the name.  The latter gives
1061  * us a simple widlcarding by device name.  On success return the
1062  * driver/hardware identifier; otherwise return -1.
1063  */
1064 int
1065 crypto_find_driver(const char *match)
1066 {
1067         struct cryptocap *cap;
1068         int i, len = strlen(match);
1069
1070         CRYPTO_DRIVER_LOCK();
1071         for (i = 0; i < crypto_drivers_size; i++) {
1072                 if (crypto_drivers[i] == NULL)
1073                         continue;
1074                 cap = crypto_drivers[i];
1075                 if (strncmp(match, device_get_nameunit(cap->cc_dev), len) == 0 ||
1076                     strncmp(match, device_get_name(cap->cc_dev), len) == 0) {
1077                         CRYPTO_DRIVER_UNLOCK();
1078                         return (i);
1079                 }
1080         }
1081         CRYPTO_DRIVER_UNLOCK();
1082         return (-1);
1083 }
1084
1085 /*
1086  * Return the device_t for the specified driver or NULL
1087  * if the driver identifier is invalid.
1088  */
1089 device_t
1090 crypto_find_device_byhid(int hid)
1091 {
1092         struct cryptocap *cap;
1093         device_t dev;
1094
1095         dev = NULL;
1096         CRYPTO_DRIVER_LOCK();
1097         cap = crypto_checkdriver(hid);
1098         if (cap != NULL)
1099                 dev = cap->cc_dev;
1100         CRYPTO_DRIVER_UNLOCK();
1101         return (dev);
1102 }
1103
1104 /*
1105  * Return the device/driver capabilities.
1106  */
1107 int
1108 crypto_getcaps(int hid)
1109 {
1110         struct cryptocap *cap;
1111         int flags;
1112
1113         flags = 0;
1114         CRYPTO_DRIVER_LOCK();
1115         cap = crypto_checkdriver(hid);
1116         if (cap != NULL)
1117                 flags = cap->cc_flags;
1118         CRYPTO_DRIVER_UNLOCK();
1119         return (flags);
1120 }
1121
1122 /*
1123  * Register support for a key-related algorithm.  This routine
1124  * is called once for each algorithm supported a driver.
1125  */
1126 int
1127 crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags)
1128 {
1129         struct cryptocap *cap;
1130         int err;
1131
1132         CRYPTO_DRIVER_LOCK();
1133
1134         cap = crypto_checkdriver(driverid);
1135         if (cap != NULL &&
1136             (CRK_ALGORITM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
1137                 /*
1138                  * XXX Do some performance testing to determine placing.
1139                  * XXX We probably need an auxiliary data structure that
1140                  * XXX describes relative performances.
1141                  */
1142
1143                 cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
1144                 if (bootverbose)
1145                         printf("crypto: %s registers key alg %u flags %u\n"
1146                                 , device_get_nameunit(cap->cc_dev)
1147                                 , kalg
1148                                 , flags
1149                         );
1150                 err = 0;
1151         } else
1152                 err = EINVAL;
1153
1154         CRYPTO_DRIVER_UNLOCK();
1155         return err;
1156 }
1157
1158 /*
1159  * Unregister all algorithms associated with a crypto driver.
1160  * If there are pending sessions using it, leave enough information
1161  * around so that subsequent calls using those sessions will
1162  * correctly detect the driver has been unregistered and reroute
1163  * requests.
1164  */
1165 int
1166 crypto_unregister_all(u_int32_t driverid)
1167 {
1168         struct cryptocap *cap;
1169
1170         CRYPTO_DRIVER_LOCK();
1171         cap = crypto_checkdriver(driverid);
1172         if (cap == NULL) {
1173                 CRYPTO_DRIVER_UNLOCK();
1174                 return (EINVAL);
1175         }
1176
1177         cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
1178         crypto_drivers[driverid] = NULL;
1179
1180         /*
1181          * XXX: This doesn't do anything to kick sessions that
1182          * have no pending operations.
1183          */
1184         while (cap->cc_sessions != 0 || cap->cc_koperations != 0)
1185                 mtx_sleep(cap, &crypto_drivers_mtx, 0, "cryunreg", 0);
1186         CRYPTO_DRIVER_UNLOCK();
1187         cap_rele(cap);
1188
1189         return (0);
1190 }
1191
1192 /*
1193  * Clear blockage on a driver.  The what parameter indicates whether
1194  * the driver is now ready for cryptop's and/or cryptokop's.
1195  */
1196 int
1197 crypto_unblock(u_int32_t driverid, int what)
1198 {
1199         struct cryptocap *cap;
1200         int err;
1201
1202         CRYPTO_Q_LOCK();
1203         cap = crypto_checkdriver(driverid);
1204         if (cap != NULL) {
1205                 if (what & CRYPTO_SYMQ)
1206                         cap->cc_qblocked = 0;
1207                 if (what & CRYPTO_ASYMQ)
1208                         cap->cc_kqblocked = 0;
1209                 if (crp_sleep)
1210                         wakeup_one(&crp_q);
1211                 err = 0;
1212         } else
1213                 err = EINVAL;
1214         CRYPTO_Q_UNLOCK();
1215
1216         return err;
1217 }
1218
1219 size_t
1220 crypto_buffer_len(struct crypto_buffer *cb)
1221 {
1222         switch (cb->cb_type) {
1223         case CRYPTO_BUF_CONTIG:
1224                 return (cb->cb_buf_len);
1225         case CRYPTO_BUF_MBUF:
1226                 if (cb->cb_mbuf->m_flags & M_PKTHDR)
1227                         return (cb->cb_mbuf->m_pkthdr.len);
1228                 return (m_length(cb->cb_mbuf, NULL));
1229         case CRYPTO_BUF_UIO:
1230                 return (cb->cb_uio->uio_resid);
1231         default:
1232                 return (0);
1233         }
1234 }
1235
1236 #ifdef INVARIANTS
1237 /* Various sanity checks on crypto requests. */
1238 static void
1239 cb_sanity(struct crypto_buffer *cb, const char *name)
1240 {
1241         KASSERT(cb->cb_type > CRYPTO_BUF_NONE && cb->cb_type <= CRYPTO_BUF_LAST,
1242             ("incoming crp with invalid %s buffer type", name));
1243         if (cb->cb_type == CRYPTO_BUF_CONTIG)
1244                 KASSERT(cb->cb_buf_len >= 0,
1245                     ("incoming crp with -ve %s buffer length", name));
1246 }
1247
1248 static void
1249 crp_sanity(struct cryptop *crp)
1250 {
1251         struct crypto_session_params *csp;
1252         struct crypto_buffer *out;
1253         size_t ilen, len, olen;
1254
1255         KASSERT(crp->crp_session != NULL, ("incoming crp without a session"));
1256         KASSERT(crp->crp_obuf.cb_type >= CRYPTO_BUF_NONE &&
1257             crp->crp_obuf.cb_type <= CRYPTO_BUF_LAST,
1258             ("incoming crp with invalid output buffer type"));
1259         KASSERT(crp->crp_etype == 0, ("incoming crp with error"));
1260         KASSERT(!(crp->crp_flags & CRYPTO_F_DONE),
1261             ("incoming crp already done"));
1262
1263         csp = &crp->crp_session->csp;
1264         cb_sanity(&crp->crp_buf, "input");
1265         ilen = crypto_buffer_len(&crp->crp_buf);
1266         olen = ilen;
1267         out = NULL;
1268         if (csp->csp_flags & CSP_F_SEPARATE_OUTPUT) {
1269                 if (crp->crp_obuf.cb_type != CRYPTO_BUF_NONE) {
1270                         cb_sanity(&crp->crp_obuf, "output");
1271                         out = &crp->crp_obuf;
1272                         olen = crypto_buffer_len(out);
1273                 }
1274         } else
1275                 KASSERT(crp->crp_obuf.cb_type == CRYPTO_BUF_NONE,
1276                     ("incoming crp with separate output buffer "
1277                     "but no session support"));
1278
1279         switch (csp->csp_mode) {
1280         case CSP_MODE_COMPRESS:
1281                 KASSERT(crp->crp_op == CRYPTO_OP_COMPRESS ||
1282                     crp->crp_op == CRYPTO_OP_DECOMPRESS,
1283                     ("invalid compression op %x", crp->crp_op));
1284                 break;
1285         case CSP_MODE_CIPHER:
1286                 KASSERT(crp->crp_op == CRYPTO_OP_ENCRYPT ||
1287                     crp->crp_op == CRYPTO_OP_DECRYPT,
1288                     ("invalid cipher op %x", crp->crp_op));
1289                 break;
1290         case CSP_MODE_DIGEST:
1291                 KASSERT(crp->crp_op == CRYPTO_OP_COMPUTE_DIGEST ||
1292                     crp->crp_op == CRYPTO_OP_VERIFY_DIGEST,
1293                     ("invalid digest op %x", crp->crp_op));
1294                 break;
1295         case CSP_MODE_AEAD:
1296                 KASSERT(crp->crp_op ==
1297                     (CRYPTO_OP_ENCRYPT | CRYPTO_OP_COMPUTE_DIGEST) ||
1298                     crp->crp_op ==
1299                     (CRYPTO_OP_DECRYPT | CRYPTO_OP_VERIFY_DIGEST),
1300                     ("invalid AEAD op %x", crp->crp_op));
1301                 if (csp->csp_cipher_alg == CRYPTO_AES_NIST_GCM_16)
1302                         KASSERT(crp->crp_flags & CRYPTO_F_IV_SEPARATE,
1303                             ("GCM without a separate IV"));
1304                 if (csp->csp_cipher_alg == CRYPTO_AES_CCM_16)
1305                         KASSERT(crp->crp_flags & CRYPTO_F_IV_SEPARATE,
1306                             ("CCM without a separate IV"));
1307                 break;
1308         case CSP_MODE_ETA:
1309                 KASSERT(crp->crp_op ==
1310                     (CRYPTO_OP_ENCRYPT | CRYPTO_OP_COMPUTE_DIGEST) ||
1311                     crp->crp_op ==
1312                     (CRYPTO_OP_DECRYPT | CRYPTO_OP_VERIFY_DIGEST),
1313                     ("invalid ETA op %x", crp->crp_op));
1314                 break;
1315         }
1316         if (csp->csp_mode == CSP_MODE_AEAD || csp->csp_mode == CSP_MODE_ETA) {
1317                 if (crp->crp_aad == NULL) {
1318                         KASSERT(crp->crp_aad_start == 0 ||
1319                             crp->crp_aad_start < ilen,
1320                             ("invalid AAD start"));
1321                         KASSERT(crp->crp_aad_length != 0 ||
1322                             crp->crp_aad_start == 0,
1323                             ("AAD with zero length and non-zero start"));
1324                         KASSERT(crp->crp_aad_length == 0 ||
1325                             crp->crp_aad_start + crp->crp_aad_length <= ilen,
1326                             ("AAD outside input length"));
1327                 } else {
1328                         KASSERT(csp->csp_flags & CSP_F_SEPARATE_AAD,
1329                             ("session doesn't support separate AAD buffer"));
1330                         KASSERT(crp->crp_aad_start == 0,
1331                             ("separate AAD buffer with non-zero AAD start"));
1332                         KASSERT(crp->crp_aad_length != 0,
1333                             ("separate AAD buffer with zero length"));
1334                 }
1335         } else {
1336                 KASSERT(crp->crp_aad == NULL && crp->crp_aad_start == 0 &&
1337                     crp->crp_aad_length == 0,
1338                     ("AAD region in request not supporting AAD"));
1339         }
1340         if (csp->csp_ivlen == 0) {
1341                 KASSERT((crp->crp_flags & CRYPTO_F_IV_SEPARATE) == 0,
1342                     ("IV_SEPARATE set when IV isn't used"));
1343                 KASSERT(crp->crp_iv_start == 0,
1344                     ("crp_iv_start set when IV isn't used"));
1345         } else if (crp->crp_flags & CRYPTO_F_IV_SEPARATE) {
1346                 KASSERT(crp->crp_iv_start == 0,
1347                     ("IV_SEPARATE used with non-zero IV start"));
1348         } else {
1349                 KASSERT(crp->crp_iv_start < ilen,
1350                     ("invalid IV start"));
1351                 KASSERT(crp->crp_iv_start + csp->csp_ivlen <= ilen,
1352                     ("IV outside buffer length"));
1353         }
1354         /* XXX: payload_start of 0 should always be < ilen? */
1355         KASSERT(crp->crp_payload_start == 0 ||
1356             crp->crp_payload_start < ilen,
1357             ("invalid payload start"));
1358         KASSERT(crp->crp_payload_start + crp->crp_payload_length <=
1359             ilen, ("payload outside input buffer"));
1360         if (out == NULL) {
1361                 KASSERT(crp->crp_payload_output_start == 0,
1362                     ("payload output start non-zero without output buffer"));
1363         } else {
1364                 KASSERT(crp->crp_payload_output_start < olen,
1365                     ("invalid payload output start"));
1366                 KASSERT(crp->crp_payload_output_start +
1367                     crp->crp_payload_length <= olen,
1368                     ("payload outside output buffer"));
1369         }
1370         if (csp->csp_mode == CSP_MODE_DIGEST ||
1371             csp->csp_mode == CSP_MODE_AEAD || csp->csp_mode == CSP_MODE_ETA) {
1372                 if (crp->crp_op & CRYPTO_OP_VERIFY_DIGEST)
1373                         len = ilen;
1374                 else
1375                         len = olen;
1376                 KASSERT(crp->crp_digest_start == 0 ||
1377                     crp->crp_digest_start < len,
1378                     ("invalid digest start"));
1379                 /* XXX: For the mlen == 0 case this check isn't perfect. */
1380                 KASSERT(crp->crp_digest_start + csp->csp_auth_mlen <= len,
1381                     ("digest outside buffer"));
1382         } else {
1383                 KASSERT(crp->crp_digest_start == 0,
1384                     ("non-zero digest start for request without a digest"));
1385         }
1386         if (csp->csp_cipher_klen != 0)
1387                 KASSERT(csp->csp_cipher_key != NULL ||
1388                     crp->crp_cipher_key != NULL,
1389                     ("cipher request without a key"));
1390         if (csp->csp_auth_klen != 0)
1391                 KASSERT(csp->csp_auth_key != NULL || crp->crp_auth_key != NULL,
1392                     ("auth request without a key"));
1393         KASSERT(crp->crp_callback != NULL, ("incoming crp without callback"));
1394 }
1395 #endif
1396
1397 /*
1398  * Add a crypto request to a queue, to be processed by the kernel thread.
1399  */
1400 int
1401 crypto_dispatch(struct cryptop *crp)
1402 {
1403         struct cryptocap *cap;
1404         int result;
1405
1406 #ifdef INVARIANTS
1407         crp_sanity(crp);
1408 #endif
1409
1410         cryptostats.cs_ops++;
1411
1412 #ifdef CRYPTO_TIMING
1413         if (crypto_timing)
1414                 binuptime(&crp->crp_tstamp);
1415 #endif
1416
1417         crp->crp_retw_id = ((uintptr_t)crp->crp_session) % crypto_workers_num;
1418
1419         if (CRYPTOP_ASYNC(crp)) {
1420                 if (crp->crp_flags & CRYPTO_F_ASYNC_KEEPORDER) {
1421                         struct crypto_ret_worker *ret_worker;
1422
1423                         ret_worker = CRYPTO_RETW(crp->crp_retw_id);
1424
1425                         CRYPTO_RETW_LOCK(ret_worker);
1426                         crp->crp_seq = ret_worker->reorder_ops++;
1427                         CRYPTO_RETW_UNLOCK(ret_worker);
1428                 }
1429
1430                 TASK_INIT(&crp->crp_task, 0, crypto_task_invoke, crp);
1431                 taskqueue_enqueue(crypto_tq, &crp->crp_task);
1432                 return (0);
1433         }
1434
1435         if ((crp->crp_flags & CRYPTO_F_BATCH) == 0) {
1436                 /*
1437                  * Caller marked the request to be processed
1438                  * immediately; dispatch it directly to the
1439                  * driver unless the driver is currently blocked.
1440                  */
1441                 cap = crp->crp_session->cap;
1442                 if (!cap->cc_qblocked) {
1443                         result = crypto_invoke(cap, crp, 0);
1444                         if (result != ERESTART)
1445                                 return (result);
1446                         /*
1447                          * The driver ran out of resources, put the request on
1448                          * the queue.
1449                          */
1450                 }
1451         }
1452         crypto_batch_enqueue(crp);
1453         return 0;
1454 }
1455
1456 void
1457 crypto_batch_enqueue(struct cryptop *crp)
1458 {
1459
1460         CRYPTO_Q_LOCK();
1461         TAILQ_INSERT_TAIL(&crp_q, crp, crp_next);
1462         if (crp_sleep)
1463                 wakeup_one(&crp_q);
1464         CRYPTO_Q_UNLOCK();
1465 }
1466
1467 /*
1468  * Add an asymetric crypto request to a queue,
1469  * to be processed by the kernel thread.
1470  */
1471 int
1472 crypto_kdispatch(struct cryptkop *krp)
1473 {
1474         int error;
1475
1476         cryptostats.cs_kops++;
1477
1478         krp->krp_cap = NULL;
1479         error = crypto_kinvoke(krp);
1480         if (error == ERESTART) {
1481                 CRYPTO_Q_LOCK();
1482                 TAILQ_INSERT_TAIL(&crp_kq, krp, krp_next);
1483                 if (crp_sleep)
1484                         wakeup_one(&crp_q);
1485                 CRYPTO_Q_UNLOCK();
1486                 error = 0;
1487         }
1488         return error;
1489 }
1490
1491 /*
1492  * Verify a driver is suitable for the specified operation.
1493  */
1494 static __inline int
1495 kdriver_suitable(const struct cryptocap *cap, const struct cryptkop *krp)
1496 {
1497         return (cap->cc_kalg[krp->krp_op] & CRYPTO_ALG_FLAG_SUPPORTED) != 0;
1498 }
1499
1500 /*
1501  * Select a driver for an asym operation.  The driver must
1502  * support the necessary algorithm.  The caller can constrain
1503  * which device is selected with the flags parameter.  The
1504  * algorithm we use here is pretty stupid; just use the first
1505  * driver that supports the algorithms we need. If there are
1506  * multiple suitable drivers we choose the driver with the
1507  * fewest active operations.  We prefer hardware-backed
1508  * drivers to software ones when either may be used.
1509  */
1510 static struct cryptocap *
1511 crypto_select_kdriver(const struct cryptkop *krp, int flags)
1512 {
1513         struct cryptocap *cap, *best;
1514         int match, hid;
1515
1516         CRYPTO_DRIVER_ASSERT();
1517
1518         /*
1519          * Look first for hardware crypto devices if permitted.
1520          */
1521         if (flags & CRYPTOCAP_F_HARDWARE)
1522                 match = CRYPTOCAP_F_HARDWARE;
1523         else
1524                 match = CRYPTOCAP_F_SOFTWARE;
1525         best = NULL;
1526 again:
1527         for (hid = 0; hid < crypto_drivers_size; hid++) {
1528                 /*
1529                  * If there is no driver for this slot, or the driver
1530                  * is not appropriate (hardware or software based on
1531                  * match), then skip.
1532                  */
1533                 cap = crypto_drivers[hid];
1534                 if (cap->cc_dev == NULL ||
1535                     (cap->cc_flags & match) == 0)
1536                         continue;
1537
1538                 /* verify all the algorithms are supported. */
1539                 if (kdriver_suitable(cap, krp)) {
1540                         if (best == NULL ||
1541                             cap->cc_koperations < best->cc_koperations)
1542                                 best = cap;
1543                 }
1544         }
1545         if (best != NULL)
1546                 return best;
1547         if (match == CRYPTOCAP_F_HARDWARE && (flags & CRYPTOCAP_F_SOFTWARE)) {
1548                 /* sort of an Algol 68-style for loop */
1549                 match = CRYPTOCAP_F_SOFTWARE;
1550                 goto again;
1551         }
1552         return best;
1553 }
1554
1555 /*
1556  * Choose a driver for an asymmetric crypto request.
1557  */
1558 static struct cryptocap *
1559 crypto_lookup_kdriver(struct cryptkop *krp)
1560 {
1561         struct cryptocap *cap;
1562         uint32_t crid;
1563
1564         /* If this request is requeued, it might already have a driver. */
1565         cap = krp->krp_cap;
1566         if (cap != NULL)
1567                 return (cap);
1568
1569         /* Use krp_crid to choose a driver. */
1570         crid = krp->krp_crid;
1571         if ((crid & (CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE)) == 0) {
1572                 cap = crypto_checkdriver(crid);
1573                 if (cap != NULL) {
1574                         /*
1575                          * Driver present, it must support the
1576                          * necessary algorithm and, if s/w drivers are
1577                          * excluded, it must be registered as
1578                          * hardware-backed.
1579                          */
1580                         if (!kdriver_suitable(cap, krp) ||
1581                             (!crypto_devallowsoft &&
1582                             (cap->cc_flags & CRYPTOCAP_F_HARDWARE) == 0))
1583                                 cap = NULL;
1584                 }
1585         } else {
1586                 /*
1587                  * No requested driver; select based on crid flags.
1588                  */
1589                 if (!crypto_devallowsoft)       /* NB: disallow s/w drivers */
1590                         crid &= ~CRYPTOCAP_F_SOFTWARE;
1591                 cap = crypto_select_kdriver(krp, crid);
1592         }
1593
1594         if (cap != NULL) {
1595                 krp->krp_cap = cap_ref(cap);
1596                 krp->krp_hid = cap->cc_hid;
1597         }
1598         return (cap);
1599 }
1600
1601 /*
1602  * Dispatch an asymmetric crypto request.
1603  */
1604 static int
1605 crypto_kinvoke(struct cryptkop *krp)
1606 {
1607         struct cryptocap *cap = NULL;
1608         int error;
1609
1610         KASSERT(krp != NULL, ("%s: krp == NULL", __func__));
1611         KASSERT(krp->krp_callback != NULL,
1612             ("%s: krp->crp_callback == NULL", __func__));
1613
1614         CRYPTO_DRIVER_LOCK();
1615         cap = crypto_lookup_kdriver(krp);
1616         if (cap == NULL) {
1617                 CRYPTO_DRIVER_UNLOCK();
1618                 krp->krp_status = ENODEV;
1619                 crypto_kdone(krp);
1620                 return (0);
1621         }
1622
1623         /*
1624          * If the device is blocked, return ERESTART to requeue it.
1625          */
1626         if (cap->cc_kqblocked) {
1627                 /*
1628                  * XXX: Previously this set krp_status to ERESTART and
1629                  * invoked crypto_kdone but the caller would still
1630                  * requeue it.
1631                  */
1632                 CRYPTO_DRIVER_UNLOCK();
1633                 return (ERESTART);
1634         }
1635
1636         cap->cc_koperations++;
1637         CRYPTO_DRIVER_UNLOCK();
1638         error = CRYPTODEV_KPROCESS(cap->cc_dev, krp, 0);
1639         if (error == ERESTART) {
1640                 CRYPTO_DRIVER_LOCK();
1641                 cap->cc_koperations--;
1642                 CRYPTO_DRIVER_UNLOCK();
1643                 return (error);
1644         }
1645
1646         KASSERT(error == 0, ("error %d returned from crypto_kprocess", error));
1647         return (0);
1648 }
1649
1650 #ifdef CRYPTO_TIMING
1651 static void
1652 crypto_tstat(struct cryptotstat *ts, struct bintime *bt)
1653 {
1654         struct bintime now, delta;
1655         struct timespec t;
1656         uint64_t u;
1657
1658         binuptime(&now);
1659         u = now.frac;
1660         delta.frac = now.frac - bt->frac;
1661         delta.sec = now.sec - bt->sec;
1662         if (u < delta.frac)
1663                 delta.sec--;
1664         bintime2timespec(&delta, &t);
1665         timespecadd(&ts->acc, &t, &ts->acc);
1666         if (timespeccmp(&t, &ts->min, <))
1667                 ts->min = t;
1668         if (timespeccmp(&t, &ts->max, >))
1669                 ts->max = t;
1670         ts->count++;
1671
1672         *bt = now;
1673 }
1674 #endif
1675
1676 static void
1677 crypto_task_invoke(void *ctx, int pending)
1678 {
1679         struct cryptocap *cap;
1680         struct cryptop *crp;
1681         int result;
1682
1683         crp = (struct cryptop *)ctx;
1684         cap = crp->crp_session->cap;
1685         result = crypto_invoke(cap, crp, 0);
1686         if (result == ERESTART)
1687                 crypto_batch_enqueue(crp);
1688 }
1689
1690 /*
1691  * Dispatch a crypto request to the appropriate crypto devices.
1692  */
1693 static int
1694 crypto_invoke(struct cryptocap *cap, struct cryptop *crp, int hint)
1695 {
1696
1697         KASSERT(crp != NULL, ("%s: crp == NULL", __func__));
1698         KASSERT(crp->crp_callback != NULL,
1699             ("%s: crp->crp_callback == NULL", __func__));
1700         KASSERT(crp->crp_session != NULL,
1701             ("%s: crp->crp_session == NULL", __func__));
1702
1703 #ifdef CRYPTO_TIMING
1704         if (crypto_timing)
1705                 crypto_tstat(&cryptostats.cs_invoke, &crp->crp_tstamp);
1706 #endif
1707         if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1708                 struct crypto_session_params csp;
1709                 crypto_session_t nses;
1710
1711                 /*
1712                  * Driver has unregistered; migrate the session and return
1713                  * an error to the caller so they'll resubmit the op.
1714                  *
1715                  * XXX: What if there are more already queued requests for this
1716                  *      session?
1717                  *
1718                  * XXX: Real solution is to make sessions refcounted
1719                  * and force callers to hold a reference when
1720                  * assigning to crp_session.  Could maybe change
1721                  * crypto_getreq to accept a session pointer to make
1722                  * that work.  Alternatively, we could abandon the
1723                  * notion of rewriting crp_session in requests forcing
1724                  * the caller to deal with allocating a new session.
1725                  * Perhaps provide a method to allow a crp's session to
1726                  * be swapped that callers could use.
1727                  */
1728                 csp = crp->crp_session->csp;
1729                 crypto_freesession(crp->crp_session);
1730
1731                 /*
1732                  * XXX: Key pointers may no longer be valid.  If we
1733                  * really want to support this we need to define the
1734                  * KPI such that 'csp' is required to be valid for the
1735                  * duration of a session by the caller perhaps.
1736                  *
1737                  * XXX: If the keys have been changed this will reuse
1738                  * the old keys.  This probably suggests making
1739                  * rekeying more explicit and updating the key
1740                  * pointers in 'csp' when the keys change.
1741                  */
1742                 if (crypto_newsession(&nses, &csp,
1743                     CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE) == 0)
1744                         crp->crp_session = nses;
1745
1746                 crp->crp_etype = EAGAIN;
1747                 crypto_done(crp);
1748                 return 0;
1749         } else {
1750                 /*
1751                  * Invoke the driver to process the request.
1752                  */
1753                 return CRYPTODEV_PROCESS(cap->cc_dev, crp, hint);
1754         }
1755 }
1756
1757 void
1758 crypto_freereq(struct cryptop *crp)
1759 {
1760
1761         if (crp == NULL)
1762                 return;
1763
1764 #ifdef DIAGNOSTIC
1765         {
1766                 struct cryptop *crp2;
1767                 struct crypto_ret_worker *ret_worker;
1768
1769                 CRYPTO_Q_LOCK();
1770                 TAILQ_FOREACH(crp2, &crp_q, crp_next) {
1771                         KASSERT(crp2 != crp,
1772                             ("Freeing cryptop from the crypto queue (%p).",
1773                             crp));
1774                 }
1775                 CRYPTO_Q_UNLOCK();
1776
1777                 FOREACH_CRYPTO_RETW(ret_worker) {
1778                         CRYPTO_RETW_LOCK(ret_worker);
1779                         TAILQ_FOREACH(crp2, &ret_worker->crp_ret_q, crp_next) {
1780                                 KASSERT(crp2 != crp,
1781                                     ("Freeing cryptop from the return queue (%p).",
1782                                     crp));
1783                         }
1784                         CRYPTO_RETW_UNLOCK(ret_worker);
1785                 }
1786         }
1787 #endif
1788
1789         uma_zfree(cryptop_zone, crp);
1790 }
1791
1792 struct cryptop *
1793 crypto_getreq(crypto_session_t cses, int how)
1794 {
1795         struct cryptop *crp;
1796
1797         MPASS(how == M_WAITOK || how == M_NOWAIT);
1798         crp = uma_zalloc(cryptop_zone, how | M_ZERO);
1799         crp->crp_session = cses;
1800         return (crp);
1801 }
1802
1803 /*
1804  * Invoke the callback on behalf of the driver.
1805  */
1806 void
1807 crypto_done(struct cryptop *crp)
1808 {
1809         KASSERT((crp->crp_flags & CRYPTO_F_DONE) == 0,
1810                 ("crypto_done: op already done, flags 0x%x", crp->crp_flags));
1811         crp->crp_flags |= CRYPTO_F_DONE;
1812         if (crp->crp_etype != 0)
1813                 cryptostats.cs_errs++;
1814 #ifdef CRYPTO_TIMING
1815         if (crypto_timing)
1816                 crypto_tstat(&cryptostats.cs_done, &crp->crp_tstamp);
1817 #endif
1818         /*
1819          * CBIMM means unconditionally do the callback immediately;
1820          * CBIFSYNC means do the callback immediately only if the
1821          * operation was done synchronously.  Both are used to avoid
1822          * doing extraneous context switches; the latter is mostly
1823          * used with the software crypto driver.
1824          */
1825         if (!CRYPTOP_ASYNC_KEEPORDER(crp) &&
1826             ((crp->crp_flags & CRYPTO_F_CBIMM) ||
1827             ((crp->crp_flags & CRYPTO_F_CBIFSYNC) &&
1828              (crypto_ses2caps(crp->crp_session) & CRYPTOCAP_F_SYNC)))) {
1829                 /*
1830                  * Do the callback directly.  This is ok when the
1831                  * callback routine does very little (e.g. the
1832                  * /dev/crypto callback method just does a wakeup).
1833                  */
1834 #ifdef CRYPTO_TIMING
1835                 if (crypto_timing) {
1836                         /*
1837                          * NB: We must copy the timestamp before
1838                          * doing the callback as the cryptop is
1839                          * likely to be reclaimed.
1840                          */
1841                         struct bintime t = crp->crp_tstamp;
1842                         crypto_tstat(&cryptostats.cs_cb, &t);
1843                         crp->crp_callback(crp);
1844                         crypto_tstat(&cryptostats.cs_finis, &t);
1845                 } else
1846 #endif
1847                         crp->crp_callback(crp);
1848         } else {
1849                 struct crypto_ret_worker *ret_worker;
1850                 bool wake;
1851
1852                 ret_worker = CRYPTO_RETW(crp->crp_retw_id);
1853                 wake = false;
1854
1855                 /*
1856                  * Normal case; queue the callback for the thread.
1857                  */
1858                 CRYPTO_RETW_LOCK(ret_worker);
1859                 if (CRYPTOP_ASYNC_KEEPORDER(crp)) {
1860                         struct cryptop *tmp;
1861
1862                         TAILQ_FOREACH_REVERSE(tmp, &ret_worker->crp_ordered_ret_q,
1863                                         cryptop_q, crp_next) {
1864                                 if (CRYPTO_SEQ_GT(crp->crp_seq, tmp->crp_seq)) {
1865                                         TAILQ_INSERT_AFTER(&ret_worker->crp_ordered_ret_q,
1866                                                         tmp, crp, crp_next);
1867                                         break;
1868                                 }
1869                         }
1870                         if (tmp == NULL) {
1871                                 TAILQ_INSERT_HEAD(&ret_worker->crp_ordered_ret_q,
1872                                                 crp, crp_next);
1873                         }
1874
1875                         if (crp->crp_seq == ret_worker->reorder_cur_seq)
1876                                 wake = true;
1877                 }
1878                 else {
1879                         if (CRYPTO_RETW_EMPTY(ret_worker))
1880                                 wake = true;
1881
1882                         TAILQ_INSERT_TAIL(&ret_worker->crp_ret_q, crp, crp_next);
1883                 }
1884
1885                 if (wake)
1886                         wakeup_one(&ret_worker->crp_ret_q);     /* shared wait channel */
1887                 CRYPTO_RETW_UNLOCK(ret_worker);
1888         }
1889 }
1890
1891 /*
1892  * Invoke the callback on behalf of the driver.
1893  */
1894 void
1895 crypto_kdone(struct cryptkop *krp)
1896 {
1897         struct crypto_ret_worker *ret_worker;
1898         struct cryptocap *cap;
1899
1900         if (krp->krp_status != 0)
1901                 cryptostats.cs_kerrs++;
1902         CRYPTO_DRIVER_LOCK();
1903         cap = krp->krp_cap;
1904         KASSERT(cap->cc_koperations > 0, ("cc_koperations == 0"));
1905         cap->cc_koperations--;
1906         if (cap->cc_koperations == 0 && cap->cc_flags & CRYPTOCAP_F_CLEANUP)
1907                 wakeup(cap);
1908         CRYPTO_DRIVER_UNLOCK();
1909         krp->krp_cap = NULL;
1910         cap_rele(cap);
1911
1912         ret_worker = CRYPTO_RETW(0);
1913
1914         CRYPTO_RETW_LOCK(ret_worker);
1915         if (CRYPTO_RETW_EMPTY(ret_worker))
1916                 wakeup_one(&ret_worker->crp_ret_q);             /* shared wait channel */
1917         TAILQ_INSERT_TAIL(&ret_worker->crp_ret_kq, krp, krp_next);
1918         CRYPTO_RETW_UNLOCK(ret_worker);
1919 }
1920
1921 int
1922 crypto_getfeat(int *featp)
1923 {
1924         int hid, kalg, feat = 0;
1925
1926         CRYPTO_DRIVER_LOCK();
1927         for (hid = 0; hid < crypto_drivers_size; hid++) {
1928                 const struct cryptocap *cap = crypto_drivers[hid];
1929
1930                 if (cap == NULL ||
1931                     ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
1932                     !crypto_devallowsoft)) {
1933                         continue;
1934                 }
1935                 for (kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
1936                         if (cap->cc_kalg[kalg] & CRYPTO_ALG_FLAG_SUPPORTED)
1937                                 feat |=  1 << kalg;
1938         }
1939         CRYPTO_DRIVER_UNLOCK();
1940         *featp = feat;
1941         return (0);
1942 }
1943
1944 /*
1945  * Terminate a thread at module unload.  The process that
1946  * initiated this is waiting for us to signal that we're gone;
1947  * wake it up and exit.  We use the driver table lock to insure
1948  * we don't do the wakeup before they're waiting.  There is no
1949  * race here because the waiter sleeps on the proc lock for the
1950  * thread so it gets notified at the right time because of an
1951  * extra wakeup that's done in exit1().
1952  */
1953 static void
1954 crypto_finis(void *chan)
1955 {
1956         CRYPTO_DRIVER_LOCK();
1957         wakeup_one(chan);
1958         CRYPTO_DRIVER_UNLOCK();
1959         kproc_exit(0);
1960 }
1961
1962 /*
1963  * Crypto thread, dispatches crypto requests.
1964  */
1965 static void
1966 crypto_proc(void)
1967 {
1968         struct cryptop *crp, *submit;
1969         struct cryptkop *krp;
1970         struct cryptocap *cap;
1971         int result, hint;
1972
1973 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
1974         fpu_kern_thread(FPU_KERN_NORMAL);
1975 #endif
1976
1977         CRYPTO_Q_LOCK();
1978         for (;;) {
1979                 /*
1980                  * Find the first element in the queue that can be
1981                  * processed and look-ahead to see if multiple ops
1982                  * are ready for the same driver.
1983                  */
1984                 submit = NULL;
1985                 hint = 0;
1986                 TAILQ_FOREACH(crp, &crp_q, crp_next) {
1987                         cap = crp->crp_session->cap;
1988                         /*
1989                          * Driver cannot disappeared when there is an active
1990                          * session.
1991                          */
1992                         KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
1993                             __func__, __LINE__));
1994                         if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
1995                                 /* Op needs to be migrated, process it. */
1996                                 if (submit == NULL)
1997                                         submit = crp;
1998                                 break;
1999                         }
2000                         if (!cap->cc_qblocked) {
2001                                 if (submit != NULL) {
2002                                         /*
2003                                          * We stop on finding another op,
2004                                          * regardless whether its for the same
2005                                          * driver or not.  We could keep
2006                                          * searching the queue but it might be
2007                                          * better to just use a per-driver
2008                                          * queue instead.
2009                                          */
2010                                         if (submit->crp_session->cap == cap)
2011                                                 hint = CRYPTO_HINT_MORE;
2012                                         break;
2013                                 } else {
2014                                         submit = crp;
2015                                         if ((submit->crp_flags & CRYPTO_F_BATCH) == 0)
2016                                                 break;
2017                                         /* keep scanning for more are q'd */
2018                                 }
2019                         }
2020                 }
2021                 if (submit != NULL) {
2022                         TAILQ_REMOVE(&crp_q, submit, crp_next);
2023                         cap = submit->crp_session->cap;
2024                         KASSERT(cap != NULL, ("%s:%u Driver disappeared.",
2025                             __func__, __LINE__));
2026                         CRYPTO_Q_UNLOCK();
2027                         result = crypto_invoke(cap, submit, hint);
2028                         CRYPTO_Q_LOCK();
2029                         if (result == ERESTART) {
2030                                 /*
2031                                  * The driver ran out of resources, mark the
2032                                  * driver ``blocked'' for cryptop's and put
2033                                  * the request back in the queue.  It would
2034                                  * best to put the request back where we got
2035                                  * it but that's hard so for now we put it
2036                                  * at the front.  This should be ok; putting
2037                                  * it at the end does not work.
2038                                  */
2039                                 cap->cc_qblocked = 1;
2040                                 TAILQ_INSERT_HEAD(&crp_q, submit, crp_next);
2041                                 cryptostats.cs_blocks++;
2042                         }
2043                 }
2044
2045                 /* As above, but for key ops */
2046                 TAILQ_FOREACH(krp, &crp_kq, krp_next) {
2047                         cap = krp->krp_cap;
2048                         if (cap->cc_flags & CRYPTOCAP_F_CLEANUP) {
2049                                 /*
2050                                  * Operation needs to be migrated,
2051                                  * clear krp_cap so a new driver is
2052                                  * selected.
2053                                  */
2054                                 krp->krp_cap = NULL;
2055                                 cap_rele(cap);
2056                                 break;
2057                         }
2058                         if (!cap->cc_kqblocked)
2059                                 break;
2060                 }
2061                 if (krp != NULL) {
2062                         TAILQ_REMOVE(&crp_kq, krp, krp_next);
2063                         CRYPTO_Q_UNLOCK();
2064                         result = crypto_kinvoke(krp);
2065                         CRYPTO_Q_LOCK();
2066                         if (result == ERESTART) {
2067                                 /*
2068                                  * The driver ran out of resources, mark the
2069                                  * driver ``blocked'' for cryptkop's and put
2070                                  * the request back in the queue.  It would
2071                                  * best to put the request back where we got
2072                                  * it but that's hard so for now we put it
2073                                  * at the front.  This should be ok; putting
2074                                  * it at the end does not work.
2075                                  */
2076                                 krp->krp_cap->cc_kqblocked = 1;
2077                                 TAILQ_INSERT_HEAD(&crp_kq, krp, krp_next);
2078                                 cryptostats.cs_kblocks++;
2079                         }
2080                 }
2081
2082                 if (submit == NULL && krp == NULL) {
2083                         /*
2084                          * Nothing more to be processed.  Sleep until we're
2085                          * woken because there are more ops to process.
2086                          * This happens either by submission or by a driver
2087                          * becoming unblocked and notifying us through
2088                          * crypto_unblock.  Note that when we wakeup we
2089                          * start processing each queue again from the
2090                          * front. It's not clear that it's important to
2091                          * preserve this ordering since ops may finish
2092                          * out of order if dispatched to different devices
2093                          * and some become blocked while others do not.
2094                          */
2095                         crp_sleep = 1;
2096                         msleep(&crp_q, &crypto_q_mtx, PWAIT, "crypto_wait", 0);
2097                         crp_sleep = 0;
2098                         if (cryptoproc == NULL)
2099                                 break;
2100                         cryptostats.cs_intrs++;
2101                 }
2102         }
2103         CRYPTO_Q_UNLOCK();
2104
2105         crypto_finis(&crp_q);
2106 }
2107
2108 /*
2109  * Crypto returns thread, does callbacks for processed crypto requests.
2110  * Callbacks are done here, rather than in the crypto drivers, because
2111  * callbacks typically are expensive and would slow interrupt handling.
2112  */
2113 static void
2114 crypto_ret_proc(struct crypto_ret_worker *ret_worker)
2115 {
2116         struct cryptop *crpt;
2117         struct cryptkop *krpt;
2118
2119         CRYPTO_RETW_LOCK(ret_worker);
2120         for (;;) {
2121                 /* Harvest return q's for completed ops */
2122                 crpt = TAILQ_FIRST(&ret_worker->crp_ordered_ret_q);
2123                 if (crpt != NULL) {
2124                         if (crpt->crp_seq == ret_worker->reorder_cur_seq) {
2125                                 TAILQ_REMOVE(&ret_worker->crp_ordered_ret_q, crpt, crp_next);
2126                                 ret_worker->reorder_cur_seq++;
2127                         } else {
2128                                 crpt = NULL;
2129                         }
2130                 }
2131
2132                 if (crpt == NULL) {
2133                         crpt = TAILQ_FIRST(&ret_worker->crp_ret_q);
2134                         if (crpt != NULL)
2135                                 TAILQ_REMOVE(&ret_worker->crp_ret_q, crpt, crp_next);
2136                 }
2137
2138                 krpt = TAILQ_FIRST(&ret_worker->crp_ret_kq);
2139                 if (krpt != NULL)
2140                         TAILQ_REMOVE(&ret_worker->crp_ret_kq, krpt, krp_next);
2141
2142                 if (crpt != NULL || krpt != NULL) {
2143                         CRYPTO_RETW_UNLOCK(ret_worker);
2144                         /*
2145                          * Run callbacks unlocked.
2146                          */
2147                         if (crpt != NULL) {
2148 #ifdef CRYPTO_TIMING
2149                                 if (crypto_timing) {
2150                                         /*
2151                                          * NB: We must copy the timestamp before
2152                                          * doing the callback as the cryptop is
2153                                          * likely to be reclaimed.
2154                                          */
2155                                         struct bintime t = crpt->crp_tstamp;
2156                                         crypto_tstat(&cryptostats.cs_cb, &t);
2157                                         crpt->crp_callback(crpt);
2158                                         crypto_tstat(&cryptostats.cs_finis, &t);
2159                                 } else
2160 #endif
2161                                         crpt->crp_callback(crpt);
2162                         }
2163                         if (krpt != NULL)
2164                                 krpt->krp_callback(krpt);
2165                         CRYPTO_RETW_LOCK(ret_worker);
2166                 } else {
2167                         /*
2168                          * Nothing more to be processed.  Sleep until we're
2169                          * woken because there are more returns to process.
2170                          */
2171                         msleep(&ret_worker->crp_ret_q, &ret_worker->crypto_ret_mtx, PWAIT,
2172                                 "crypto_ret_wait", 0);
2173                         if (ret_worker->cryptoretproc == NULL)
2174                                 break;
2175                         cryptostats.cs_rets++;
2176                 }
2177         }
2178         CRYPTO_RETW_UNLOCK(ret_worker);
2179
2180         crypto_finis(&ret_worker->crp_ret_q);
2181 }
2182
2183 #ifdef DDB
2184 static void
2185 db_show_drivers(void)
2186 {
2187         int hid;
2188
2189         db_printf("%12s %4s %4s %8s %2s %2s\n"
2190                 , "Device"
2191                 , "Ses"
2192                 , "Kops"
2193                 , "Flags"
2194                 , "QB"
2195                 , "KB"
2196         );
2197         for (hid = 0; hid < crypto_drivers_size; hid++) {
2198                 const struct cryptocap *cap = crypto_drivers[hid];
2199                 if (cap == NULL)
2200                         continue;
2201                 db_printf("%-12s %4u %4u %08x %2u %2u\n"
2202                     , device_get_nameunit(cap->cc_dev)
2203                     , cap->cc_sessions
2204                     , cap->cc_koperations
2205                     , cap->cc_flags
2206                     , cap->cc_qblocked
2207                     , cap->cc_kqblocked
2208                 );
2209         }
2210 }
2211
2212 DB_SHOW_COMMAND(crypto, db_show_crypto)
2213 {
2214         struct cryptop *crp;
2215         struct crypto_ret_worker *ret_worker;
2216
2217         db_show_drivers();
2218         db_printf("\n");
2219
2220         db_printf("%4s %8s %4s %4s %4s %4s %8s %8s\n",
2221             "HID", "Caps", "Ilen", "Olen", "Etype", "Flags",
2222             "Device", "Callback");
2223         TAILQ_FOREACH(crp, &crp_q, crp_next) {
2224                 db_printf("%4u %08x %4u %4u %04x %8p %8p\n"
2225                     , crp->crp_session->cap->cc_hid
2226                     , (int) crypto_ses2caps(crp->crp_session)
2227                     , crp->crp_olen
2228                     , crp->crp_etype
2229                     , crp->crp_flags
2230                     , device_get_nameunit(crp->crp_session->cap->cc_dev)
2231                     , crp->crp_callback
2232                 );
2233         }
2234         FOREACH_CRYPTO_RETW(ret_worker) {
2235                 db_printf("\n%8s %4s %4s %4s %8s\n",
2236                     "ret_worker", "HID", "Etype", "Flags", "Callback");
2237                 if (!TAILQ_EMPTY(&ret_worker->crp_ret_q)) {
2238                         TAILQ_FOREACH(crp, &ret_worker->crp_ret_q, crp_next) {
2239                                 db_printf("%8td %4u %4u %04x %8p\n"
2240                                     , CRYPTO_RETW_ID(ret_worker)
2241                                     , crp->crp_session->cap->cc_hid
2242                                     , crp->crp_etype
2243                                     , crp->crp_flags
2244                                     , crp->crp_callback
2245                                 );
2246                         }
2247                 }
2248         }
2249 }
2250
2251 DB_SHOW_COMMAND(kcrypto, db_show_kcrypto)
2252 {
2253         struct cryptkop *krp;
2254         struct crypto_ret_worker *ret_worker;
2255
2256         db_show_drivers();
2257         db_printf("\n");
2258
2259         db_printf("%4s %5s %4s %4s %8s %4s %8s\n",
2260             "Op", "Status", "#IP", "#OP", "CRID", "HID", "Callback");
2261         TAILQ_FOREACH(krp, &crp_kq, krp_next) {
2262                 db_printf("%4u %5u %4u %4u %08x %4u %8p\n"
2263                     , krp->krp_op
2264                     , krp->krp_status
2265                     , krp->krp_iparams, krp->krp_oparams
2266                     , krp->krp_crid, krp->krp_hid
2267                     , krp->krp_callback
2268                 );
2269         }
2270
2271         ret_worker = CRYPTO_RETW(0);
2272         if (!TAILQ_EMPTY(&ret_worker->crp_ret_q)) {
2273                 db_printf("%4s %5s %8s %4s %8s\n",
2274                     "Op", "Status", "CRID", "HID", "Callback");
2275                 TAILQ_FOREACH(krp, &ret_worker->crp_ret_kq, krp_next) {
2276                         db_printf("%4u %5u %08x %4u %8p\n"
2277                             , krp->krp_op
2278                             , krp->krp_status
2279                             , krp->krp_crid, krp->krp_hid
2280                             , krp->krp_callback
2281                         );
2282                 }
2283         }
2284 }
2285 #endif
2286
2287 int crypto_modevent(module_t mod, int type, void *unused);
2288
2289 /*
2290  * Initialization code, both for static and dynamic loading.
2291  * Note this is not invoked with the usual MODULE_DECLARE
2292  * mechanism but instead is listed as a dependency by the
2293  * cryptosoft driver.  This guarantees proper ordering of
2294  * calls on module load/unload.
2295  */
2296 int
2297 crypto_modevent(module_t mod, int type, void *unused)
2298 {
2299         int error = EINVAL;
2300
2301         switch (type) {
2302         case MOD_LOAD:
2303                 error = crypto_init();
2304                 if (error == 0 && bootverbose)
2305                         printf("crypto: <crypto core>\n");
2306                 break;
2307         case MOD_UNLOAD:
2308                 /*XXX disallow if active sessions */
2309                 error = 0;
2310                 crypto_destroy();
2311                 return 0;
2312         }
2313         return error;
2314 }
2315 MODULE_VERSION(crypto, 1);
2316 MODULE_DEPEND(crypto, zlib, 1, 1, 1);