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