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