xref: /freebsd/sys/kern/vfs_aio.c (revision 3642298923e528d795e3a30ec165d2b469e28b40)
1 /*-
2  * Copyright (c) 1997 John S. Dyson.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. John S. Dyson's name may not be used to endorse or promote products
10  *    derived from this software without specific prior written permission.
11  *
12  * DISCLAIMER:  This code isn't warranted to do anything useful.  Anything
13  * bad that happens because of using this software isn't the responsibility
14  * of the author.  This software is distributed AS-IS.
15  */
16 
17 /*
18  * This file contains support for the POSIX 1003.1B AIO/LIO facility.
19  */
20 
21 #include <sys/cdefs.h>
22 __FBSDID("$FreeBSD$");
23 
24 #include <sys/param.h>
25 #include <sys/systm.h>
26 #include <sys/malloc.h>
27 #include <sys/bio.h>
28 #include <sys/buf.h>
29 #include <sys/eventhandler.h>
30 #include <sys/sysproto.h>
31 #include <sys/filedesc.h>
32 #include <sys/kernel.h>
33 #include <sys/module.h>
34 #include <sys/kthread.h>
35 #include <sys/fcntl.h>
36 #include <sys/file.h>
37 #include <sys/limits.h>
38 #include <sys/lock.h>
39 #include <sys/mutex.h>
40 #include <sys/unistd.h>
41 #include <sys/proc.h>
42 #include <sys/resourcevar.h>
43 #include <sys/signalvar.h>
44 #include <sys/protosw.h>
45 #include <sys/socketvar.h>
46 #include <sys/syscall.h>
47 #include <sys/sysent.h>
48 #include <sys/sysctl.h>
49 #include <sys/sx.h>
50 #include <sys/vnode.h>
51 #include <sys/conf.h>
52 #include <sys/event.h>
53 
54 #include <posix4/posix4.h>
55 #include <vm/vm.h>
56 #include <vm/vm_extern.h>
57 #include <vm/pmap.h>
58 #include <vm/vm_map.h>
59 #include <vm/uma.h>
60 #include <sys/aio.h>
61 
62 #include "opt_vfs_aio.h"
63 
64 NET_NEEDS_GIANT("aio");
65 
66 /*
67  * Counter for allocating reference ids to new jobs.  Wrapped to 1 on
68  * overflow.
69  */
70 static	long jobrefid;
71 
72 #define JOBST_NULL		0x0
73 #define JOBST_JOBQGLOBAL	0x2
74 #define JOBST_JOBRUNNING	0x3
75 #define JOBST_JOBFINISHED	0x4
76 #define	JOBST_JOBQBUF		0x5
77 #define	JOBST_JOBBFINISHED	0x6
78 
79 #ifndef MAX_AIO_PER_PROC
80 #define MAX_AIO_PER_PROC	32
81 #endif
82 
83 #ifndef MAX_AIO_QUEUE_PER_PROC
84 #define MAX_AIO_QUEUE_PER_PROC	256 /* Bigger than AIO_LISTIO_MAX */
85 #endif
86 
87 #ifndef MAX_AIO_PROCS
88 #define MAX_AIO_PROCS		32
89 #endif
90 
91 #ifndef MAX_AIO_QUEUE
92 #define	MAX_AIO_QUEUE		1024 /* Bigger than AIO_LISTIO_MAX */
93 #endif
94 
95 #ifndef TARGET_AIO_PROCS
96 #define TARGET_AIO_PROCS	4
97 #endif
98 
99 #ifndef MAX_BUF_AIO
100 #define MAX_BUF_AIO		16
101 #endif
102 
103 #ifndef AIOD_TIMEOUT_DEFAULT
104 #define	AIOD_TIMEOUT_DEFAULT	(10 * hz)
105 #endif
106 
107 #ifndef AIOD_LIFETIME_DEFAULT
108 #define AIOD_LIFETIME_DEFAULT	(30 * hz)
109 #endif
110 
111 static SYSCTL_NODE(_vfs, OID_AUTO, aio, CTLFLAG_RW, 0, "Async IO management");
112 
113 static int max_aio_procs = MAX_AIO_PROCS;
114 SYSCTL_INT(_vfs_aio, OID_AUTO, max_aio_procs,
115 	CTLFLAG_RW, &max_aio_procs, 0,
116 	"Maximum number of kernel threads to use for handling async IO ");
117 
118 static int num_aio_procs = 0;
119 SYSCTL_INT(_vfs_aio, OID_AUTO, num_aio_procs,
120 	CTLFLAG_RD, &num_aio_procs, 0,
121 	"Number of presently active kernel threads for async IO");
122 
123 /*
124  * The code will adjust the actual number of AIO processes towards this
125  * number when it gets a chance.
126  */
127 static int target_aio_procs = TARGET_AIO_PROCS;
128 SYSCTL_INT(_vfs_aio, OID_AUTO, target_aio_procs, CTLFLAG_RW, &target_aio_procs,
129 	0, "Preferred number of ready kernel threads for async IO");
130 
131 static int max_queue_count = MAX_AIO_QUEUE;
132 SYSCTL_INT(_vfs_aio, OID_AUTO, max_aio_queue, CTLFLAG_RW, &max_queue_count, 0,
133     "Maximum number of aio requests to queue, globally");
134 
135 static int num_queue_count = 0;
136 SYSCTL_INT(_vfs_aio, OID_AUTO, num_queue_count, CTLFLAG_RD, &num_queue_count, 0,
137     "Number of queued aio requests");
138 
139 static int num_buf_aio = 0;
140 SYSCTL_INT(_vfs_aio, OID_AUTO, num_buf_aio, CTLFLAG_RD, &num_buf_aio, 0,
141     "Number of aio requests presently handled by the buf subsystem");
142 
143 /* Number of async I/O thread in the process of being started */
144 /* XXX This should be local to _aio_aqueue() */
145 static int num_aio_resv_start = 0;
146 
147 static int aiod_timeout;
148 SYSCTL_INT(_vfs_aio, OID_AUTO, aiod_timeout, CTLFLAG_RW, &aiod_timeout, 0,
149     "Timeout value for synchronous aio operations");
150 
151 static int aiod_lifetime;
152 SYSCTL_INT(_vfs_aio, OID_AUTO, aiod_lifetime, CTLFLAG_RW, &aiod_lifetime, 0,
153     "Maximum lifetime for idle aiod");
154 
155 static int unloadable = 0;
156 SYSCTL_INT(_vfs_aio, OID_AUTO, unloadable, CTLFLAG_RW, &unloadable, 0,
157     "Allow unload of aio (not recommended)");
158 
159 
160 static int max_aio_per_proc = MAX_AIO_PER_PROC;
161 SYSCTL_INT(_vfs_aio, OID_AUTO, max_aio_per_proc, CTLFLAG_RW, &max_aio_per_proc,
162     0, "Maximum active aio requests per process (stored in the process)");
163 
164 static int max_aio_queue_per_proc = MAX_AIO_QUEUE_PER_PROC;
165 SYSCTL_INT(_vfs_aio, OID_AUTO, max_aio_queue_per_proc, CTLFLAG_RW,
166     &max_aio_queue_per_proc, 0,
167     "Maximum queued aio requests per process (stored in the process)");
168 
169 static int max_buf_aio = MAX_BUF_AIO;
170 SYSCTL_INT(_vfs_aio, OID_AUTO, max_buf_aio, CTLFLAG_RW, &max_buf_aio, 0,
171     "Maximum buf aio requests per process (stored in the process)");
172 
173 struct aiocblist {
174 	TAILQ_ENTRY(aiocblist) list;	/* List of jobs */
175 	TAILQ_ENTRY(aiocblist) plist;	/* List of jobs for proc */
176 	int	jobflags;
177 	int	jobstate;
178 	int	inputcharge;
179 	int	outputcharge;
180 	struct	buf *bp;		/* Buffer pointer */
181 	struct	proc *userproc;		/* User process */ /* Not td! */
182 	struct  ucred *cred;		/* Active credential when created */
183 	struct	file *fd_file;		/* Pointer to file structure */
184 	struct	aio_liojob *lio;	/* Optional lio job */
185 	struct	aiocb *uuaiocb;		/* Pointer in userspace of aiocb */
186 	struct	knlist klist;		/* list of knotes */
187 	struct	aiocb uaiocb;		/* Kernel I/O control block */
188 };
189 
190 /* jobflags */
191 #define AIOCBLIST_RUNDOWN	0x4
192 #define AIOCBLIST_DONE		0x10
193 
194 /*
195  * AIO process info
196  */
197 #define AIOP_FREE	0x1			/* proc on free queue */
198 
199 struct aiothreadlist {
200 	int aiothreadflags;			/* AIO proc flags */
201 	TAILQ_ENTRY(aiothreadlist) list;	/* List of processes */
202 	struct thread *aiothread;		/* The AIO thread */
203 };
204 
205 /*
206  * data-structure for lio signal management
207  */
208 struct aio_liojob {
209 	int	lioj_flags;
210 	int	lioj_buffer_count;
211 	int	lioj_buffer_finished_count;
212 	int	lioj_queue_count;
213 	int	lioj_queue_finished_count;
214 	struct	sigevent lioj_signal;	/* signal on all I/O done */
215 	TAILQ_ENTRY(aio_liojob) lioj_list;
216 };
217 #define	LIOJ_SIGNAL		0x1	/* signal on all done (lio) */
218 #define	LIOJ_SIGNAL_POSTED	0x2	/* signal has been posted */
219 
220 /*
221  * per process aio data structure
222  */
223 struct kaioinfo {
224 	int	kaio_flags;		/* per process kaio flags */
225 	int	kaio_maxactive_count;	/* maximum number of AIOs */
226 	int	kaio_active_count;	/* number of currently used AIOs */
227 	int	kaio_qallowed_count;	/* maxiumu size of AIO queue */
228 	int	kaio_queue_count;	/* size of AIO queue */
229 	int	kaio_ballowed_count;	/* maximum number of buffers */
230 	int	kaio_queue_finished_count; /* number of daemon jobs finished */
231 	int	kaio_buffer_count;	/* number of physio buffers */
232 	int	kaio_buffer_finished_count; /* count of I/O done */
233 	TAILQ_HEAD(,aio_liojob) kaio_liojoblist; /* list of lio jobs */
234 	TAILQ_HEAD(,aiocblist) kaio_jobqueue;	/* job queue for process */
235 	TAILQ_HEAD(,aiocblist) kaio_jobdone;	/* done queue for process */
236 	TAILQ_HEAD(,aiocblist) kaio_bufqueue;	/* buffer job queue for process */
237 	TAILQ_HEAD(,aiocblist) kaio_bufdone;	/* buffer done queue for process */
238 	TAILQ_HEAD(,aiocblist) kaio_sockqueue;	/* queue for aios waiting on sockets */
239 };
240 
241 #define KAIO_RUNDOWN	0x1	/* process is being run down */
242 #define KAIO_WAKEUP	0x2	/* wakeup process when there is a significant event */
243 
244 static TAILQ_HEAD(,aiothreadlist) aio_freeproc;		/* Idle daemons */
245 static struct mtx aio_freeproc_mtx;
246 
247 static TAILQ_HEAD(,aiocblist) aio_jobs;			/* Async job list */
248 
249 static void	aio_init_aioinfo(struct proc *p);
250 static void	aio_onceonly(void);
251 static int	aio_free_entry(struct aiocblist *aiocbe);
252 static void	aio_process(struct aiocblist *aiocbe);
253 static int	aio_newproc(void);
254 static int	aio_aqueue(struct thread *td, struct aiocb *job, int type);
255 static void	aio_physwakeup(struct buf *bp);
256 static void	aio_proc_rundown(void *arg, struct proc *p);
257 static int	aio_fphysio(struct aiocblist *aiocbe);
258 static int	aio_qphysio(struct proc *p, struct aiocblist *iocb);
259 static void	aio_daemon(void *uproc);
260 static void	aio_swake_cb(struct socket *, struct sockbuf *);
261 static int	aio_unload(void);
262 static int	filt_aioattach(struct knote *kn);
263 static void	filt_aiodetach(struct knote *kn);
264 static int	filt_aio(struct knote *kn, long hint);
265 
266 /*
267  * Zones for:
268  * 	kaio	Per process async io info
269  *	aiop	async io thread data
270  *	aiocb	async io jobs
271  *	aiol	list io job pointer - internal to aio_suspend XXX
272  *	aiolio	list io jobs
273  */
274 static uma_zone_t kaio_zone, aiop_zone, aiocb_zone, aiol_zone, aiolio_zone;
275 
276 /* kqueue filters for aio */
277 static struct filterops aio_filtops =
278 	{ 0, filt_aioattach, filt_aiodetach, filt_aio };
279 
280 static eventhandler_tag exit_tag, exec_tag;
281 
282 /*
283  * Main operations function for use as a kernel module.
284  */
285 static int
286 aio_modload(struct module *module, int cmd, void *arg)
287 {
288 	int error = 0;
289 
290 	switch (cmd) {
291 	case MOD_LOAD:
292 		aio_onceonly();
293 		break;
294 	case MOD_UNLOAD:
295 		error = aio_unload();
296 		break;
297 	case MOD_SHUTDOWN:
298 		break;
299 	default:
300 		error = EINVAL;
301 		break;
302 	}
303 	return (error);
304 }
305 
306 static moduledata_t aio_mod = {
307 	"aio",
308 	&aio_modload,
309 	NULL
310 };
311 
312 SYSCALL_MODULE_HELPER(aio_return);
313 SYSCALL_MODULE_HELPER(aio_suspend);
314 SYSCALL_MODULE_HELPER(aio_cancel);
315 SYSCALL_MODULE_HELPER(aio_error);
316 SYSCALL_MODULE_HELPER(aio_read);
317 SYSCALL_MODULE_HELPER(aio_write);
318 SYSCALL_MODULE_HELPER(aio_waitcomplete);
319 SYSCALL_MODULE_HELPER(lio_listio);
320 
321 DECLARE_MODULE(aio, aio_mod,
322 	SI_SUB_VFS, SI_ORDER_ANY);
323 MODULE_VERSION(aio, 1);
324 
325 /*
326  * Startup initialization
327  */
328 static void
329 aio_onceonly(void)
330 {
331 
332 	/* XXX: should probably just use so->callback */
333 	aio_swake = &aio_swake_cb;
334 	exit_tag = EVENTHANDLER_REGISTER(process_exit, aio_proc_rundown, NULL,
335 	    EVENTHANDLER_PRI_ANY);
336 	exec_tag = EVENTHANDLER_REGISTER(process_exec, aio_proc_rundown, NULL,
337 	    EVENTHANDLER_PRI_ANY);
338 	kqueue_add_filteropts(EVFILT_AIO, &aio_filtops);
339 	TAILQ_INIT(&aio_freeproc);
340 	mtx_init(&aio_freeproc_mtx, "aio_freeproc", NULL, MTX_DEF);
341 	TAILQ_INIT(&aio_jobs);
342 	kaio_zone = uma_zcreate("AIO", sizeof(struct kaioinfo), NULL, NULL,
343 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
344 	aiop_zone = uma_zcreate("AIOP", sizeof(struct aiothreadlist), NULL,
345 	    NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
346 	aiocb_zone = uma_zcreate("AIOCB", sizeof(struct aiocblist), NULL, NULL,
347 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
348 	aiol_zone = uma_zcreate("AIOL", AIO_LISTIO_MAX*sizeof(intptr_t) , NULL,
349 	    NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
350 	aiolio_zone = uma_zcreate("AIOLIO", sizeof(struct aio_liojob), NULL,
351 	    NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
352 	aiod_timeout = AIOD_TIMEOUT_DEFAULT;
353 	aiod_lifetime = AIOD_LIFETIME_DEFAULT;
354 	jobrefid = 1;
355 	async_io_version = _POSIX_VERSION;
356 	p31b_setcfg(CTL_P1003_1B_AIO_LISTIO_MAX, AIO_LISTIO_MAX);
357 	p31b_setcfg(CTL_P1003_1B_AIO_MAX, MAX_AIO_QUEUE);
358 	p31b_setcfg(CTL_P1003_1B_AIO_PRIO_DELTA_MAX, 0);
359 }
360 
361 /*
362  * Callback for unload of AIO when used as a module.
363  */
364 static int
365 aio_unload(void)
366 {
367 	int error;
368 
369 	/*
370 	 * XXX: no unloads by default, it's too dangerous.
371 	 * perhaps we could do it if locked out callers and then
372 	 * did an aio_proc_rundown() on each process.
373 	 */
374 	if (!unloadable)
375 		return (EOPNOTSUPP);
376 
377 	error = kqueue_del_filteropts(EVFILT_AIO);
378 	if (error)
379 		return error;
380 
381 	async_io_version = 0;
382 	aio_swake = NULL;
383 	EVENTHANDLER_DEREGISTER(process_exit, exit_tag);
384 	EVENTHANDLER_DEREGISTER(process_exec, exec_tag);
385 	p31b_setcfg(CTL_P1003_1B_AIO_LISTIO_MAX, -1);
386 	p31b_setcfg(CTL_P1003_1B_AIO_MAX, -1);
387 	p31b_setcfg(CTL_P1003_1B_AIO_PRIO_DELTA_MAX, -1);
388 	return (0);
389 }
390 
391 /*
392  * Init the per-process aioinfo structure.  The aioinfo limits are set
393  * per-process for user limit (resource) management.
394  */
395 static void
396 aio_init_aioinfo(struct proc *p)
397 {
398 	struct kaioinfo *ki;
399 
400 	ki = uma_zalloc(kaio_zone, M_WAITOK);
401 	ki->kaio_flags = 0;
402 	ki->kaio_maxactive_count = max_aio_per_proc;
403 	ki->kaio_active_count = 0;
404 	ki->kaio_qallowed_count = max_aio_queue_per_proc;
405 	ki->kaio_queue_count = 0;
406 	ki->kaio_ballowed_count = max_buf_aio;
407 	ki->kaio_buffer_count = 0;
408 	ki->kaio_buffer_finished_count = 0;
409 	TAILQ_INIT(&ki->kaio_jobdone);
410 	TAILQ_INIT(&ki->kaio_jobqueue);
411 	TAILQ_INIT(&ki->kaio_bufdone);
412 	TAILQ_INIT(&ki->kaio_bufqueue);
413 	TAILQ_INIT(&ki->kaio_liojoblist);
414 	TAILQ_INIT(&ki->kaio_sockqueue);
415 	PROC_LOCK(p);
416 	if (p->p_aioinfo == NULL) {
417 		p->p_aioinfo = ki;
418 		PROC_UNLOCK(p);
419 	} else {
420 		PROC_UNLOCK(p);
421 		uma_zfree(kaio_zone, ki);
422 	}
423 
424 	while (num_aio_procs < target_aio_procs)
425 		aio_newproc();
426 }
427 
428 /*
429  * Free a job entry.  Wait for completion if it is currently active, but don't
430  * delay forever.  If we delay, we return a flag that says that we have to
431  * restart the queue scan.
432  */
433 static int
434 aio_free_entry(struct aiocblist *aiocbe)
435 {
436 	struct kaioinfo *ki;
437 	struct aio_liojob *lj;
438 	struct proc *p;
439 	int error;
440 	int s;
441 
442 	if (aiocbe->jobstate == JOBST_NULL)
443 		panic("aio_free_entry: freeing already free job");
444 
445 	p = aiocbe->userproc;
446 	ki = p->p_aioinfo;
447 	lj = aiocbe->lio;
448 	if (ki == NULL)
449 		panic("aio_free_entry: missing p->p_aioinfo");
450 
451 	while (aiocbe->jobstate == JOBST_JOBRUNNING) {
452 		aiocbe->jobflags |= AIOCBLIST_RUNDOWN;
453 		tsleep(aiocbe, PRIBIO, "jobwai", 0);
454 	}
455 	if (aiocbe->bp == NULL) {
456 		if (ki->kaio_queue_count <= 0)
457 			panic("aio_free_entry: process queue size <= 0");
458 		if (num_queue_count <= 0)
459 			panic("aio_free_entry: system wide queue size <= 0");
460 
461 		if (lj) {
462 			lj->lioj_queue_count--;
463 			if (aiocbe->jobflags & AIOCBLIST_DONE)
464 				lj->lioj_queue_finished_count--;
465 		}
466 		ki->kaio_queue_count--;
467 		if (aiocbe->jobflags & AIOCBLIST_DONE)
468 			ki->kaio_queue_finished_count--;
469 		num_queue_count--;
470 	} else {
471 		if (lj) {
472 			lj->lioj_buffer_count--;
473 			if (aiocbe->jobflags & AIOCBLIST_DONE)
474 				lj->lioj_buffer_finished_count--;
475 		}
476 		if (aiocbe->jobflags & AIOCBLIST_DONE)
477 			ki->kaio_buffer_finished_count--;
478 		ki->kaio_buffer_count--;
479 		num_buf_aio--;
480 	}
481 
482 	/* aiocbe is going away, we need to destroy any knotes */
483 	/* XXXKSE Note the thread here is used to eventually find the
484 	 * owning process again, but it is also used to do a fo_close
485 	 * and that requires the thread. (but does it require the
486 	 * OWNING thread? (or maybe the running thread?)
487 	 * There is a semantic problem here...
488 	 */
489 	knlist_delete(&aiocbe->klist, FIRST_THREAD_IN_PROC(p), 0); /* XXXKSE */
490 
491 	if ((ki->kaio_flags & KAIO_WAKEUP) || ((ki->kaio_flags & KAIO_RUNDOWN)
492 	    && ((ki->kaio_buffer_count == 0) && (ki->kaio_queue_count == 0)))) {
493 		ki->kaio_flags &= ~KAIO_WAKEUP;
494 		wakeup(p);
495 	}
496 
497 	if (aiocbe->jobstate == JOBST_JOBQBUF) {
498 		if ((error = aio_fphysio(aiocbe)) != 0)
499 			return (error);
500 		if (aiocbe->jobstate != JOBST_JOBBFINISHED)
501 			panic("aio_free_entry: invalid physio finish-up state");
502 		s = splbio();
503 		TAILQ_REMOVE(&ki->kaio_bufdone, aiocbe, plist);
504 		splx(s);
505 	} else if (aiocbe->jobstate == JOBST_JOBQGLOBAL) {
506 		s = splnet();
507 		TAILQ_REMOVE(&aio_jobs, aiocbe, list);
508 		TAILQ_REMOVE(&ki->kaio_jobqueue, aiocbe, plist);
509 		splx(s);
510 	} else if (aiocbe->jobstate == JOBST_JOBFINISHED)
511 		TAILQ_REMOVE(&ki->kaio_jobdone, aiocbe, plist);
512 	else if (aiocbe->jobstate == JOBST_JOBBFINISHED) {
513 		s = splbio();
514 		TAILQ_REMOVE(&ki->kaio_bufdone, aiocbe, plist);
515 		splx(s);
516 		if (aiocbe->bp) {
517 			vunmapbuf(aiocbe->bp);
518 			relpbuf(aiocbe->bp, NULL);
519 			aiocbe->bp = NULL;
520 		}
521 	}
522 	if (lj && (lj->lioj_buffer_count == 0) && (lj->lioj_queue_count == 0)) {
523 		TAILQ_REMOVE(&ki->kaio_liojoblist, lj, lioj_list);
524 		uma_zfree(aiolio_zone, lj);
525 	}
526 	aiocbe->jobstate = JOBST_NULL;
527 	fdrop(aiocbe->fd_file, curthread);
528 	crfree(aiocbe->cred);
529 	uma_zfree(aiocb_zone, aiocbe);
530 	return (0);
531 }
532 
533 /*
534  * Rundown the jobs for a given process.
535  */
536 static void
537 aio_proc_rundown(void *arg, struct proc *p)
538 {
539 	int s;
540 	struct kaioinfo *ki;
541 	struct aio_liojob *lj, *ljn;
542 	struct aiocblist *aiocbe, *aiocbn;
543 	struct file *fp;
544 	struct socket *so;
545 
546 	ki = p->p_aioinfo;
547 	if (ki == NULL)
548 		return;
549 
550 	mtx_lock(&Giant);
551 	ki->kaio_flags |= LIOJ_SIGNAL_POSTED;
552 	while ((ki->kaio_active_count > 0) || (ki->kaio_buffer_count >
553 	    ki->kaio_buffer_finished_count)) {
554 		ki->kaio_flags |= KAIO_RUNDOWN;
555 		if (tsleep(p, PRIBIO, "kaiowt", aiod_timeout))
556 			break;
557 	}
558 
559 	/*
560 	 * Move any aio ops that are waiting on socket I/O to the normal job
561 	 * queues so they are cleaned up with any others.
562 	 */
563 	s = splnet();
564 	for (aiocbe = TAILQ_FIRST(&ki->kaio_sockqueue); aiocbe; aiocbe =
565 	    aiocbn) {
566 		aiocbn = TAILQ_NEXT(aiocbe, plist);
567 		fp = aiocbe->fd_file;
568 		if (fp != NULL) {
569 			so = fp->f_data;
570 			TAILQ_REMOVE(&so->so_aiojobq, aiocbe, list);
571 			if (TAILQ_EMPTY(&so->so_aiojobq)) {
572 				SOCKBUF_LOCK(&so->so_snd);
573 				so->so_snd.sb_flags &= ~SB_AIO;
574 				SOCKBUF_UNLOCK(&so->so_snd);
575 				SOCKBUF_LOCK(&so->so_rcv);
576 				so->so_rcv.sb_flags &= ~SB_AIO;
577 				SOCKBUF_UNLOCK(&so->so_rcv);
578 			}
579 		}
580 		TAILQ_REMOVE(&ki->kaio_sockqueue, aiocbe, plist);
581 		TAILQ_INSERT_HEAD(&aio_jobs, aiocbe, list);
582 		TAILQ_INSERT_HEAD(&ki->kaio_jobqueue, aiocbe, plist);
583 	}
584 	splx(s);
585 
586 restart1:
587 	for (aiocbe = TAILQ_FIRST(&ki->kaio_jobdone); aiocbe; aiocbe = aiocbn) {
588 		aiocbn = TAILQ_NEXT(aiocbe, plist);
589 		if (aio_free_entry(aiocbe))
590 			goto restart1;
591 	}
592 
593 restart2:
594 	for (aiocbe = TAILQ_FIRST(&ki->kaio_jobqueue); aiocbe; aiocbe =
595 	    aiocbn) {
596 		aiocbn = TAILQ_NEXT(aiocbe, plist);
597 		if (aio_free_entry(aiocbe))
598 			goto restart2;
599 	}
600 
601 /*
602  * Note the use of lots of splbio here, trying to avoid splbio for long chains
603  * of I/O.  Probably unnecessary.
604  */
605 restart3:
606 	s = splbio();
607 	while (TAILQ_FIRST(&ki->kaio_bufqueue)) {
608 		ki->kaio_flags |= KAIO_WAKEUP;
609 		tsleep(p, PRIBIO, "aioprn", 0);
610 		splx(s);
611 		goto restart3;
612 	}
613 	splx(s);
614 
615 restart4:
616 	s = splbio();
617 	for (aiocbe = TAILQ_FIRST(&ki->kaio_bufdone); aiocbe; aiocbe = aiocbn) {
618 		aiocbn = TAILQ_NEXT(aiocbe, plist);
619 		if (aio_free_entry(aiocbe)) {
620 			splx(s);
621 			goto restart4;
622 		}
623 	}
624 	splx(s);
625 
626 	/*
627 	 * If we've slept, jobs might have moved from one queue to another.
628 	 * Retry rundown if we didn't manage to empty the queues.
629 	 */
630 	if (TAILQ_FIRST(&ki->kaio_jobdone) != NULL ||
631 	    TAILQ_FIRST(&ki->kaio_jobqueue) != NULL ||
632 	    TAILQ_FIRST(&ki->kaio_bufqueue) != NULL ||
633 	    TAILQ_FIRST(&ki->kaio_bufdone) != NULL)
634 		goto restart1;
635 
636 	for (lj = TAILQ_FIRST(&ki->kaio_liojoblist); lj; lj = ljn) {
637 		ljn = TAILQ_NEXT(lj, lioj_list);
638 		if ((lj->lioj_buffer_count == 0) && (lj->lioj_queue_count ==
639 		    0)) {
640 			TAILQ_REMOVE(&ki->kaio_liojoblist, lj, lioj_list);
641 			uma_zfree(aiolio_zone, lj);
642 		} else {
643 #ifdef DIAGNOSTIC
644 			printf("LIO job not cleaned up: B:%d, BF:%d, Q:%d, "
645 			    "QF:%d\n", lj->lioj_buffer_count,
646 			    lj->lioj_buffer_finished_count,
647 			    lj->lioj_queue_count,
648 			    lj->lioj_queue_finished_count);
649 #endif
650 		}
651 	}
652 
653 	uma_zfree(kaio_zone, ki);
654 	p->p_aioinfo = NULL;
655 	mtx_unlock(&Giant);
656 }
657 
658 /*
659  * Select a job to run (called by an AIO daemon).
660  */
661 static struct aiocblist *
662 aio_selectjob(struct aiothreadlist *aiop)
663 {
664 	int s;
665 	struct aiocblist *aiocbe;
666 	struct kaioinfo *ki;
667 	struct proc *userp;
668 
669 	s = splnet();
670 	for (aiocbe = TAILQ_FIRST(&aio_jobs); aiocbe; aiocbe =
671 	    TAILQ_NEXT(aiocbe, list)) {
672 		userp = aiocbe->userproc;
673 		ki = userp->p_aioinfo;
674 
675 		if (ki->kaio_active_count < ki->kaio_maxactive_count) {
676 			TAILQ_REMOVE(&aio_jobs, aiocbe, list);
677 			splx(s);
678 			return (aiocbe);
679 		}
680 	}
681 	splx(s);
682 
683 	return (NULL);
684 }
685 
686 /*
687  * The AIO processing activity.  This is the code that does the I/O request for
688  * the non-physio version of the operations.  The normal vn operations are used,
689  * and this code should work in all instances for every type of file, including
690  * pipes, sockets, fifos, and regular files.
691  */
692 static void
693 aio_process(struct aiocblist *aiocbe)
694 {
695 	struct ucred *td_savedcred;
696 	struct thread *td;
697 	struct proc *mycp;
698 	struct aiocb *cb;
699 	struct file *fp;
700 	struct uio auio;
701 	struct iovec aiov;
702 	int cnt;
703 	int error;
704 	int oublock_st, oublock_end;
705 	int inblock_st, inblock_end;
706 
707 	td = curthread;
708 	td_savedcred = td->td_ucred;
709 	td->td_ucred = aiocbe->cred;
710 	mycp = td->td_proc;
711 	cb = &aiocbe->uaiocb;
712 	fp = aiocbe->fd_file;
713 
714 	aiov.iov_base = (void *)(uintptr_t)cb->aio_buf;
715 	aiov.iov_len = cb->aio_nbytes;
716 
717 	auio.uio_iov = &aiov;
718 	auio.uio_iovcnt = 1;
719 	auio.uio_offset = cb->aio_offset;
720 	auio.uio_resid = cb->aio_nbytes;
721 	cnt = cb->aio_nbytes;
722 	auio.uio_segflg = UIO_USERSPACE;
723 	auio.uio_td = td;
724 
725 	inblock_st = mycp->p_stats->p_ru.ru_inblock;
726 	oublock_st = mycp->p_stats->p_ru.ru_oublock;
727 	/*
728 	 * _aio_aqueue() acquires a reference to the file that is
729 	 * released in aio_free_entry().
730 	 */
731 	if (cb->aio_lio_opcode == LIO_READ) {
732 		auio.uio_rw = UIO_READ;
733 		error = fo_read(fp, &auio, fp->f_cred, FOF_OFFSET, td);
734 	} else {
735 		auio.uio_rw = UIO_WRITE;
736 		error = fo_write(fp, &auio, fp->f_cred, FOF_OFFSET, td);
737 	}
738 	inblock_end = mycp->p_stats->p_ru.ru_inblock;
739 	oublock_end = mycp->p_stats->p_ru.ru_oublock;
740 
741 	aiocbe->inputcharge = inblock_end - inblock_st;
742 	aiocbe->outputcharge = oublock_end - oublock_st;
743 
744 	if ((error) && (auio.uio_resid != cnt)) {
745 		if (error == ERESTART || error == EINTR || error == EWOULDBLOCK)
746 			error = 0;
747 		if ((error == EPIPE) && (cb->aio_lio_opcode == LIO_WRITE)) {
748 			PROC_LOCK(aiocbe->userproc);
749 			psignal(aiocbe->userproc, SIGPIPE);
750 			PROC_UNLOCK(aiocbe->userproc);
751 		}
752 	}
753 
754 	cnt -= auio.uio_resid;
755 	cb->_aiocb_private.error = error;
756 	cb->_aiocb_private.status = cnt;
757 	td->td_ucred = td_savedcred;
758 }
759 
760 /*
761  * The AIO daemon, most of the actual work is done in aio_process,
762  * but the setup (and address space mgmt) is done in this routine.
763  */
764 static void
765 aio_daemon(void *uproc)
766 {
767 	int s;
768 	struct aio_liojob *lj;
769 	struct aiocb *cb;
770 	struct aiocblist *aiocbe;
771 	struct aiothreadlist *aiop;
772 	struct kaioinfo *ki;
773 	struct proc *curcp, *mycp, *userp;
774 	struct vmspace *myvm, *tmpvm;
775 	struct thread *td = curthread;
776 	struct pgrp *newpgrp;
777 	struct session *newsess;
778 
779 	/*
780 	 * Local copies of curproc (cp) and vmspace (myvm)
781 	 */
782 	mycp = td->td_proc;
783 	myvm = mycp->p_vmspace;
784 
785 	KASSERT(mycp->p_textvp == NULL, ("kthread has a textvp"));
786 
787 	/*
788 	 * Allocate and ready the aio control info.  There is one aiop structure
789 	 * per daemon.
790 	 */
791 	aiop = uma_zalloc(aiop_zone, M_WAITOK);
792 	aiop->aiothread = td;
793 	aiop->aiothreadflags |= AIOP_FREE;
794 
795 	/*
796 	 * Place thread (lightweight process) onto the AIO free thread list.
797 	 */
798 	mtx_lock(&aio_freeproc_mtx);
799 	TAILQ_INSERT_HEAD(&aio_freeproc, aiop, list);
800 	mtx_unlock(&aio_freeproc_mtx);
801 
802 	/*
803 	 * Get rid of our current filedescriptors.  AIOD's don't need any
804 	 * filedescriptors, except as temporarily inherited from the client.
805 	 */
806 	mtx_lock(&Giant);
807 	fdfree(td);
808 
809 	mtx_unlock(&Giant);
810 	/* The daemon resides in its own pgrp. */
811 	MALLOC(newpgrp, struct pgrp *, sizeof(struct pgrp), M_PGRP,
812 		M_WAITOK | M_ZERO);
813 	MALLOC(newsess, struct session *, sizeof(struct session), M_SESSION,
814 		M_WAITOK | M_ZERO);
815 
816 	sx_xlock(&proctree_lock);
817 	enterpgrp(mycp, mycp->p_pid, newpgrp, newsess);
818 	sx_xunlock(&proctree_lock);
819 	mtx_lock(&Giant);
820 
821 	/*
822 	 * Wakeup parent process.  (Parent sleeps to keep from blasting away
823 	 * and creating too many daemons.)
824 	 */
825 	wakeup(mycp);
826 
827 	for (;;) {
828 		/*
829 		 * curcp is the current daemon process context.
830 		 * userp is the current user process context.
831 		 */
832 		curcp = mycp;
833 
834 		/*
835 		 * Take daemon off of free queue
836 		 */
837 		mtx_lock(&aio_freeproc_mtx);
838 		if (aiop->aiothreadflags & AIOP_FREE) {
839 			TAILQ_REMOVE(&aio_freeproc, aiop, list);
840 			aiop->aiothreadflags &= ~AIOP_FREE;
841 		}
842 		mtx_unlock(&aio_freeproc_mtx);
843 
844 		/*
845 		 * Check for jobs.
846 		 */
847 		while ((aiocbe = aio_selectjob(aiop)) != NULL) {
848 			cb = &aiocbe->uaiocb;
849 			userp = aiocbe->userproc;
850 
851 			aiocbe->jobstate = JOBST_JOBRUNNING;
852 
853 			/*
854 			 * Connect to process address space for user program.
855 			 */
856 			if (userp != curcp) {
857 				/*
858 				 * Save the current address space that we are
859 				 * connected to.
860 				 */
861 				tmpvm = mycp->p_vmspace;
862 
863 				/*
864 				 * Point to the new user address space, and
865 				 * refer to it.
866 				 */
867 				mycp->p_vmspace = userp->p_vmspace;
868 				atomic_add_int(&mycp->p_vmspace->vm_refcnt, 1);
869 
870 				/* Activate the new mapping. */
871 				pmap_activate(FIRST_THREAD_IN_PROC(mycp));
872 
873 				/*
874 				 * If the old address space wasn't the daemons
875 				 * own address space, then we need to remove the
876 				 * daemon's reference from the other process
877 				 * that it was acting on behalf of.
878 				 */
879 				if (tmpvm != myvm) {
880 					vmspace_free(tmpvm);
881 				}
882 				curcp = userp;
883 			}
884 
885 			ki = userp->p_aioinfo;
886 			lj = aiocbe->lio;
887 
888 			/* Account for currently active jobs. */
889 			ki->kaio_active_count++;
890 
891 			/* Do the I/O function. */
892 			aio_process(aiocbe);
893 
894 			/* Decrement the active job count. */
895 			ki->kaio_active_count--;
896 
897 			/*
898 			 * Increment the completion count for wakeup/signal
899 			 * comparisons.
900 			 */
901 			aiocbe->jobflags |= AIOCBLIST_DONE;
902 			ki->kaio_queue_finished_count++;
903 			if (lj)
904 				lj->lioj_queue_finished_count++;
905 			if ((ki->kaio_flags & KAIO_WAKEUP) || ((ki->kaio_flags
906 			    & KAIO_RUNDOWN) && (ki->kaio_active_count == 0))) {
907 				ki->kaio_flags &= ~KAIO_WAKEUP;
908 				wakeup(userp);
909 			}
910 
911 			s = splbio();
912 			if (lj && (lj->lioj_flags &
913 			    (LIOJ_SIGNAL|LIOJ_SIGNAL_POSTED)) == LIOJ_SIGNAL) {
914 				if ((lj->lioj_queue_finished_count ==
915 				    lj->lioj_queue_count) &&
916 				    (lj->lioj_buffer_finished_count ==
917 				    lj->lioj_buffer_count)) {
918 					PROC_LOCK(userp);
919 					psignal(userp,
920 					    lj->lioj_signal.sigev_signo);
921 					PROC_UNLOCK(userp);
922 					lj->lioj_flags |= LIOJ_SIGNAL_POSTED;
923 				}
924 			}
925 			splx(s);
926 
927 			aiocbe->jobstate = JOBST_JOBFINISHED;
928 
929 			s = splnet();
930 			TAILQ_REMOVE(&ki->kaio_jobqueue, aiocbe, plist);
931 			TAILQ_INSERT_TAIL(&ki->kaio_jobdone, aiocbe, plist);
932 			splx(s);
933 			KNOTE_UNLOCKED(&aiocbe->klist, 0);
934 
935 			if (aiocbe->jobflags & AIOCBLIST_RUNDOWN) {
936 				wakeup(aiocbe);
937 				aiocbe->jobflags &= ~AIOCBLIST_RUNDOWN;
938 			}
939 
940 			if (cb->aio_sigevent.sigev_notify == SIGEV_SIGNAL) {
941 				PROC_LOCK(userp);
942 				psignal(userp, cb->aio_sigevent.sigev_signo);
943 				PROC_UNLOCK(userp);
944 			}
945 		}
946 
947 		/*
948 		 * Disconnect from user address space.
949 		 */
950 		if (curcp != mycp) {
951 			/* Get the user address space to disconnect from. */
952 			tmpvm = mycp->p_vmspace;
953 
954 			/* Get original address space for daemon. */
955 			mycp->p_vmspace = myvm;
956 
957 			/* Activate the daemon's address space. */
958 			pmap_activate(FIRST_THREAD_IN_PROC(mycp));
959 #ifdef DIAGNOSTIC
960 			if (tmpvm == myvm) {
961 				printf("AIOD: vmspace problem -- %d\n",
962 				    mycp->p_pid);
963 			}
964 #endif
965 			/* Remove our vmspace reference. */
966 			vmspace_free(tmpvm);
967 
968 			curcp = mycp;
969 		}
970 
971 		mtx_lock(&aio_freeproc_mtx);
972 		TAILQ_INSERT_HEAD(&aio_freeproc, aiop, list);
973 		aiop->aiothreadflags |= AIOP_FREE;
974 
975 		/*
976 		 * If daemon is inactive for a long time, allow it to exit,
977 		 * thereby freeing resources.
978 		 */
979 		if (msleep(aiop->aiothread, &aio_freeproc_mtx, PDROP | PRIBIO,
980 		    "aiordy", aiod_lifetime)) {
981 			s = splnet();
982 			if (TAILQ_EMPTY(&aio_jobs)) {
983 				mtx_lock(&aio_freeproc_mtx);
984 				if ((aiop->aiothreadflags & AIOP_FREE) &&
985 				    (num_aio_procs > target_aio_procs)) {
986 					TAILQ_REMOVE(&aio_freeproc, aiop, list);
987 					mtx_unlock(&aio_freeproc_mtx);
988 					splx(s);
989 					uma_zfree(aiop_zone, aiop);
990 					num_aio_procs--;
991 #ifdef DIAGNOSTIC
992 					if (mycp->p_vmspace->vm_refcnt <= 1) {
993 						printf("AIOD: bad vm refcnt for"
994 						    " exiting daemon: %d\n",
995 						    mycp->p_vmspace->vm_refcnt);
996 					}
997 #endif
998 					kthread_exit(0);
999 				}
1000 				mtx_unlock(&aio_freeproc_mtx);
1001 			}
1002 			splx(s);
1003 		}
1004 	}
1005 }
1006 
1007 /*
1008  * Create a new AIO daemon.  This is mostly a kernel-thread fork routine.  The
1009  * AIO daemon modifies its environment itself.
1010  */
1011 static int
1012 aio_newproc(void)
1013 {
1014 	int error;
1015 	struct proc *p;
1016 
1017 	error = kthread_create(aio_daemon, curproc, &p, RFNOWAIT, 0, "aiod%d",
1018 	    num_aio_procs);
1019 	if (error)
1020 		return (error);
1021 
1022 	/*
1023 	 * Wait until daemon is started, but continue on just in case to
1024 	 * handle error conditions.
1025 	 */
1026 	error = tsleep(p, PZERO, "aiosta", aiod_timeout);
1027 
1028 	num_aio_procs++;
1029 
1030 	return (error);
1031 }
1032 
1033 /*
1034  * Try the high-performance, low-overhead physio method for eligible
1035  * VCHR devices.  This method doesn't use an aio helper thread, and
1036  * thus has very low overhead.
1037  *
1038  * Assumes that the caller, _aio_aqueue(), has incremented the file
1039  * structure's reference count, preventing its deallocation for the
1040  * duration of this call.
1041  */
1042 static int
1043 aio_qphysio(struct proc *p, struct aiocblist *aiocbe)
1044 {
1045 	int error;
1046 	struct aiocb *cb;
1047 	struct file *fp;
1048 	struct buf *bp;
1049 	struct vnode *vp;
1050 	struct kaioinfo *ki;
1051 	struct aio_liojob *lj;
1052 	int s;
1053 	int notify;
1054 
1055 	cb = &aiocbe->uaiocb;
1056 	fp = aiocbe->fd_file;
1057 
1058 	if (fp->f_type != DTYPE_VNODE)
1059 		return (-1);
1060 
1061 	vp = fp->f_vnode;
1062 
1063 	/*
1064 	 * If its not a disk, we don't want to return a positive error.
1065 	 * It causes the aio code to not fall through to try the thread
1066 	 * way when you're talking to a regular file.
1067 	 */
1068 	if (!vn_isdisk(vp, &error)) {
1069 		if (error == ENOTBLK)
1070 			return (-1);
1071 		else
1072 			return (error);
1073 	}
1074 
1075  	if (cb->aio_nbytes % vp->v_bufobj.bo_bsize)
1076 		return (-1);
1077 
1078 	if (cb->aio_nbytes >
1079 	    MAXPHYS - (((vm_offset_t) cb->aio_buf) & PAGE_MASK))
1080 		return (-1);
1081 
1082 	ki = p->p_aioinfo;
1083 	if (ki->kaio_buffer_count >= ki->kaio_ballowed_count)
1084 		return (-1);
1085 
1086 	ki->kaio_buffer_count++;
1087 
1088 	lj = aiocbe->lio;
1089 	if (lj)
1090 		lj->lioj_buffer_count++;
1091 
1092 	/* Create and build a buffer header for a transfer. */
1093 	bp = (struct buf *)getpbuf(NULL);
1094 	BUF_KERNPROC(bp);
1095 
1096 	/*
1097 	 * Get a copy of the kva from the physical buffer.
1098 	 */
1099 	error = 0;
1100 
1101 	bp->b_bcount = cb->aio_nbytes;
1102 	bp->b_bufsize = cb->aio_nbytes;
1103 	bp->b_iodone = aio_physwakeup;
1104 	bp->b_saveaddr = bp->b_data;
1105 	bp->b_data = (void *)(uintptr_t)cb->aio_buf;
1106 	bp->b_offset = cb->aio_offset;
1107 	bp->b_iooffset = cb->aio_offset;
1108 	bp->b_blkno = btodb(cb->aio_offset);
1109 	bp->b_iocmd = cb->aio_lio_opcode == LIO_WRITE ? BIO_WRITE : BIO_READ;
1110 
1111 	/*
1112 	 * Bring buffer into kernel space.
1113 	 */
1114 	if (vmapbuf(bp) < 0) {
1115 		error = EFAULT;
1116 		goto doerror;
1117 	}
1118 
1119 	s = splbio();
1120 	aiocbe->bp = bp;
1121 	bp->b_caller1 = (void *)aiocbe;
1122 	TAILQ_INSERT_TAIL(&ki->kaio_bufqueue, aiocbe, plist);
1123 	aiocbe->jobstate = JOBST_JOBQBUF;
1124 	cb->_aiocb_private.status = cb->aio_nbytes;
1125 	num_buf_aio++;
1126 	bp->b_error = 0;
1127 
1128 	splx(s);
1129 
1130 	/* Perform transfer. */
1131 	dev_strategy(vp->v_rdev, bp);
1132 
1133 	notify = 0;
1134 	s = splbio();
1135 
1136 	/*
1137 	 * If we had an error invoking the request, or an error in processing
1138 	 * the request before we have returned, we process it as an error in
1139 	 * transfer.  Note that such an I/O error is not indicated immediately,
1140 	 * but is returned using the aio_error mechanism.  In this case,
1141 	 * aio_suspend will return immediately.
1142 	 */
1143 	if (bp->b_error || (bp->b_ioflags & BIO_ERROR)) {
1144 		struct aiocb *job = aiocbe->uuaiocb;
1145 
1146 		aiocbe->uaiocb._aiocb_private.status = 0;
1147 		suword(&job->_aiocb_private.status, 0);
1148 		aiocbe->uaiocb._aiocb_private.error = bp->b_error;
1149 		suword(&job->_aiocb_private.error, bp->b_error);
1150 
1151 		ki->kaio_buffer_finished_count++;
1152 
1153 		if (aiocbe->jobstate != JOBST_JOBBFINISHED) {
1154 			aiocbe->jobstate = JOBST_JOBBFINISHED;
1155 			aiocbe->jobflags |= AIOCBLIST_DONE;
1156 			TAILQ_REMOVE(&ki->kaio_bufqueue, aiocbe, plist);
1157 			TAILQ_INSERT_TAIL(&ki->kaio_bufdone, aiocbe, plist);
1158 			notify = 1;
1159 		}
1160 	}
1161 	splx(s);
1162 	if (notify)
1163 		KNOTE_UNLOCKED(&aiocbe->klist, 0);
1164 	return (0);
1165 
1166 doerror:
1167 	ki->kaio_buffer_count--;
1168 	if (lj)
1169 		lj->lioj_buffer_count--;
1170 	aiocbe->bp = NULL;
1171 	relpbuf(bp, NULL);
1172 	return (error);
1173 }
1174 
1175 /*
1176  * This waits/tests physio completion.
1177  */
1178 static int
1179 aio_fphysio(struct aiocblist *iocb)
1180 {
1181 	int s;
1182 	struct buf *bp;
1183 	int error;
1184 
1185 	bp = iocb->bp;
1186 
1187 	s = splbio();
1188 	while ((bp->b_flags & B_DONE) == 0) {
1189 		if (tsleep(bp, PRIBIO, "physstr", aiod_timeout)) {
1190 			if ((bp->b_flags & B_DONE) == 0) {
1191 				splx(s);
1192 				return (EINPROGRESS);
1193 			} else
1194 				break;
1195 		}
1196 	}
1197 	splx(s);
1198 
1199 	/* Release mapping into kernel space. */
1200 	vunmapbuf(bp);
1201 	iocb->bp = 0;
1202 
1203 	error = 0;
1204 
1205 	/* Check for an error. */
1206 	if (bp->b_ioflags & BIO_ERROR)
1207 		error = bp->b_error;
1208 
1209 	relpbuf(bp, NULL);
1210 	return (error);
1211 }
1212 
1213 /*
1214  * Wake up aio requests that may be serviceable now.
1215  */
1216 static void
1217 aio_swake_cb(struct socket *so, struct sockbuf *sb)
1218 {
1219 	struct aiocblist *cb,*cbn;
1220 	struct proc *p;
1221 	struct kaioinfo *ki = NULL;
1222 	int opcode, wakecount = 0;
1223 	struct aiothreadlist *aiop;
1224 
1225 	if (sb == &so->so_snd) {
1226 		opcode = LIO_WRITE;
1227 		SOCKBUF_LOCK(&so->so_snd);
1228 		so->so_snd.sb_flags &= ~SB_AIO;
1229 		SOCKBUF_UNLOCK(&so->so_snd);
1230 	} else {
1231 		opcode = LIO_READ;
1232 		SOCKBUF_LOCK(&so->so_rcv);
1233 		so->so_rcv.sb_flags &= ~SB_AIO;
1234 		SOCKBUF_UNLOCK(&so->so_rcv);
1235 	}
1236 
1237 	for (cb = TAILQ_FIRST(&so->so_aiojobq); cb; cb = cbn) {
1238 		cbn = TAILQ_NEXT(cb, list);
1239 		if (opcode == cb->uaiocb.aio_lio_opcode) {
1240 			p = cb->userproc;
1241 			ki = p->p_aioinfo;
1242 			TAILQ_REMOVE(&so->so_aiojobq, cb, list);
1243 			TAILQ_REMOVE(&ki->kaio_sockqueue, cb, plist);
1244 			TAILQ_INSERT_TAIL(&aio_jobs, cb, list);
1245 			TAILQ_INSERT_TAIL(&ki->kaio_jobqueue, cb, plist);
1246 			wakecount++;
1247 			if (cb->jobstate != JOBST_JOBQGLOBAL)
1248 				panic("invalid queue value");
1249 		}
1250 	}
1251 
1252 	while (wakecount--) {
1253 		mtx_lock(&aio_freeproc_mtx);
1254 		if ((aiop = TAILQ_FIRST(&aio_freeproc)) != 0) {
1255 			TAILQ_REMOVE(&aio_freeproc, aiop, list);
1256 			aiop->aiothreadflags &= ~AIOP_FREE;
1257 			wakeup(aiop->aiothread);
1258 		}
1259 		mtx_unlock(&aio_freeproc_mtx);
1260 	}
1261 }
1262 
1263 /*
1264  * Queue a new AIO request.  Choosing either the threaded or direct physio VCHR
1265  * technique is done in this code.
1266  */
1267 static int
1268 _aio_aqueue(struct thread *td, struct aiocb *job, struct aio_liojob *lj, int type)
1269 {
1270 	struct proc *p = td->td_proc;
1271 	struct filedesc *fdp;
1272 	struct file *fp;
1273 	unsigned int fd;
1274 	struct socket *so;
1275 	int s;
1276 	int error;
1277 	int opcode;
1278 	struct aiocblist *aiocbe;
1279 	struct aiothreadlist *aiop;
1280 	struct kaioinfo *ki;
1281 	struct kevent kev;
1282 	struct kqueue *kq;
1283 	struct file *kq_fp;
1284 	struct sockbuf *sb;
1285 
1286 	aiocbe = uma_zalloc(aiocb_zone, M_WAITOK);
1287 	aiocbe->inputcharge = 0;
1288 	aiocbe->outputcharge = 0;
1289 	/* XXX - need a lock */
1290 	knlist_init(&aiocbe->klist, NULL, NULL, NULL, NULL);
1291 
1292 	suword(&job->_aiocb_private.status, -1);
1293 	suword(&job->_aiocb_private.error, 0);
1294 	suword(&job->_aiocb_private.kernelinfo, -1);
1295 
1296 	error = copyin(job, &aiocbe->uaiocb, sizeof(aiocbe->uaiocb));
1297 	if (error) {
1298 		suword(&job->_aiocb_private.error, error);
1299 		uma_zfree(aiocb_zone, aiocbe);
1300 		return (error);
1301 	}
1302 	if (aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_SIGNAL &&
1303 		!_SIG_VALID(aiocbe->uaiocb.aio_sigevent.sigev_signo)) {
1304 		uma_zfree(aiocb_zone, aiocbe);
1305 		return (EINVAL);
1306 	}
1307 
1308 	/* Save userspace address of the job info. */
1309 	aiocbe->uuaiocb = job;
1310 
1311 	/* Get the opcode. */
1312 	if (type != LIO_NOP)
1313 		aiocbe->uaiocb.aio_lio_opcode = type;
1314 	opcode = aiocbe->uaiocb.aio_lio_opcode;
1315 
1316 	/* Get the fd info for process. */
1317 	fdp = p->p_fd;
1318 
1319 	/*
1320 	 * Range check file descriptor.
1321 	 */
1322 	FILEDESC_LOCK(fdp);
1323 	fd = aiocbe->uaiocb.aio_fildes;
1324 	if (fd >= fdp->fd_nfiles) {
1325 		FILEDESC_UNLOCK(fdp);
1326 		uma_zfree(aiocb_zone, aiocbe);
1327 		if (type == 0)
1328 			suword(&job->_aiocb_private.error, EBADF);
1329 		return (EBADF);
1330 	}
1331 
1332 	fp = aiocbe->fd_file = fdp->fd_ofiles[fd];
1333 	if ((fp == NULL) ||
1334 	    ((opcode == LIO_WRITE) && ((fp->f_flag & FWRITE) == 0)) ||
1335 	    ((opcode == LIO_READ) && ((fp->f_flag & FREAD) == 0))) {
1336 		FILEDESC_UNLOCK(fdp);
1337 		uma_zfree(aiocb_zone, aiocbe);
1338 		if (type == 0)
1339 			suword(&job->_aiocb_private.error, EBADF);
1340 		return (EBADF);
1341 	}
1342 	fhold(fp);
1343 	FILEDESC_UNLOCK(fdp);
1344 
1345 	if (aiocbe->uaiocb.aio_offset == -1LL) {
1346 		error = EINVAL;
1347 		goto aqueue_fail;
1348 	}
1349 	error = suword(&job->_aiocb_private.kernelinfo, jobrefid);
1350 	if (error) {
1351 		error = EINVAL;
1352 		goto aqueue_fail;
1353 	}
1354 	aiocbe->uaiocb._aiocb_private.kernelinfo = (void *)(intptr_t)jobrefid;
1355 	if (jobrefid == LONG_MAX)
1356 		jobrefid = 1;
1357 	else
1358 		jobrefid++;
1359 
1360 	if (opcode == LIO_NOP) {
1361 		fdrop(fp, td);
1362 		uma_zfree(aiocb_zone, aiocbe);
1363 		if (type == 0) {
1364 			suword(&job->_aiocb_private.error, 0);
1365 			suword(&job->_aiocb_private.status, 0);
1366 			suword(&job->_aiocb_private.kernelinfo, 0);
1367 		}
1368 		return (0);
1369 	}
1370 	if ((opcode != LIO_READ) && (opcode != LIO_WRITE)) {
1371 		if (type == 0)
1372 			suword(&job->_aiocb_private.status, 0);
1373 		error = EINVAL;
1374 		goto aqueue_fail;
1375 	}
1376 
1377 	if (aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_KEVENT) {
1378 		kev.ident = aiocbe->uaiocb.aio_sigevent.sigev_notify_kqueue;
1379 		kev.udata = aiocbe->uaiocb.aio_sigevent.sigev_value.sigval_ptr;
1380 	} else
1381 		goto no_kqueue;
1382 	if ((u_int)kev.ident >= fdp->fd_nfiles ||
1383 	    (kq_fp = fdp->fd_ofiles[kev.ident]) == NULL ||
1384 	    (kq_fp->f_type != DTYPE_KQUEUE)) {
1385 		error = EBADF;
1386 		goto aqueue_fail;
1387 	}
1388 	kq = kq_fp->f_data;
1389 	kev.ident = (uintptr_t)aiocbe->uuaiocb;
1390 	kev.filter = EVFILT_AIO;
1391 	kev.flags = EV_ADD | EV_ENABLE | EV_FLAG1;
1392 	kev.data = (intptr_t)aiocbe;
1393 	error = kqueue_register(kq, &kev, td, 1);
1394 aqueue_fail:
1395 	if (error) {
1396 		fdrop(fp, td);
1397 		uma_zfree(aiocb_zone, aiocbe);
1398 		if (type == 0)
1399 			suword(&job->_aiocb_private.error, error);
1400 		goto done;
1401 	}
1402 no_kqueue:
1403 
1404 	suword(&job->_aiocb_private.error, EINPROGRESS);
1405 	aiocbe->uaiocb._aiocb_private.error = EINPROGRESS;
1406 	aiocbe->userproc = p;
1407 	aiocbe->cred = crhold(td->td_ucred);
1408 	aiocbe->jobflags = 0;
1409 	aiocbe->lio = lj;
1410 	ki = p->p_aioinfo;
1411 
1412 	if (fp->f_type == DTYPE_SOCKET) {
1413 		/*
1414 		 * Alternate queueing for socket ops: Reach down into the
1415 		 * descriptor to get the socket data.  Then check to see if the
1416 		 * socket is ready to be read or written (based on the requested
1417 		 * operation).
1418 		 *
1419 		 * If it is not ready for io, then queue the aiocbe on the
1420 		 * socket, and set the flags so we get a call when sbnotify()
1421 		 * happens.
1422 		 *
1423 		 * Note if opcode is neither LIO_WRITE nor LIO_READ we lock
1424 		 * and unlock the snd sockbuf for no reason.
1425 		 */
1426 		so = fp->f_data;
1427 		sb = (opcode == LIO_READ) ? &so->so_rcv : &so->so_snd;
1428 		SOCKBUF_LOCK(sb);
1429 		s = splnet();
1430 		if (((opcode == LIO_READ) && (!soreadable(so))) || ((opcode ==
1431 		    LIO_WRITE) && (!sowriteable(so)))) {
1432 			TAILQ_INSERT_TAIL(&so->so_aiojobq, aiocbe, list);
1433 			TAILQ_INSERT_TAIL(&ki->kaio_sockqueue, aiocbe, plist);
1434 			sb->sb_flags |= SB_AIO;
1435 			aiocbe->jobstate = JOBST_JOBQGLOBAL; /* XXX */
1436 			ki->kaio_queue_count++;
1437 			num_queue_count++;
1438 			SOCKBUF_UNLOCK(sb);
1439 			splx(s);
1440 			error = 0;
1441 			goto done;
1442 		}
1443 		SOCKBUF_UNLOCK(sb);
1444 		splx(s);
1445 	}
1446 
1447 	if ((error = aio_qphysio(p, aiocbe)) == 0)
1448 		goto done;
1449 	if (error > 0) {
1450 		suword(&job->_aiocb_private.status, 0);
1451 		aiocbe->uaiocb._aiocb_private.error = error;
1452 		suword(&job->_aiocb_private.error, error);
1453 		goto done;
1454 	}
1455 
1456 	/* No buffer for daemon I/O. */
1457 	aiocbe->bp = NULL;
1458 
1459 	ki->kaio_queue_count++;
1460 	if (lj)
1461 		lj->lioj_queue_count++;
1462 	s = splnet();
1463 	TAILQ_INSERT_TAIL(&ki->kaio_jobqueue, aiocbe, plist);
1464 	TAILQ_INSERT_TAIL(&aio_jobs, aiocbe, list);
1465 	splx(s);
1466 	aiocbe->jobstate = JOBST_JOBQGLOBAL;
1467 
1468 	num_queue_count++;
1469 	error = 0;
1470 
1471 	/*
1472 	 * If we don't have a free AIO process, and we are below our quota, then
1473 	 * start one.  Otherwise, depend on the subsequent I/O completions to
1474 	 * pick-up this job.  If we don't sucessfully create the new process
1475 	 * (thread) due to resource issues, we return an error for now (EAGAIN),
1476 	 * which is likely not the correct thing to do.
1477 	 */
1478 	mtx_lock(&aio_freeproc_mtx);
1479 retryproc:
1480 	if ((aiop = TAILQ_FIRST(&aio_freeproc)) != NULL) {
1481 		TAILQ_REMOVE(&aio_freeproc, aiop, list);
1482 		aiop->aiothreadflags &= ~AIOP_FREE;
1483 		wakeup(aiop->aiothread);
1484 	} else if (((num_aio_resv_start + num_aio_procs) < max_aio_procs) &&
1485 	    ((ki->kaio_active_count + num_aio_resv_start) <
1486 	    ki->kaio_maxactive_count)) {
1487 		num_aio_resv_start++;
1488 		mtx_unlock(&aio_freeproc_mtx);
1489 		if ((error = aio_newproc()) == 0) {
1490 			mtx_lock(&aio_freeproc_mtx);
1491 			num_aio_resv_start--;
1492 			goto retryproc;
1493 		}
1494 		mtx_lock(&aio_freeproc_mtx);
1495 		num_aio_resv_start--;
1496 	}
1497 	mtx_unlock(&aio_freeproc_mtx);
1498 done:
1499 	return (error);
1500 }
1501 
1502 /*
1503  * This routine queues an AIO request, checking for quotas.
1504  */
1505 static int
1506 aio_aqueue(struct thread *td, struct aiocb *job, int type)
1507 {
1508 	struct proc *p = td->td_proc;
1509 	struct kaioinfo *ki;
1510 
1511 	if (p->p_aioinfo == NULL)
1512 		aio_init_aioinfo(p);
1513 
1514 	if (num_queue_count >= max_queue_count)
1515 		return (EAGAIN);
1516 
1517 	ki = p->p_aioinfo;
1518 	if (ki->kaio_queue_count >= ki->kaio_qallowed_count)
1519 		return (EAGAIN);
1520 
1521 	return _aio_aqueue(td, job, NULL, type);
1522 }
1523 
1524 /*
1525  * Support the aio_return system call, as a side-effect, kernel resources are
1526  * released.
1527  */
1528 int
1529 aio_return(struct thread *td, struct aio_return_args *uap)
1530 {
1531 	struct proc *p = td->td_proc;
1532 	int s;
1533 	long jobref;
1534 	struct aiocblist *cb, *ncb;
1535 	struct aiocb *ujob;
1536 	struct kaioinfo *ki;
1537 
1538 	ujob = uap->aiocbp;
1539 	jobref = fuword(&ujob->_aiocb_private.kernelinfo);
1540 	if (jobref == -1 || jobref == 0)
1541 		return (EINVAL);
1542 
1543 	ki = p->p_aioinfo;
1544 	if (ki == NULL)
1545 		return (EINVAL);
1546 	PROC_LOCK(p);
1547 	TAILQ_FOREACH(cb, &ki->kaio_jobdone, plist) {
1548 		if (((intptr_t) cb->uaiocb._aiocb_private.kernelinfo) ==
1549 		    jobref) {
1550 			if (cb->uaiocb.aio_lio_opcode == LIO_WRITE) {
1551 				p->p_stats->p_ru.ru_oublock +=
1552 				    cb->outputcharge;
1553 				cb->outputcharge = 0;
1554 			} else if (cb->uaiocb.aio_lio_opcode == LIO_READ) {
1555 				p->p_stats->p_ru.ru_inblock += cb->inputcharge;
1556 				cb->inputcharge = 0;
1557 			}
1558 			goto done;
1559 		}
1560 	}
1561 	s = splbio();
1562 	for (cb = TAILQ_FIRST(&ki->kaio_bufdone); cb; cb = ncb) {
1563 		ncb = TAILQ_NEXT(cb, plist);
1564 		if (((intptr_t) cb->uaiocb._aiocb_private.kernelinfo)
1565 		    == jobref) {
1566 			break;
1567 		}
1568 	}
1569 	splx(s);
1570  done:
1571 	PROC_UNLOCK(p);
1572 	if (cb != NULL) {
1573 		if (ujob == cb->uuaiocb) {
1574 			td->td_retval[0] =
1575 			    cb->uaiocb._aiocb_private.status;
1576 		} else
1577 			td->td_retval[0] = EFAULT;
1578 		aio_free_entry(cb);
1579 		return (0);
1580 	}
1581 	return (EINVAL);
1582 }
1583 
1584 /*
1585  * Allow a process to wakeup when any of the I/O requests are completed.
1586  */
1587 int
1588 aio_suspend(struct thread *td, struct aio_suspend_args *uap)
1589 {
1590 	struct proc *p = td->td_proc;
1591 	struct timeval atv;
1592 	struct timespec ts;
1593 	struct aiocb *const *cbptr, *cbp;
1594 	struct kaioinfo *ki;
1595 	struct aiocblist *cb;
1596 	int i;
1597 	int njoblist;
1598 	int error, s, timo;
1599 	long *ijoblist;
1600 	struct aiocb **ujoblist;
1601 
1602 	if (uap->nent < 0 || uap->nent > AIO_LISTIO_MAX)
1603 		return (EINVAL);
1604 
1605 	timo = 0;
1606 	if (uap->timeout) {
1607 		/* Get timespec struct. */
1608 		if ((error = copyin(uap->timeout, &ts, sizeof(ts))) != 0)
1609 			return (error);
1610 
1611 		if (ts.tv_nsec < 0 || ts.tv_nsec >= 1000000000)
1612 			return (EINVAL);
1613 
1614 		TIMESPEC_TO_TIMEVAL(&atv, &ts);
1615 		if (itimerfix(&atv))
1616 			return (EINVAL);
1617 		timo = tvtohz(&atv);
1618 	}
1619 
1620 	ki = p->p_aioinfo;
1621 	if (ki == NULL)
1622 		return (EAGAIN);
1623 
1624 	njoblist = 0;
1625 	ijoblist = uma_zalloc(aiol_zone, M_WAITOK);
1626 	ujoblist = uma_zalloc(aiol_zone, M_WAITOK);
1627 	cbptr = uap->aiocbp;
1628 
1629 	for (i = 0; i < uap->nent; i++) {
1630 		cbp = (struct aiocb *)(intptr_t)fuword(&cbptr[i]);
1631 		if (cbp == 0)
1632 			continue;
1633 		ujoblist[njoblist] = cbp;
1634 		ijoblist[njoblist] = fuword(&cbp->_aiocb_private.kernelinfo);
1635 		njoblist++;
1636 	}
1637 
1638 	if (njoblist == 0) {
1639 		uma_zfree(aiol_zone, ijoblist);
1640 		uma_zfree(aiol_zone, ujoblist);
1641 		return (0);
1642 	}
1643 
1644 	error = 0;
1645 	for (;;) {
1646 		PROC_LOCK(p);
1647 		TAILQ_FOREACH(cb, &ki->kaio_jobdone, plist) {
1648 			for (i = 0; i < njoblist; i++) {
1649 				if (((intptr_t)
1650 				    cb->uaiocb._aiocb_private.kernelinfo) ==
1651 				    ijoblist[i]) {
1652 					PROC_UNLOCK(p);
1653 					if (ujoblist[i] != cb->uuaiocb)
1654 						error = EINVAL;
1655 					uma_zfree(aiol_zone, ijoblist);
1656 					uma_zfree(aiol_zone, ujoblist);
1657 					return (error);
1658 				}
1659 			}
1660 		}
1661 
1662 		s = splbio();
1663 		for (cb = TAILQ_FIRST(&ki->kaio_bufdone); cb; cb =
1664 		    TAILQ_NEXT(cb, plist)) {
1665 			for (i = 0; i < njoblist; i++) {
1666 				if (((intptr_t)
1667 				    cb->uaiocb._aiocb_private.kernelinfo) ==
1668 				    ijoblist[i]) {
1669 					PROC_UNLOCK(p);
1670 					splx(s);
1671 					if (ujoblist[i] != cb->uuaiocb)
1672 						error = EINVAL;
1673 					uma_zfree(aiol_zone, ijoblist);
1674 					uma_zfree(aiol_zone, ujoblist);
1675 					return (error);
1676 				}
1677 			}
1678 		}
1679 
1680 		ki->kaio_flags |= KAIO_WAKEUP;
1681 		error = msleep(p, &p->p_mtx, PDROP | PRIBIO | PCATCH, "aiospn",
1682 		    timo);
1683 		splx(s);
1684 
1685 		if (error == ERESTART || error == EINTR) {
1686 			uma_zfree(aiol_zone, ijoblist);
1687 			uma_zfree(aiol_zone, ujoblist);
1688 			return (EINTR);
1689 		} else if (error == EWOULDBLOCK) {
1690 			uma_zfree(aiol_zone, ijoblist);
1691 			uma_zfree(aiol_zone, ujoblist);
1692 			return (EAGAIN);
1693 		}
1694 	}
1695 
1696 /* NOTREACHED */
1697 	return (EINVAL);
1698 }
1699 
1700 /*
1701  * aio_cancel cancels any non-physio aio operations not currently in
1702  * progress.
1703  */
1704 int
1705 aio_cancel(struct thread *td, struct aio_cancel_args *uap)
1706 {
1707 	struct proc *p = td->td_proc;
1708 	struct kaioinfo *ki;
1709 	struct aiocblist *cbe, *cbn;
1710 	struct file *fp;
1711 	struct filedesc *fdp;
1712 	struct socket *so;
1713 	struct proc *po;
1714 	int s,error;
1715 	int cancelled=0;
1716 	int notcancelled=0;
1717 	struct vnode *vp;
1718 
1719 	fdp = p->p_fd;
1720 	if ((u_int)uap->fd >= fdp->fd_nfiles ||
1721 	    (fp = fdp->fd_ofiles[uap->fd]) == NULL)
1722 		return (EBADF);
1723 
1724 	if (fp->f_type == DTYPE_VNODE) {
1725 		vp = fp->f_vnode;
1726 
1727 		if (vn_isdisk(vp,&error)) {
1728 			td->td_retval[0] = AIO_NOTCANCELED;
1729 			return (0);
1730 		}
1731 	} else if (fp->f_type == DTYPE_SOCKET) {
1732 		so = fp->f_data;
1733 
1734 		s = splnet();
1735 
1736 		for (cbe = TAILQ_FIRST(&so->so_aiojobq); cbe; cbe = cbn) {
1737 			cbn = TAILQ_NEXT(cbe, list);
1738 			if ((uap->aiocbp == NULL) ||
1739 				(uap->aiocbp == cbe->uuaiocb) ) {
1740 				po = cbe->userproc;
1741 				ki = po->p_aioinfo;
1742 				TAILQ_REMOVE(&so->so_aiojobq, cbe, list);
1743 				TAILQ_REMOVE(&ki->kaio_sockqueue, cbe, plist);
1744 				TAILQ_INSERT_TAIL(&ki->kaio_jobdone, cbe, plist);
1745 				if (ki->kaio_flags & KAIO_WAKEUP) {
1746 					wakeup(po);
1747 				}
1748 				cbe->jobstate = JOBST_JOBFINISHED;
1749 				cbe->uaiocb._aiocb_private.status=-1;
1750 				cbe->uaiocb._aiocb_private.error=ECANCELED;
1751 				cancelled++;
1752 /* XXX cancelled, knote? */
1753 				if (cbe->uaiocb.aio_sigevent.sigev_notify ==
1754 				    SIGEV_SIGNAL) {
1755 					PROC_LOCK(cbe->userproc);
1756 					psignal(cbe->userproc, cbe->uaiocb.aio_sigevent.sigev_signo);
1757 					PROC_UNLOCK(cbe->userproc);
1758 				}
1759 				if (uap->aiocbp)
1760 					break;
1761 			}
1762 		}
1763 		splx(s);
1764 
1765 		if ((cancelled) && (uap->aiocbp)) {
1766 			td->td_retval[0] = AIO_CANCELED;
1767 			return (0);
1768 		}
1769 	}
1770 	ki=p->p_aioinfo;
1771 	if (ki == NULL)
1772 		goto done;
1773 	s = splnet();
1774 
1775 	for (cbe = TAILQ_FIRST(&ki->kaio_jobqueue); cbe; cbe = cbn) {
1776 		cbn = TAILQ_NEXT(cbe, plist);
1777 
1778 		if ((uap->fd == cbe->uaiocb.aio_fildes) &&
1779 		    ((uap->aiocbp == NULL ) ||
1780 		     (uap->aiocbp == cbe->uuaiocb))) {
1781 
1782 			if (cbe->jobstate == JOBST_JOBQGLOBAL) {
1783 				TAILQ_REMOVE(&aio_jobs, cbe, list);
1784 				TAILQ_REMOVE(&ki->kaio_jobqueue, cbe, plist);
1785 				TAILQ_INSERT_TAIL(&ki->kaio_jobdone, cbe,
1786 				    plist);
1787 				cancelled++;
1788 				ki->kaio_queue_finished_count++;
1789 				cbe->jobstate = JOBST_JOBFINISHED;
1790 				cbe->uaiocb._aiocb_private.status = -1;
1791 				cbe->uaiocb._aiocb_private.error = ECANCELED;
1792 /* XXX cancelled, knote? */
1793 				if (cbe->uaiocb.aio_sigevent.sigev_notify ==
1794 				    SIGEV_SIGNAL) {
1795 					PROC_LOCK(cbe->userproc);
1796 					psignal(cbe->userproc, cbe->uaiocb.aio_sigevent.sigev_signo);
1797 					PROC_UNLOCK(cbe->userproc);
1798 				}
1799 			} else {
1800 				notcancelled++;
1801 			}
1802 		}
1803 	}
1804 	splx(s);
1805 done:
1806 	if (notcancelled) {
1807 		td->td_retval[0] = AIO_NOTCANCELED;
1808 		return (0);
1809 	}
1810 	if (cancelled) {
1811 		td->td_retval[0] = AIO_CANCELED;
1812 		return (0);
1813 	}
1814 	td->td_retval[0] = AIO_ALLDONE;
1815 
1816 	return (0);
1817 }
1818 
1819 /*
1820  * aio_error is implemented in the kernel level for compatibility purposes only.
1821  * For a user mode async implementation, it would be best to do it in a userland
1822  * subroutine.
1823  */
1824 int
1825 aio_error(struct thread *td, struct aio_error_args *uap)
1826 {
1827 	struct proc *p = td->td_proc;
1828 	int s;
1829 	struct aiocblist *cb;
1830 	struct kaioinfo *ki;
1831 	long jobref;
1832 
1833 	ki = p->p_aioinfo;
1834 	if (ki == NULL)
1835 		return (EINVAL);
1836 
1837 	jobref = fuword(&uap->aiocbp->_aiocb_private.kernelinfo);
1838 	if ((jobref == -1) || (jobref == 0))
1839 		return (EINVAL);
1840 
1841 	PROC_LOCK(p);
1842 	TAILQ_FOREACH(cb, &ki->kaio_jobdone, plist) {
1843 		if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1844 		    jobref) {
1845 			PROC_UNLOCK(p);
1846 			td->td_retval[0] = cb->uaiocb._aiocb_private.error;
1847 			return (0);
1848 		}
1849 	}
1850 
1851 	s = splnet();
1852 
1853 	for (cb = TAILQ_FIRST(&ki->kaio_jobqueue); cb; cb = TAILQ_NEXT(cb,
1854 	    plist)) {
1855 		if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1856 		    jobref) {
1857 			PROC_UNLOCK(p);
1858 			td->td_retval[0] = EINPROGRESS;
1859 			splx(s);
1860 			return (0);
1861 		}
1862 	}
1863 
1864 	for (cb = TAILQ_FIRST(&ki->kaio_sockqueue); cb; cb = TAILQ_NEXT(cb,
1865 	    plist)) {
1866 		if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1867 		    jobref) {
1868 			PROC_UNLOCK(p);
1869 			td->td_retval[0] = EINPROGRESS;
1870 			splx(s);
1871 			return (0);
1872 		}
1873 	}
1874 	splx(s);
1875 
1876 	s = splbio();
1877 	for (cb = TAILQ_FIRST(&ki->kaio_bufdone); cb; cb = TAILQ_NEXT(cb,
1878 	    plist)) {
1879 		if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1880 		    jobref) {
1881 			PROC_UNLOCK(p);
1882 			td->td_retval[0] = cb->uaiocb._aiocb_private.error;
1883 			splx(s);
1884 			return (0);
1885 		}
1886 	}
1887 
1888 	for (cb = TAILQ_FIRST(&ki->kaio_bufqueue); cb; cb = TAILQ_NEXT(cb,
1889 	    plist)) {
1890 		if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1891 		    jobref) {
1892 			PROC_UNLOCK(p);
1893 			td->td_retval[0] = EINPROGRESS;
1894 			splx(s);
1895 			return (0);
1896 		}
1897 	}
1898 	splx(s);
1899 	PROC_UNLOCK(p);
1900 
1901 #if (0)
1902 	/*
1903 	 * Hack for lio.
1904 	 */
1905 	status = fuword(&uap->aiocbp->_aiocb_private.status);
1906 	if (status == -1)
1907 		return fuword(&uap->aiocbp->_aiocb_private.error);
1908 #endif
1909 	return (EINVAL);
1910 }
1911 
1912 /* syscall - asynchronous read from a file (REALTIME) */
1913 int
1914 aio_read(struct thread *td, struct aio_read_args *uap)
1915 {
1916 
1917 	return aio_aqueue(td, uap->aiocbp, LIO_READ);
1918 }
1919 
1920 /* syscall - asynchronous write to a file (REALTIME) */
1921 int
1922 aio_write(struct thread *td, struct aio_write_args *uap)
1923 {
1924 
1925 	return aio_aqueue(td, uap->aiocbp, LIO_WRITE);
1926 }
1927 
1928 /* syscall - list directed I/O (REALTIME) */
1929 int
1930 lio_listio(struct thread *td, struct lio_listio_args *uap)
1931 {
1932 	struct proc *p = td->td_proc;
1933 	int nent, nentqueued;
1934 	struct aiocb *iocb, * const *cbptr;
1935 	struct aiocblist *cb;
1936 	struct kaioinfo *ki;
1937 	struct aio_liojob *lj;
1938 	int error, runningcode;
1939 	int nerror;
1940 	int i;
1941 	int s;
1942 
1943 	if ((uap->mode != LIO_NOWAIT) && (uap->mode != LIO_WAIT))
1944 		return (EINVAL);
1945 
1946 	nent = uap->nent;
1947 	if (nent < 0 || nent > AIO_LISTIO_MAX)
1948 		return (EINVAL);
1949 
1950 	if (p->p_aioinfo == NULL)
1951 		aio_init_aioinfo(p);
1952 
1953 	if ((nent + num_queue_count) > max_queue_count)
1954 		return (EAGAIN);
1955 
1956 	ki = p->p_aioinfo;
1957 	if ((nent + ki->kaio_queue_count) > ki->kaio_qallowed_count)
1958 		return (EAGAIN);
1959 
1960 	lj = uma_zalloc(aiolio_zone, M_WAITOK);
1961 	if (!lj)
1962 		return (EAGAIN);
1963 
1964 	lj->lioj_flags = 0;
1965 	lj->lioj_buffer_count = 0;
1966 	lj->lioj_buffer_finished_count = 0;
1967 	lj->lioj_queue_count = 0;
1968 	lj->lioj_queue_finished_count = 0;
1969 
1970 	/*
1971 	 * Setup signal.
1972 	 */
1973 	if (uap->sig && (uap->mode == LIO_NOWAIT)) {
1974 		error = copyin(uap->sig, &lj->lioj_signal,
1975 		    sizeof(lj->lioj_signal));
1976 		if (error) {
1977 			uma_zfree(aiolio_zone, lj);
1978 			return (error);
1979 		}
1980 		if (!_SIG_VALID(lj->lioj_signal.sigev_signo)) {
1981 			uma_zfree(aiolio_zone, lj);
1982 			return (EINVAL);
1983 		}
1984 		lj->lioj_flags |= LIOJ_SIGNAL;
1985 	}
1986 	TAILQ_INSERT_TAIL(&ki->kaio_liojoblist, lj, lioj_list);
1987 	/*
1988 	 * Get pointers to the list of I/O requests.
1989 	 */
1990 	nerror = 0;
1991 	nentqueued = 0;
1992 	cbptr = uap->acb_list;
1993 	for (i = 0; i < uap->nent; i++) {
1994 		iocb = (struct aiocb *)(intptr_t)fuword(&cbptr[i]);
1995 		if (((intptr_t)iocb != -1) && ((intptr_t)iocb != 0)) {
1996 			error = _aio_aqueue(td, iocb, lj, 0);
1997 			if (error == 0)
1998 				nentqueued++;
1999 			else
2000 				nerror++;
2001 		}
2002 	}
2003 
2004 	/*
2005 	 * If we haven't queued any, then just return error.
2006 	 */
2007 	if (nentqueued == 0)
2008 		return (0);
2009 
2010 	/*
2011 	 * Calculate the appropriate error return.
2012 	 */
2013 	runningcode = 0;
2014 	if (nerror)
2015 		runningcode = EIO;
2016 
2017 	if (uap->mode == LIO_WAIT) {
2018 		int command, found;
2019 		long jobref;
2020 
2021 		for (;;) {
2022 			found = 0;
2023 			for (i = 0; i < uap->nent; i++) {
2024 				/*
2025 				 * Fetch address of the control buf pointer in
2026 				 * user space.
2027 				 */
2028 				iocb = (struct aiocb *)
2029 				    (intptr_t)fuword(&cbptr[i]);
2030 				if (((intptr_t)iocb == -1) || ((intptr_t)iocb
2031 				    == 0))
2032 					continue;
2033 
2034 				/*
2035 				 * Fetch the associated command from user space.
2036 				 */
2037 				command = fuword(&iocb->aio_lio_opcode);
2038 				if (command == LIO_NOP) {
2039 					found++;
2040 					continue;
2041 				}
2042 
2043 				jobref =
2044 				    fuword(&iocb->_aiocb_private.kernelinfo);
2045 
2046 				TAILQ_FOREACH(cb, &ki->kaio_jobdone, plist) {
2047 					if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo)
2048 					    == jobref) {
2049 						if (cb->uaiocb.aio_lio_opcode
2050 						    == LIO_WRITE) {
2051 							p->p_stats->p_ru.ru_oublock
2052 							    +=
2053 							    cb->outputcharge;
2054 							cb->outputcharge = 0;
2055 						} else if (cb->uaiocb.aio_lio_opcode
2056 						    == LIO_READ) {
2057 							p->p_stats->p_ru.ru_inblock
2058 							    += cb->inputcharge;
2059 							cb->inputcharge = 0;
2060 						}
2061 						found++;
2062 						break;
2063 					}
2064 				}
2065 
2066 				s = splbio();
2067 				TAILQ_FOREACH(cb, &ki->kaio_bufdone, plist) {
2068 					if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo)
2069 					    == jobref) {
2070 						found++;
2071 						break;
2072 					}
2073 				}
2074 				splx(s);
2075 			}
2076 
2077 			/*
2078 			 * If all I/Os have been disposed of, then we can
2079 			 * return.
2080 			 */
2081 			if (found == nentqueued)
2082 				return (runningcode);
2083 
2084 			ki->kaio_flags |= KAIO_WAKEUP;
2085 			error = tsleep(p, PRIBIO | PCATCH, "aiospn", 0);
2086 
2087 			if (error == EINTR)
2088 				return (EINTR);
2089 			else if (error == EWOULDBLOCK)
2090 				return (EAGAIN);
2091 		}
2092 	}
2093 
2094 	return (runningcode);
2095 }
2096 
2097 /*
2098  * Interrupt handler for physio, performs the necessary process wakeups, and
2099  * signals.
2100  */
2101 static void
2102 aio_physwakeup(struct buf *bp)
2103 {
2104 	struct aiocblist *aiocbe;
2105 	struct proc *p;
2106 	struct kaioinfo *ki;
2107 	struct aio_liojob *lj;
2108 
2109 	mtx_lock(&Giant);
2110 	bp->b_flags |= B_DONE;
2111 	wakeup(bp);
2112 
2113 	aiocbe = (struct aiocblist *)bp->b_caller1;
2114 	if (aiocbe) {
2115 		p = aiocbe->userproc;
2116 
2117 		aiocbe->jobstate = JOBST_JOBBFINISHED;
2118 		aiocbe->uaiocb._aiocb_private.status -= bp->b_resid;
2119 		aiocbe->uaiocb._aiocb_private.error = 0;
2120 		aiocbe->jobflags |= AIOCBLIST_DONE;
2121 
2122 		if (bp->b_ioflags & BIO_ERROR)
2123 			aiocbe->uaiocb._aiocb_private.error = bp->b_error;
2124 
2125 		lj = aiocbe->lio;
2126 		if (lj) {
2127 			lj->lioj_buffer_finished_count++;
2128 
2129 			/*
2130 			 * wakeup/signal if all of the interrupt jobs are done.
2131 			 */
2132 			if (lj->lioj_buffer_finished_count ==
2133 			    lj->lioj_buffer_count &&
2134 			    lj->lioj_queue_finished_count ==
2135 			    lj->lioj_queue_count) {
2136 				/*
2137 				 * Post a signal if it is called for.
2138 				 */
2139 				if ((lj->lioj_flags &
2140 				    (LIOJ_SIGNAL|LIOJ_SIGNAL_POSTED)) ==
2141 				    LIOJ_SIGNAL) {
2142 					PROC_LOCK(p);
2143 					psignal(p, lj->lioj_signal.sigev_signo);
2144 					PROC_UNLOCK(p);
2145 					lj->lioj_flags |= LIOJ_SIGNAL_POSTED;
2146 				}
2147 			}
2148 		}
2149 
2150 		ki = p->p_aioinfo;
2151 		if (ki) {
2152 			ki->kaio_buffer_finished_count++;
2153 			TAILQ_REMOVE(&ki->kaio_bufqueue, aiocbe, plist);
2154 			TAILQ_INSERT_TAIL(&ki->kaio_bufdone, aiocbe, plist);
2155 
2156 			KNOTE_UNLOCKED(&aiocbe->klist, 0);
2157 			/* Do the wakeup. */
2158 			if (ki->kaio_flags & (KAIO_RUNDOWN|KAIO_WAKEUP)) {
2159 				ki->kaio_flags &= ~KAIO_WAKEUP;
2160 				wakeup(p);
2161 			}
2162 		}
2163 
2164 		if (aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_SIGNAL) {
2165 			PROC_LOCK(p);
2166 			psignal(p, aiocbe->uaiocb.aio_sigevent.sigev_signo);
2167 			PROC_UNLOCK(p);
2168 		}
2169 	}
2170 	mtx_unlock(&Giant);
2171 }
2172 
2173 /* syscall - wait for the next completion of an aio request */
2174 int
2175 aio_waitcomplete(struct thread *td, struct aio_waitcomplete_args *uap)
2176 {
2177 	struct proc *p = td->td_proc;
2178 	struct timeval atv;
2179 	struct timespec ts;
2180 	struct kaioinfo *ki;
2181 	struct aiocblist *cb = NULL;
2182 	int error, s, timo;
2183 
2184 	suword(uap->aiocbp, (int)NULL);
2185 
2186 	timo = 0;
2187 	if (uap->timeout) {
2188 		/* Get timespec struct. */
2189 		error = copyin(uap->timeout, &ts, sizeof(ts));
2190 		if (error)
2191 			return (error);
2192 
2193 		if ((ts.tv_nsec < 0) || (ts.tv_nsec >= 1000000000))
2194 			return (EINVAL);
2195 
2196 		TIMESPEC_TO_TIMEVAL(&atv, &ts);
2197 		if (itimerfix(&atv))
2198 			return (EINVAL);
2199 		timo = tvtohz(&atv);
2200 	}
2201 
2202 	ki = p->p_aioinfo;
2203 	if (ki == NULL)
2204 		return (EAGAIN);
2205 
2206 	for (;;) {
2207 		PROC_LOCK(p);
2208 		if ((cb = TAILQ_FIRST(&ki->kaio_jobdone)) != 0) {
2209 			PROC_UNLOCK(p);
2210 			suword(uap->aiocbp, (uintptr_t)cb->uuaiocb);
2211 			td->td_retval[0] = cb->uaiocb._aiocb_private.status;
2212 			if (cb->uaiocb.aio_lio_opcode == LIO_WRITE) {
2213 				p->p_stats->p_ru.ru_oublock +=
2214 				    cb->outputcharge;
2215 				cb->outputcharge = 0;
2216 			} else if (cb->uaiocb.aio_lio_opcode == LIO_READ) {
2217 				p->p_stats->p_ru.ru_inblock += cb->inputcharge;
2218 				cb->inputcharge = 0;
2219 			}
2220 			error = cb->uaiocb._aiocb_private.error;
2221 			aio_free_entry(cb);
2222 			return (error);
2223 		}
2224 
2225 		s = splbio();
2226  		if ((cb = TAILQ_FIRST(&ki->kaio_bufdone)) != 0 ) {
2227 			PROC_UNLOCK(p);
2228 			splx(s);
2229 			suword(uap->aiocbp, (uintptr_t)cb->uuaiocb);
2230 			error = cb->uaiocb._aiocb_private.error;
2231 			td->td_retval[0] = cb->uaiocb._aiocb_private.status;
2232 			aio_free_entry(cb);
2233 			return (error);
2234 		}
2235 
2236 		ki->kaio_flags |= KAIO_WAKEUP;
2237 		error = msleep(p, &p->p_mtx, PDROP | PRIBIO | PCATCH, "aiowc",
2238 		    timo);
2239 		splx(s);
2240 
2241 		if (error == ERESTART)
2242 			return (EINTR);
2243 		else if (error < 0)
2244 			return (error);
2245 		else if (error == EINTR)
2246 			return (EINTR);
2247 		else if (error == EWOULDBLOCK)
2248 			return (EAGAIN);
2249 	}
2250 }
2251 
2252 /* kqueue attach function */
2253 static int
2254 filt_aioattach(struct knote *kn)
2255 {
2256 	struct aiocblist *aiocbe = (struct aiocblist *)kn->kn_sdata;
2257 
2258 	/*
2259 	 * The aiocbe pointer must be validated before using it, so
2260 	 * registration is restricted to the kernel; the user cannot
2261 	 * set EV_FLAG1.
2262 	 */
2263 	if ((kn->kn_flags & EV_FLAG1) == 0)
2264 		return (EPERM);
2265 	kn->kn_flags &= ~EV_FLAG1;
2266 
2267 	knlist_add(&aiocbe->klist, kn, 0);
2268 
2269 	return (0);
2270 }
2271 
2272 /* kqueue detach function */
2273 static void
2274 filt_aiodetach(struct knote *kn)
2275 {
2276 	struct aiocblist *aiocbe = (struct aiocblist *)kn->kn_sdata;
2277 
2278 	knlist_remove(&aiocbe->klist, kn, 0);
2279 }
2280 
2281 /* kqueue filter function */
2282 /*ARGSUSED*/
2283 static int
2284 filt_aio(struct knote *kn, long hint)
2285 {
2286 	struct aiocblist *aiocbe = (struct aiocblist *)kn->kn_sdata;
2287 
2288 	kn->kn_data = aiocbe->uaiocb._aiocb_private.error;
2289 	if (aiocbe->jobstate != JOBST_JOBFINISHED &&
2290 	    aiocbe->jobstate != JOBST_JOBBFINISHED)
2291 		return (0);
2292 	kn->kn_flags |= EV_EOF;
2293 	return (1);
2294 }
2295