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