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