Home | History | Annotate | Line # | Download | only in kern
sys_aio.c revision 1.10
      1 /*	$NetBSD: sys_aio.c,v 1.10 2007/11/28 19:30:56 rmind Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2007, Mindaugas Rasiukevicius <rmind at NetBSD org>
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     17  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     18  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     26  * POSSIBILITY OF SUCH DAMAGE.
     27  */
     28 
     29 /*
     30  * TODO:
     31  *   1. Additional work for VCHR and maybe VBLK devices.
     32  *   2. Consider making the job-finding O(n) per one file descriptor.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 __KERNEL_RCSID(0, "$NetBSD: sys_aio.c,v 1.10 2007/11/28 19:30:56 rmind Exp $");
     37 
     38 #include "opt_ddb.h"
     39 
     40 #include <sys/param.h>
     41 #include <sys/condvar.h>
     42 #include <sys/file.h>
     43 #include <sys/filedesc.h>
     44 #include <sys/kernel.h>
     45 #include <sys/kmem.h>
     46 #include <sys/lwp.h>
     47 #include <sys/mutex.h>
     48 #include <sys/pool.h>
     49 #include <sys/proc.h>
     50 #include <sys/queue.h>
     51 #include <sys/signal.h>
     52 #include <sys/signalvar.h>
     53 #include <sys/syscallargs.h>
     54 #include <sys/sysctl.h>
     55 #include <sys/systm.h>
     56 #include <sys/types.h>
     57 #include <sys/vnode.h>
     58 
     59 #include <uvm/uvm_extern.h>
     60 
     61 /*
     62  * System-wide limits and counter of AIO operations.
     63  * XXXSMP: We should spin-lock it, or modify atomically.
     64  */
     65 static u_int aio_listio_max = AIO_LISTIO_MAX;
     66 static u_int aio_max = AIO_MAX;
     67 static u_int aio_jobs_count;
     68 
     69 static struct pool aio_job_pool;
     70 static struct pool aio_lio_pool;
     71 
     72 /* Prototypes */
     73 void aio_worker(void *);
     74 static void aio_process(struct aio_job *);
     75 static void aio_sendsig(struct proc *, struct sigevent *);
     76 static int aio_enqueue_job(int, void *, struct lio_req *);
     77 
     78 /*
     79  * Initialize the AIO system.
     80  */
     81 void
     82 aio_sysinit(void)
     83 {
     84 
     85 	pool_init(&aio_job_pool, sizeof(struct aio_job), 0, 0, 0,
     86 	    "aio_jobs_pool", &pool_allocator_nointr, IPL_NONE);
     87 	pool_init(&aio_lio_pool, sizeof(struct lio_req), 0, 0, 0,
     88 	    "aio_lio_pool", &pool_allocator_nointr, IPL_NONE);
     89 }
     90 
     91 /*
     92  * Initialize Asynchronous I/O data structures for the process.
     93  */
     94 int
     95 aio_init(struct proc *p)
     96 {
     97 	struct aioproc *aio;
     98 	struct lwp *l;
     99 	int error;
    100 	bool inmem;
    101 	vaddr_t uaddr;
    102 
    103 	/* Allocate and initialize AIO structure */
    104 	aio = kmem_zalloc(sizeof(struct aioproc), KM_NOSLEEP);
    105 	if (aio == NULL)
    106 		return EAGAIN;
    107 
    108 	/* Initialize queue and their synchronization structures */
    109 	mutex_init(&aio->aio_mtx, MUTEX_DEFAULT, IPL_NONE);
    110 	cv_init(&aio->aio_worker_cv, "aiowork");
    111 	cv_init(&aio->done_cv, "aiodone");
    112 	TAILQ_INIT(&aio->jobs_queue);
    113 
    114 	/*
    115 	 * Create an AIO worker thread.
    116 	 * XXX: Currently, AIO thread is not protected against user's actions.
    117 	 */
    118 	inmem = uvm_uarea_alloc(&uaddr);
    119 	if (uaddr == 0) {
    120 		aio_exit(p, aio);
    121 		return EAGAIN;
    122 	}
    123 	error = lwp_create(curlwp, p, uaddr, inmem, 0, NULL, 0, aio_worker,
    124 	    NULL, &l, curlwp->l_class);
    125 	if (error != 0) {
    126 		uvm_uarea_free(uaddr, curcpu());
    127 		aio_exit(p, aio);
    128 		return error;
    129 	}
    130 
    131 	/* Recheck if we are really first */
    132 	mutex_enter(&p->p_mutex);
    133 	if (p->p_aio) {
    134 		mutex_exit(&p->p_mutex);
    135 		aio_exit(p, aio);
    136 		lwp_exit(l);
    137 		return 0;
    138 	}
    139 	p->p_aio = aio;
    140 	mutex_exit(&p->p_mutex);
    141 
    142 	/* Complete the initialization of thread, and run it */
    143 	mutex_enter(&p->p_smutex);
    144 	aio->aio_worker = l;
    145 	p->p_nrlwps++;
    146 	lwp_lock(l);
    147 	l->l_stat = LSRUN;
    148 	l->l_priority = PRI_KERNEL - 1;
    149 	sched_enqueue(l, false);
    150 	lwp_unlock(l);
    151 	mutex_exit(&p->p_smutex);
    152 
    153 	return 0;
    154 }
    155 
    156 /*
    157  * Exit of Asynchronous I/O subsystem of process.
    158  */
    159 void
    160 aio_exit(struct proc *p, struct aioproc *aio)
    161 {
    162 	struct aio_job *a_job;
    163 
    164 	if (aio == NULL)
    165 		return;
    166 
    167 	/* Free AIO queue */
    168 	while (!TAILQ_EMPTY(&aio->jobs_queue)) {
    169 		a_job = TAILQ_FIRST(&aio->jobs_queue);
    170 		TAILQ_REMOVE(&aio->jobs_queue, a_job, list);
    171 		pool_put(&aio_job_pool, a_job);
    172 		aio_jobs_count--; /* XXXSMP */
    173 	}
    174 
    175 	/* Destroy and free the entire AIO data structure */
    176 	cv_destroy(&aio->aio_worker_cv);
    177 	cv_destroy(&aio->done_cv);
    178 	mutex_destroy(&aio->aio_mtx);
    179 	kmem_free(aio, sizeof(struct aioproc));
    180 }
    181 
    182 /*
    183  * AIO worker thread and processor.
    184  */
    185 void
    186 aio_worker(void *arg)
    187 {
    188 	struct proc *p = curlwp->l_proc;
    189 	struct aioproc *aio = p->p_aio;
    190 	struct aio_job *a_job;
    191 	struct lio_req *lio;
    192 	sigset_t oss, nss;
    193 	int error, refcnt;
    194 
    195 	/*
    196 	 * Make an empty signal mask, so it
    197 	 * handles only SIGKILL and SIGSTOP.
    198 	 */
    199 	sigfillset(&nss);
    200 	mutex_enter(&p->p_smutex);
    201 	error = sigprocmask1(curlwp, SIG_SETMASK, &nss, &oss);
    202 	mutex_exit(&p->p_smutex);
    203 	KASSERT(error == 0);
    204 
    205 	for (;;) {
    206 		/*
    207 		 * Loop for each job in the queue.  If there
    208 		 * are no jobs then sleep.
    209 		 */
    210 		mutex_enter(&aio->aio_mtx);
    211 		while ((a_job = TAILQ_FIRST(&aio->jobs_queue)) == NULL) {
    212 			if (cv_wait_sig(&aio->aio_worker_cv, &aio->aio_mtx)) {
    213 				/*
    214 				 * Thread was interrupted - check for
    215 				 * pending exit or suspend.
    216 				 */
    217 				mutex_exit(&aio->aio_mtx);
    218 				lwp_userret(curlwp);
    219 				mutex_enter(&aio->aio_mtx);
    220 			}
    221 		}
    222 
    223 		/* Take the job from the queue */
    224 		aio->curjob = a_job;
    225 		TAILQ_REMOVE(&aio->jobs_queue, a_job, list);
    226 
    227 		aio_jobs_count--; /* XXXSMP */
    228 		aio->jobs_count--;
    229 
    230 		mutex_exit(&aio->aio_mtx);
    231 
    232 		/* Process an AIO operation */
    233 		aio_process(a_job);
    234 
    235 		/* Copy data structure back to the user-space */
    236 		(void)copyout(&a_job->aiocbp, a_job->aiocb_uptr,
    237 		    sizeof(struct aiocb));
    238 
    239 		mutex_enter(&aio->aio_mtx);
    240 		aio->curjob = NULL;
    241 
    242 		/* Decrease a reference counter, if there is a LIO structure */
    243 		lio = a_job->lio;
    244 		refcnt = (lio != NULL ? --lio->refcnt : -1);
    245 
    246 		/* Notify all suspenders */
    247 		cv_broadcast(&aio->done_cv);
    248 		mutex_exit(&aio->aio_mtx);
    249 
    250 		/* Send a signal, if any */
    251 		aio_sendsig(p, &a_job->aiocbp.aio_sigevent);
    252 
    253 		/* Destroy the LIO structure */
    254 		if (refcnt == 0) {
    255 			aio_sendsig(p, &lio->sig);
    256 			pool_put(&aio_lio_pool, lio);
    257 		}
    258 
    259 		/* Destroy the the job */
    260 		pool_put(&aio_job_pool, a_job);
    261 	}
    262 
    263 	/* NOTREACHED */
    264 }
    265 
    266 static void
    267 aio_process(struct aio_job *a_job)
    268 {
    269 	struct proc *p = curlwp->l_proc;
    270 	struct aiocb *aiocbp = &a_job->aiocbp;
    271 	struct file *fp;
    272 	struct filedesc	*fdp = p->p_fd;
    273 	int fd = aiocbp->aio_fildes;
    274 	int error = 0;
    275 
    276 	KASSERT(fdp != NULL);
    277 	KASSERT(a_job->aio_op != 0);
    278 
    279 	if ((a_job->aio_op & (AIO_READ | AIO_WRITE)) != 0) {
    280 		struct iovec aiov;
    281 		struct uio auio;
    282 
    283 		if (aiocbp->aio_nbytes > SSIZE_MAX) {
    284 			error = EINVAL;
    285 			goto done;
    286 		}
    287 
    288 		fp = fd_getfile(fdp, fd);
    289 		if (fp == NULL) {
    290 			error = EBADF;
    291 			goto done;
    292 		}
    293 
    294 		aiov.iov_base = (void *)(uintptr_t)aiocbp->aio_buf;
    295 		aiov.iov_len = aiocbp->aio_nbytes;
    296 		auio.uio_iov = &aiov;
    297 		auio.uio_iovcnt = 1;
    298 		auio.uio_resid = aiocbp->aio_nbytes;
    299 		auio.uio_vmspace = p->p_vmspace;
    300 
    301 		FILE_USE(fp);
    302 		if (a_job->aio_op & AIO_READ) {
    303 			/*
    304 			 * Perform a Read operation
    305 			 */
    306 			KASSERT((a_job->aio_op & AIO_WRITE) == 0);
    307 
    308 			if ((fp->f_flag & FREAD) == 0) {
    309 				FILE_UNUSE(fp, curlwp);
    310 				error = EBADF;
    311 				goto done;
    312 			}
    313 			auio.uio_rw = UIO_READ;
    314 			error = (*fp->f_ops->fo_read)(fp, &aiocbp->aio_offset,
    315 			    &auio, fp->f_cred, FOF_UPDATE_OFFSET);
    316 		} else {
    317 			/*
    318 			 * Perform a Write operation
    319 			 */
    320 			KASSERT(a_job->aio_op & AIO_WRITE);
    321 
    322 			if ((fp->f_flag & FWRITE) == 0) {
    323 				FILE_UNUSE(fp, curlwp);
    324 				error = EBADF;
    325 				goto done;
    326 			}
    327 			auio.uio_rw = UIO_WRITE;
    328 			error = (*fp->f_ops->fo_write)(fp, &aiocbp->aio_offset,
    329 			    &auio, fp->f_cred, FOF_UPDATE_OFFSET);
    330 		}
    331 		FILE_UNUSE(fp, curlwp);
    332 
    333 		/* Store the result value */
    334 		a_job->aiocbp.aio_nbytes -= auio.uio_resid;
    335 		a_job->aiocbp._retval = (error == 0) ?
    336 		    a_job->aiocbp.aio_nbytes : -1;
    337 
    338 	} else if ((a_job->aio_op & (AIO_SYNC | AIO_DSYNC)) != 0) {
    339 		/*
    340 		 * Perform a file Sync operation
    341 		 */
    342 		struct vnode *vp;
    343 
    344 		if ((error = getvnode(fdp, fd, &fp)) != 0)
    345 			goto done;
    346 
    347 		if ((fp->f_flag & FWRITE) == 0) {
    348 			FILE_UNUSE(fp, curlwp);
    349 			error = EBADF;
    350 			goto done;
    351 		}
    352 
    353 		vp = (struct vnode *)fp->f_data;
    354 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
    355 		if (a_job->aio_op & AIO_DSYNC) {
    356 			error = VOP_FSYNC(vp, fp->f_cred,
    357 			    FSYNC_WAIT | FSYNC_DATAONLY, 0, 0);
    358 		} else if (a_job->aio_op & AIO_SYNC) {
    359 			error = VOP_FSYNC(vp, fp->f_cred,
    360 			    FSYNC_WAIT, 0, 0);
    361 			if (error == 0 && bioopsp != NULL &&
    362 			    vp->v_mount &&
    363 			    (vp->v_mount->mnt_flag & MNT_SOFTDEP))
    364 			    bioopsp->io_fsync(vp, 0);
    365 		}
    366 		VOP_UNLOCK(vp, 0);
    367 		FILE_UNUSE(fp, curlwp);
    368 
    369 		/* Store the result value */
    370 		a_job->aiocbp._retval = (error == 0) ? 0 : -1;
    371 
    372 	} else
    373 		panic("aio_process: invalid operation code\n");
    374 
    375 done:
    376 	/* Job is done, set the error, if any */
    377 	a_job->aiocbp._errno = error;
    378 	a_job->aiocbp._state = JOB_DONE;
    379 }
    380 
    381 /*
    382  * Send AIO signal.
    383  */
    384 static void
    385 aio_sendsig(struct proc *p, struct sigevent *sig)
    386 {
    387 	ksiginfo_t ksi;
    388 
    389 	if (sig->sigev_signo == 0 || sig->sigev_notify == SIGEV_NONE)
    390 		return;
    391 
    392 	KSI_INIT(&ksi);
    393 	ksi.ksi_signo = sig->sigev_signo;
    394 	ksi.ksi_code = SI_ASYNCIO;
    395 	ksi.ksi_value = sig->sigev_value;
    396 	mutex_enter(&proclist_mutex);
    397 	kpsignal(p, &ksi, NULL);
    398 	mutex_exit(&proclist_mutex);
    399 }
    400 
    401 /*
    402  * Enqueue the job.
    403  */
    404 static int
    405 aio_enqueue_job(int op, void *aiocb_uptr, struct lio_req *lio)
    406 {
    407 	struct proc *p = curlwp->l_proc;
    408 	struct aioproc *aio;
    409 	struct aio_job *a_job;
    410 	struct aiocb aiocbp;
    411 	struct sigevent *sig;
    412 	int error;
    413 
    414 	/* Check for the limit */
    415 	if (aio_jobs_count + 1 > aio_max) /* XXXSMP */
    416 		return EAGAIN;
    417 
    418 	/* Get the data structure from user-space */
    419 	error = copyin(aiocb_uptr, &aiocbp, sizeof(struct aiocb));
    420 	if (error)
    421 		return error;
    422 
    423 	/* Check if signal is set, and validate it */
    424 	sig = &aiocbp.aio_sigevent;
    425 	if (sig->sigev_signo < 0 || sig->sigev_signo >= NSIG ||
    426 	    sig->sigev_notify < SIGEV_NONE || sig->sigev_notify > SIGEV_SA)
    427 		return EINVAL;
    428 
    429 	/* Buffer and byte count */
    430 	if (((AIO_SYNC | AIO_DSYNC) & op) == 0)
    431 		if (aiocbp.aio_buf == NULL || aiocbp.aio_nbytes > SSIZE_MAX)
    432 			return EINVAL;
    433 
    434 	/* Check the opcode, if LIO_NOP - simply ignore */
    435 	if (op == AIO_LIO) {
    436 		KASSERT(lio != NULL);
    437 		if (aiocbp.aio_lio_opcode == LIO_WRITE)
    438 			op = AIO_WRITE;
    439 		else if (aiocbp.aio_lio_opcode == LIO_READ)
    440 			op = AIO_READ;
    441 		else
    442 			return (aiocbp.aio_lio_opcode == LIO_NOP) ? 0 : EINVAL;
    443 	} else {
    444 		KASSERT(lio == NULL);
    445 	}
    446 
    447 	/*
    448 	 * Look for already existing job.  If found - the job is in-progress.
    449 	 * According to POSIX this is invalid, so return the error.
    450 	 */
    451 	aio = p->p_aio;
    452 	if (aio) {
    453 		mutex_enter(&aio->aio_mtx);
    454 		if (aio->curjob) {
    455 			a_job = aio->curjob;
    456 			if (a_job->aiocb_uptr == aiocb_uptr) {
    457 				mutex_exit(&aio->aio_mtx);
    458 				return EINVAL;
    459 			}
    460 		}
    461 		TAILQ_FOREACH(a_job, &aio->jobs_queue, list) {
    462 			if (a_job->aiocb_uptr != aiocb_uptr)
    463 				continue;
    464 			mutex_exit(&aio->aio_mtx);
    465 			return EINVAL;
    466 		}
    467 		mutex_exit(&aio->aio_mtx);
    468 	}
    469 
    470 	/*
    471 	 * Check if AIO structure is initialized, if not - initialize it.
    472 	 * In LIO case, we did that already.  We will recheck this with
    473 	 * the lock in aio_init().
    474 	 */
    475 	if (lio == NULL && p->p_aio == NULL)
    476 		if (aio_init(p))
    477 			return EAGAIN;
    478 	aio = p->p_aio;
    479 
    480 	/*
    481 	 * Set the state with errno, and copy data
    482 	 * structure back to the user-space.
    483 	 */
    484 	aiocbp._state = JOB_WIP;
    485 	aiocbp._errno = EINPROGRESS;
    486 	aiocbp._retval = -1;
    487 	error = copyout(&aiocbp, aiocb_uptr, sizeof(struct aiocb));
    488 	if (error)
    489 		return error;
    490 
    491 	/* Allocate and initialize a new AIO job */
    492 	a_job = pool_get(&aio_job_pool, PR_WAITOK);
    493 	memset(a_job, 0, sizeof(struct aio_job));
    494 
    495 	/*
    496 	 * Set the data.
    497 	 * Store the user-space pointer for searching.  Since we
    498 	 * are storing only per proc pointers - it is safe.
    499 	 */
    500 	memcpy(&a_job->aiocbp, &aiocbp, sizeof(struct aiocb));
    501 	a_job->aiocb_uptr = aiocb_uptr;
    502 	a_job->aio_op |= op;
    503 	a_job->lio = lio;
    504 
    505 	/*
    506 	 * Add the job to the queue, update the counters, and
    507 	 * notify the AIO worker thread to handle the job.
    508 	 */
    509 	mutex_enter(&aio->aio_mtx);
    510 
    511 	/* Fail, if the limit was reached */
    512 	if (aio->jobs_count >= aio_listio_max) {
    513 		mutex_exit(&aio->aio_mtx);
    514 		pool_put(&aio_job_pool, a_job);
    515 		return EAGAIN;
    516 	}
    517 
    518 	TAILQ_INSERT_TAIL(&aio->jobs_queue, a_job, list);
    519 	aio_jobs_count++; /* XXXSMP */
    520 	aio->jobs_count++;
    521 	if (lio)
    522 		lio->refcnt++;
    523 	cv_signal(&aio->aio_worker_cv);
    524 
    525 	mutex_exit(&aio->aio_mtx);
    526 
    527 	/*
    528 	 * One would handle the errors only with aio_error() function.
    529 	 * This way is appropriate according to POSIX.
    530 	 */
    531 	return 0;
    532 }
    533 
    534 /*
    535  * Syscall functions.
    536  */
    537 
    538 int
    539 sys_aio_cancel(struct lwp *l, void *v, register_t *retval)
    540 {
    541 	struct sys_aio_cancel_args /* {
    542 		syscallarg(int) fildes;
    543 		syscallarg(struct aiocb *) aiocbp;
    544 	} */ *uap = v;
    545 	struct proc *p = l->l_proc;
    546 	struct aioproc *aio;
    547 	struct aio_job *a_job;
    548 	struct aiocb *aiocbp_ptr;
    549 	struct lio_req *lio;
    550 	struct filedesc	*fdp = p->p_fd;
    551 	unsigned int cn, errcnt, fildes;
    552 
    553 	TAILQ_HEAD(, aio_job) tmp_jobs_list;
    554 
    555 	/* Check for invalid file descriptor */
    556 	fildes = (unsigned int)SCARG(uap, fildes);
    557 	if (fildes >= fdp->fd_nfiles || fdp->fd_ofiles[fildes] == NULL)
    558 		return EBADF;
    559 
    560 	/* Check if AIO structure is initialized */
    561 	if (p->p_aio == NULL) {
    562 		*retval = AIO_NOTCANCELED;
    563 		return 0;
    564 	}
    565 
    566 	aio = p->p_aio;
    567 	aiocbp_ptr = (struct aiocb *)SCARG(uap, aiocbp);
    568 
    569 	mutex_enter(&aio->aio_mtx);
    570 
    571 	/* Cancel the jobs, and remove them from the queue */
    572 	cn = 0;
    573 	TAILQ_INIT(&tmp_jobs_list);
    574 	TAILQ_FOREACH(a_job, &aio->jobs_queue, list) {
    575 		if (aiocbp_ptr) {
    576 			if (aiocbp_ptr != a_job->aiocb_uptr)
    577 				continue;
    578 			if (fildes != a_job->aiocbp.aio_fildes) {
    579 				mutex_exit(&aio->aio_mtx);
    580 				return EBADF;
    581 			}
    582 		} else if (a_job->aiocbp.aio_fildes != fildes)
    583 			continue;
    584 
    585 		TAILQ_REMOVE(&aio->jobs_queue, a_job, list);
    586 		TAILQ_INSERT_TAIL(&tmp_jobs_list, a_job, list);
    587 
    588 		/* Decrease the counters */
    589 		aio_jobs_count--; /* XXXSMP */
    590 		aio->jobs_count--;
    591 		lio = a_job->lio;
    592 		if (lio != NULL && --lio->refcnt != 0)
    593 			a_job->lio = NULL;
    594 
    595 		cn++;
    596 		if (aiocbp_ptr)
    597 			break;
    598 	}
    599 
    600 	/* There are canceled jobs */
    601 	if (cn)
    602 		*retval = AIO_CANCELED;
    603 
    604 	/* We cannot cancel current job */
    605 	a_job = aio->curjob;
    606 	if (a_job && ((a_job->aiocbp.aio_fildes == fildes) ||
    607 	    (a_job->aiocb_uptr == aiocbp_ptr)))
    608 		*retval = AIO_NOTCANCELED;
    609 
    610 	mutex_exit(&aio->aio_mtx);
    611 
    612 	/* Free the jobs after the lock */
    613 	errcnt = 0;
    614 	while (!TAILQ_EMPTY(&tmp_jobs_list)) {
    615 		a_job = TAILQ_FIRST(&tmp_jobs_list);
    616 		TAILQ_REMOVE(&tmp_jobs_list, a_job, list);
    617 		/* Set the errno and copy structures back to the user-space */
    618 		a_job->aiocbp._errno = ECANCELED;
    619 		a_job->aiocbp._state = JOB_DONE;
    620 		if (copyout(&a_job->aiocbp, a_job->aiocb_uptr,
    621 		    sizeof(struct aiocb)))
    622 			errcnt++;
    623 		/* Send a signal if any */
    624 		aio_sendsig(p, &a_job->aiocbp.aio_sigevent);
    625 		if (a_job->lio) {
    626 			lio = a_job->lio;
    627 			aio_sendsig(p, &lio->sig);
    628 			pool_put(&aio_lio_pool, lio);
    629 		}
    630 		pool_put(&aio_job_pool, a_job);
    631 	}
    632 
    633 	if (errcnt)
    634 		return EFAULT;
    635 
    636 	/* Set a correct return value */
    637 	if (*retval == 0)
    638 		*retval = AIO_ALLDONE;
    639 
    640 	return 0;
    641 }
    642 
    643 int
    644 sys_aio_error(struct lwp *l, void *v, register_t *retval)
    645 {
    646 	struct sys_aio_error_args /* {
    647 		syscallarg(const struct aiocb *) aiocbp;
    648 	} */ *uap = v;
    649 	struct proc *p = l->l_proc;
    650 	struct aioproc *aio = p->p_aio;
    651 	struct aiocb aiocbp;
    652 	int error;
    653 
    654 	if (aio == NULL)
    655 		return EINVAL;
    656 
    657 	error = copyin(SCARG(uap, aiocbp), &aiocbp, sizeof(struct aiocb));
    658 	if (error)
    659 		return error;
    660 
    661 	if (aiocbp._state == JOB_NONE)
    662 		return EINVAL;
    663 
    664 	*retval = aiocbp._errno;
    665 
    666 	return 0;
    667 }
    668 
    669 int
    670 sys_aio_fsync(struct lwp *l, void *v, register_t *retval)
    671 {
    672 	struct sys_aio_fsync_args /* {
    673 		syscallarg(int) op;
    674 		syscallarg(struct aiocb *) aiocbp;
    675 	} */ *uap = v;
    676 	int op = SCARG(uap, op);
    677 
    678 	if ((op != O_DSYNC) && (op != O_SYNC))
    679 		return EINVAL;
    680 
    681 	op = O_DSYNC ? AIO_DSYNC : AIO_SYNC;
    682 
    683 	return aio_enqueue_job(op, SCARG(uap, aiocbp), NULL);
    684 }
    685 
    686 int
    687 sys_aio_read(struct lwp *l, void *v, register_t *retval)
    688 {
    689 	struct sys_aio_read_args /* {
    690 		syscallarg(struct aiocb *) aiocbp;
    691 	} */ *uap = v;
    692 
    693 	return aio_enqueue_job(AIO_READ, SCARG(uap, aiocbp), NULL);
    694 }
    695 
    696 int
    697 sys_aio_return(struct lwp *l, void *v, register_t *retval)
    698 {
    699 	struct sys_aio_return_args /* {
    700 		syscallarg(struct aiocb *) aiocbp;
    701 	} */ *uap = v;
    702 	struct proc *p = l->l_proc;
    703 	struct aioproc *aio = p->p_aio;
    704 	struct aiocb aiocbp;
    705 	int error;
    706 
    707 	if (aio == NULL)
    708 		return EINVAL;
    709 
    710 	error = copyin(SCARG(uap, aiocbp), &aiocbp, sizeof(struct aiocb));
    711 	if (error)
    712 		return error;
    713 
    714 	if (aiocbp._errno == EINPROGRESS || aiocbp._state != JOB_DONE)
    715 		return EINVAL;
    716 
    717 	*retval = aiocbp._retval;
    718 
    719 	/* Reset the internal variables */
    720 	aiocbp._errno = 0;
    721 	aiocbp._retval = -1;
    722 	aiocbp._state = JOB_NONE;
    723 	error = copyout(&aiocbp, SCARG(uap, aiocbp), sizeof(struct aiocb));
    724 
    725 	return error;
    726 }
    727 
    728 int
    729 sys_aio_suspend(struct lwp *l, void *v, register_t *retval)
    730 {
    731 	struct sys_aio_suspend_args /* {
    732 		syscallarg(const struct aiocb *const[]) list;
    733 		syscallarg(int) nent;
    734 		syscallarg(const struct timespec *) timeout;
    735 	} */ *uap = v;
    736 	struct proc *p = l->l_proc;
    737 	struct aioproc *aio;
    738 	struct aio_job *a_job;
    739 	struct aiocb **aiocbp_list;
    740 	struct timespec ts;
    741 	int i, error, nent, timo;
    742 
    743 	if (p->p_aio == NULL)
    744 		return EAGAIN;
    745 	aio = p->p_aio;
    746 
    747 	nent = SCARG(uap, nent);
    748 	if (nent <= 0 || nent > aio_listio_max)
    749 		return EAGAIN;
    750 
    751 	if (SCARG(uap, timeout)) {
    752 		/* Convert timespec to ticks */
    753 		error = copyin(SCARG(uap, timeout), &ts,
    754 		    sizeof(struct timespec));
    755 		if (error)
    756 			return error;
    757 		timo = mstohz((ts.tv_sec * 1000) + (ts.tv_nsec / 1000000));
    758 		if (timo == 0 && ts.tv_sec == 0 && ts.tv_nsec > 0)
    759 			timo = 1;
    760 		if (timo <= 0)
    761 			return EAGAIN;
    762 	} else
    763 		timo = 0;
    764 
    765 	/* Get the list from user-space */
    766 	aiocbp_list = kmem_zalloc(nent * sizeof(struct aio_job), KM_SLEEP);
    767 	error = copyin(SCARG(uap, list), aiocbp_list,
    768 	    nent * sizeof(struct aiocb));
    769 	if (error) {
    770 		kmem_free(aiocbp_list, nent * sizeof(struct aio_job));
    771 		return error;
    772 	}
    773 
    774 	mutex_enter(&aio->aio_mtx);
    775 	for (;;) {
    776 
    777 		for (i = 0; i < nent; i++) {
    778 
    779 			/* Skip NULL entries */
    780 			if (aiocbp_list[i] == NULL)
    781 				continue;
    782 
    783 			/* Skip current job */
    784 			if (aio->curjob) {
    785 				a_job = aio->curjob;
    786 				if (a_job->aiocb_uptr == aiocbp_list[i])
    787 					continue;
    788 			}
    789 
    790 			/* Look for a job in the queue */
    791 			TAILQ_FOREACH(a_job, &aio->jobs_queue, list)
    792 				if (a_job->aiocb_uptr == aiocbp_list[i])
    793 					break;
    794 
    795 			if (a_job == NULL) {
    796 				struct aiocb aiocbp;
    797 
    798 				mutex_exit(&aio->aio_mtx);
    799 
    800 				error = copyin(aiocbp_list[i], &aiocbp,
    801 				    sizeof(struct aiocb));
    802 				if (error == 0 && aiocbp._state != JOB_DONE) {
    803 					mutex_enter(&aio->aio_mtx);
    804 					continue;
    805 				}
    806 
    807 				kmem_free(aiocbp_list,
    808 				    nent * sizeof(struct aio_job));
    809 				return error;
    810 			}
    811 		}
    812 
    813 		/* Wait for a signal or when timeout occurs */
    814 		error = cv_timedwait_sig(&aio->done_cv, &aio->aio_mtx, timo);
    815 		if (error) {
    816 			if (error == EWOULDBLOCK)
    817 				error = EAGAIN;
    818 			break;
    819 		}
    820 	}
    821 	mutex_exit(&aio->aio_mtx);
    822 
    823 	kmem_free(aiocbp_list, nent * sizeof(struct aio_job));
    824 	return error;
    825 }
    826 
    827 int
    828 sys_aio_write(struct lwp *l, void *v, register_t *retval)
    829 {
    830 	struct sys_aio_write_args /* {
    831 		syscallarg(struct aiocb *) aiocbp;
    832 	} */ *uap = v;
    833 
    834 	return aio_enqueue_job(AIO_WRITE, SCARG(uap, aiocbp), NULL);
    835 }
    836 
    837 int
    838 sys_lio_listio(struct lwp *l, void *v, register_t *retval)
    839 {
    840 	struct sys_lio_listio_args /* {
    841 		syscallarg(int) mode;
    842 		syscallarg(struct aiocb *const[]) list;
    843 		syscallarg(int) nent;
    844 		syscallarg(struct sigevent *) sig;
    845 	} */ *uap = v;
    846 	struct proc *p = l->l_proc;
    847 	struct aioproc *aio;
    848 	struct aiocb **aiocbp_list;
    849 	struct lio_req *lio;
    850 	int i, error, errcnt, mode, nent;
    851 
    852 	mode = SCARG(uap, mode);
    853 	nent = SCARG(uap, nent);
    854 
    855 	/* Check for the limits, and invalid values */
    856 	if (nent < 1 || nent > aio_listio_max)
    857 		return EINVAL;
    858 	if (aio_jobs_count + nent > aio_max) /* XXXSMP */
    859 		return EAGAIN;
    860 
    861 	/* Check if AIO structure is initialized, if not - initialize it */
    862 	if (p->p_aio == NULL)
    863 		if (aio_init(p))
    864 			return EAGAIN;
    865 	aio = p->p_aio;
    866 
    867 	/* Create a LIO structure */
    868 	lio = pool_get(&aio_lio_pool, PR_WAITOK);
    869 	lio->refcnt = 1;
    870 	error = 0;
    871 
    872 	switch (mode) {
    873 	case LIO_WAIT:
    874 		memset(&lio->sig, 0, sizeof(struct sigevent));
    875 		break;
    876 	case LIO_NOWAIT:
    877 		/* Check for signal, validate it */
    878 		if (SCARG(uap, sig)) {
    879 			struct sigevent *sig = &lio->sig;
    880 
    881 			error = copyin(SCARG(uap, sig), &lio->sig,
    882 			    sizeof(struct sigevent));
    883 			if (error == 0 &&
    884 			    (sig->sigev_signo < 0 ||
    885 			    sig->sigev_signo >= NSIG ||
    886 			    sig->sigev_notify < SIGEV_NONE ||
    887 			    sig->sigev_notify > SIGEV_SA))
    888 				error = EINVAL;
    889 		} else
    890 			memset(&lio->sig, 0, sizeof(struct sigevent));
    891 		break;
    892 	default:
    893 		error = EINVAL;
    894 		break;
    895 	}
    896 
    897 	if (error != 0) {
    898 		pool_put(&aio_lio_pool, lio);
    899 		return error;
    900 	}
    901 
    902 	/* Get the list from user-space */
    903 	aiocbp_list = kmem_zalloc(nent * sizeof(struct aio_job), KM_SLEEP);
    904 	error = copyin(SCARG(uap, list), aiocbp_list,
    905 	    nent * sizeof(struct aiocb));
    906 	if (error) {
    907 		mutex_enter(&aio->aio_mtx);
    908 		goto err;
    909 	}
    910 
    911 	/* Enqueue all jobs */
    912 	errcnt = 0;
    913 	for (i = 0; i < nent; i++) {
    914 		error = aio_enqueue_job(AIO_LIO, aiocbp_list[i], lio);
    915 		/*
    916 		 * According to POSIX, in such error case it may
    917 		 * fail with other I/O operations initiated.
    918 		 */
    919 		if (error)
    920 			errcnt++;
    921 	}
    922 
    923 	mutex_enter(&aio->aio_mtx);
    924 
    925 	/* Return an error, if any */
    926 	if (errcnt) {
    927 		error = EIO;
    928 		goto err;
    929 	}
    930 
    931 	if (mode == LIO_WAIT) {
    932 		/*
    933 		 * Wait for AIO completion.  In such case,
    934 		 * the LIO structure will be freed here.
    935 		 */
    936 		while (lio->refcnt > 1 && error == 0)
    937 			error = cv_wait_sig(&aio->done_cv, &aio->aio_mtx);
    938 		if (error)
    939 			error = EINTR;
    940 	}
    941 
    942 err:
    943 	if (--lio->refcnt != 0)
    944 		lio = NULL;
    945 	mutex_exit(&aio->aio_mtx);
    946 	if (lio != NULL) {
    947 		aio_sendsig(p, &lio->sig);
    948 		pool_put(&aio_lio_pool, lio);
    949 	}
    950 	kmem_free(aiocbp_list, nent * sizeof(struct aio_job));
    951 	return error;
    952 }
    953 
    954 /*
    955  * SysCtl
    956  */
    957 
    958 static int
    959 sysctl_aio_listio_max(SYSCTLFN_ARGS)
    960 {
    961 	struct sysctlnode node;
    962 	int error, newsize;
    963 
    964 	node = *rnode;
    965 	node.sysctl_data = &newsize;
    966 
    967 	newsize = aio_listio_max;
    968 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    969 	if (error || newp == NULL)
    970 		return error;
    971 
    972 	/* XXXSMP */
    973 	if (newsize < 1 || newsize > aio_max)
    974 		return EINVAL;
    975 	aio_listio_max = newsize;
    976 
    977 	return 0;
    978 }
    979 
    980 static int
    981 sysctl_aio_max(SYSCTLFN_ARGS)
    982 {
    983 	struct sysctlnode node;
    984 	int error, newsize;
    985 
    986 	node = *rnode;
    987 	node.sysctl_data = &newsize;
    988 
    989 	newsize = aio_max;
    990 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    991 	if (error || newp == NULL)
    992 		return error;
    993 
    994 	/* XXXSMP */
    995 	if (newsize < 1 || newsize < aio_listio_max)
    996 		return EINVAL;
    997 	aio_max = newsize;
    998 
    999 	return 0;
   1000 }
   1001 
   1002 SYSCTL_SETUP(sysctl_aio_setup, "sysctl aio setup")
   1003 {
   1004 
   1005 	sysctl_createv(clog, 0, NULL, NULL,
   1006 		CTLFLAG_PERMANENT,
   1007 		CTLTYPE_NODE, "kern", NULL,
   1008 		NULL, 0, NULL, 0,
   1009 		CTL_KERN, CTL_EOL);
   1010 	sysctl_createv(clog, 0, NULL, NULL,
   1011 		CTLFLAG_PERMANENT | CTLFLAG_IMMEDIATE,
   1012 		CTLTYPE_INT, "posix_aio",
   1013 		SYSCTL_DESCR("Version of IEEE Std 1003.1 and its "
   1014 			     "Asynchronous I/O option to which the "
   1015 			     "system attempts to conform"),
   1016 		NULL, _POSIX_ASYNCHRONOUS_IO, NULL, 0,
   1017 		CTL_KERN, CTL_CREATE, CTL_EOL);
   1018 	sysctl_createv(clog, 0, NULL, NULL,
   1019 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1020 		CTLTYPE_INT, "aio_listio_max",
   1021 		SYSCTL_DESCR("Maximum number of asynchronous I/O "
   1022 			     "operations in a single list I/O call"),
   1023 		sysctl_aio_listio_max, 0, &aio_listio_max, 0,
   1024 		CTL_KERN, CTL_CREATE, CTL_EOL);
   1025 	sysctl_createv(clog, 0, NULL, NULL,
   1026 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1027 		CTLTYPE_INT, "aio_max",
   1028 		SYSCTL_DESCR("Maximum number of asynchronous I/O "
   1029 			     "operations"),
   1030 		sysctl_aio_max, 0, &aio_max, 0,
   1031 		CTL_KERN, CTL_CREATE, CTL_EOL);
   1032 }
   1033 
   1034 /*
   1035  * Debugging
   1036  */
   1037 #if defined(DDB)
   1038 void
   1039 aio_print_jobs(void (*pr)(const char *, ...))
   1040 {
   1041 	struct proc *p = (curlwp == NULL ? NULL : curlwp->l_proc);
   1042 	struct aioproc *aio;
   1043 	struct aio_job *a_job;
   1044 	struct aiocb *aiocbp;
   1045 
   1046 	if (p == NULL) {
   1047 		(*pr)("AIO: We are not in the processes right now.\n");
   1048 		return;
   1049 	}
   1050 
   1051 	aio = p->p_aio;
   1052 	if (aio == NULL) {
   1053 		(*pr)("AIO data is not initialized (PID = %d).\n", p->p_pid);
   1054 		return;
   1055 	}
   1056 
   1057 	(*pr)("AIO: PID = %d\n", p->p_pid);
   1058 	(*pr)("AIO: Global count of the jobs = %u\n", aio_jobs_count);
   1059 	(*pr)("AIO: Count of the jobs = %u\n", aio->jobs_count);
   1060 
   1061 	if (aio->curjob) {
   1062 		a_job = aio->curjob;
   1063 		(*pr)("\nAIO current job:\n");
   1064 		(*pr)(" opcode = %d, errno = %d, state = %d, aiocb_ptr = %p\n",
   1065 		    a_job->aio_op, a_job->aiocbp._errno,
   1066 		    a_job->aiocbp._state, a_job->aiocb_uptr);
   1067 		aiocbp = &a_job->aiocbp;
   1068 		(*pr)("   fd = %d, offset = %u, buf = %p, nbytes = %u\n",
   1069 		    aiocbp->aio_fildes, aiocbp->aio_offset,
   1070 		    aiocbp->aio_buf, aiocbp->aio_nbytes);
   1071 	}
   1072 
   1073 	(*pr)("\nAIO queue:\n");
   1074 	TAILQ_FOREACH(a_job, &aio->jobs_queue, list) {
   1075 		(*pr)(" opcode = %d, errno = %d, state = %d, aiocb_ptr = %p\n",
   1076 		    a_job->aio_op, a_job->aiocbp._errno,
   1077 		    a_job->aiocbp._state, a_job->aiocb_uptr);
   1078 		aiocbp = &a_job->aiocbp;
   1079 		(*pr)("   fd = %d, offset = %u, buf = %p, nbytes = %u\n",
   1080 		    aiocbp->aio_fildes, aiocbp->aio_offset,
   1081 		    aiocbp->aio_buf, aiocbp->aio_nbytes);
   1082 	}
   1083 }
   1084 #endif /* defined(DDB) */
   1085