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