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