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