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