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