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