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