xref: /freebsd/sys/crypto/aesni/aesni.c (revision ec0ea6efa1ad229d75c394c1a9b9cac33af2b1d3)
1 /*-
2  * Copyright (c) 2005-2008 Pawel Jakub Dawidek <pjd@FreeBSD.org>
3  * Copyright (c) 2010 Konstantin Belousov <kib@FreeBSD.org>
4  * Copyright (c) 2014-2021 The FreeBSD Foundation
5  * Copyright (c) 2017 Conrad Meyer <cem@FreeBSD.org>
6  * All rights reserved.
7  *
8  * Portions of this software were developed by John-Mark Gurney
9  * under sponsorship of the FreeBSD Foundation and
10  * Rubicon Communications, LLC (Netgate).
11  *
12  * Portions of this software were developed by Ararat River
13  * Consulting, LLC under sponsorship of the FreeBSD Foundation.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include <sys/param.h>
41 #include <sys/bus.h>
42 #include <sys/kernel.h>
43 #include <sys/kobj.h>
44 #include <sys/libkern.h>
45 #include <sys/lock.h>
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/module.h>
49 #include <sys/mutex.h>
50 #include <sys/smp.h>
51 #include <sys/systm.h>
52 #include <sys/uio.h>
53 
54 #include <crypto/aesni/aesni.h>
55 #include <crypto/aesni/sha_sse.h>
56 #include <crypto/sha1.h>
57 #include <crypto/sha2/sha224.h>
58 #include <crypto/sha2/sha256.h>
59 
60 #include <opencrypto/cryptodev.h>
61 #include <opencrypto/gmac.h>
62 #include <cryptodev_if.h>
63 
64 #include <machine/md_var.h>
65 #include <machine/specialreg.h>
66 #include <machine/fpu.h>
67 
68 static struct mtx_padalign *ctx_mtx;
69 static struct fpu_kern_ctx **ctx_fpu;
70 
71 struct aesni_softc {
72 	int32_t cid;
73 	bool	has_aes;
74 	bool	has_sha;
75 };
76 
77 #define ACQUIRE_CTX(i, ctx)					\
78 	do {							\
79 		(i) = PCPU_GET(cpuid);				\
80 		mtx_lock(&ctx_mtx[(i)]);			\
81 		(ctx) = ctx_fpu[(i)];				\
82 	} while (0)
83 #define RELEASE_CTX(i, ctx)					\
84 	do {							\
85 		mtx_unlock(&ctx_mtx[(i)]);			\
86 		(i) = -1;					\
87 		(ctx) = NULL;					\
88 	} while (0)
89 
90 static int aesni_cipher_setup(struct aesni_session *ses,
91     const struct crypto_session_params *csp);
92 static int aesni_cipher_process(struct aesni_session *ses, struct cryptop *crp);
93 static int aesni_cipher_crypt(struct aesni_session *ses, struct cryptop *crp,
94     const struct crypto_session_params *csp);
95 static int aesni_cipher_mac(struct aesni_session *ses, struct cryptop *crp,
96     const struct crypto_session_params *csp);
97 
98 MALLOC_DEFINE(M_AESNI, "aesni_data", "AESNI Data");
99 
100 static void
101 aesni_identify(driver_t *drv, device_t parent)
102 {
103 
104 	/* NB: order 10 is so we get attached after h/w devices */
105 	if (device_find_child(parent, "aesni", -1) == NULL &&
106 	    BUS_ADD_CHILD(parent, 10, "aesni", -1) == 0)
107 		panic("aesni: could not attach");
108 }
109 
110 static void
111 detect_cpu_features(bool *has_aes, bool *has_sha)
112 {
113 
114 	*has_aes = ((cpu_feature2 & CPUID2_AESNI) != 0 &&
115 	    (cpu_feature2 & CPUID2_SSE41) != 0);
116 	*has_sha = ((cpu_stdext_feature & CPUID_STDEXT_SHA) != 0 &&
117 	    (cpu_feature2 & CPUID2_SSSE3) != 0);
118 }
119 
120 static int
121 aesni_probe(device_t dev)
122 {
123 	bool has_aes, has_sha;
124 
125 	detect_cpu_features(&has_aes, &has_sha);
126 	if (!has_aes && !has_sha) {
127 		device_printf(dev, "No AES or SHA support.\n");
128 		return (EINVAL);
129 	} else if (has_aes && has_sha)
130 		device_set_desc(dev,
131 		    "AES-CBC,AES-CCM,AES-GCM,AES-ICM,AES-XTS,SHA1,SHA256");
132 	else if (has_aes)
133 		device_set_desc(dev,
134 		    "AES-CBC,AES-CCM,AES-GCM,AES-ICM,AES-XTS");
135 	else
136 		device_set_desc(dev, "SHA1,SHA256");
137 
138 	return (0);
139 }
140 
141 static void
142 aesni_cleanctx(void)
143 {
144 	int i;
145 
146 	/* XXX - no way to return driverid */
147 	CPU_FOREACH(i) {
148 		if (ctx_fpu[i] != NULL) {
149 			mtx_destroy(&ctx_mtx[i]);
150 			fpu_kern_free_ctx(ctx_fpu[i]);
151 		}
152 		ctx_fpu[i] = NULL;
153 	}
154 	free(ctx_mtx, M_AESNI);
155 	ctx_mtx = NULL;
156 	free(ctx_fpu, M_AESNI);
157 	ctx_fpu = NULL;
158 }
159 
160 static int
161 aesni_attach(device_t dev)
162 {
163 	struct aesni_softc *sc;
164 	int i;
165 
166 	sc = device_get_softc(dev);
167 
168 	sc->cid = crypto_get_driverid(dev, sizeof(struct aesni_session),
169 	    CRYPTOCAP_F_SOFTWARE | CRYPTOCAP_F_SYNC |
170 	    CRYPTOCAP_F_ACCEL_SOFTWARE);
171 	if (sc->cid < 0) {
172 		device_printf(dev, "Could not get crypto driver id.\n");
173 		return (ENOMEM);
174 	}
175 
176 	ctx_mtx = malloc(sizeof *ctx_mtx * (mp_maxid + 1), M_AESNI,
177 	    M_WAITOK|M_ZERO);
178 	ctx_fpu = malloc(sizeof *ctx_fpu * (mp_maxid + 1), M_AESNI,
179 	    M_WAITOK|M_ZERO);
180 
181 	CPU_FOREACH(i) {
182 #ifdef __amd64__
183 		ctx_fpu[i] = fpu_kern_alloc_ctx_domain(
184 		    pcpu_find(i)->pc_domain, FPU_KERN_NORMAL);
185 #else
186 		ctx_fpu[i] = fpu_kern_alloc_ctx(FPU_KERN_NORMAL);
187 #endif
188 		mtx_init(&ctx_mtx[i], "anifpumtx", NULL, MTX_DEF|MTX_NEW);
189 	}
190 
191 	detect_cpu_features(&sc->has_aes, &sc->has_sha);
192 	return (0);
193 }
194 
195 static int
196 aesni_detach(device_t dev)
197 {
198 	struct aesni_softc *sc;
199 
200 	sc = device_get_softc(dev);
201 
202 	crypto_unregister_all(sc->cid);
203 
204 	aesni_cleanctx();
205 
206 	return (0);
207 }
208 
209 static bool
210 aesni_auth_supported(struct aesni_softc *sc,
211     const struct crypto_session_params *csp)
212 {
213 
214 	if (!sc->has_sha)
215 		return (false);
216 
217 	switch (csp->csp_auth_alg) {
218 	case CRYPTO_SHA1:
219 	case CRYPTO_SHA2_224:
220 	case CRYPTO_SHA2_256:
221 	case CRYPTO_SHA1_HMAC:
222 	case CRYPTO_SHA2_224_HMAC:
223 	case CRYPTO_SHA2_256_HMAC:
224 		break;
225 	default:
226 		return (false);
227 	}
228 
229 	return (true);
230 }
231 
232 static bool
233 aesni_cipher_supported(struct aesni_softc *sc,
234     const struct crypto_session_params *csp)
235 {
236 
237 	if (!sc->has_aes)
238 		return (false);
239 
240 	switch (csp->csp_cipher_alg) {
241 	case CRYPTO_AES_CBC:
242 	case CRYPTO_AES_ICM:
243 		switch (csp->csp_cipher_klen * 8) {
244 		case 128:
245 		case 192:
246 		case 256:
247 			break;
248 		default:
249 			CRYPTDEB("invalid CBC/ICM key length");
250 			return (false);
251 		}
252 		if (csp->csp_ivlen != AES_BLOCK_LEN)
253 			return (false);
254 		break;
255 	case CRYPTO_AES_XTS:
256 		switch (csp->csp_cipher_klen * 8) {
257 		case 256:
258 		case 512:
259 			break;
260 		default:
261 			CRYPTDEB("invalid XTS key length");
262 			return (false);
263 		}
264 		if (csp->csp_ivlen != AES_XTS_IV_LEN)
265 			return (false);
266 		break;
267 	default:
268 		return (false);
269 	}
270 
271 	return (true);
272 }
273 
274 #define SUPPORTED_SES (CSP_F_SEPARATE_OUTPUT | CSP_F_SEPARATE_AAD | CSP_F_ESN)
275 
276 static int
277 aesni_probesession(device_t dev, const struct crypto_session_params *csp)
278 {
279 	struct aesni_softc *sc;
280 
281 	sc = device_get_softc(dev);
282 	if ((csp->csp_flags & ~(SUPPORTED_SES)) != 0)
283 		return (EINVAL);
284 	switch (csp->csp_mode) {
285 	case CSP_MODE_DIGEST:
286 		if (!aesni_auth_supported(sc, csp))
287 			return (EINVAL);
288 		break;
289 	case CSP_MODE_CIPHER:
290 		if (!aesni_cipher_supported(sc, csp))
291 			return (EINVAL);
292 		break;
293 	case CSP_MODE_AEAD:
294 		switch (csp->csp_cipher_alg) {
295 		case CRYPTO_AES_NIST_GCM_16:
296 			switch (csp->csp_cipher_klen * 8) {
297 			case 128:
298 			case 192:
299 			case 256:
300 				break;
301 			default:
302 				CRYPTDEB("invalid GCM key length");
303 				return (EINVAL);
304 			}
305 			if (csp->csp_auth_mlen != 0 &&
306 			    csp->csp_auth_mlen != GMAC_DIGEST_LEN)
307 				return (EINVAL);
308 			if (!sc->has_aes)
309 				return (EINVAL);
310 			break;
311 		case CRYPTO_AES_CCM_16:
312 			switch (csp->csp_cipher_klen * 8) {
313 			case 128:
314 			case 192:
315 			case 256:
316 				break;
317 			default:
318 				CRYPTDEB("invalid CCM key length");
319 				return (EINVAL);
320 			}
321 			if (!sc->has_aes)
322 				return (EINVAL);
323 			break;
324 		default:
325 			return (EINVAL);
326 		}
327 		break;
328 	case CSP_MODE_ETA:
329 		if (!aesni_auth_supported(sc, csp) ||
330 		    !aesni_cipher_supported(sc, csp))
331 			return (EINVAL);
332 		break;
333 	default:
334 		return (EINVAL);
335 	}
336 
337 	return (CRYPTODEV_PROBE_ACCEL_SOFTWARE);
338 }
339 
340 static int
341 aesni_newsession(device_t dev, crypto_session_t cses,
342     const struct crypto_session_params *csp)
343 {
344 	struct aesni_session *ses;
345 	int error;
346 
347 	ses = crypto_get_driver_session(cses);
348 
349 	switch (csp->csp_mode) {
350 	case CSP_MODE_DIGEST:
351 	case CSP_MODE_CIPHER:
352 	case CSP_MODE_AEAD:
353 	case CSP_MODE_ETA:
354 		break;
355 	default:
356 		return (EINVAL);
357 	}
358 	error = aesni_cipher_setup(ses, csp);
359 	if (error != 0) {
360 		CRYPTDEB("setup failed");
361 		return (error);
362 	}
363 
364 	return (0);
365 }
366 
367 static int
368 aesni_process(device_t dev, struct cryptop *crp, int hint __unused)
369 {
370 	struct aesni_session *ses;
371 	int error;
372 
373 	ses = crypto_get_driver_session(crp->crp_session);
374 
375 	error = aesni_cipher_process(ses, crp);
376 
377 	crp->crp_etype = error;
378 	crypto_done(crp);
379 	return (0);
380 }
381 
382 static uint8_t *
383 aesni_cipher_alloc(struct cryptop *crp, int start, int length, bool *allocated)
384 {
385 	uint8_t *addr;
386 
387 	addr = crypto_contiguous_subsegment(crp, start, length);
388 	if (addr != NULL) {
389 		*allocated = false;
390 		return (addr);
391 	}
392 	addr = malloc(length, M_AESNI, M_NOWAIT);
393 	if (addr != NULL) {
394 		*allocated = true;
395 		crypto_copydata(crp, start, length, addr);
396 	} else
397 		*allocated = false;
398 	return (addr);
399 }
400 
401 static device_method_t aesni_methods[] = {
402 	DEVMETHOD(device_identify, aesni_identify),
403 	DEVMETHOD(device_probe, aesni_probe),
404 	DEVMETHOD(device_attach, aesni_attach),
405 	DEVMETHOD(device_detach, aesni_detach),
406 
407 	DEVMETHOD(cryptodev_probesession, aesni_probesession),
408 	DEVMETHOD(cryptodev_newsession, aesni_newsession),
409 	DEVMETHOD(cryptodev_process, aesni_process),
410 
411 	DEVMETHOD_END
412 };
413 
414 static driver_t aesni_driver = {
415 	"aesni",
416 	aesni_methods,
417 	sizeof(struct aesni_softc),
418 };
419 static devclass_t aesni_devclass;
420 
421 DRIVER_MODULE(aesni, nexus, aesni_driver, aesni_devclass, 0, 0);
422 MODULE_VERSION(aesni, 1);
423 MODULE_DEPEND(aesni, crypto, 1, 1, 1);
424 
425 static int
426 intel_sha1_update(void *vctx, const void *vdata, u_int datalen)
427 {
428 	struct sha1_ctxt *ctx = vctx;
429 	const char *data = vdata;
430 	size_t gaplen;
431 	size_t gapstart;
432 	size_t off;
433 	size_t copysiz;
434 	u_int blocks;
435 
436 	off = 0;
437 	/* Do any aligned blocks without redundant copying. */
438 	if (datalen >= 64 && ctx->count % 64 == 0) {
439 		blocks = datalen / 64;
440 		ctx->c.b64[0] += blocks * 64 * 8;
441 		intel_sha1_step(ctx->h.b32, data + off, blocks);
442 		off += blocks * 64;
443 	}
444 
445 	while (off < datalen) {
446 		gapstart = ctx->count % 64;
447 		gaplen = 64 - gapstart;
448 
449 		copysiz = (gaplen < datalen - off) ? gaplen : datalen - off;
450 		bcopy(&data[off], &ctx->m.b8[gapstart], copysiz);
451 		ctx->count += copysiz;
452 		ctx->count %= 64;
453 		ctx->c.b64[0] += copysiz * 8;
454 		if (ctx->count % 64 == 0)
455 			intel_sha1_step(ctx->h.b32, (void *)ctx->m.b8, 1);
456 		off += copysiz;
457 	}
458 
459 	return (0);
460 }
461 
462 static void
463 SHA1_Init_fn(void *ctx)
464 {
465 	sha1_init(ctx);
466 }
467 
468 static void
469 SHA1_Finalize_fn(void *digest, void *ctx)
470 {
471 	sha1_result(ctx, digest);
472 }
473 
474 static int
475 intel_sha256_update(void *vctx, const void *vdata, u_int len)
476 {
477 	SHA256_CTX *ctx = vctx;
478 	uint64_t bitlen;
479 	uint32_t r;
480 	u_int blocks;
481 	const unsigned char *src = vdata;
482 
483 	/* Number of bytes left in the buffer from previous updates */
484 	r = (ctx->count >> 3) & 0x3f;
485 
486 	/* Convert the length into a number of bits */
487 	bitlen = len << 3;
488 
489 	/* Update number of bits */
490 	ctx->count += bitlen;
491 
492 	/* Handle the case where we don't need to perform any transforms */
493 	if (len < 64 - r) {
494 		memcpy(&ctx->buf[r], src, len);
495 		return (0);
496 	}
497 
498 	/* Finish the current block */
499 	memcpy(&ctx->buf[r], src, 64 - r);
500 	intel_sha256_step(ctx->state, ctx->buf, 1);
501 	src += 64 - r;
502 	len -= 64 - r;
503 
504 	/* Perform complete blocks */
505 	if (len >= 64) {
506 		blocks = len / 64;
507 		intel_sha256_step(ctx->state, src, blocks);
508 		src += blocks * 64;
509 		len -= blocks * 64;
510 	}
511 
512 	/* Copy left over data into buffer */
513 	memcpy(ctx->buf, src, len);
514 
515 	return (0);
516 }
517 
518 static void
519 SHA224_Init_fn(void *ctx)
520 {
521 	SHA224_Init(ctx);
522 }
523 
524 static void
525 SHA224_Finalize_fn(void *digest, void *ctx)
526 {
527 	SHA224_Final(digest, ctx);
528 }
529 
530 static void
531 SHA256_Init_fn(void *ctx)
532 {
533 	SHA256_Init(ctx);
534 }
535 
536 static void
537 SHA256_Finalize_fn(void *digest, void *ctx)
538 {
539 	SHA256_Final(digest, ctx);
540 }
541 
542 static int
543 aesni_authprepare(struct aesni_session *ses, int klen)
544 {
545 
546 	if (klen > SHA1_BLOCK_LEN)
547 		return (EINVAL);
548 	if ((ses->hmac && klen == 0) || (!ses->hmac && klen != 0))
549 		return (EINVAL);
550 	return (0);
551 }
552 
553 static int
554 aesni_cipher_setup(struct aesni_session *ses,
555     const struct crypto_session_params *csp)
556 {
557 	struct fpu_kern_ctx *ctx;
558 	uint8_t *schedbase;
559 	int kt, ctxidx, error;
560 
561 	schedbase = (uint8_t *)roundup2((uintptr_t)ses->schedules,
562 	    AES_SCHED_ALIGN);
563 	ses->enc_schedule = schedbase;
564 	ses->dec_schedule = schedbase + AES_SCHED_LEN;
565 	ses->xts_schedule = schedbase + AES_SCHED_LEN * 2;
566 
567 	switch (csp->csp_auth_alg) {
568 	case CRYPTO_SHA1_HMAC:
569 		ses->hmac = true;
570 		/* FALLTHROUGH */
571 	case CRYPTO_SHA1:
572 		ses->hash_len = SHA1_HASH_LEN;
573 		ses->hash_init = SHA1_Init_fn;
574 		ses->hash_update = intel_sha1_update;
575 		ses->hash_finalize = SHA1_Finalize_fn;
576 		break;
577 	case CRYPTO_SHA2_224_HMAC:
578 		ses->hmac = true;
579 		/* FALLTHROUGH */
580 	case CRYPTO_SHA2_224:
581 		ses->hash_len = SHA2_224_HASH_LEN;
582 		ses->hash_init = SHA224_Init_fn;
583 		ses->hash_update = intel_sha256_update;
584 		ses->hash_finalize = SHA224_Finalize_fn;
585 		break;
586 	case CRYPTO_SHA2_256_HMAC:
587 		ses->hmac = true;
588 		/* FALLTHROUGH */
589 	case CRYPTO_SHA2_256:
590 		ses->hash_len = SHA2_256_HASH_LEN;
591 		ses->hash_init = SHA256_Init_fn;
592 		ses->hash_update = intel_sha256_update;
593 		ses->hash_finalize = SHA256_Finalize_fn;
594 		break;
595 	}
596 
597 	if (ses->hash_len != 0) {
598 		if (csp->csp_auth_mlen == 0)
599 			ses->mlen = ses->hash_len;
600 		else
601 			ses->mlen = csp->csp_auth_mlen;
602 
603 		error = aesni_authprepare(ses, csp->csp_auth_klen);
604 		if (error != 0)
605 			return (error);
606 	} else if (csp->csp_cipher_alg == CRYPTO_AES_CCM_16) {
607 		if (csp->csp_auth_mlen == 0)
608 			ses->mlen = AES_CBC_MAC_HASH_LEN;
609 		else
610 			ses->mlen = csp->csp_auth_mlen;
611 	}
612 
613 	kt = is_fpu_kern_thread(0) || (csp->csp_cipher_alg == 0);
614 	if (!kt) {
615 		ACQUIRE_CTX(ctxidx, ctx);
616 		fpu_kern_enter(curthread, ctx,
617 		    FPU_KERN_NORMAL | FPU_KERN_KTHR);
618 	}
619 
620 	error = 0;
621 	if (csp->csp_cipher_key != NULL)
622 		aesni_cipher_setup_common(ses, csp, csp->csp_cipher_key,
623 		    csp->csp_cipher_klen);
624 
625 	if (!kt) {
626 		fpu_kern_leave(curthread, ctx);
627 		RELEASE_CTX(ctxidx, ctx);
628 	}
629 	return (error);
630 }
631 
632 static int
633 aesni_cipher_process(struct aesni_session *ses, struct cryptop *crp)
634 {
635 	const struct crypto_session_params *csp;
636 	struct fpu_kern_ctx *ctx;
637 	int error, ctxidx;
638 	bool kt;
639 
640 	csp = crypto_get_params(crp->crp_session);
641 	switch (csp->csp_cipher_alg) {
642 	case CRYPTO_AES_CCM_16:
643 		if (crp->crp_payload_length > ccm_max_payload_length(csp))
644 			return (EMSGSIZE);
645 		/* FALLTHROUGH */
646 	case CRYPTO_AES_ICM:
647 	case CRYPTO_AES_NIST_GCM_16:
648 		if ((crp->crp_flags & CRYPTO_F_IV_SEPARATE) == 0)
649 			return (EINVAL);
650 		break;
651 	case CRYPTO_AES_CBC:
652 	case CRYPTO_AES_XTS:
653 		/* CBC & XTS can only handle full blocks for now */
654 		if ((crp->crp_payload_length % AES_BLOCK_LEN) != 0)
655 			return (EINVAL);
656 		break;
657 	}
658 
659 	ctx = NULL;
660 	ctxidx = 0;
661 	error = 0;
662 	kt = is_fpu_kern_thread(0);
663 	if (!kt) {
664 		ACQUIRE_CTX(ctxidx, ctx);
665 		fpu_kern_enter(curthread, ctx,
666 		    FPU_KERN_NORMAL | FPU_KERN_KTHR);
667 	}
668 
669 	/* Do work */
670 	if (csp->csp_mode == CSP_MODE_ETA) {
671 		if (CRYPTO_OP_IS_ENCRYPT(crp->crp_op)) {
672 			error = aesni_cipher_crypt(ses, crp, csp);
673 			if (error == 0)
674 				error = aesni_cipher_mac(ses, crp, csp);
675 		} else {
676 			error = aesni_cipher_mac(ses, crp, csp);
677 			if (error == 0)
678 				error = aesni_cipher_crypt(ses, crp, csp);
679 		}
680 	} else if (csp->csp_mode == CSP_MODE_DIGEST)
681 		error = aesni_cipher_mac(ses, crp, csp);
682 	else
683 		error = aesni_cipher_crypt(ses, crp, csp);
684 
685 	if (!kt) {
686 		fpu_kern_leave(curthread, ctx);
687 		RELEASE_CTX(ctxidx, ctx);
688 	}
689 	return (error);
690 }
691 
692 static int
693 aesni_cipher_crypt(struct aesni_session *ses, struct cryptop *crp,
694     const struct crypto_session_params *csp)
695 {
696 	uint8_t iv[AES_BLOCK_LEN], tag[GMAC_DIGEST_LEN];
697 	uint8_t *authbuf, *buf, *outbuf;
698 	int error;
699 	bool encflag, allocated, authallocated, outallocated, outcopy;
700 
701 	if (crp->crp_payload_length == 0) {
702 		buf = NULL;
703 		allocated = false;
704 	} else {
705 		buf = aesni_cipher_alloc(crp, crp->crp_payload_start,
706 		    crp->crp_payload_length, &allocated);
707 		if (buf == NULL)
708 			return (ENOMEM);
709 	}
710 
711 	outallocated = false;
712 	authallocated = false;
713 	authbuf = NULL;
714 	if (csp->csp_cipher_alg == CRYPTO_AES_NIST_GCM_16 ||
715 	    csp->csp_cipher_alg == CRYPTO_AES_CCM_16) {
716 		if (crp->crp_aad_length == 0) {
717 			authbuf = NULL;
718 		} else if (crp->crp_aad != NULL) {
719 			authbuf = crp->crp_aad;
720 		} else {
721 			authbuf = aesni_cipher_alloc(crp, crp->crp_aad_start,
722 			    crp->crp_aad_length, &authallocated);
723 			if (authbuf == NULL) {
724 				error = ENOMEM;
725 				goto out;
726 			}
727 		}
728 	}
729 
730 	if (CRYPTO_HAS_OUTPUT_BUFFER(crp) && crp->crp_payload_length > 0) {
731 		outbuf = crypto_buffer_contiguous_subsegment(&crp->crp_obuf,
732 		    crp->crp_payload_output_start, crp->crp_payload_length);
733 		if (outbuf == NULL) {
734 			outcopy = true;
735 			if (allocated)
736 				outbuf = buf;
737 			else {
738 				outbuf = malloc(crp->crp_payload_length,
739 				    M_AESNI, M_NOWAIT);
740 				if (outbuf == NULL) {
741 					error = ENOMEM;
742 					goto out;
743 				}
744 				outallocated = true;
745 			}
746 		} else
747 			outcopy = false;
748 	} else {
749 		outbuf = buf;
750 		outcopy = allocated;
751 	}
752 
753 	error = 0;
754 	encflag = CRYPTO_OP_IS_ENCRYPT(crp->crp_op);
755 	if (crp->crp_cipher_key != NULL)
756 		aesni_cipher_setup_common(ses, csp, crp->crp_cipher_key,
757 		    csp->csp_cipher_klen);
758 
759 	crypto_read_iv(crp, iv);
760 
761 	switch (csp->csp_cipher_alg) {
762 	case CRYPTO_AES_CBC:
763 		if (encflag)
764 			aesni_encrypt_cbc(ses->rounds, ses->enc_schedule,
765 			    crp->crp_payload_length, buf, outbuf, iv);
766 		else {
767 			if (buf != outbuf)
768 				memcpy(outbuf, buf, crp->crp_payload_length);
769 			aesni_decrypt_cbc(ses->rounds, ses->dec_schedule,
770 			    crp->crp_payload_length, outbuf, iv);
771 		}
772 		break;
773 	case CRYPTO_AES_ICM:
774 		/* encryption & decryption are the same */
775 		aesni_encrypt_icm(ses->rounds, ses->enc_schedule,
776 		    crp->crp_payload_length, buf, outbuf, iv);
777 		break;
778 	case CRYPTO_AES_XTS:
779 		if (encflag)
780 			aesni_encrypt_xts(ses->rounds, ses->enc_schedule,
781 			    ses->xts_schedule, crp->crp_payload_length, buf,
782 			    outbuf, iv);
783 		else
784 			aesni_decrypt_xts(ses->rounds, ses->dec_schedule,
785 			    ses->xts_schedule, crp->crp_payload_length, buf,
786 			    outbuf, iv);
787 		break;
788 	case CRYPTO_AES_NIST_GCM_16:
789 		if (encflag) {
790 			memset(tag, 0, sizeof(tag));
791 			AES_GCM_encrypt(buf, outbuf, authbuf, iv, tag,
792 			    crp->crp_payload_length, crp->crp_aad_length,
793 			    csp->csp_ivlen, ses->enc_schedule, ses->rounds);
794 			crypto_copyback(crp, crp->crp_digest_start, sizeof(tag),
795 			    tag);
796 		} else {
797 			crypto_copydata(crp, crp->crp_digest_start, sizeof(tag),
798 			    tag);
799 			if (!AES_GCM_decrypt(buf, outbuf, authbuf, iv, tag,
800 			    crp->crp_payload_length, crp->crp_aad_length,
801 			    csp->csp_ivlen, ses->enc_schedule, ses->rounds))
802 				error = EBADMSG;
803 		}
804 		break;
805 	case CRYPTO_AES_CCM_16:
806 		if (encflag) {
807 			memset(tag, 0, sizeof(tag));
808 			AES_CCM_encrypt(buf, outbuf, authbuf, iv, tag,
809 			    crp->crp_payload_length, crp->crp_aad_length,
810 			    csp->csp_ivlen, ses->mlen, ses->enc_schedule,
811 			    ses->rounds);
812 			crypto_copyback(crp, crp->crp_digest_start, ses->mlen,
813 			    tag);
814 		} else {
815 			crypto_copydata(crp, crp->crp_digest_start, ses->mlen,
816 			    tag);
817 			if (!AES_CCM_decrypt(buf, outbuf, authbuf, iv, tag,
818 			    crp->crp_payload_length, crp->crp_aad_length,
819 			    csp->csp_ivlen, ses->mlen, ses->enc_schedule,
820 			    ses->rounds))
821 				error = EBADMSG;
822 		}
823 		break;
824 	}
825 	if (outcopy && error == 0)
826 		crypto_copyback(crp, CRYPTO_HAS_OUTPUT_BUFFER(crp) ?
827 		    crp->crp_payload_output_start : crp->crp_payload_start,
828 		    crp->crp_payload_length, outbuf);
829 
830 out:
831 	if (allocated)
832 		zfree(buf, M_AESNI);
833 	if (authallocated)
834 		zfree(authbuf, M_AESNI);
835 	if (outallocated)
836 		zfree(outbuf, M_AESNI);
837 	explicit_bzero(iv, sizeof(iv));
838 	explicit_bzero(tag, sizeof(tag));
839 	return (error);
840 }
841 
842 static int
843 aesni_cipher_mac(struct aesni_session *ses, struct cryptop *crp,
844     const struct crypto_session_params *csp)
845 {
846 	union {
847 		struct SHA256Context sha2 __aligned(16);
848 		struct sha1_ctxt sha1 __aligned(16);
849 	} sctx;
850 	uint32_t res[SHA2_256_HASH_LEN / sizeof(uint32_t)];
851 	const uint8_t *key;
852 	int i, keylen;
853 
854 	if (crp->crp_auth_key != NULL)
855 		key = crp->crp_auth_key;
856 	else
857 		key = csp->csp_auth_key;
858 	keylen = csp->csp_auth_klen;
859 
860 	if (ses->hmac) {
861 		uint8_t hmac_key[SHA1_BLOCK_LEN] __aligned(16);
862 
863 		/* Inner hash: (K ^ IPAD) || data */
864 		ses->hash_init(&sctx);
865 		for (i = 0; i < keylen; i++)
866 			hmac_key[i] = key[i] ^ HMAC_IPAD_VAL;
867 		for (i = keylen; i < sizeof(hmac_key); i++)
868 			hmac_key[i] = 0 ^ HMAC_IPAD_VAL;
869 		ses->hash_update(&sctx, hmac_key, sizeof(hmac_key));
870 
871 		if (crp->crp_aad != NULL)
872 			ses->hash_update(&sctx, crp->crp_aad,
873 			    crp->crp_aad_length);
874 		else
875 			crypto_apply(crp, crp->crp_aad_start,
876 			    crp->crp_aad_length, ses->hash_update, &sctx);
877 		if (CRYPTO_HAS_OUTPUT_BUFFER(crp) &&
878 		    CRYPTO_OP_IS_ENCRYPT(crp->crp_op))
879 			crypto_apply_buf(&crp->crp_obuf,
880 			    crp->crp_payload_output_start,
881 			    crp->crp_payload_length,
882 			    ses->hash_update, &sctx);
883 		else
884 			crypto_apply(crp, crp->crp_payload_start,
885 			    crp->crp_payload_length, ses->hash_update, &sctx);
886 
887 		if (csp->csp_flags & CSP_F_ESN)
888 			ses->hash_update(&sctx, crp->crp_esn, 4);
889 
890 		ses->hash_finalize(res, &sctx);
891 
892 		/* Outer hash: (K ^ OPAD) || inner hash */
893 		ses->hash_init(&sctx);
894 		for (i = 0; i < keylen; i++)
895 			hmac_key[i] = key[i] ^ HMAC_OPAD_VAL;
896 		for (i = keylen; i < sizeof(hmac_key); i++)
897 			hmac_key[i] = 0 ^ HMAC_OPAD_VAL;
898 		ses->hash_update(&sctx, hmac_key, sizeof(hmac_key));
899 		ses->hash_update(&sctx, res, ses->hash_len);
900 		ses->hash_finalize(res, &sctx);
901 		explicit_bzero(hmac_key, sizeof(hmac_key));
902 	} else {
903 		ses->hash_init(&sctx);
904 
905 		if (crp->crp_aad != NULL)
906 			ses->hash_update(&sctx, crp->crp_aad,
907 			    crp->crp_aad_length);
908 		else
909 			crypto_apply(crp, crp->crp_aad_start,
910 			    crp->crp_aad_length, ses->hash_update, &sctx);
911 		if (CRYPTO_HAS_OUTPUT_BUFFER(crp) &&
912 		    CRYPTO_OP_IS_ENCRYPT(crp->crp_op))
913 			crypto_apply_buf(&crp->crp_obuf,
914 			    crp->crp_payload_output_start,
915 			    crp->crp_payload_length,
916 			    ses->hash_update, &sctx);
917 		else
918 			crypto_apply(crp, crp->crp_payload_start,
919 			    crp->crp_payload_length,
920 			    ses->hash_update, &sctx);
921 
922 		ses->hash_finalize(res, &sctx);
923 	}
924 
925 	if (crp->crp_op & CRYPTO_OP_VERIFY_DIGEST) {
926 		uint32_t res2[SHA2_256_HASH_LEN / sizeof(uint32_t)];
927 
928 		crypto_copydata(crp, crp->crp_digest_start, ses->mlen, res2);
929 		if (timingsafe_bcmp(res, res2, ses->mlen) != 0)
930 			return (EBADMSG);
931 		explicit_bzero(res2, sizeof(res2));
932 	} else
933 		crypto_copyback(crp, crp->crp_digest_start, ses->mlen, res);
934 	explicit_bzero(res, sizeof(res));
935 	return (0);
936 }
937