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