xref: /freebsd/sys/crypto/aesni/aesni.c (revision 0957b409)
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/systm.h>
39 #include <sys/kernel.h>
40 #include <sys/kobj.h>
41 #include <sys/libkern.h>
42 #include <sys/lock.h>
43 #include <sys/module.h>
44 #include <sys/malloc.h>
45 #include <sys/bus.h>
46 #include <sys/uio.h>
47 #include <sys/mbuf.h>
48 #include <sys/smp.h>
49 
50 #include <crypto/aesni/aesni.h>
51 #include <crypto/aesni/sha_sse.h>
52 #include <crypto/sha1.h>
53 #include <crypto/sha2/sha224.h>
54 #include <crypto/sha2/sha256.h>
55 
56 #include <opencrypto/cryptodev.h>
57 #include <opencrypto/gmac.h>
58 #include <cryptodev_if.h>
59 
60 #include <machine/md_var.h>
61 #include <machine/specialreg.h>
62 #if defined(__i386__)
63 #include <machine/npx.h>
64 #elif defined(__amd64__)
65 #include <machine/fpu.h>
66 #endif
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_newsession(device_t, crypto_session_t cses,
91     struct cryptoini *cri);
92 static int aesni_cipher_setup(struct aesni_session *ses,
93     struct cryptoini *encini, struct cryptoini *authini);
94 static int aesni_cipher_process(struct aesni_session *ses,
95     struct cryptodesc *enccrd, struct cryptodesc *authcrd, struct cryptop *crp);
96 static int aesni_cipher_crypt(struct aesni_session *ses,
97     struct cryptodesc *enccrd, struct cryptodesc *authcrd, struct cryptop *crp);
98 static int aesni_cipher_mac(struct aesni_session *ses, struct cryptodesc *crd,
99     struct cryptop *crp);
100 
101 MALLOC_DEFINE(M_AESNI, "aesni_data", "AESNI Data");
102 
103 static void
104 aesni_identify(driver_t *drv, device_t parent)
105 {
106 
107 	/* NB: order 10 is so we get attached after h/w devices */
108 	if (device_find_child(parent, "aesni", -1) == NULL &&
109 	    BUS_ADD_CHILD(parent, 10, "aesni", -1) == 0)
110 		panic("aesni: could not attach");
111 }
112 
113 static void
114 detect_cpu_features(bool *has_aes, bool *has_sha)
115 {
116 
117 	*has_aes = ((cpu_feature2 & CPUID2_AESNI) != 0 &&
118 	    (cpu_feature2 & CPUID2_SSE41) != 0);
119 	*has_sha = ((cpu_stdext_feature & CPUID_STDEXT_SHA) != 0 &&
120 	    (cpu_feature2 & CPUID2_SSSE3) != 0);
121 }
122 
123 static int
124 aesni_probe(device_t dev)
125 {
126 	bool has_aes, has_sha;
127 
128 	detect_cpu_features(&has_aes, &has_sha);
129 	if (!has_aes && !has_sha) {
130 		device_printf(dev, "No AES or SHA support.\n");
131 		return (EINVAL);
132 	} else if (has_aes && has_sha)
133 		device_set_desc(dev,
134 		    "AES-CBC,AES-XTS,AES-GCM,AES-ICM,SHA1,SHA256");
135 	else if (has_aes)
136 		device_set_desc(dev, "AES-CBC,AES-XTS,AES-GCM,AES-ICM");
137 	else
138 		device_set_desc(dev, "SHA1,SHA256");
139 
140 	return (0);
141 }
142 
143 static void
144 aesni_cleanctx(void)
145 {
146 	int i;
147 
148 	/* XXX - no way to return driverid */
149 	CPU_FOREACH(i) {
150 		if (ctx_fpu[i] != NULL) {
151 			mtx_destroy(&ctx_mtx[i]);
152 			fpu_kern_free_ctx(ctx_fpu[i]);
153 		}
154 		ctx_fpu[i] = NULL;
155 	}
156 	free(ctx_mtx, M_AESNI);
157 	ctx_mtx = NULL;
158 	free(ctx_fpu, M_AESNI);
159 	ctx_fpu = NULL;
160 }
161 
162 static int
163 aesni_attach(device_t dev)
164 {
165 	struct aesni_softc *sc;
166 	int i;
167 
168 	sc = device_get_softc(dev);
169 
170 	sc->cid = crypto_get_driverid(dev, sizeof(struct aesni_session),
171 	    CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SYNC);
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 	if (sc->has_aes) {
189 		crypto_register(sc->cid, CRYPTO_AES_CBC, 0, 0);
190 		crypto_register(sc->cid, CRYPTO_AES_ICM, 0, 0);
191 		crypto_register(sc->cid, CRYPTO_AES_NIST_GCM_16, 0, 0);
192 		crypto_register(sc->cid, CRYPTO_AES_128_NIST_GMAC, 0, 0);
193 		crypto_register(sc->cid, CRYPTO_AES_192_NIST_GMAC, 0, 0);
194 		crypto_register(sc->cid, CRYPTO_AES_256_NIST_GMAC, 0, 0);
195 		crypto_register(sc->cid, CRYPTO_AES_XTS, 0, 0);
196 	}
197 	if (sc->has_sha) {
198 		crypto_register(sc->cid, CRYPTO_SHA1, 0, 0);
199 		crypto_register(sc->cid, CRYPTO_SHA1_HMAC, 0, 0);
200 		crypto_register(sc->cid, CRYPTO_SHA2_224, 0, 0);
201 		crypto_register(sc->cid, CRYPTO_SHA2_224_HMAC, 0, 0);
202 		crypto_register(sc->cid, CRYPTO_SHA2_256, 0, 0);
203 		crypto_register(sc->cid, CRYPTO_SHA2_256_HMAC, 0, 0);
204 	}
205 	return (0);
206 }
207 
208 static int
209 aesni_detach(device_t dev)
210 {
211 	struct aesni_softc *sc;
212 
213 	sc = device_get_softc(dev);
214 
215 	crypto_unregister_all(sc->cid);
216 
217 	aesni_cleanctx();
218 
219 	return (0);
220 }
221 
222 static int
223 aesni_newsession(device_t dev, crypto_session_t cses, struct cryptoini *cri)
224 {
225 	struct aesni_softc *sc;
226 	struct aesni_session *ses;
227 	struct cryptoini *encini, *authini;
228 	bool gcm_hash, gcm;
229 	int error;
230 
231 	KASSERT(cses != NULL, ("EDOOFUS"));
232 	if (cri == NULL) {
233 		CRYPTDEB("no cri");
234 		return (EINVAL);
235 	}
236 
237 	sc = device_get_softc(dev);
238 
239 	ses = crypto_get_driver_session(cses);
240 
241 	authini = NULL;
242 	encini = NULL;
243 	gcm = false;
244 	gcm_hash = false;
245 	for (; cri != NULL; cri = cri->cri_next) {
246 		switch (cri->cri_alg) {
247 		case CRYPTO_AES_NIST_GCM_16:
248 			gcm = true;
249 			/* FALLTHROUGH */
250 		case CRYPTO_AES_CBC:
251 		case CRYPTO_AES_ICM:
252 		case CRYPTO_AES_XTS:
253 			if (!sc->has_aes)
254 				goto unhandled;
255 			if (encini != NULL) {
256 				CRYPTDEB("encini already set");
257 				return (EINVAL);
258 			}
259 			encini = cri;
260 			break;
261 		case CRYPTO_AES_128_NIST_GMAC:
262 		case CRYPTO_AES_192_NIST_GMAC:
263 		case CRYPTO_AES_256_NIST_GMAC:
264 			/*
265 			 * nothing to do here, maybe in the future cache some
266 			 * values for GHASH
267 			 */
268 			gcm_hash = true;
269 			break;
270 		case CRYPTO_SHA1:
271 		case CRYPTO_SHA1_HMAC:
272 		case CRYPTO_SHA2_224:
273 		case CRYPTO_SHA2_224_HMAC:
274 		case CRYPTO_SHA2_256:
275 		case CRYPTO_SHA2_256_HMAC:
276 			if (!sc->has_sha)
277 				goto unhandled;
278 			if (authini != NULL) {
279 				CRYPTDEB("authini already set");
280 				return (EINVAL);
281 			}
282 			authini = cri;
283 			break;
284 		default:
285 unhandled:
286 			CRYPTDEB("unhandled algorithm");
287 			return (EINVAL);
288 		}
289 	}
290 	if (encini == NULL && authini == NULL) {
291 		CRYPTDEB("no cipher");
292 		return (EINVAL);
293 	}
294 	/*
295 	 * GMAC algorithms are only supported with simultaneous GCM.  Likewise
296 	 * GCM is not supported without GMAC.
297 	 */
298 	if (gcm_hash != gcm)
299 		return (EINVAL);
300 
301 	if (encini != NULL)
302 		ses->algo = encini->cri_alg;
303 	if (authini != NULL)
304 		ses->auth_algo = authini->cri_alg;
305 
306 	error = aesni_cipher_setup(ses, encini, authini);
307 	if (error != 0) {
308 		CRYPTDEB("setup failed");
309 		return (error);
310 	}
311 
312 	return (0);
313 }
314 
315 static int
316 aesni_process(device_t dev, struct cryptop *crp, int hint __unused)
317 {
318 	struct aesni_session *ses;
319 	struct cryptodesc *crd, *enccrd, *authcrd;
320 	int error, needauth;
321 
322 	ses = NULL;
323 	error = 0;
324 	enccrd = NULL;
325 	authcrd = NULL;
326 	needauth = 0;
327 
328 	/* Sanity check. */
329 	if (crp == NULL)
330 		return (EINVAL);
331 
332 	if (crp->crp_callback == NULL || crp->crp_desc == NULL ||
333 	    crp->crp_session == NULL) {
334 		error = EINVAL;
335 		goto out;
336 	}
337 
338 	for (crd = crp->crp_desc; crd != NULL; crd = crd->crd_next) {
339 		switch (crd->crd_alg) {
340 		case CRYPTO_AES_NIST_GCM_16:
341 			needauth = 1;
342 			/* FALLTHROUGH */
343 		case CRYPTO_AES_CBC:
344 		case CRYPTO_AES_ICM:
345 		case CRYPTO_AES_XTS:
346 			if (enccrd != NULL) {
347 				error = EINVAL;
348 				goto out;
349 			}
350 			enccrd = crd;
351 			break;
352 
353 		case CRYPTO_AES_128_NIST_GMAC:
354 		case CRYPTO_AES_192_NIST_GMAC:
355 		case CRYPTO_AES_256_NIST_GMAC:
356 		case CRYPTO_SHA1:
357 		case CRYPTO_SHA1_HMAC:
358 		case CRYPTO_SHA2_224:
359 		case CRYPTO_SHA2_224_HMAC:
360 		case CRYPTO_SHA2_256:
361 		case CRYPTO_SHA2_256_HMAC:
362 			if (authcrd != NULL) {
363 				error = EINVAL;
364 				goto out;
365 			}
366 			authcrd = crd;
367 			break;
368 
369 		default:
370 			error = EINVAL;
371 			goto out;
372 		}
373 	}
374 
375 	if ((enccrd == NULL && authcrd == NULL) ||
376 	    (needauth && authcrd == NULL)) {
377 		error = EINVAL;
378 		goto out;
379 	}
380 
381 	/* CBC & XTS can only handle full blocks for now */
382 	if (enccrd != NULL && (enccrd->crd_alg == CRYPTO_AES_CBC ||
383 	    enccrd->crd_alg == CRYPTO_AES_XTS) &&
384 	    (enccrd->crd_len % AES_BLOCK_LEN) != 0) {
385 		error = EINVAL;
386 		goto out;
387 	}
388 
389 	ses = crypto_get_driver_session(crp->crp_session);
390 	KASSERT(ses != NULL, ("EDOOFUS"));
391 
392 	error = aesni_cipher_process(ses, enccrd, authcrd, crp);
393 	if (error != 0)
394 		goto out;
395 
396 out:
397 	crp->crp_etype = error;
398 	crypto_done(crp);
399 	return (error);
400 }
401 
402 static uint8_t *
403 aesni_cipher_alloc(struct cryptodesc *enccrd, struct cryptop *crp,
404     bool *allocated)
405 {
406 	uint8_t *addr;
407 
408 	addr = crypto_contiguous_subsegment(crp->crp_flags,
409 	    crp->crp_buf, enccrd->crd_skip, enccrd->crd_len);
410 	if (addr != NULL) {
411 		*allocated = false;
412 		return (addr);
413 	}
414 	addr = malloc(enccrd->crd_len, M_AESNI, M_NOWAIT);
415 	if (addr != NULL) {
416 		*allocated = true;
417 		crypto_copydata(crp->crp_flags, crp->crp_buf, enccrd->crd_skip,
418 		    enccrd->crd_len, addr);
419 	} else
420 		*allocated = false;
421 	return (addr);
422 }
423 
424 static device_method_t aesni_methods[] = {
425 	DEVMETHOD(device_identify, aesni_identify),
426 	DEVMETHOD(device_probe, aesni_probe),
427 	DEVMETHOD(device_attach, aesni_attach),
428 	DEVMETHOD(device_detach, aesni_detach),
429 
430 	DEVMETHOD(cryptodev_newsession, aesni_newsession),
431 	DEVMETHOD(cryptodev_process, aesni_process),
432 
433 	DEVMETHOD_END
434 };
435 
436 static driver_t aesni_driver = {
437 	"aesni",
438 	aesni_methods,
439 	sizeof(struct aesni_softc),
440 };
441 static devclass_t aesni_devclass;
442 
443 DRIVER_MODULE(aesni, nexus, aesni_driver, aesni_devclass, 0, 0);
444 MODULE_VERSION(aesni, 1);
445 MODULE_DEPEND(aesni, crypto, 1, 1, 1);
446 
447 static int
448 aesni_authprepare(struct aesni_session *ses, int klen, const void *cri_key)
449 {
450 	int keylen;
451 
452 	if (klen % 8 != 0)
453 		return (EINVAL);
454 	keylen = klen / 8;
455 	if (keylen > sizeof(ses->hmac_key))
456 		return (EINVAL);
457 	if (ses->auth_algo == CRYPTO_SHA1 && keylen > 0)
458 		return (EINVAL);
459 	memcpy(ses->hmac_key, cri_key, keylen);
460 	return (0);
461 }
462 
463 static int
464 aesni_cipher_setup(struct aesni_session *ses, struct cryptoini *encini,
465     struct cryptoini *authini)
466 {
467 	struct fpu_kern_ctx *ctx;
468 	int kt, ctxidx, error;
469 
470 	switch (ses->auth_algo) {
471 	case CRYPTO_SHA1:
472 	case CRYPTO_SHA1_HMAC:
473 	case CRYPTO_SHA2_224:
474 	case CRYPTO_SHA2_224_HMAC:
475 	case CRYPTO_SHA2_256:
476 	case CRYPTO_SHA2_256_HMAC:
477 		error = aesni_authprepare(ses, authini->cri_klen,
478 		    authini->cri_key);
479 		if (error != 0)
480 			return (error);
481 		ses->mlen = authini->cri_mlen;
482 	}
483 
484 	kt = is_fpu_kern_thread(0) || (encini == NULL);
485 	if (!kt) {
486 		ACQUIRE_CTX(ctxidx, ctx);
487 		fpu_kern_enter(curthread, ctx,
488 		    FPU_KERN_NORMAL | FPU_KERN_KTHR);
489 	}
490 
491 	error = 0;
492 	if (encini != NULL)
493 		error = aesni_cipher_setup_common(ses, encini->cri_key,
494 		    encini->cri_klen);
495 
496 	if (!kt) {
497 		fpu_kern_leave(curthread, ctx);
498 		RELEASE_CTX(ctxidx, ctx);
499 	}
500 	return (error);
501 }
502 
503 static int
504 intel_sha1_update(void *vctx, const void *vdata, u_int datalen)
505 {
506 	struct sha1_ctxt *ctx = vctx;
507 	const char *data = vdata;
508 	size_t gaplen;
509 	size_t gapstart;
510 	size_t off;
511 	size_t copysiz;
512 	u_int blocks;
513 
514 	off = 0;
515 	/* Do any aligned blocks without redundant copying. */
516 	if (datalen >= 64 && ctx->count % 64 == 0) {
517 		blocks = datalen / 64;
518 		ctx->c.b64[0] += blocks * 64 * 8;
519 		intel_sha1_step(ctx->h.b32, data + off, blocks);
520 		off += blocks * 64;
521 	}
522 
523 	while (off < datalen) {
524 		gapstart = ctx->count % 64;
525 		gaplen = 64 - gapstart;
526 
527 		copysiz = (gaplen < datalen - off) ? gaplen : datalen - off;
528 		bcopy(&data[off], &ctx->m.b8[gapstart], copysiz);
529 		ctx->count += copysiz;
530 		ctx->count %= 64;
531 		ctx->c.b64[0] += copysiz * 8;
532 		if (ctx->count % 64 == 0)
533 			intel_sha1_step(ctx->h.b32, (void *)ctx->m.b8, 1);
534 		off += copysiz;
535 	}
536 	return (0);
537 }
538 
539 static void
540 SHA1_Init_fn(void *ctx)
541 {
542 	sha1_init(ctx);
543 }
544 
545 static void
546 SHA1_Finalize_fn(void *digest, void *ctx)
547 {
548 	sha1_result(ctx, digest);
549 }
550 
551 static int
552 intel_sha256_update(void *vctx, const void *vdata, u_int len)
553 {
554 	SHA256_CTX *ctx = vctx;
555 	uint64_t bitlen;
556 	uint32_t r;
557 	u_int blocks;
558 	const unsigned char *src = vdata;
559 
560 	/* Number of bytes left in the buffer from previous updates */
561 	r = (ctx->count >> 3) & 0x3f;
562 
563 	/* Convert the length into a number of bits */
564 	bitlen = len << 3;
565 
566 	/* Update number of bits */
567 	ctx->count += bitlen;
568 
569 	/* Handle the case where we don't need to perform any transforms */
570 	if (len < 64 - r) {
571 		memcpy(&ctx->buf[r], src, len);
572 		return (0);
573 	}
574 
575 	/* Finish the current block */
576 	memcpy(&ctx->buf[r], src, 64 - r);
577 	intel_sha256_step(ctx->state, ctx->buf, 1);
578 	src += 64 - r;
579 	len -= 64 - r;
580 
581 	/* Perform complete blocks */
582 	if (len >= 64) {
583 		blocks = len / 64;
584 		intel_sha256_step(ctx->state, src, blocks);
585 		src += blocks * 64;
586 		len -= blocks * 64;
587 	}
588 
589 	/* Copy left over data into buffer */
590 	memcpy(ctx->buf, src, len);
591 	return (0);
592 }
593 
594 static void
595 SHA224_Init_fn(void *ctx)
596 {
597 	SHA224_Init(ctx);
598 }
599 
600 static void
601 SHA224_Finalize_fn(void *digest, void *ctx)
602 {
603 	SHA224_Final(digest, ctx);
604 }
605 
606 static void
607 SHA256_Init_fn(void *ctx)
608 {
609 	SHA256_Init(ctx);
610 }
611 
612 static void
613 SHA256_Finalize_fn(void *digest, void *ctx)
614 {
615 	SHA256_Final(digest, ctx);
616 }
617 
618 /*
619  * Compute the HASH( (key ^ xorbyte) || buf )
620  */
621 static void
622 hmac_internal(void *ctx, uint32_t *res,
623 	int (*update)(void *, const void *, u_int),
624 	void (*finalize)(void *, void *), uint8_t *key, uint8_t xorbyte,
625 	const void *buf, size_t off, size_t buflen, int crpflags)
626 {
627 	size_t i;
628 
629 	for (i = 0; i < 64; i++)
630 		key[i] ^= xorbyte;
631 	update(ctx, key, 64);
632 	for (i = 0; i < 64; i++)
633 		key[i] ^= xorbyte;
634 
635 	crypto_apply(crpflags, __DECONST(void *, buf), off, buflen,
636 	    __DECONST(int (*)(void *, void *, u_int), update), ctx);
637 	finalize(res, ctx);
638 }
639 
640 static int
641 aesni_cipher_process(struct aesni_session *ses, struct cryptodesc *enccrd,
642     struct cryptodesc *authcrd, struct cryptop *crp)
643 {
644 	struct fpu_kern_ctx *ctx;
645 	int error, ctxidx;
646 	bool kt;
647 
648 	if (enccrd != NULL) {
649 		if ((enccrd->crd_alg == CRYPTO_AES_ICM ||
650 		    enccrd->crd_alg == CRYPTO_AES_NIST_GCM_16) &&
651 		    (enccrd->crd_flags & CRD_F_IV_EXPLICIT) == 0)
652 			return (EINVAL);
653 	}
654 
655 	ctx = NULL;
656 	ctxidx = 0;
657 	error = 0;
658 	kt = is_fpu_kern_thread(0);
659 	if (!kt) {
660 		ACQUIRE_CTX(ctxidx, ctx);
661 		fpu_kern_enter(curthread, ctx,
662 		    FPU_KERN_NORMAL | FPU_KERN_KTHR);
663 	}
664 
665 	/* Do work */
666 	if (enccrd != NULL && authcrd != NULL) {
667 		/* Perform the first operation */
668 		if (crp->crp_desc == enccrd)
669 			error = aesni_cipher_crypt(ses, enccrd, authcrd, crp);
670 		else
671 			error = aesni_cipher_mac(ses, authcrd, crp);
672 		if (error != 0)
673 			goto out;
674 		/* Perform the second operation */
675 		if (crp->crp_desc == enccrd)
676 			error = aesni_cipher_mac(ses, authcrd, crp);
677 		else
678 			error = aesni_cipher_crypt(ses, enccrd, authcrd, crp);
679 	} else if (enccrd != NULL)
680 		error = aesni_cipher_crypt(ses, enccrd, authcrd, crp);
681 	else
682 		error = aesni_cipher_mac(ses, authcrd, crp);
683 
684 	if (error != 0)
685 		goto out;
686 
687 out:
688 	if (!kt) {
689 		fpu_kern_leave(curthread, ctx);
690 		RELEASE_CTX(ctxidx, ctx);
691 	}
692 	return (error);
693 }
694 
695 static int
696 aesni_cipher_crypt(struct aesni_session *ses, struct cryptodesc *enccrd,
697 	struct cryptodesc *authcrd, struct cryptop *crp)
698 {
699 	uint8_t iv[AES_BLOCK_LEN], tag[GMAC_DIGEST_LEN], *buf, *authbuf;
700 	int error, ivlen;
701 	bool encflag, allocated, authallocated;
702 
703 	KASSERT(ses->algo != CRYPTO_AES_NIST_GCM_16 || authcrd != NULL,
704 	    ("AES_NIST_GCM_16 must include MAC descriptor"));
705 
706 	ivlen = 0;
707 	authbuf = NULL;
708 
709 	buf = aesni_cipher_alloc(enccrd, crp, &allocated);
710 	if (buf == NULL)
711 		return (ENOMEM);
712 
713 	authallocated = false;
714 	if (ses->algo == CRYPTO_AES_NIST_GCM_16) {
715 		authbuf = aesni_cipher_alloc(authcrd, crp, &authallocated);
716 		if (authbuf == NULL) {
717 			error = ENOMEM;
718 			goto out;
719 		}
720 	}
721 
722 	error = 0;
723 	encflag = (enccrd->crd_flags & CRD_F_ENCRYPT) == CRD_F_ENCRYPT;
724 	if ((enccrd->crd_flags & CRD_F_KEY_EXPLICIT) != 0) {
725 		error = aesni_cipher_setup_common(ses, enccrd->crd_key,
726 		    enccrd->crd_klen);
727 		if (error != 0)
728 			goto out;
729 	}
730 
731 	switch (enccrd->crd_alg) {
732 	case CRYPTO_AES_CBC:
733 	case CRYPTO_AES_ICM:
734 		ivlen = AES_BLOCK_LEN;
735 		break;
736 	case CRYPTO_AES_XTS:
737 		ivlen = 8;
738 		break;
739 	case CRYPTO_AES_NIST_GCM_16:
740 		ivlen = 12;	/* should support arbitarily larger */
741 		break;
742 	}
743 
744 	/* Setup iv */
745 	if (encflag) {
746 		if ((enccrd->crd_flags & CRD_F_IV_EXPLICIT) != 0)
747 			bcopy(enccrd->crd_iv, iv, ivlen);
748 		else
749 			arc4rand(iv, ivlen, 0);
750 
751 		if ((enccrd->crd_flags & CRD_F_IV_PRESENT) == 0)
752 			crypto_copyback(crp->crp_flags, crp->crp_buf,
753 			    enccrd->crd_inject, ivlen, iv);
754 	} else {
755 		if ((enccrd->crd_flags & CRD_F_IV_EXPLICIT) != 0)
756 			bcopy(enccrd->crd_iv, iv, ivlen);
757 		else
758 			crypto_copydata(crp->crp_flags, crp->crp_buf,
759 			    enccrd->crd_inject, ivlen, iv);
760 	}
761 
762 	switch (ses->algo) {
763 	case CRYPTO_AES_CBC:
764 		if (encflag)
765 			aesni_encrypt_cbc(ses->rounds, ses->enc_schedule,
766 			    enccrd->crd_len, buf, buf, iv);
767 		else
768 			aesni_decrypt_cbc(ses->rounds, ses->dec_schedule,
769 			    enccrd->crd_len, buf, iv);
770 		break;
771 	case CRYPTO_AES_ICM:
772 		/* encryption & decryption are the same */
773 		aesni_encrypt_icm(ses->rounds, ses->enc_schedule,
774 		    enccrd->crd_len, buf, buf, iv);
775 		break;
776 	case CRYPTO_AES_XTS:
777 		if (encflag)
778 			aesni_encrypt_xts(ses->rounds, ses->enc_schedule,
779 			    ses->xts_schedule, enccrd->crd_len, buf, buf,
780 			    iv);
781 		else
782 			aesni_decrypt_xts(ses->rounds, ses->dec_schedule,
783 			    ses->xts_schedule, enccrd->crd_len, buf, buf,
784 			    iv);
785 		break;
786 	case CRYPTO_AES_NIST_GCM_16:
787 		if (!encflag)
788 			crypto_copydata(crp->crp_flags, crp->crp_buf,
789 			    authcrd->crd_inject, GMAC_DIGEST_LEN, tag);
790 		else
791 			bzero(tag, sizeof tag);
792 
793 		if (encflag) {
794 			AES_GCM_encrypt(buf, buf, authbuf, iv, tag,
795 			    enccrd->crd_len, authcrd->crd_len, ivlen,
796 			    ses->enc_schedule, ses->rounds);
797 
798 			if (authcrd != NULL)
799 				crypto_copyback(crp->crp_flags, crp->crp_buf,
800 				    authcrd->crd_inject, GMAC_DIGEST_LEN, tag);
801 		} else {
802 			if (!AES_GCM_decrypt(buf, buf, authbuf, iv, tag,
803 			    enccrd->crd_len, authcrd->crd_len, ivlen,
804 			    ses->enc_schedule, ses->rounds))
805 				error = EBADMSG;
806 		}
807 		break;
808 	}
809 
810 	if (allocated)
811 		crypto_copyback(crp->crp_flags, crp->crp_buf, enccrd->crd_skip,
812 		    enccrd->crd_len, buf);
813 
814 out:
815 	if (allocated) {
816 		explicit_bzero(buf, enccrd->crd_len);
817 		free(buf, M_AESNI);
818 	}
819 	if (authallocated) {
820 		explicit_bzero(authbuf, authcrd->crd_len);
821 		free(authbuf, M_AESNI);
822 	}
823 	return (error);
824 }
825 
826 static int
827 aesni_cipher_mac(struct aesni_session *ses, struct cryptodesc *crd,
828     struct cryptop *crp)
829 {
830 	union {
831 		struct SHA256Context sha2 __aligned(16);
832 		struct sha1_ctxt sha1 __aligned(16);
833 	} sctx;
834 	uint32_t res[SHA2_256_HASH_LEN / sizeof(uint32_t)];
835 	int hashlen, error;
836 	void *ctx;
837 	void (*InitFn)(void *);
838 	int (*UpdateFn)(void *, const void *, unsigned);
839 	void (*FinalizeFn)(void *, void *);
840 
841 	bool hmac;
842 
843 	if ((crd->crd_flags & ~CRD_F_KEY_EXPLICIT) != 0) {
844 		CRYPTDEB("%s: Unsupported MAC flags: 0x%x", __func__,
845 		    (crd->crd_flags & ~CRD_F_KEY_EXPLICIT));
846 		return (EINVAL);
847 	}
848 	if ((crd->crd_flags & CRD_F_KEY_EXPLICIT) != 0) {
849 		error = aesni_authprepare(ses, crd->crd_klen, crd->crd_key);
850 		if (error != 0)
851 			return (error);
852 	}
853 
854 	hmac = false;
855 	switch (ses->auth_algo) {
856 	case CRYPTO_SHA1_HMAC:
857 		hmac = true;
858 		/* FALLTHROUGH */
859 	case CRYPTO_SHA1:
860 		hashlen = SHA1_HASH_LEN;
861 		InitFn = SHA1_Init_fn;
862 		UpdateFn = intel_sha1_update;
863 		FinalizeFn = SHA1_Finalize_fn;
864 		ctx = &sctx.sha1;
865 		break;
866 
867 	case CRYPTO_SHA2_256_HMAC:
868 		hmac = true;
869 		/* FALLTHROUGH */
870 	case CRYPTO_SHA2_256:
871 		hashlen = SHA2_256_HASH_LEN;
872 		InitFn = SHA256_Init_fn;
873 		UpdateFn = intel_sha256_update;
874 		FinalizeFn = SHA256_Finalize_fn;
875 		ctx = &sctx.sha2;
876 		break;
877 
878 	case CRYPTO_SHA2_224_HMAC:
879 		hmac = true;
880 		/* FALLTHROUGH */
881 	case CRYPTO_SHA2_224:
882 		hashlen = SHA2_224_HASH_LEN;
883 		InitFn = SHA224_Init_fn;
884 		UpdateFn = intel_sha256_update;
885 		FinalizeFn = SHA224_Finalize_fn;
886 		ctx = &sctx.sha2;
887 		break;
888 	default:
889 		/*
890 		 * AES-GMAC authentication is verified while processing the
891 		 * enccrd
892 		 */
893 		return (0);
894 	}
895 
896 	if (hmac) {
897 		/* Inner hash: (K ^ IPAD) || data */
898 		InitFn(ctx);
899 		hmac_internal(ctx, res, UpdateFn, FinalizeFn, ses->hmac_key,
900 		    0x36, crp->crp_buf, crd->crd_skip, crd->crd_len,
901 		    crp->crp_flags);
902 		/* Outer hash: (K ^ OPAD) || inner hash */
903 		InitFn(ctx);
904 		hmac_internal(ctx, res, UpdateFn, FinalizeFn, ses->hmac_key,
905 		    0x5C, res, 0, hashlen, 0);
906 	} else {
907 		InitFn(ctx);
908 		crypto_apply(crp->crp_flags, crp->crp_buf, crd->crd_skip,
909 		    crd->crd_len, __DECONST(int (*)(void *, void *, u_int),
910 		    UpdateFn), ctx);
911 		FinalizeFn(res, ctx);
912 	}
913 
914 	if (ses->mlen != 0 && ses->mlen < hashlen)
915 		hashlen = ses->mlen;
916 
917 	crypto_copyback(crp->crp_flags, crp->crp_buf, crd->crd_inject, hashlen,
918 	    (void *)res);
919 	return (0);
920 }
921