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