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