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