Home | History | Annotate | Line # | Download | only in opencrypto
cryptodev.c revision 1.115
      1 /*	$NetBSD: cryptodev.c,v 1.115 2022/05/21 23:11:03 riastradh Exp $ */
      2 /*	$FreeBSD: src/sys/opencrypto/cryptodev.c,v 1.4.2.4 2003/06/03 00:09:02 sam Exp $	*/
      3 /*	$OpenBSD: cryptodev.c,v 1.53 2002/07/10 22:21:30 mickey Exp $	*/
      4 
      5 /*-
      6  * Copyright (c) 2008 The NetBSD Foundation, Inc.
      7  * All rights reserved.
      8  *
      9  * This code is derived from software contributed to The NetBSD Foundation
     10  * by Coyote Point Systems, Inc.
     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 NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     31  * POSSIBILITY OF SUCH DAMAGE.
     32  */
     33 
     34 /*
     35  * Copyright (c) 2001 Theo de Raadt
     36  *
     37  * Redistribution and use in source and binary forms, with or without
     38  * modification, are permitted provided that the following conditions
     39  * are met:
     40  *
     41  * 1. Redistributions of source code must retain the above copyright
     42  *   notice, this list of conditions and the following disclaimer.
     43  * 2. Redistributions in binary form must reproduce the above copyright
     44  *   notice, this list of conditions and the following disclaimer in the
     45  *   documentation and/or other materials provided with the distribution.
     46  * 3. The name of the author may not be used to endorse or promote products
     47  *   derived from this software without specific prior written permission.
     48  *
     49  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     50  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     51  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     52  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     53  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     54  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     55  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     56  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     57  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     58  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     59  *
     60  * Effort sponsored in part by the Defense Advanced Research Projects
     61  * Agency (DARPA) and Air Force Research Laboratory, Air Force
     62  * Materiel Command, USAF, under agreement number F30602-01-2-0537.
     63  *
     64  */
     65 
     66 #include <sys/cdefs.h>
     67 __KERNEL_RCSID(0, "$NetBSD: cryptodev.c,v 1.115 2022/05/21 23:11:03 riastradh Exp $");
     68 
     69 #include <sys/param.h>
     70 #include <sys/systm.h>
     71 #include <sys/kmem.h>
     72 #include <sys/malloc.h>
     73 #include <sys/mbuf.h>
     74 #include <sys/pool.h>
     75 #include <sys/sysctl.h>
     76 #include <sys/file.h>
     77 #include <sys/filedesc.h>
     78 #include <sys/errno.h>
     79 #include <sys/md5.h>
     80 #include <sys/sha1.h>
     81 #include <sys/conf.h>
     82 #include <sys/device.h>
     83 #include <sys/kauth.h>
     84 #include <sys/select.h>
     85 #include <sys/poll.h>
     86 #include <sys/atomic.h>
     87 #include <sys/stat.h>
     88 #include <sys/module.h>
     89 #include <sys/compat_stub.h>
     90 
     91 #ifdef _KERNEL_OPT
     92 #include "opt_ocf.h"
     93 #include "opt_compat_netbsd.h"
     94 #endif
     95 
     96 #include <opencrypto/cryptodev.h>
     97 #include <opencrypto/ocryptodev.h>
     98 #include <opencrypto/cryptodev_internal.h>
     99 #include <opencrypto/xform.h>
    100 
    101 #include "ioconf.h"
    102 
    103 kmutex_t cryptodev_mtx;
    104 
    105 struct csession {
    106 	TAILQ_ENTRY(csession) next;
    107 	u_int64_t	sid;
    108 	u_int32_t	ses;
    109 
    110 	u_int32_t	cipher;		/* note: shares name space in crd_alg */
    111 	const struct enc_xform *txform;
    112 	u_int32_t	mac;		/* note: shares name space in crd_alg */
    113 	const struct auth_hash *thash;
    114 	u_int32_t	comp_alg;	/* note: shares name space in crd_alg */
    115 	const struct comp_algo *tcomp;
    116 
    117 	void *		key;
    118 	int		keylen;
    119 	u_char		tmp_iv[EALG_MAX_BLOCK_LEN];
    120 
    121 	void *		mackey;
    122 	int		mackeylen;
    123 	u_char		tmp_mac[CRYPTO_MAX_MAC_LEN];
    124 
    125 	struct iovec	iovec[1];	/* user requests never have more */
    126 	struct uio	uio;
    127 	int		error;
    128 };
    129 
    130 struct fcrypt {
    131 	TAILQ_HEAD(csessionlist, csession) csessions;
    132 	TAILQ_HEAD(crprethead, cryptop) crp_ret_mq;
    133 	TAILQ_HEAD(krprethead, cryptkop) crp_ret_mkq;
    134 	int		sesn;
    135 	struct selinfo	sinfo;
    136 	u_int32_t	requestid;
    137 	struct timespec atime;
    138 	struct timespec mtime;
    139 	struct timespec btime;
    140 };
    141 
    142 /* For our fixed-size allocations */
    143 static struct pool fcrpl;
    144 static struct pool csepl;
    145 
    146 /* Declaration of master device (fd-cloning/ctxt-allocating) entrypoints */
    147 static int	cryptoopen(dev_t dev, int flag, int mode, struct lwp *l);
    148 static int	cryptoread(dev_t dev, struct uio *uio, int ioflag);
    149 static int	cryptowrite(dev_t dev, struct uio *uio, int ioflag);
    150 static int	cryptoselect(dev_t dev, int rw, struct lwp *l);
    151 
    152 static int	crypto_refcount = 0;	/* Prevent detaching while in use */
    153 
    154 /* Declaration of cloned-device (per-ctxt) entrypoints */
    155 static int	cryptof_read(struct file *, off_t *, struct uio *,
    156     kauth_cred_t, int);
    157 static int	cryptof_write(struct file *, off_t *, struct uio *,
    158     kauth_cred_t, int);
    159 static int	cryptof_ioctl(struct file *, u_long, void *);
    160 static int	cryptof_close(struct file *);
    161 static int 	cryptof_poll(struct file *, int);
    162 static int 	cryptof_stat(struct file *, struct stat *);
    163 
    164 static const struct fileops cryptofops = {
    165 	.fo_name = "cryptof",
    166 	.fo_read = cryptof_read,
    167 	.fo_write = cryptof_write,
    168 	.fo_ioctl = cryptof_ioctl,
    169 	.fo_fcntl = fnullop_fcntl,
    170 	.fo_poll = cryptof_poll,
    171 	.fo_stat = cryptof_stat,
    172 	.fo_close = cryptof_close,
    173 	.fo_kqfilter = fnullop_kqfilter,
    174 	.fo_restart = fnullop_restart,
    175 };
    176 
    177 struct csession *cryptodev_csefind(struct fcrypt *, u_int);
    178 static struct	csession *csefind(struct fcrypt *, u_int);
    179 static int	csedelete(struct fcrypt *, struct csession *);
    180 static struct	csession *cseadd(struct fcrypt *, struct csession *);
    181 static struct	csession *csecreate(struct fcrypt *, u_int64_t, void *,
    182     u_int64_t, void *, u_int64_t, u_int32_t, u_int32_t, u_int32_t,
    183     const struct enc_xform *, const struct auth_hash *,
    184     const struct comp_algo *);
    185 static int	csefree(struct csession *);
    186 
    187 static int	cryptodev_key(struct crypt_kop *);
    188 static int	cryptodev_mkey(struct fcrypt *, struct crypt_n_kop *, int);
    189 static int	cryptodev_msessionfin(struct fcrypt *, int, u_int32_t *);
    190 
    191 static int	cryptodev_cb(struct cryptop *);
    192 static int	cryptodevkey_cb(struct cryptkop *);
    193 
    194 static int	cryptodev_mcb(struct cryptop *);
    195 static int	cryptodevkey_mcb(struct cryptkop *);
    196 
    197 static int 	cryptodev_getmstatus(struct fcrypt *, struct crypt_result *,
    198     int);
    199 static int	cryptodev_getstatus(struct fcrypt *, struct crypt_result *);
    200 
    201 /*
    202  * sysctl-able control variables for /dev/crypto now defined in crypto.c:
    203  * crypto_usercrypto, crypto_userasmcrypto, crypto_devallowsoft.
    204  */
    205 
    206 /* ARGSUSED */
    207 int
    208 cryptof_read(file_t *fp, off_t *poff,
    209     struct uio *uio, kauth_cred_t cred, int flags)
    210 {
    211 	return EIO;
    212 }
    213 
    214 /* ARGSUSED */
    215 int
    216 cryptof_write(file_t *fp, off_t *poff,
    217     struct uio *uio, kauth_cred_t cred, int flags)
    218 {
    219 	return EIO;
    220 }
    221 
    222 /* ARGSUSED */
    223 int
    224 cryptof_ioctl(struct file *fp, u_long cmd, void *data)
    225 {
    226 	struct fcrypt *fcr = fp->f_fcrypt;
    227 	struct csession *cse;
    228 	struct session_op *sop;
    229 	struct session_n_op *snop;
    230 	struct crypt_op *cop;
    231 	struct crypt_mop *mop;
    232 	struct crypt_mkop *mkop;
    233 	struct crypt_n_op *cnop;
    234 	struct crypt_n_kop *knop;
    235 	struct crypt_sgop *sgop;
    236 	struct crypt_sfop *sfop;
    237 	struct cryptret *crypt_ret;
    238 	struct crypt_result *crypt_res;
    239 	u_int32_t ses;
    240 	u_int32_t *sesid;
    241 	int error = 0;
    242 	size_t count;
    243 
    244 	/* backwards compatibility */
    245         file_t *criofp;
    246 	struct fcrypt *criofcr;
    247 	int criofd;
    248 
    249 	mutex_enter(&cryptodev_mtx);
    250 	getnanotime(&fcr->atime);
    251 	mutex_exit(&cryptodev_mtx);
    252 
    253 	switch (cmd) {
    254         case CRIOGET:   /* XXX deprecated, remove after 5.0 */
    255 		if ((error = fd_allocfile(&criofp, &criofd)) != 0)
    256 			return error;
    257 		criofcr = pool_get(&fcrpl, PR_WAITOK);
    258 		mutex_enter(&cryptodev_mtx);
    259 		TAILQ_INIT(&criofcr->csessions);
    260 		TAILQ_INIT(&criofcr->crp_ret_mq);
    261 		TAILQ_INIT(&criofcr->crp_ret_mkq);
    262 		selinit(&criofcr->sinfo);
    263 
    264                 /*
    265                  * Don't ever return session 0, to allow detection of
    266                  * failed creation attempts with multi-create ioctl.
    267                  */
    268 		criofcr->sesn = 1;
    269 		criofcr->requestid = 1;
    270 		crypto_refcount++;
    271 		mutex_exit(&cryptodev_mtx);
    272 		(void)fd_clone(criofp, criofd, (FREAD|FWRITE),
    273 			      &cryptofops, criofcr);
    274 		*(u_int32_t *)data = criofd;
    275 		return error;
    276 		break;
    277 	case CIOCGSESSION:
    278 		sop = (struct session_op *)data;
    279 		error = cryptodev_session(fcr, sop);
    280 		break;
    281 	case CIOCNGSESSION:
    282 		sgop = (struct crypt_sgop *)data;
    283 		if (sgop->count <= 0
    284 		    || SIZE_MAX / sizeof(struct session_n_op) <= sgop->count) {
    285 			error = EINVAL;
    286 			break;
    287 		}
    288 		snop = kmem_alloc((sgop->count *
    289 				  sizeof(struct session_n_op)), KM_SLEEP);
    290 		error = copyin(sgop->sessions, snop, sgop->count *
    291 			       sizeof(struct session_n_op));
    292 		if (error) {
    293 			goto mbail;
    294 		}
    295 
    296 		mutex_enter(&cryptodev_mtx);
    297 		fcr->mtime = fcr->atime;
    298 		mutex_exit(&cryptodev_mtx);
    299 		error = cryptodev_msession(fcr, snop, sgop->count);
    300 		if (error) {
    301 			goto mbail;
    302 		}
    303 
    304 		error = copyout(snop, sgop->sessions, sgop->count *
    305 		    sizeof(struct session_n_op));
    306 mbail:
    307 		kmem_free(snop, sgop->count * sizeof(struct session_n_op));
    308 		break;
    309 	case CIOCFSESSION:
    310 		mutex_enter(&cryptodev_mtx);
    311 		fcr->mtime = fcr->atime;
    312 		ses = *(u_int32_t *)data;
    313 		cse = csefind(fcr, ses);
    314 		if (cse == NULL) {
    315 			mutex_exit(&cryptodev_mtx);
    316 			return EINVAL;
    317 		}
    318 		csedelete(fcr, cse);
    319 		mutex_exit(&cryptodev_mtx);
    320 		error = csefree(cse);
    321 		break;
    322 	case CIOCNFSESSION:
    323 		mutex_enter(&cryptodev_mtx);
    324 		fcr->mtime = fcr->atime;
    325 		mutex_exit(&cryptodev_mtx);
    326 		sfop = (struct crypt_sfop *)data;
    327 		if (sfop->count <= 0
    328 		    || SIZE_MAX / sizeof(u_int32_t) <= sfop->count) {
    329 			error = EINVAL;
    330 			break;
    331 		}
    332 		sesid = kmem_alloc((sfop->count * sizeof(u_int32_t)),
    333 		    KM_SLEEP);
    334 		error = copyin(sfop->sesid, sesid,
    335 		    (sfop->count * sizeof(u_int32_t)));
    336 		if (!error) {
    337 			error = cryptodev_msessionfin(fcr, sfop->count, sesid);
    338 		}
    339 		kmem_free(sesid, (sfop->count * sizeof(u_int32_t)));
    340 		break;
    341 	case CIOCCRYPT:
    342 		mutex_enter(&cryptodev_mtx);
    343 		fcr->mtime = fcr->atime;
    344 		cop = (struct crypt_op *)data;
    345 		cse = csefind(fcr, cop->ses);
    346 		mutex_exit(&cryptodev_mtx);
    347 		if (cse == NULL) {
    348 			DPRINTF("csefind failed\n");
    349 			return EINVAL;
    350 		}
    351 		error = cryptodev_op(cse, cop, curlwp);
    352 		DPRINTF("cryptodev_op error = %d\n", error);
    353 		break;
    354 	case CIOCNCRYPTM:
    355 		mutex_enter(&cryptodev_mtx);
    356 		fcr->mtime = fcr->atime;
    357 		mutex_exit(&cryptodev_mtx);
    358 		mop = (struct crypt_mop *)data;
    359 		if (mop->count <= 0
    360 		    || SIZE_MAX / sizeof(struct crypt_n_op) <= mop->count) {
    361 			error = EINVAL;
    362 			break;
    363 		}
    364 		cnop = kmem_alloc((mop->count * sizeof(struct crypt_n_op)),
    365 		    KM_SLEEP);
    366 		error = copyin(mop->reqs, cnop,
    367 		    (mop->count * sizeof(struct crypt_n_op)));
    368 		if(!error) {
    369 			error = cryptodev_mop(fcr, cnop, mop->count, curlwp);
    370 			if (!error) {
    371 				error = copyout(cnop, mop->reqs,
    372 				    (mop->count * sizeof(struct crypt_n_op)));
    373 			}
    374 		}
    375 		kmem_free(cnop, (mop->count * sizeof(struct crypt_n_op)));
    376 		break;
    377 	case CIOCKEY:
    378 		error = cryptodev_key((struct crypt_kop *)data);
    379 		DPRINTF("cryptodev_key error = %d\n", error);
    380 		break;
    381 	case CIOCNFKEYM:
    382 		mutex_enter(&cryptodev_mtx);
    383 		fcr->mtime = fcr->atime;
    384 		mutex_exit(&cryptodev_mtx);
    385 		mkop = (struct crypt_mkop *)data;
    386 		if (mkop->count <= 0
    387 		    || SIZE_MAX / sizeof(struct crypt_n_kop) <= mkop->count) {
    388 			error = EINVAL;
    389 			break;
    390 		}
    391 		knop = kmem_alloc((mkop->count * sizeof(struct crypt_n_kop)),
    392 		    KM_SLEEP);
    393 		error = copyin(mkop->reqs, knop,
    394 		    (mkop->count * sizeof(struct crypt_n_kop)));
    395 		if (!error) {
    396 			error = cryptodev_mkey(fcr, knop, mkop->count);
    397 			if (!error)
    398 				error = copyout(knop, mkop->reqs,
    399 				    (mkop->count * sizeof(struct crypt_n_kop)));
    400 		}
    401 		kmem_free(knop, (mkop->count * sizeof(struct crypt_n_kop)));
    402 		break;
    403 	case CIOCASYMFEAT:
    404 		error = crypto_getfeat((int *)data);
    405 		break;
    406 	case CIOCNCRYPTRETM:
    407 		mutex_enter(&cryptodev_mtx);
    408 		fcr->mtime = fcr->atime;
    409 		mutex_exit(&cryptodev_mtx);
    410 		crypt_ret = (struct cryptret *)data;
    411 		count = crypt_ret->count;
    412 		if (count <= 0
    413 		    || SIZE_MAX / sizeof(struct crypt_result) <= count) {
    414 			error = EINVAL;
    415 			break;
    416 		}
    417 		crypt_res = kmem_alloc((count * sizeof(struct crypt_result)),
    418 		    KM_SLEEP);
    419 		error = copyin(crypt_ret->results, crypt_res,
    420 		    (count * sizeof(struct crypt_result)));
    421 		if (error)
    422 			goto reterr;
    423 		crypt_ret->count = cryptodev_getmstatus(fcr, crypt_res,
    424 		    crypt_ret->count);
    425 		/* sanity check count */
    426 		if (crypt_ret->count > count) {
    427 			printf("%s.%d: error returned count %zd > original "
    428 			    " count %zd\n",
    429 			    __FILE__, __LINE__, crypt_ret->count, count);
    430 			crypt_ret->count = count;
    431 
    432 		}
    433 		error = copyout(crypt_res, crypt_ret->results,
    434 		    (crypt_ret->count * sizeof(struct crypt_result)));
    435 reterr:
    436 		kmem_free(crypt_res, (count * sizeof(struct crypt_result)));
    437 		break;
    438 	case CIOCNCRYPTRET:
    439 		error = cryptodev_getstatus(fcr, (struct crypt_result *)data);
    440 		break;
    441 	default:
    442 		/* Check for backward compatible commands */
    443 
    444 		MODULE_HOOK_CALL(ocryptof_50_hook, (fp, cmd, data),
    445 		    enosys(), error);
    446 		if (error == ENOSYS)
    447 			error = EINVAL;
    448 		return error;
    449 	}
    450 	return error;
    451 }
    452 
    453 int
    454 cryptodev_op(struct csession *cse, struct crypt_op *cop, struct lwp *l)
    455 {
    456 	struct cryptop *crp = NULL;
    457 	struct cryptodesc *crde = NULL, *crda = NULL, *crdc = NULL;
    458 	int error;
    459 	int iov_len = cop->len;
    460 	int flags=0;
    461 	int dst_len;	/* copyout size */
    462 
    463 	if (cop->len > 256*1024-4)
    464 		return E2BIG;
    465 
    466 	if (cse->txform) {
    467 		if (cop->len < cse->txform->blocksize
    468 		    + (cop->iv ? 0 : cse->txform->ivsize) ||
    469 		    (cop->len - (cop->iv ? 0 : cse->txform->ivsize))
    470 		    % cse->txform->blocksize != 0)
    471 			return EINVAL;
    472 	}
    473 
    474 	DPRINTF("cryptodev_op[%u]: iov_len %d\n",
    475 		CRYPTO_SESID2LID(cse->sid), iov_len);
    476 	if ((cse->tcomp) && cop->dst_len) {
    477 		if (iov_len < cop->dst_len) {
    478 			/* Need larger iov to deal with decompress */
    479 			iov_len = cop->dst_len;
    480 		}
    481 		DPRINTF("cryptodev_op: iov_len -> %d for decompress\n", iov_len);
    482 	}
    483 
    484 	(void)memset(&cse->uio, 0, sizeof(cse->uio));
    485 	cse->uio.uio_iovcnt = 1;
    486 	cse->uio.uio_resid = 0;
    487 	cse->uio.uio_rw = UIO_WRITE;
    488 	cse->uio.uio_iov = cse->iovec;
    489 	UIO_SETUP_SYSSPACE(&cse->uio);
    490 	memset(&cse->iovec, 0, sizeof(cse->iovec));
    491 
    492 	/* the iov needs to be big enough to handle the uncompressed
    493 	 * data.... */
    494 	cse->uio.uio_iov[0].iov_len = iov_len;
    495 	if (iov_len > 0)
    496 		cse->uio.uio_iov[0].iov_base = kmem_alloc(iov_len, KM_SLEEP);
    497 	cse->uio.uio_resid = cse->uio.uio_iov[0].iov_len;
    498 	DPRINTF("lid[%u]: uio.iov_base %p malloced %d bytes\n",
    499 		CRYPTO_SESID2LID(cse->sid),
    500 		cse->uio.uio_iov[0].iov_base, iov_len);
    501 
    502 	crp = crypto_getreq((cse->tcomp != NULL) + (cse->txform != NULL) + (cse->thash != NULL));
    503 	if (crp == NULL) {
    504 		error = ENOMEM;
    505 		goto bail;
    506 	}
    507 	DPRINTF("lid[%u]: crp %p\n", CRYPTO_SESID2LID(cse->sid), crp);
    508 
    509 	/* crds are always ordered tcomp, thash, then txform */
    510 	/* with optional missing links */
    511 
    512 	/* XXX: If we're going to compress then hash or encrypt, we need
    513 	 * to be able to pass on the new size of the data.
    514 	 */
    515 
    516 	if (cse->tcomp) {
    517 		crdc = crp->crp_desc;
    518 	}
    519 
    520 	if (cse->thash) {
    521 		crda = crdc ? crdc->crd_next : crp->crp_desc;
    522 		if (cse->txform && crda)
    523 			crde = crda->crd_next;
    524 	} else {
    525 		if (cse->txform) {
    526 			crde = crdc ? crdc->crd_next : crp->crp_desc;
    527 		} else if (!cse->tcomp) {
    528 			error = EINVAL;
    529 			goto bail;
    530 		}
    531 	}
    532 
    533 	DPRINTF("ocf[%u]: iov_len %zu, cop->len %u\n",
    534 			CRYPTO_SESID2LID(cse->sid),
    535 			cse->uio.uio_iov[0].iov_len,
    536 			cop->len);
    537 
    538 	if ((error = copyin(cop->src, cse->uio.uio_iov[0].iov_base, cop->len)))
    539 	{
    540 		printf("copyin failed %s %d \n", (char *)cop->src, error);
    541 		goto bail;
    542 	}
    543 
    544 	if (crdc) {
    545 		switch (cop->op) {
    546 		case COP_COMP:
    547 			crdc->crd_flags |= CRD_F_COMP;
    548 			break;
    549 		case COP_DECOMP:
    550 			crdc->crd_flags &= ~CRD_F_COMP;
    551 			break;
    552 		default:
    553 			break;
    554 		}
    555 		/* more data to follow? */
    556 		if (cop->flags & COP_F_MORE) {
    557 			flags |= CRYPTO_F_MORE;
    558 		}
    559 		crdc->crd_len = cop->len;
    560 		crdc->crd_inject = 0;
    561 
    562 		crdc->crd_alg = cse->comp_alg;
    563 		crdc->crd_key = NULL;
    564 		crdc->crd_klen = 0;
    565 		DPRINTF("lid[%u]: crdc setup for comp_alg %d.\n",
    566 			CRYPTO_SESID2LID(cse->sid), crdc->crd_alg);
    567 	}
    568 
    569 	if (crda) {
    570 		crda->crd_skip = 0;
    571 		crda->crd_len = cop->len;
    572 		crda->crd_inject = 0;	/* ??? */
    573 
    574 		crda->crd_alg = cse->mac;
    575 		crda->crd_key = cse->mackey;
    576 		crda->crd_klen = cse->mackeylen * 8;
    577 		DPRINTF("crda setup for mac %d.\n", crda->crd_alg);
    578 	}
    579 
    580 	if (crde) {
    581 		switch (cop->op) {
    582 		case COP_ENCRYPT:
    583 			crde->crd_flags |= CRD_F_ENCRYPT;
    584 			break;
    585 		case COP_DECRYPT:
    586 			crde->crd_flags &= ~CRD_F_ENCRYPT;
    587 			break;
    588 		default:
    589 			break;
    590 		}
    591 		crde->crd_len = cop->len;
    592 		crde->crd_inject = 0;
    593 
    594 		if (cse->cipher == CRYPTO_AES_GCM_16 && crda)
    595 			crda->crd_len = 0;
    596 		else if (cse->cipher == CRYPTO_AES_GMAC)
    597 			crde->crd_len = 0;
    598 
    599 		crde->crd_alg = cse->cipher;
    600 		crde->crd_key = cse->key;
    601 		crde->crd_klen = cse->keylen * 8;
    602 		DPRINTF("crde setup for cipher %d.\n", crde->crd_alg);
    603 	}
    604 
    605 
    606 	crp->crp_ilen = cop->len;
    607 	crp->crp_flags = CRYPTO_F_IOV | (cop->flags & COP_F_BATCH) | flags;
    608 	crp->crp_buf = (void *)&cse->uio;
    609 	crp->crp_callback = cryptodev_cb;
    610 	crp->crp_sid = cse->sid;
    611 	crp->crp_opaque = cse;
    612 
    613 	if (cop->iv) {
    614 		if (crde == NULL) {
    615 			error = EINVAL;
    616 			goto bail;
    617 		}
    618 		if (cse->txform->ivsize == 0) {
    619 			error = EINVAL;
    620 			goto bail;
    621 		}
    622 		if ((error = copyin(cop->iv, cse->tmp_iv,
    623 		    cse->txform->ivsize)))
    624 			goto bail;
    625 		(void)memcpy(crde->crd_iv, cse->tmp_iv, cse->txform->ivsize);
    626 		crde->crd_flags |= CRD_F_IV_EXPLICIT | CRD_F_IV_PRESENT;
    627 		crde->crd_skip = 0;
    628 	} else if (crde) {
    629 		if (cse->txform->ivsize == 0) {
    630 			crde->crd_skip = 0;
    631 		} else {
    632 			if (!(crde->crd_flags & CRD_F_ENCRYPT))
    633 				crde->crd_flags |= CRD_F_IV_PRESENT;
    634 			crde->crd_skip = cse->txform->ivsize;
    635 			crde->crd_len -= cse->txform->ivsize;
    636 		}
    637 	}
    638 
    639 	if (cop->mac) {
    640 		if (crda == NULL) {
    641 			error = EINVAL;
    642 			goto bail;
    643 		}
    644 		crp->crp_mac = cse->tmp_mac;
    645 	}
    646 
    647 	cv_init(&crp->crp_cv, "crydev");
    648 	error = crypto_dispatch(crp);
    649 	if (error) {
    650 		DPRINTF("not waiting, error.\n");
    651 		cv_destroy(&crp->crp_cv);
    652 		goto bail;
    653 	}
    654 
    655 	mutex_enter(&cryptodev_mtx);
    656 	while (!(crp->crp_devflags & CRYPTODEV_F_RET)) {
    657 		DPRINTF("cse->sid[%d]: sleeping on cv %p for crp %p\n",
    658 			(uint32_t)cse->sid, &crp->crp_cv, crp);
    659 		cv_wait(&crp->crp_cv, &cryptodev_mtx);	/* XXX cv_wait_sig? */
    660 	}
    661 	mutex_exit(&cryptodev_mtx);
    662 	cv_destroy(&crp->crp_cv);
    663 
    664 	if (crp->crp_etype != 0) {
    665 		DPRINTF("crp_etype %d\n", crp->crp_etype);
    666 		error = crp->crp_etype;
    667 		goto bail;
    668 	}
    669 
    670 	if (cse->error) {
    671 		DPRINTF("cse->error %d\n", cse->error);
    672 		error = cse->error;
    673 		goto bail;
    674 	}
    675 
    676 	dst_len = crp->crp_ilen;
    677 	/* let the user know how much data was returned */
    678 	if (crp->crp_olen) {
    679 		if (crp->crp_olen > (cop->dst_len ? cop->dst_len : cop->len)) {
    680 			error = ENOSPC;
    681 			goto bail;
    682 		}
    683 		dst_len = cop->dst_len = crp->crp_olen;
    684 	}
    685 
    686 	if (cop->dst) {
    687 		DPRINTF("copyout %d bytes to %p\n", dst_len, cop->dst);
    688 	}
    689 	if (cop->dst &&
    690 	    (error = copyout(cse->uio.uio_iov[0].iov_base, cop->dst, dst_len)))
    691 	{
    692 		DPRINTF("copyout error %d\n", error);
    693 		goto bail;
    694 	}
    695 
    696 	if (cop->mac &&
    697 	    (error = copyout(crp->crp_mac, cop->mac, cse->thash->authsize))) {
    698 		DPRINTF("mac copyout error %d\n", error);
    699 		goto bail;
    700 	}
    701 
    702 
    703 bail:
    704 	if (crp) {
    705 		crypto_freereq(crp);
    706 	}
    707 	if (cse->uio.uio_iov[0].iov_base) {
    708 		kmem_free(cse->uio.uio_iov[0].iov_base,iov_len);
    709 	}
    710 
    711 	return error;
    712 }
    713 
    714 static int
    715 cryptodev_cb(struct cryptop *crp)
    716 {
    717 	struct csession *cse = crp->crp_opaque;
    718 	int error = 0;
    719 
    720 	mutex_enter(&cryptodev_mtx);
    721 	cse->error = crp->crp_etype;
    722 	if (crp->crp_etype == EAGAIN) {
    723 		/* always drop mutex to call dispatch routine */
    724 		mutex_exit(&cryptodev_mtx);
    725 		error = crypto_dispatch(crp);
    726 		mutex_enter(&cryptodev_mtx);
    727 	}
    728 	if (error != 0 || (crp->crp_flags & CRYPTO_F_DONE)) {
    729 		crp->crp_devflags |= CRYPTODEV_F_RET;
    730 		cv_signal(&crp->crp_cv);
    731 	}
    732 	mutex_exit(&cryptodev_mtx);
    733 	return 0;
    734 }
    735 
    736 static int
    737 cryptodev_mcb(struct cryptop *crp)
    738 {
    739 	struct csession *cse = crp->crp_opaque;
    740 
    741 	mutex_enter(&cryptodev_mtx);
    742 	cse->error = crp->crp_etype;
    743 	if (crp->crp_etype == EAGAIN) {
    744 		mutex_exit(&cryptodev_mtx);
    745 		(void)crypto_dispatch(crp);
    746 		mutex_enter(&cryptodev_mtx);
    747 	}
    748 
    749 	TAILQ_INSERT_TAIL(&crp->fcrp->crp_ret_mq, crp, crp_next);
    750 	selnotify(&crp->fcrp->sinfo, 0, 0);
    751 	mutex_exit(&cryptodev_mtx);
    752 	return 0;
    753 }
    754 
    755 static int
    756 cryptodevkey_cb(struct cryptkop *krp)
    757 {
    758 
    759 	mutex_enter(&cryptodev_mtx);
    760 	krp->krp_devflags |= CRYPTODEV_F_RET;
    761 	cv_signal(&krp->krp_cv);
    762 	mutex_exit(&cryptodev_mtx);
    763 	return 0;
    764 }
    765 
    766 static int
    767 cryptodevkey_mcb(struct cryptkop *krp)
    768 {
    769 
    770 	mutex_enter(&cryptodev_mtx);
    771 	cv_signal(&krp->krp_cv);
    772 	TAILQ_INSERT_TAIL(&krp->fcrp->crp_ret_mkq, krp, krp_next);
    773 	selnotify(&krp->fcrp->sinfo, 0, 0);
    774 	mutex_exit(&cryptodev_mtx);
    775 	return 0;
    776 }
    777 
    778 static int
    779 cryptodev_key(struct crypt_kop *kop)
    780 {
    781 	struct cryptkop *krp = NULL;
    782 	int error = EINVAL;
    783 	int in, out, size, i;
    784 
    785 	if (kop->crk_iparams + kop->crk_oparams > CRK_MAXPARAM)
    786 		return EFBIG;
    787 
    788 	in = kop->crk_iparams;
    789 	out = kop->crk_oparams;
    790 	switch (kop->crk_op) {
    791 	case CRK_MOD_EXP:
    792 		if (in == 3 && out == 1)
    793 			break;
    794 		return EINVAL;
    795 	case CRK_MOD_EXP_CRT:
    796 		if (in == 6 && out == 1)
    797 			break;
    798 		return EINVAL;
    799 	case CRK_DSA_SIGN:
    800 		if (in == 5 && out == 2)
    801 			break;
    802 		return EINVAL;
    803 	case CRK_DSA_VERIFY:
    804 		if (in == 7 && out == 0)
    805 			break;
    806 		return EINVAL;
    807 	case CRK_DH_COMPUTE_KEY:
    808 		if (in == 3 && out == 1)
    809 			break;
    810 		return EINVAL;
    811 	case CRK_MOD_ADD:
    812 		if (in == 3 && out == 1)
    813 			break;
    814 		return EINVAL;
    815 	case CRK_MOD_ADDINV:
    816 		if (in == 2 && out == 1)
    817 			break;
    818 		return EINVAL;
    819 	case CRK_MOD_SUB:
    820 		if (in == 3 && out == 1)
    821 			break;
    822 		return EINVAL;
    823 	case CRK_MOD_MULT:
    824 		if (in == 3 && out == 1)
    825 			break;
    826 		return EINVAL;
    827 	case CRK_MOD_MULTINV:
    828 		if (in == 2 && out == 1)
    829 			break;
    830 		return EINVAL;
    831 	case CRK_MOD:
    832 		if (in == 2 && out == 1)
    833 			break;
    834 		return EINVAL;
    835 	default:
    836 		return EINVAL;
    837 	}
    838 
    839 	krp = crypto_kgetreq(1, PR_WAITOK);
    840 	if (krp == NULL) {
    841 		/* limited by opencrypto.crypto_ret_kq.maxlen */
    842 		return ENOMEM;
    843 	}
    844 	(void)memset(krp, 0, sizeof *krp);
    845 	cv_init(&krp->krp_cv, "crykdev");
    846 	krp->krp_op = kop->crk_op;
    847 	krp->krp_status = kop->crk_status;
    848 	krp->krp_iparams = kop->crk_iparams;
    849 	krp->krp_oparams = kop->crk_oparams;
    850 	krp->krp_status = 0;
    851 	krp->krp_callback = cryptodevkey_cb;
    852 
    853 	for (i = 0; i < CRK_MAXPARAM; i++)
    854 		krp->krp_param[i].crp_nbits = kop->crk_param[i].crp_nbits;
    855 	for (i = 0; i < krp->krp_iparams + krp->krp_oparams; i++) {
    856 		size = (krp->krp_param[i].crp_nbits + 7) / 8;
    857 		if (size == 0)
    858 			continue;
    859 		krp->krp_param[i].crp_p = kmem_alloc(size, KM_SLEEP);
    860 		if (i >= krp->krp_iparams)
    861 			continue;
    862 		error = copyin(kop->crk_param[i].crp_p,
    863 		    krp->krp_param[i].crp_p, size);
    864 		if (error)
    865 			goto fail;
    866 	}
    867 
    868 	error = crypto_kdispatch(krp);
    869 	if (error != 0) {
    870 		goto fail;
    871 	}
    872 
    873 	mutex_enter(&cryptodev_mtx);
    874 	while (!(krp->krp_devflags & CRYPTODEV_F_RET)) {
    875 		cv_wait(&krp->krp_cv, &cryptodev_mtx);	/* XXX cv_wait_sig? */
    876 	}
    877 	mutex_exit(&cryptodev_mtx);
    878 
    879 	if (krp->krp_status != 0) {
    880 		DPRINTF("krp->krp_status 0x%08x\n", krp->krp_status);
    881 		error = krp->krp_status;
    882 		goto fail;
    883 	}
    884 
    885 	for (i = krp->krp_iparams; i < krp->krp_iparams + krp->krp_oparams;
    886 	    i++) {
    887 		size = (krp->krp_param[i].crp_nbits + 7) / 8;
    888 		if (size == 0)
    889 			continue;
    890 		error = copyout(krp->krp_param[i].crp_p,
    891 		    kop->crk_param[i].crp_p, size);
    892 		if (error) {
    893 			DPRINTF("copyout oparam %d failed, "
    894 			    "error=%d\n", i-krp->krp_iparams, error);
    895 			goto fail;
    896 		}
    897 	}
    898 
    899 fail:
    900 	kop->crk_status = krp->krp_status;
    901 	for (i = 0; i < CRK_MAXPARAM; i++) {
    902 		struct crparam *kp = &(krp->krp_param[i]);
    903 		if (krp->krp_param[i].crp_p) {
    904 			size = (kp->crp_nbits + 7)  / 8;
    905 			KASSERT(size > 0);
    906 			(void)memset(kp->crp_p, 0, size);
    907 			kmem_free(kp->crp_p, size);
    908 		}
    909 	}
    910 	cv_destroy(&krp->krp_cv);
    911 	crypto_kfreereq(krp);
    912 	DPRINTF("error=0x%08x\n", error);
    913 	return error;
    914 }
    915 
    916 /* ARGSUSED */
    917 static int
    918 cryptof_close(struct file *fp)
    919 {
    920 	struct fcrypt *fcr = fp->f_fcrypt;
    921 	struct csession *cse;
    922 
    923 	mutex_enter(&cryptodev_mtx);
    924 	while ((cse = TAILQ_FIRST(&fcr->csessions))) {
    925 		TAILQ_REMOVE(&fcr->csessions, cse, next);
    926 		mutex_exit(&cryptodev_mtx);
    927 		(void)csefree(cse);
    928 		mutex_enter(&cryptodev_mtx);
    929 	}
    930 	seldestroy(&fcr->sinfo);
    931 	fp->f_fcrypt = NULL;
    932 	crypto_refcount--;
    933 	mutex_exit(&cryptodev_mtx);
    934 
    935 	pool_put(&fcrpl, fcr);
    936 	return 0;
    937 }
    938 
    939 /* needed for compatibility module */
    940 struct	csession *cryptodev_csefind(struct fcrypt *fcr, u_int ses)
    941 {
    942 	return csefind(fcr, ses);
    943 }
    944 
    945 /* csefind: call with cryptodev_mtx held. */
    946 static struct csession *
    947 csefind(struct fcrypt *fcr, u_int ses)
    948 {
    949 	struct csession *cse, *cnext, *ret = NULL;
    950 
    951 	KASSERT(mutex_owned(&cryptodev_mtx));
    952 	TAILQ_FOREACH_SAFE(cse, &fcr->csessions, next, cnext)
    953 		if (cse->ses == ses)
    954 			ret = cse;
    955 
    956 	return ret;
    957 }
    958 
    959 /* csedelete: call with cryptodev_mtx held. */
    960 static int
    961 csedelete(struct fcrypt *fcr, struct csession *cse_del)
    962 {
    963 	struct csession *cse, *cnext;
    964 	int ret = 0;
    965 
    966 	KASSERT(mutex_owned(&cryptodev_mtx));
    967 	TAILQ_FOREACH_SAFE(cse, &fcr->csessions, next, cnext) {
    968 		if (cse == cse_del) {
    969 			TAILQ_REMOVE(&fcr->csessions, cse, next);
    970 			ret = 1;
    971 		}
    972 	}
    973 	return ret;
    974 }
    975 
    976 static struct csession *
    977 cseadd(struct fcrypt *fcr, struct csession *cse)
    978 {
    979 	mutex_enter(&cryptodev_mtx);
    980 	/* don't let session ID wrap! */
    981 	if (fcr->sesn + 1 == 0) return NULL;
    982 	TAILQ_INSERT_TAIL(&fcr->csessions, cse, next);
    983 	cse->ses = fcr->sesn++;
    984 	mutex_exit(&cryptodev_mtx);
    985 	return cse;
    986 }
    987 
    988 static struct csession *
    989 csecreate(struct fcrypt *fcr, u_int64_t sid, void *key, u_int64_t keylen,
    990     void *mackey, u_int64_t mackeylen, u_int32_t cipher, u_int32_t mac,
    991     u_int32_t comp_alg, const struct enc_xform *txform,
    992     const struct auth_hash *thash, const struct comp_algo *tcomp)
    993 {
    994 	struct csession *cse;
    995 
    996 	cse = pool_get(&csepl, PR_NOWAIT);
    997 	if (cse == NULL)
    998 		return NULL;
    999 	cse->key = key;
   1000 	cse->keylen = keylen/8;
   1001 	cse->mackey = mackey;
   1002 	cse->mackeylen = mackeylen/8;
   1003 	cse->sid = sid;
   1004 	cse->cipher = cipher;
   1005 	cse->mac = mac;
   1006 	cse->comp_alg = comp_alg;
   1007 	cse->txform = txform;
   1008 	cse->thash = thash;
   1009 	cse->tcomp = tcomp;
   1010 	cse->error = 0;
   1011 	if (cseadd(fcr, cse))
   1012 		return cse;
   1013 	else {
   1014 		pool_put(&csepl, cse);
   1015 		return NULL;
   1016 	}
   1017 }
   1018 
   1019 static int
   1020 csefree(struct csession *cse)
   1021 {
   1022 	int error;
   1023 
   1024 	error = crypto_freesession(cse->sid);
   1025 	if (cse->key)
   1026 		free(cse->key, M_XDATA);
   1027 	if (cse->mackey)
   1028 		free(cse->mackey, M_XDATA);
   1029 	pool_put(&csepl, cse);
   1030 	return error;
   1031 }
   1032 
   1033 static int
   1034 cryptoopen(dev_t dev, int flag, int mode,
   1035     struct lwp *l)
   1036 {
   1037 	file_t *fp;
   1038         struct fcrypt *fcr;
   1039         int fd, error;
   1040 
   1041 	if (crypto_usercrypto == 0)
   1042 		return ENXIO;
   1043 
   1044 	if ((error = fd_allocfile(&fp, &fd)) != 0)
   1045 		return error;
   1046 
   1047 	fcr = pool_get(&fcrpl, PR_WAITOK);
   1048 	getnanotime(&fcr->btime);
   1049 	fcr->atime = fcr->mtime = fcr->btime;
   1050 	mutex_enter(&cryptodev_mtx);
   1051 	TAILQ_INIT(&fcr->csessions);
   1052 	TAILQ_INIT(&fcr->crp_ret_mq);
   1053 	TAILQ_INIT(&fcr->crp_ret_mkq);
   1054 	selinit(&fcr->sinfo);
   1055 	/*
   1056 	 * Don't ever return session 0, to allow detection of
   1057 	 * failed creation attempts with multi-create ioctl.
   1058 	 */
   1059 	fcr->sesn = 1;
   1060 	fcr->requestid = 1;
   1061 	crypto_refcount++;
   1062 	mutex_exit(&cryptodev_mtx);
   1063 	return fd_clone(fp, fd, flag, &cryptofops, fcr);
   1064 }
   1065 
   1066 static int
   1067 cryptoread(dev_t dev, struct uio *uio, int ioflag)
   1068 {
   1069 	return EIO;
   1070 }
   1071 
   1072 static int
   1073 cryptowrite(dev_t dev, struct uio *uio, int ioflag)
   1074 {
   1075 	return EIO;
   1076 }
   1077 
   1078 int
   1079 cryptoselect(dev_t dev, int rw, struct lwp *l)
   1080 {
   1081 	return 0;
   1082 }
   1083 
   1084 /*static*/
   1085 struct cdevsw crypto_cdevsw = {
   1086 	.d_open = cryptoopen,
   1087 	.d_close = noclose,
   1088 	.d_read = cryptoread,
   1089 	.d_write = cryptowrite,
   1090 	.d_ioctl = noioctl,
   1091 	.d_stop = nostop,
   1092 	.d_tty = notty,
   1093 	.d_poll = cryptoselect /*nopoll*/,
   1094 	.d_mmap = nommap,
   1095 	.d_kqfilter = nokqfilter,
   1096 	.d_discard = nodiscard,
   1097 	.d_flag = D_OTHER
   1098 };
   1099 
   1100 int
   1101 cryptodev_mop(struct fcrypt *fcr,
   1102               struct crypt_n_op * cnop,
   1103               int count, struct lwp *l)
   1104 {
   1105 	struct cryptop *crp = NULL;
   1106 	struct cryptodesc *crde = NULL, *crda = NULL, *crdc = NULL;
   1107 	int req, error=0;
   1108 	struct csession *cse;
   1109 	int flags=0;
   1110 	int iov_len;
   1111 
   1112 	for (req = 0; req < count; req++) {
   1113 		mutex_enter(&cryptodev_mtx);
   1114 		cse = csefind(fcr, cnop[req].ses);
   1115 		if (cse == NULL) {
   1116 			DPRINTF("csefind failed\n");
   1117 			cnop[req].status = EINVAL;
   1118 			mutex_exit(&cryptodev_mtx);
   1119 			continue;
   1120 		}
   1121 		mutex_exit(&cryptodev_mtx);
   1122 
   1123 		if (cnop[req].len > 256*1024-4) {
   1124 			DPRINTF("length failed\n");
   1125 			cnop[req].status = EINVAL;
   1126 			continue;
   1127 		}
   1128 		if (cse->txform) {
   1129 			if (cnop[req].len < cse->txform->blocksize -
   1130 			    (cnop[req].iv ? 0 : cse->txform->ivsize) ||
   1131 			    (cnop[req].len -
   1132 			     (cnop[req].iv ? 0 : cse->txform->ivsize))
   1133 			    % cse->txform->blocksize) {
   1134 				cnop[req].status = EINVAL;
   1135 				continue;
   1136 			}
   1137 		}
   1138 
   1139 		/* sanitize */
   1140 		if (cnop[req].len <= 0) {
   1141 			cnop[req].status = ENOMEM;
   1142 			goto bail;
   1143 		}
   1144 
   1145 		crp = crypto_getreq((cse->txform != NULL) +
   1146 				    (cse->thash != NULL) +
   1147 				    (cse->tcomp != NULL));
   1148 		if (crp == NULL) {
   1149 			cnop[req].status = ENOMEM;
   1150 			goto bail;
   1151 		}
   1152 
   1153 		iov_len = cnop[req].len;
   1154 		/* got a compression/decompression max size? */
   1155 		if ((cse->tcomp) && cnop[req].dst_len) {
   1156 			if (iov_len < cnop[req].dst_len) {
   1157 				/* Need larger iov to deal with decompress */
   1158 				iov_len = cnop[req].dst_len;
   1159 			}
   1160 			DPRINTF("iov_len -> %d for decompress\n", iov_len);
   1161 		}
   1162 
   1163 		(void)memset(&crp->uio, 0, sizeof(crp->uio));
   1164 		crp->uio.uio_iovcnt = 1;
   1165 		crp->uio.uio_resid = 0;
   1166 		crp->uio.uio_rw = UIO_WRITE;
   1167 		crp->uio.uio_iov = crp->iovec;
   1168 		UIO_SETUP_SYSSPACE(&crp->uio);
   1169 		memset(&crp->iovec, 0, sizeof(crp->iovec));
   1170 		crp->uio.uio_iov[0].iov_len = iov_len;
   1171 		DPRINTF("kmem_alloc(%d) for iov \n", iov_len);
   1172 		crp->uio.uio_iov[0].iov_base = kmem_alloc(iov_len, KM_SLEEP);
   1173 		crp->uio.uio_resid = crp->uio.uio_iov[0].iov_len;
   1174 
   1175 		if (cse->tcomp) {
   1176 			crdc = crp->crp_desc;
   1177 		}
   1178 
   1179 		if (cse->thash) {
   1180 			crda = crdc ? crdc->crd_next : crp->crp_desc;
   1181 			if (cse->txform && crda)
   1182 				crde = crda->crd_next;
   1183 		} else {
   1184 			if (cse->txform) {
   1185 				crde = crdc ? crdc->crd_next : crp->crp_desc;
   1186 			} else if (!cse->tcomp) {
   1187 				error = EINVAL;
   1188 				goto bail;
   1189 			}
   1190 		}
   1191 
   1192 		if ((copyin(cnop[req].src,
   1193 		    crp->uio.uio_iov[0].iov_base, cnop[req].len))) {
   1194 			cnop[req].status = EINVAL;
   1195 			goto bail;
   1196 		}
   1197 
   1198 		if (crdc) {
   1199 			switch (cnop[req].op) {
   1200 			case COP_COMP:
   1201 				crdc->crd_flags |= CRD_F_COMP;
   1202 				break;
   1203 			case COP_DECOMP:
   1204 				crdc->crd_flags &= ~CRD_F_COMP;
   1205 				break;
   1206 			default:
   1207 				break;
   1208 			}
   1209 			/* more data to follow? */
   1210 			if (cnop[req].flags & COP_F_MORE) {
   1211 				flags |= CRYPTO_F_MORE;
   1212 			}
   1213 			crdc->crd_len = cnop[req].len;
   1214 			crdc->crd_inject = 0;
   1215 
   1216 			crdc->crd_alg = cse->comp_alg;
   1217 			crdc->crd_key = NULL;
   1218 			crdc->crd_klen = 0;
   1219 			DPRINTF("cse->sid[%d]: crdc setup for comp_alg %d"
   1220 				 " len %d.\n",
   1221 				(uint32_t)cse->sid, crdc->crd_alg,
   1222 				crdc->crd_len);
   1223 		}
   1224 
   1225 		if (crda) {
   1226 			crda->crd_skip = 0;
   1227 			crda->crd_len = cnop[req].len;
   1228 			crda->crd_inject = 0;	/* ??? */
   1229 
   1230 			crda->crd_alg = cse->mac;
   1231 			crda->crd_key = cse->mackey;
   1232 			crda->crd_klen = cse->mackeylen * 8;
   1233 		}
   1234 
   1235 		if (crde) {
   1236 			if (cnop[req].op == COP_ENCRYPT)
   1237 				crde->crd_flags |= CRD_F_ENCRYPT;
   1238 			else
   1239 				crde->crd_flags &= ~CRD_F_ENCRYPT;
   1240 			crde->crd_len = cnop[req].len;
   1241 			crde->crd_inject = 0;
   1242 
   1243 			crde->crd_alg = cse->cipher;
   1244 #ifdef notyet		/* XXX must notify h/w driver new key, drain */
   1245 			if(cnop[req].key && cnop[req].keylen) {
   1246 				crde->crd_key = malloc(cnop[req].keylen,
   1247 						    M_XDATA, M_WAITOK);
   1248 				if((error = copyin(cnop[req].key,
   1249 				    crde->crd_key, cnop[req].keylen))) {
   1250 					cnop[req].status = EINVAL;
   1251 					goto bail;
   1252 				}
   1253 				crde->crd_klen =  cnop[req].keylen * 8;
   1254 			} else { ... }
   1255 #endif
   1256 			crde->crd_key = cse->key;
   1257 			crde->crd_klen = cse->keylen * 8;
   1258 		}
   1259 
   1260 		crp->crp_ilen = cnop[req].len;
   1261 		crp->crp_flags = CRYPTO_F_IOV |
   1262 		    (cnop[req].flags & COP_F_BATCH) | flags;
   1263 		crp->crp_buf = (void *)&crp->uio;
   1264 		crp->crp_callback = cryptodev_mcb;
   1265 		crp->crp_sid = cse->sid;
   1266 		crp->crp_opaque = cse;
   1267 		crp->fcrp = fcr;
   1268 		crp->dst = cnop[req].dst;
   1269 		crp->len = cnop[req].len; /* input len, iov may be larger */
   1270 		crp->mac = cnop[req].mac;
   1271 		DPRINTF("iov_base %p dst %p len %d mac %p\n",
   1272 			    crp->uio.uio_iov[0].iov_base, crp->dst, crp->len,
   1273 			    crp->mac);
   1274 
   1275 		if (cnop[req].iv) {
   1276 			if (crde == NULL) {
   1277 				cnop[req].status = EINVAL;
   1278 				goto bail;
   1279 			}
   1280 			if (cse->cipher == CRYPTO_ARC4) { /* XXX use flag? */
   1281 				cnop[req].status = EINVAL;
   1282 				goto bail;
   1283 			}
   1284 			if ((error = copyin(cnop[req].iv, crp->tmp_iv,
   1285 			    cse->txform->ivsize))) {
   1286 				cnop[req].status = EINVAL;
   1287 				goto bail;
   1288 			}
   1289 			(void)memcpy(crde->crd_iv, crp->tmp_iv,
   1290 			    cse->txform->ivsize);
   1291 			crde->crd_flags |= CRD_F_IV_EXPLICIT | CRD_F_IV_PRESENT;
   1292 			crde->crd_skip = 0;
   1293 		} else if (crde) {
   1294 			if (cse->cipher == CRYPTO_ARC4) { /* XXX use flag? */
   1295 				crde->crd_skip = 0;
   1296 			} else {
   1297 				if (!(crde->crd_flags & CRD_F_ENCRYPT))
   1298 					crde->crd_flags |= CRD_F_IV_PRESENT;
   1299 				crde->crd_skip = cse->txform->ivsize;
   1300 				crde->crd_len -= cse->txform->ivsize;
   1301 			}
   1302 		}
   1303 
   1304 		if (cnop[req].mac) {
   1305 			if (crda == NULL) {
   1306 				cnop[req].status = EINVAL;
   1307 				goto bail;
   1308 			}
   1309 			crp->crp_mac=cse->tmp_mac;
   1310 		}
   1311 		cnop[req].reqid = atomic_inc_32_nv(&(fcr->requestid));
   1312 		crp->crp_reqid = cnop[req].reqid;
   1313 		crp->crp_usropaque = cnop[req].opaque;
   1314 		cv_init(&crp->crp_cv, "crydev");
   1315 #ifdef notyet
   1316 eagain:
   1317 #endif
   1318 		cnop[req].status = crypto_dispatch(crp);
   1319 		mutex_enter(&cryptodev_mtx);	/* XXX why mutex? */
   1320 
   1321 		switch (cnop[req].status) {
   1322 #ifdef notyet	/* don't loop forever -- but EAGAIN not possible here yet */
   1323 		case EAGAIN:
   1324 			mutex_exit(&cryptodev_mtx);
   1325 			goto eagain;
   1326 			break;
   1327 #endif
   1328 		case 0:
   1329 			break;
   1330 		default:
   1331 			DPRINTF("not waiting, error.\n");
   1332 			mutex_exit(&cryptodev_mtx);
   1333 			cv_destroy(&crp->crp_cv);
   1334 			goto bail;
   1335 		}
   1336 
   1337 		mutex_exit(&cryptodev_mtx);
   1338 		cv_destroy(&crp->crp_cv);
   1339 bail:
   1340 		if (cnop[req].status) {
   1341 			if (crp) {
   1342 				if (crp->uio.uio_iov[0].iov_base) {
   1343 					kmem_free(crp->uio.uio_iov[0].iov_base,
   1344 					    crp->uio.uio_iov[0].iov_len);
   1345 				}
   1346 				crypto_freereq(crp);
   1347 			}
   1348 			error = 0;
   1349 		}
   1350 	}
   1351 	return error;
   1352 }
   1353 
   1354 static int
   1355 cryptodev_mkey(struct fcrypt *fcr, struct crypt_n_kop *kop, int count)
   1356 {
   1357 	struct cryptkop *krp = NULL;
   1358 	int error = EINVAL;
   1359 	int in, out, size, i, req;
   1360 
   1361 	for (req = 0; req < count; req++) {
   1362 		if (kop[req].crk_iparams + kop[req].crk_oparams > CRK_MAXPARAM)
   1363 			return EFBIG;
   1364 
   1365 		in = kop[req].crk_iparams;
   1366 		out = kop[req].crk_oparams;
   1367 		switch (kop[req].crk_op) {
   1368 		case CRK_MOD_EXP:
   1369 			if (in == 3 && out == 1)
   1370 				break;
   1371 			kop[req].crk_status = EINVAL;
   1372 			continue;
   1373 		case CRK_MOD_EXP_CRT:
   1374 			if (in == 6 && out == 1)
   1375 				break;
   1376 			kop[req].crk_status = EINVAL;
   1377 			continue;
   1378 		case CRK_DSA_SIGN:
   1379 			if (in == 5 && out == 2)
   1380 				break;
   1381 			kop[req].crk_status = EINVAL;
   1382 			continue;
   1383 		case CRK_DSA_VERIFY:
   1384 			if (in == 7 && out == 0)
   1385 				break;
   1386 			kop[req].crk_status = EINVAL;
   1387 			continue;
   1388 		case CRK_DH_COMPUTE_KEY:
   1389 			if (in == 3 && out == 1)
   1390 				break;
   1391 			kop[req].crk_status = EINVAL;
   1392 			continue;
   1393 		case CRK_MOD_ADD:
   1394 			if (in == 3 && out == 1)
   1395 				break;
   1396 			kop[req].crk_status = EINVAL;
   1397 			continue;
   1398 		case CRK_MOD_ADDINV:
   1399 			if (in == 2 && out == 1)
   1400 				break;
   1401 			kop[req].crk_status = EINVAL;
   1402 			continue;
   1403 		case CRK_MOD_SUB:
   1404 			if (in == 3 && out == 1)
   1405 				break;
   1406 			kop[req].crk_status = EINVAL;
   1407 			continue;
   1408 		case CRK_MOD_MULT:
   1409 			if (in == 3 && out == 1)
   1410 				break;
   1411 			kop[req].crk_status = EINVAL;
   1412 			continue;
   1413 		case CRK_MOD_MULTINV:
   1414 			if (in == 2 && out == 1)
   1415 				break;
   1416 			kop[req].crk_status = EINVAL;
   1417 			continue;
   1418 		case CRK_MOD:
   1419 			if (in == 2 && out == 1)
   1420 				break;
   1421 			kop[req].crk_status = EINVAL;
   1422 			continue;
   1423 		default:
   1424 			kop[req].crk_status = EINVAL;
   1425 			continue;
   1426 		}
   1427 
   1428 		krp = crypto_kgetreq(1, PR_WAITOK);
   1429 		if (krp == NULL) {
   1430 			/* limited by opencrypto.crypto_ret_kq.maxlen */
   1431 			continue;
   1432 		}
   1433 		(void)memset(krp, 0, sizeof *krp);
   1434 		cv_init(&krp->krp_cv, "crykdev");
   1435 		krp->krp_op = kop[req].crk_op;
   1436 		krp->krp_status = kop[req].crk_status;
   1437 		krp->krp_iparams = kop[req].crk_iparams;
   1438 		krp->krp_oparams = kop[req].crk_oparams;
   1439 		krp->krp_status = 0;
   1440 		krp->krp_callback = cryptodevkey_mcb;
   1441 		(void)memcpy(krp->crk_param, kop[req].crk_param,
   1442 		    sizeof(kop[req].crk_param));
   1443 
   1444 		krp->krp_flags = 0;
   1445 
   1446 		for (i = 0; i < CRK_MAXPARAM; i++)
   1447 			krp->krp_param[i].crp_nbits =
   1448 			    kop[req].crk_param[i].crp_nbits;
   1449 		for (i = 0; i < krp->krp_iparams + krp->krp_oparams; i++) {
   1450 			size = (krp->krp_param[i].crp_nbits + 7) / 8;
   1451 			if (size == 0)
   1452 				continue;
   1453 			krp->krp_param[i].crp_p =
   1454 			    kmem_alloc(size, KM_SLEEP);
   1455 			if (i >= krp->krp_iparams)
   1456 				continue;
   1457 			kop[req].crk_status =
   1458 			    copyin(kop[req].crk_param[i].crp_p,
   1459 			    krp->krp_param[i].crp_p, size);
   1460 			if (kop[req].crk_status)
   1461 				goto fail;
   1462 		}
   1463 		krp->fcrp = fcr;
   1464 
   1465 		kop[req].crk_reqid = atomic_inc_32_nv(&(fcr->requestid));
   1466 		krp->krp_reqid = kop[req].crk_reqid;
   1467 		krp->krp_usropaque = kop[req].crk_opaque;
   1468 
   1469 		kop[req].crk_status = crypto_kdispatch(krp);
   1470 		if (kop[req].crk_status != 0) {
   1471 			goto fail;
   1472 		}
   1473 
   1474 fail:
   1475 		if(kop[req].crk_status) {
   1476 			if (krp) {
   1477 				kop[req].crk_status = krp->krp_status;
   1478 				for (i = 0; i < CRK_MAXPARAM; i++) {
   1479 					struct crparam *kp =
   1480 						&(krp->krp_param[i]);
   1481 					if (kp->crp_p) {
   1482 						size = (kp->crp_nbits + 7) / 8;
   1483 						KASSERT(size > 0);
   1484 						memset(kp->crp_p, 0, size);
   1485 						kmem_free(kp->crp_p, size);
   1486 					}
   1487 				}
   1488 				cv_destroy(&krp->krp_cv);
   1489 				crypto_kfreereq(krp);
   1490 			}
   1491 		}
   1492 		error = 0;
   1493 	}
   1494 	DPRINTF("error=0x%08x\n", error);
   1495 	return error;
   1496 }
   1497 
   1498 int
   1499 cryptodev_session(struct fcrypt *fcr, struct session_op *sop)
   1500 {
   1501 	struct cryptoini cria, crie;
   1502 	struct cryptoini cric;		/* compressor */
   1503 	struct cryptoini *crihead = NULL;
   1504 	const struct enc_xform *txform = NULL;
   1505 	const struct auth_hash *thash = NULL;
   1506 	const struct comp_algo *tcomp = NULL;
   1507 	struct csession *cse;
   1508 	u_int64_t sid;
   1509 	int error = 0;
   1510 
   1511 	DPRINTF("cipher=%d, mac=%d\n", sop->cipher, sop->mac);
   1512 
   1513 	/* XXX there must be a way to not embed the list of xforms here */
   1514 	switch (sop->cipher) {
   1515 	case 0:
   1516 		break;
   1517 	case CRYPTO_DES_CBC:
   1518 		txform = &enc_xform_des;
   1519 		break;
   1520 	case CRYPTO_3DES_CBC:
   1521 		txform = &enc_xform_3des;
   1522 		break;
   1523 	case CRYPTO_BLF_CBC:
   1524 		txform = &enc_xform_blf;
   1525 		break;
   1526 	case CRYPTO_CAST_CBC:
   1527 		txform = &enc_xform_cast5;
   1528 		break;
   1529 	case CRYPTO_SKIPJACK_CBC:
   1530 		txform = &enc_xform_skipjack;
   1531 		break;
   1532 	case CRYPTO_AES_CBC:
   1533 		txform = &enc_xform_aes;
   1534 		break;
   1535 	case CRYPTO_CAMELLIA_CBC:
   1536 		txform = &enc_xform_camellia;
   1537 		break;
   1538 	case CRYPTO_AES_CTR:
   1539 		txform = &enc_xform_aes_ctr;
   1540 		break;
   1541 	case CRYPTO_AES_GCM_16:
   1542 		txform = &enc_xform_aes_gcm;
   1543 		break;
   1544 	case CRYPTO_AES_GMAC:
   1545 		txform = &enc_xform_aes_gmac;
   1546 		break;
   1547 	case CRYPTO_NULL_CBC:
   1548 		txform = &enc_xform_null;
   1549 		break;
   1550 	case CRYPTO_ARC4:
   1551 		txform = &enc_xform_arc4;
   1552 		break;
   1553 	default:
   1554 		DPRINTF("Invalid cipher %d\n", sop->cipher);
   1555 		return EINVAL;
   1556 	}
   1557 
   1558 	switch (sop->comp_alg) {
   1559 	case 0:
   1560 		break;
   1561 	case CRYPTO_DEFLATE_COMP:
   1562 		tcomp = &comp_algo_deflate;
   1563 		break;
   1564 	case CRYPTO_GZIP_COMP:
   1565 		tcomp = &comp_algo_gzip;
   1566 		DPRINTF("tcomp for GZIP\n");
   1567 		break;
   1568 	default:
   1569 		DPRINTF("Invalid compression alg %d\n", sop->comp_alg);
   1570 		return EINVAL;
   1571 	}
   1572 
   1573 	switch (sop->mac) {
   1574 	case 0:
   1575 		break;
   1576 	case CRYPTO_MD5_HMAC:
   1577 		thash = &auth_hash_hmac_md5;
   1578 		break;
   1579 	case CRYPTO_SHA1_HMAC:
   1580 		thash = &auth_hash_hmac_sha1;
   1581 		break;
   1582 	case CRYPTO_MD5_HMAC_96:
   1583 		thash = &auth_hash_hmac_md5_96;
   1584 		break;
   1585 	case CRYPTO_SHA1_HMAC_96:
   1586 		thash = &auth_hash_hmac_sha1_96;
   1587 		break;
   1588 	case CRYPTO_SHA2_HMAC:
   1589 		/* XXX switching on key length seems questionable */
   1590 		if (sop->mackeylen == auth_hash_hmac_sha2_256.keysize) {
   1591 			thash = &auth_hash_hmac_sha2_256;
   1592 		} else if (sop->mackeylen == auth_hash_hmac_sha2_384.keysize) {
   1593 			thash = &auth_hash_hmac_sha2_384;
   1594 		} else if (sop->mackeylen == auth_hash_hmac_sha2_512.keysize) {
   1595 			thash = &auth_hash_hmac_sha2_512;
   1596 		} else {
   1597 			DPRINTF("Invalid mackeylen %d\n", sop->mackeylen);
   1598 			return EINVAL;
   1599 		}
   1600 		break;
   1601 	case CRYPTO_SHA2_384_HMAC:
   1602 		thash = &auth_hash_hmac_sha2_384;
   1603 		break;
   1604 	case CRYPTO_SHA2_512_HMAC:
   1605 		thash = &auth_hash_hmac_sha2_512;
   1606 		break;
   1607 	case CRYPTO_RIPEMD160_HMAC:
   1608 		thash = &auth_hash_hmac_ripemd_160;
   1609 		break;
   1610 	case CRYPTO_RIPEMD160_HMAC_96:
   1611 		thash = &auth_hash_hmac_ripemd_160_96;
   1612 		break;
   1613 	case CRYPTO_MD5:
   1614 		thash = &auth_hash_md5;
   1615 		break;
   1616 	case CRYPTO_SHA1:
   1617 		thash = &auth_hash_sha1;
   1618 		break;
   1619 	case CRYPTO_AES_XCBC_MAC_96:
   1620 		thash = &auth_hash_aes_xcbc_mac_96;
   1621 		break;
   1622 	case CRYPTO_AES_128_GMAC:
   1623 		thash = &auth_hash_gmac_aes_128;
   1624 		break;
   1625 	case CRYPTO_AES_192_GMAC:
   1626 		thash = &auth_hash_gmac_aes_192;
   1627 		break;
   1628 	case CRYPTO_AES_256_GMAC:
   1629 		thash = &auth_hash_gmac_aes_256;
   1630 		break;
   1631 	case CRYPTO_NULL_HMAC:
   1632 		thash = &auth_hash_null;
   1633 		break;
   1634 	default:
   1635 		DPRINTF("Invalid mac %d\n", sop->mac);
   1636 		return EINVAL;
   1637 	}
   1638 
   1639 	memset(&crie, 0, sizeof(crie));
   1640 	memset(&cria, 0, sizeof(cria));
   1641 	memset(&cric, 0, sizeof(cric));
   1642 
   1643 	if (tcomp) {
   1644 		cric.cri_alg = tcomp->type;
   1645 		cric.cri_klen = 0;
   1646 		DPRINTF("tcomp->type = %d\n", tcomp->type);
   1647 
   1648 		crihead = &cric;
   1649 		if (txform) {
   1650 			cric.cri_next = &crie;
   1651 		} else if (thash) {
   1652 			cric.cri_next = &cria;
   1653 		}
   1654 	}
   1655 
   1656 	if (txform) {
   1657 		crie.cri_alg = txform->type;
   1658 		crie.cri_klen = sop->keylen * 8;
   1659 		if (sop->keylen > txform->maxkey ||
   1660 		    sop->keylen < txform->minkey) {
   1661 			DPRINTF("keylen %d not in [%d,%d]\n",
   1662 			    sop->keylen, txform->minkey, txform->maxkey);
   1663 			error = EINVAL;
   1664 			goto bail;
   1665 		}
   1666 
   1667 		crie.cri_key = malloc(crie.cri_klen / 8, M_XDATA, M_WAITOK);
   1668 		if ((error = copyin(sop->key, crie.cri_key, crie.cri_klen / 8)))
   1669 			goto bail;
   1670 		if (!crihead) {
   1671 			crihead = &crie;
   1672 		}
   1673 		if (thash)
   1674 			crie.cri_next = &cria;
   1675 	}
   1676 
   1677 	if (thash) {
   1678 		cria.cri_alg = thash->type;
   1679 		cria.cri_klen = sop->mackeylen * 8;
   1680 		if (sop->mackeylen != thash->keysize) {
   1681 			DPRINTF("mackeylen %d != keysize %d\n",
   1682 			    sop->mackeylen, thash->keysize);
   1683 			error = EINVAL;
   1684 			goto bail;
   1685 		}
   1686 		if (cria.cri_klen) {
   1687 			cria.cri_key = malloc(cria.cri_klen / 8, M_XDATA,
   1688 			    M_WAITOK);
   1689 			if ((error = copyin(sop->mackey, cria.cri_key,
   1690 			    cria.cri_klen / 8))) {
   1691 				goto bail;
   1692 			}
   1693 		}
   1694 		if (!crihead) {
   1695 			crihead = &cria;
   1696 		}
   1697 	}
   1698 
   1699 	error = crypto_newsession(&sid, crihead, crypto_devallowsoft);
   1700 	if (!error) {
   1701 		DPRINTF("got session %d\n", (uint32_t)sid);
   1702 		cse = csecreate(fcr, sid, crie.cri_key, crie.cri_klen,
   1703 		    cria.cri_key, cria.cri_klen, (txform ? sop->cipher : 0), sop->mac,
   1704 		    (tcomp ? sop->comp_alg : 0), txform, thash, tcomp);
   1705 		if (cse != NULL) {
   1706 			sop->ses = cse->ses;
   1707 		} else {
   1708 			DPRINTF("csecreate failed\n");
   1709 			crypto_freesession(sid);
   1710 			error = EINVAL;
   1711 		}
   1712 	} else {
   1713 		DPRINTF("SIOCSESSION violates kernel parameters %d\n", error);
   1714 	}
   1715 bail:
   1716 	if (error) {
   1717 		if (crie.cri_key) {
   1718 			memset(crie.cri_key, 0, crie.cri_klen / 8);
   1719 			free(crie.cri_key, M_XDATA);
   1720 		}
   1721 		if (cria.cri_key) {
   1722 			memset(cria.cri_key, 0, cria.cri_klen / 8);
   1723 			free(cria.cri_key, M_XDATA);
   1724 		}
   1725 	}
   1726 	return error;
   1727 }
   1728 
   1729 int
   1730 cryptodev_msession(struct fcrypt *fcr, struct session_n_op *sn_ops,
   1731 		   int count)
   1732 {
   1733 	int i;
   1734 
   1735 	for (i = 0; i < count; i++, sn_ops++) {
   1736 		struct session_op s_op;
   1737 		s_op.cipher =		sn_ops->cipher;
   1738 		s_op.mac =		sn_ops->mac;
   1739 		s_op.comp_alg =		sn_ops->comp_alg;
   1740 		s_op.keylen =		sn_ops->keylen;
   1741 		s_op.key =		sn_ops->key;
   1742 		s_op.mackeylen =	sn_ops->mackeylen;
   1743 		s_op.mackey =		sn_ops->mackey;
   1744 		s_op.ses =		~0;
   1745 
   1746 		sn_ops->status = cryptodev_session(fcr, &s_op);
   1747 
   1748 		sn_ops->ses =		s_op.ses;
   1749 	}
   1750 
   1751 	return 0;
   1752 }
   1753 
   1754 static int
   1755 cryptodev_msessionfin(struct fcrypt *fcr, int count, u_int32_t *sesid)
   1756 {
   1757 	struct csession *cse;
   1758 	int req, error = 0;
   1759 
   1760 	mutex_enter(&cryptodev_mtx);
   1761 	for(req = 0; req < count; req++) {
   1762 		cse = csefind(fcr, sesid[req]);
   1763 		if (cse == NULL)
   1764 			continue;
   1765 		csedelete(fcr, cse);
   1766 		mutex_exit(&cryptodev_mtx);
   1767 		error = csefree(cse);
   1768 		mutex_enter(&cryptodev_mtx);
   1769 	}
   1770 	mutex_exit(&cryptodev_mtx);
   1771 	return error;
   1772 }
   1773 
   1774 /*
   1775  * collect as many completed requests as are availble, or count completed
   1776  * requests whichever is less.
   1777  * return the number of requests.
   1778  */
   1779 static int
   1780 cryptodev_getmstatus(struct fcrypt *fcr, struct crypt_result *crypt_res,
   1781     int count)
   1782 {
   1783 	struct cryptop *crp = NULL;
   1784 	struct cryptkop *krp = NULL;
   1785 	struct csession *cse;
   1786 	int i, size, req = 0;
   1787 	int completed=0;
   1788 
   1789 	/* On queue so nobody else can grab them
   1790 	 * and copyout can be delayed-- no locking */
   1791 	TAILQ_HEAD(, cryptop) crp_delfree_q =
   1792 		TAILQ_HEAD_INITIALIZER(crp_delfree_q);
   1793 	TAILQ_HEAD(, cryptkop) krp_delfree_q =
   1794 		TAILQ_HEAD_INITIALIZER(krp_delfree_q);
   1795 
   1796 	/* at this point we do not know which response user is requesting for
   1797 	 * (symmetric or asymmetric) so we copyout one from each i.e if the
   1798 	 * count is 2 then 1 from symmetric and 1 from asymmetric queue and
   1799 	 * if 3 then 2 symmetric and 1 asymmetric and so on */
   1800 
   1801 	/* pull off a list of requests while protected from changes */
   1802 	mutex_enter(&cryptodev_mtx);
   1803 	while (req < count) {
   1804 		crp = TAILQ_FIRST(&fcr->crp_ret_mq);
   1805 		if (crp) {
   1806 			TAILQ_REMOVE(&fcr->crp_ret_mq, crp, crp_next);
   1807 			TAILQ_INSERT_TAIL(&crp_delfree_q, crp, crp_next);
   1808 			cse = (struct csession *)crp->crp_opaque;
   1809 
   1810 			/* see if the session is still valid */
   1811 			cse = csefind(fcr, cse->ses);
   1812 			if (cse != NULL) {
   1813 				crypt_res[req].status = 0;
   1814 			} else {
   1815 				DPRINTF("csefind failed\n");
   1816 				crypt_res[req].status = EINVAL;
   1817 			}
   1818 			req++;
   1819 		}
   1820 		if(req < count) {
   1821 			crypt_res[req].status = 0;
   1822 			krp = TAILQ_FIRST(&fcr->crp_ret_mkq);
   1823 			if (krp) {
   1824 				TAILQ_REMOVE(&fcr->crp_ret_mkq, krp, krp_next);
   1825 				TAILQ_INSERT_TAIL(&krp_delfree_q, krp, krp_next);
   1826 			req++;
   1827 			}
   1828 		}
   1829 	}
   1830 	mutex_exit(&cryptodev_mtx);
   1831 
   1832 	/* now do all the work outside the mutex */
   1833 	for(req=0; req < count ;) {
   1834 		crp = TAILQ_FIRST(&crp_delfree_q);
   1835 		if (crp) {
   1836 			if (crypt_res[req].status != 0) {
   1837 				/* csefind failed during collection */
   1838 				goto bail;
   1839 			}
   1840 			cse = (struct csession *)crp->crp_opaque;
   1841 			crypt_res[req].reqid = crp->crp_reqid;
   1842 			crypt_res[req].opaque = crp->crp_usropaque;
   1843 			completed++;
   1844 
   1845 			if (crp->crp_etype != 0) {
   1846 				crypt_res[req].status = crp->crp_etype;
   1847 				goto bail;
   1848 			}
   1849 
   1850 			if (cse->error) {
   1851 				crypt_res[req].status = cse->error;
   1852 				goto bail;
   1853 			}
   1854 
   1855 			if (crp->dst && (crypt_res[req].status =
   1856 			    copyout(crp->uio.uio_iov[0].iov_base, crp->dst,
   1857 			    crp->len)))
   1858 				goto bail;
   1859 
   1860 			if (crp->mac && (crypt_res[req].status =
   1861 			    copyout(crp->crp_mac, crp->mac,
   1862 			    cse->thash->authsize)))
   1863 				goto bail;
   1864 
   1865 bail:
   1866 			TAILQ_REMOVE(&crp_delfree_q, crp, crp_next);
   1867 			kmem_free(crp->uio.uio_iov[0].iov_base,
   1868 			    crp->uio.uio_iov[0].iov_len);
   1869 			crypto_freereq(crp);
   1870 			req++;
   1871 		}
   1872 
   1873 		if (req < count) {
   1874 			krp = TAILQ_FIRST(&krp_delfree_q);
   1875 			if (krp) {
   1876 				crypt_res[req].reqid = krp->krp_reqid;
   1877 				crypt_res[req].opaque = krp->krp_usropaque;
   1878 				completed++;
   1879 				if (krp->krp_status != 0) {
   1880 					DPRINTF("krp->krp_status 0x%08x\n",
   1881 					    krp->krp_status);
   1882 					crypt_res[req].status = krp->krp_status;
   1883 					goto fail;
   1884 				}
   1885 
   1886 				for (i = krp->krp_iparams; i < krp->krp_iparams
   1887 				    + krp->krp_oparams; i++) {
   1888 					size = (krp->krp_param[i].crp_nbits
   1889 					    + 7) / 8;
   1890 					if (size == 0)
   1891 						continue;
   1892 					crypt_res[req].status = copyout
   1893 					    (krp->krp_param[i].crp_p,
   1894 					    krp->crk_param[i].crp_p, size);
   1895 					if (crypt_res[req].status) {
   1896 						DPRINTF("copyout oparam %d failed, "
   1897 						    "error=%d\n",
   1898 						    i - krp->krp_iparams,
   1899 						    crypt_res[req].status);
   1900 						goto fail;
   1901 					}
   1902 				}
   1903 fail:
   1904 				TAILQ_REMOVE(&krp_delfree_q, krp, krp_next);
   1905 				/* not sure what to do for this */
   1906 				/* kop[req].crk_status = krp->krp_status; */
   1907 				for (i = 0; i < CRK_MAXPARAM; i++) {
   1908 					struct crparam *kp = &(krp->krp_param[i]);
   1909 					if (kp->crp_p) {
   1910 						size = (kp->crp_nbits + 7) / 8;
   1911 						KASSERT(size > 0);
   1912 						(void)memset(kp->crp_p, 0, size);
   1913 						kmem_free(kp->crp_p, size);
   1914 					}
   1915 				}
   1916 				cv_destroy(&krp->krp_cv);
   1917 				crypto_kfreereq(krp);
   1918 				req++;
   1919 			}
   1920 		}
   1921 	}
   1922 
   1923 	return completed;
   1924 }
   1925 
   1926 static int
   1927 cryptodev_getstatus (struct fcrypt *fcr, struct crypt_result *crypt_res)
   1928 {
   1929         struct cryptop *crp = NULL, *cnext;
   1930         struct cryptkop *krp = NULL, *knext;
   1931         struct csession *cse;
   1932         int i, size, req = 0;
   1933 
   1934 	mutex_enter(&cryptodev_mtx);
   1935 	/* Here we dont know for which request the user is requesting the
   1936 	 * response so checking in both the queues */
   1937 	TAILQ_FOREACH_SAFE(crp, &fcr->crp_ret_mq, crp_next, cnext) {
   1938 		if(crp && (crp->crp_reqid == crypt_res->reqid)) {
   1939 			cse = (struct csession *)crp->crp_opaque;
   1940 		        crypt_res->opaque = crp->crp_usropaque;
   1941 			cse = csefind(fcr, cse->ses);
   1942 			if (cse == NULL) {
   1943 				DPRINTF("csefind failed\n");
   1944 				crypt_res->status = EINVAL;
   1945 				goto bail;
   1946 			}
   1947 
   1948 			if (crp->crp_etype != 0) {
   1949 				crypt_res->status = crp->crp_etype;
   1950 				goto bail;
   1951 			}
   1952 
   1953 			if (cse->error) {
   1954 				crypt_res->status = cse->error;
   1955 				goto bail;
   1956 			}
   1957 
   1958 			if (crp->dst && (crypt_res->status =
   1959 			    copyout(crp->uio.uio_iov[0].iov_base,
   1960 			    crp->dst, crp->len)))
   1961 				goto bail;
   1962 
   1963 			if (crp->mac && (crypt_res->status =
   1964 			    copyout(crp->crp_mac, crp->mac,
   1965 			    cse->thash->authsize)))
   1966 				goto bail;
   1967 bail:
   1968 			TAILQ_REMOVE(&fcr->crp_ret_mq, crp, crp_next);
   1969 
   1970 			mutex_exit(&cryptodev_mtx);
   1971 			crypto_freereq(crp);
   1972 			return 0;
   1973 		}
   1974 	}
   1975 
   1976 	TAILQ_FOREACH_SAFE(krp, &fcr->crp_ret_mkq, krp_next, knext) {
   1977 		if(krp && (krp->krp_reqid == crypt_res->reqid)) {
   1978 			crypt_res[req].opaque = krp->krp_usropaque;
   1979 			if (krp->krp_status != 0) {
   1980 				DPRINTF("krp->krp_status 0x%08x\n",
   1981 				    krp->krp_status);
   1982 				crypt_res[req].status = krp->krp_status;
   1983 				goto fail;
   1984 			}
   1985 
   1986 			for (i = krp->krp_iparams; i < krp->krp_iparams +
   1987 			    krp->krp_oparams; i++) {
   1988 				size = (krp->krp_param[i].crp_nbits + 7) / 8;
   1989 				if (size == 0)
   1990 					continue;
   1991 				crypt_res[req].status = copyout(
   1992 				    krp->krp_param[i].crp_p,
   1993 				    krp->crk_param[i].crp_p, size);
   1994 				if (crypt_res[req].status) {
   1995 					DPRINTF("copyout oparam "
   1996 					    "%d failed, error=%d\n",
   1997 					    i - krp->krp_iparams,
   1998 					    crypt_res[req].status);
   1999 					goto fail;
   2000 				}
   2001 			}
   2002 fail:
   2003 			TAILQ_REMOVE(&fcr->crp_ret_mkq, krp, krp_next);
   2004 			mutex_exit(&cryptodev_mtx);
   2005 			/* not sure what to do for this */
   2006 			/* kop[req].crk_status = krp->krp_status; */
   2007 			for (i = 0; i < CRK_MAXPARAM; i++) {
   2008 				struct crparam *kp = &(krp->krp_param[i]);
   2009 				if (kp->crp_p) {
   2010 					size = (kp->crp_nbits + 7) / 8;
   2011 					KASSERT(size > 0);
   2012 					memset(kp->crp_p, 0, size);
   2013 					kmem_free(kp->crp_p, size);
   2014 				}
   2015 			}
   2016 			cv_destroy(&krp->krp_cv);
   2017 			crypto_kfreereq(krp);
   2018 			return 0;
   2019 		}
   2020 	}
   2021 	mutex_exit(&cryptodev_mtx);
   2022 	return EINPROGRESS;
   2023 }
   2024 
   2025 static int
   2026 cryptof_stat(struct file *fp, struct stat *st)
   2027 {
   2028 	struct fcrypt *fcr = fp->f_fcrypt;
   2029 
   2030 	(void)memset(st, 0, sizeof(*st));
   2031 
   2032 	mutex_enter(&cryptodev_mtx);
   2033 	st->st_dev = makedev(cdevsw_lookup_major(&crypto_cdevsw), fcr->sesn);
   2034 	st->st_atimespec = fcr->atime;
   2035 	st->st_mtimespec = fcr->mtime;
   2036 	st->st_ctimespec = st->st_birthtimespec = fcr->btime;
   2037 	st->st_uid = kauth_cred_geteuid(fp->f_cred);
   2038 	st->st_gid = kauth_cred_getegid(fp->f_cred);
   2039 	mutex_exit(&cryptodev_mtx);
   2040 
   2041 	return 0;
   2042 }
   2043 
   2044 static int
   2045 cryptof_poll(struct file *fp, int events)
   2046 {
   2047 	struct fcrypt *fcr = fp->f_fcrypt;
   2048 	int revents = 0;
   2049 
   2050 	if (!(events & (POLLIN | POLLRDNORM))) {
   2051 		/* only support read and POLLIN */
   2052 		return 0;
   2053 	}
   2054 
   2055 	mutex_enter(&cryptodev_mtx);
   2056 	if (TAILQ_EMPTY(&fcr->crp_ret_mq) && TAILQ_EMPTY(&fcr->crp_ret_mkq)) {
   2057 		/* no completed requests pending, save the poll for later */
   2058 		selrecord(curlwp, &fcr->sinfo);
   2059 	} else {
   2060 		/* let the app(s) know that there are completed requests */
   2061 		revents = events & (POLLIN | POLLRDNORM);
   2062 	}
   2063 	mutex_exit(&cryptodev_mtx);
   2064 
   2065 	return revents;
   2066 }
   2067 
   2068 /*
   2069  * Pseudo-device initialization routine for /dev/crypto
   2070  */
   2071 void
   2072 cryptoattach(int num)
   2073 {
   2074 
   2075 	crypto_init();
   2076 
   2077 	mutex_init(&cryptodev_mtx, MUTEX_DEFAULT, IPL_NONE);
   2078 
   2079 	pool_init(&fcrpl, sizeof(struct fcrypt), 0, 0, 0, "fcrpl",
   2080 	    NULL, IPL_NONE);
   2081 	pool_init(&csepl, sizeof(struct csession), 0, 0, 0, "csepl",
   2082 	    NULL, IPL_NONE);
   2083 
   2084 	/*
   2085 	 * Preallocate space for 64 users, with 5 sessions each.
   2086 	 * (consider that a TLS protocol session requires at least
   2087 	 * 3DES, MD5, and SHA1 (both hashes are used in the PRF) for
   2088 	 * the negotiation, plus HMAC_SHA1 for the actual SSL records,
   2089 	 * consuming one session here for each algorithm.
   2090 	 */
   2091 	pool_prime(&fcrpl, 64);
   2092 	pool_prime(&csepl, 64 * 5);
   2093 }
   2094 
   2095 void	crypto_attach(device_t, device_t, void *);
   2096 
   2097 void
   2098 crypto_attach(device_t parent, device_t self, void * opaque)
   2099 {
   2100 
   2101 	cryptoattach(0);
   2102 }
   2103 
   2104 int	crypto_detach(device_t, int);
   2105 
   2106 int
   2107 crypto_detach(device_t self, int num)
   2108 {
   2109 
   2110 	pool_destroy(&fcrpl);
   2111 	pool_destroy(&csepl);
   2112 
   2113 	mutex_destroy(&cryptodev_mtx);
   2114 
   2115 	return 0;
   2116 }
   2117 
   2118 int crypto_match(device_t, cfdata_t, void *);
   2119 
   2120 int
   2121 crypto_match(device_t parent, cfdata_t data, void *opaque)
   2122 {
   2123 
   2124 	return 1;
   2125 }
   2126 
   2127 MODULE(MODULE_CLASS_DRIVER, crypto, "opencrypto");
   2128 
   2129 CFDRIVER_DECL(crypto, DV_DULL, NULL);
   2130 
   2131 CFATTACH_DECL2_NEW(crypto, 0, crypto_match, crypto_attach, crypto_detach,
   2132     NULL, NULL, NULL);
   2133 
   2134 #ifdef _MODULE
   2135 static int cryptoloc[] = { -1, -1 };
   2136 
   2137 static struct cfdata crypto_cfdata[] = {
   2138 	{
   2139 		.cf_name = "crypto",
   2140 		.cf_atname = "crypto",
   2141 		.cf_unit = 0,
   2142 		.cf_fstate = 0,
   2143 		.cf_loc = cryptoloc,
   2144 		.cf_flags = 0,
   2145 		.cf_pspec = NULL,
   2146 	},
   2147 	{ NULL, NULL, 0, 0, NULL, 0, NULL }
   2148 };
   2149 #endif
   2150 
   2151 static int
   2152 crypto_modcmd(modcmd_t cmd, void *arg)
   2153 {
   2154 	int error = 0;
   2155 #ifdef _MODULE
   2156 	devmajor_t cmajor = NODEVMAJOR, bmajor = NODEVMAJOR;
   2157 #endif
   2158 
   2159 	switch (cmd) {
   2160 	case MODULE_CMD_INIT:
   2161 #ifdef _MODULE
   2162 
   2163 		error = devsw_attach(crypto_cd.cd_name, NULL, &bmajor,
   2164 		    &crypto_cdevsw, &cmajor);
   2165 		if (error) {
   2166 			aprint_error("%s: unable to register devsw, error %d\n",
   2167 				crypto_cd.cd_name, error);
   2168 			return error;
   2169 		}
   2170 
   2171 		error = config_cfdriver_attach(&crypto_cd);
   2172 		if (error) {
   2173 			devsw_detach(NULL, &crypto_cdevsw);
   2174 			return error;
   2175 		}
   2176 
   2177 		error = config_cfattach_attach(crypto_cd.cd_name, &crypto_ca);
   2178 		if (error) {
   2179 			config_cfdriver_detach(&crypto_cd);
   2180 			devsw_detach(NULL, &crypto_cdevsw);
   2181 			aprint_error("%s: unable to register cfattach\n",
   2182 				crypto_cd.cd_name);
   2183 
   2184 			return error;
   2185 		}
   2186 
   2187 		error = config_cfdata_attach(crypto_cfdata, 1);
   2188 		if (error) {
   2189 			config_cfattach_detach(crypto_cd.cd_name, &crypto_ca);
   2190 			config_cfdriver_detach(&crypto_cd);
   2191 			devsw_detach(NULL, &crypto_cdevsw);
   2192 			aprint_error("%s: unable to register cfdata\n",
   2193 				crypto_cd.cd_name);
   2194 
   2195 			return error;
   2196 		}
   2197 
   2198 		(void)config_attach_pseudo(crypto_cfdata);
   2199 #endif
   2200 
   2201 		return error;
   2202 	case MODULE_CMD_FINI:
   2203 #ifdef _MODULE
   2204 		if (crypto_refcount != 0)
   2205 			return EBUSY;
   2206 		error = config_cfdata_detach(crypto_cfdata);
   2207 		if (error) {
   2208 			return error;
   2209 		}
   2210 
   2211 		config_cfattach_detach(crypto_cd.cd_name, &crypto_ca);
   2212 		config_cfdriver_detach(&crypto_cd);
   2213 		devsw_detach(NULL, &crypto_cdevsw);
   2214 #endif
   2215 
   2216 		return error;
   2217 #ifdef _MODULE
   2218 	case MODULE_CMD_AUTOUNLOAD:
   2219 #if 0	/*
   2220 	 * XXX Completely disable auto-unload for now, since there is still
   2221 	 * XXX a (small) window where in-module ref-counting doesn't help
   2222 	 */
   2223 		if (crypto_refcount != 0)
   2224 #endif
   2225 			return EBUSY;
   2226 	/* FALLTHROUGH */
   2227 #endif
   2228 	default:
   2229 		return ENOTTY;
   2230 	}
   2231 }
   2232