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