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