xref: /dragonfly/sys/kern/vfs_aio.c (revision 3f5e28f4)
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.40 2007/04/30 07:18:54 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 *curcp, *mycp, *userp;
623 	struct vmspace *myvm;
624 	struct ucred *cr;
625 
626 	/*
627 	 * Local copies of curproc (cp) and vmspace (myvm).  Get extra
628 	 * reference on myvm so we can use pmap_replacevm()
629 	 */
630 	mycp = curproc;
631 	myvm = mycp->p_vmspace;
632 	sysref_get(&myvm->vm_sysref);
633 
634 	if (mycp->p_textvp) {
635 		vrele(mycp->p_textvp);
636 		mycp->p_textvp = NULL;
637 	}
638 
639 	/*
640 	 * Allocate and ready the aio control info.  There is one aiop structure
641 	 * per daemon.
642 	 */
643 	aiop = zalloc(aiop_zone);
644 	aiop->aioproc = mycp;
645 	aiop->aioprocflags |= AIOP_FREE;
646 
647 	crit_enter();
648 
649 	/*
650 	 * Place thread (lightweight process) onto the AIO free thread list.
651 	 */
652 	if (TAILQ_EMPTY(&aio_freeproc))
653 		wakeup(&aio_freeproc);
654 	TAILQ_INSERT_HEAD(&aio_freeproc, aiop, list);
655 
656 	crit_exit();
657 
658 	/* Make up a name for the daemon. */
659 	strcpy(mycp->p_comm, "aiod");
660 
661 	/*
662 	 * Get rid of our current filedescriptors.  AIOD's don't need any
663 	 * filedescriptors, except as temporarily inherited from the client.
664 	 * Credentials are also cloned, and made equivalent to "root".
665 	 */
666 	fdfree(mycp);
667 	mycp->p_fd = NULL;
668 	cr = cratom(&mycp->p_ucred);
669 	cr->cr_uid = 0;
670 	uireplace(&cr->cr_uidinfo, uifind(0));
671 	cr->cr_ngroups = 1;
672 	cr->cr_groups[0] = 1;
673 
674 	/* The daemon resides in its own pgrp. */
675 	enterpgrp(mycp, mycp->p_pid, 1);
676 
677 	/* Mark special process type. */
678 	mycp->p_flag |= P_SYSTEM | P_KTHREADP;
679 
680 	/*
681 	 * Wakeup parent process.  (Parent sleeps to keep from blasting away
682 	 * and creating too many daemons.)
683 	 */
684 	wakeup(mycp);
685 
686 	for (;;) {
687 		/*
688 		 * curcp is the current daemon process context.
689 		 * userp is the current user process context.
690 		 */
691 		curcp = mycp;
692 
693 		/*
694 		 * Take daemon off of free queue
695 		 */
696 		if (aiop->aioprocflags & AIOP_FREE) {
697 			crit_enter();
698 			TAILQ_REMOVE(&aio_freeproc, aiop, list);
699 			TAILQ_INSERT_TAIL(&aio_activeproc, aiop, list);
700 			aiop->aioprocflags &= ~AIOP_FREE;
701 			crit_exit();
702 		}
703 		aiop->aioprocflags &= ~AIOP_SCHED;
704 
705 		/*
706 		 * Check for jobs.
707 		 */
708 		while ((aiocbe = aio_selectjob(aiop)) != NULL) {
709 			cb = &aiocbe->uaiocb;
710 			userp = aiocbe->userproc;
711 
712 			aiocbe->jobstate = JOBST_JOBRUNNING;
713 
714 			/*
715 			 * Connect to process address space for user program.
716 			 */
717 			if (userp != curcp) {
718 				pmap_replacevm(mycp, userp->p_vmspace, 1);
719 				curcp = userp;
720 			}
721 
722 			ki = userp->p_aioinfo;
723 			lj = aiocbe->lio;
724 
725 			/* Account for currently active jobs. */
726 			ki->kaio_active_count++;
727 
728 			/* Do the I/O function. */
729 			aio_process(aiocbe);
730 
731 			/* Decrement the active job count. */
732 			ki->kaio_active_count--;
733 
734 			/*
735 			 * Increment the completion count for wakeup/signal
736 			 * comparisons.
737 			 */
738 			aiocbe->jobflags |= AIOCBLIST_DONE;
739 			ki->kaio_queue_finished_count++;
740 			if (lj)
741 				lj->lioj_queue_finished_count++;
742 			if ((ki->kaio_flags & KAIO_WAKEUP) || ((ki->kaio_flags
743 			    & KAIO_RUNDOWN) && (ki->kaio_active_count == 0))) {
744 				ki->kaio_flags &= ~KAIO_WAKEUP;
745 				wakeup(userp);
746 			}
747 
748 			crit_enter();
749 			if (lj && (lj->lioj_flags &
750 			    (LIOJ_SIGNAL|LIOJ_SIGNAL_POSTED)) == LIOJ_SIGNAL) {
751 				if ((lj->lioj_queue_finished_count ==
752 				    lj->lioj_queue_count) &&
753 				    (lj->lioj_buffer_finished_count ==
754 				    lj->lioj_buffer_count)) {
755 						ksignal(userp,
756 						    lj->lioj_signal.sigev_signo);
757 						lj->lioj_flags |=
758 						    LIOJ_SIGNAL_POSTED;
759 				}
760 			}
761 			crit_exit();
762 
763 			aiocbe->jobstate = JOBST_JOBFINISHED;
764 
765 			crit_enter();
766 			TAILQ_REMOVE(&ki->kaio_jobqueue, aiocbe, plist);
767 			TAILQ_INSERT_TAIL(&ki->kaio_jobdone, aiocbe, plist);
768 			crit_exit();
769 			KNOTE(&aiocbe->klist, 0);
770 
771 			if (aiocbe->jobflags & AIOCBLIST_RUNDOWN) {
772 				wakeup(aiocbe);
773 				aiocbe->jobflags &= ~AIOCBLIST_RUNDOWN;
774 			}
775 
776 			if (cb->aio_sigevent.sigev_notify == SIGEV_SIGNAL) {
777 				ksignal(userp, cb->aio_sigevent.sigev_signo);
778 			}
779 		}
780 
781 		/*
782 		 * Disconnect from user address space.
783 		 */
784 		if (curcp != mycp) {
785 			/* swap our original address space back in */
786 			pmap_replacevm(mycp, myvm, 1);
787 			curcp = mycp;
788 		}
789 
790 		/*
791 		 * If we are the first to be put onto the free queue, wakeup
792 		 * anyone waiting for a daemon.
793 		 */
794 		crit_enter();
795 		TAILQ_REMOVE(&aio_activeproc, aiop, list);
796 		if (TAILQ_EMPTY(&aio_freeproc))
797 			wakeup(&aio_freeproc);
798 		TAILQ_INSERT_HEAD(&aio_freeproc, aiop, list);
799 		aiop->aioprocflags |= AIOP_FREE;
800 		crit_exit();
801 
802 		/*
803 		 * If daemon is inactive for a long time, allow it to exit,
804 		 * thereby freeing resources.
805 		 */
806 		if (((aiop->aioprocflags & AIOP_SCHED) == 0) && tsleep(mycp,
807 		    0, "aiordy", aiod_lifetime)) {
808 			crit_enter();
809 			if (TAILQ_EMPTY(&aio_jobs)) {
810 				if ((aiop->aioprocflags & AIOP_FREE) &&
811 				    (num_aio_procs > target_aio_procs)) {
812 					TAILQ_REMOVE(&aio_freeproc, aiop, list);
813 					crit_exit();
814 					zfree(aiop_zone, aiop);
815 					num_aio_procs--;
816 #ifdef DIAGNOSTIC
817 					if (mycp->p_vmspace->vm_sysref.refcnt <= 1) {
818 						kprintf("AIOD: bad vm refcnt for"
819 						    " exiting daemon: %d\n",
820 						    mycp->p_vmspace->vm_sysref.refcnt);
821 					}
822 #endif
823 					sysref_put(&myvm->vm_sysref);
824 					exit1(0);
825 				}
826 			}
827 			crit_exit();
828 		}
829 	}
830 }
831 
832 /*
833  * Create a new AIO daemon.  This is mostly a kernel-thread fork routine.  The
834  * AIO daemon modifies its environment itself.
835  */
836 static int
837 aio_newproc(void)
838 {
839 	int error;
840 	struct lwp *lp, *nlp;
841 	struct proc *np;
842 
843 	lp = &lwp0;
844 	error = fork1(lp, RFPROC|RFMEM|RFNOWAIT, &np);
845 	if (error)
846 		return error;
847 	nlp = ONLY_LWP_IN_PROC(np);
848 	cpu_set_fork_handler(nlp, aio_daemon, curproc);
849 	start_forked_proc(lp, np);
850 
851 	/*
852 	 * Wait until daemon is started, but continue on just in case to
853 	 * handle error conditions.
854 	 */
855 	error = tsleep(np, 0, "aiosta", aiod_timeout);
856 	num_aio_procs++;
857 
858 	return error;
859 }
860 
861 /*
862  * Try the high-performance, low-overhead physio method for eligible
863  * VCHR devices.  This method doesn't use an aio helper thread, and
864  * thus has very low overhead.
865  *
866  * Assumes that the caller, _aio_aqueue(), has incremented the file
867  * structure's reference count, preventing its deallocation for the
868  * duration of this call.
869  */
870 static int
871 aio_qphysio(struct proc *p, struct aiocblist *aiocbe)
872 {
873 	int error;
874 	struct aiocb *cb;
875 	struct file *fp;
876 	struct buf *bp;
877 	struct vnode *vp;
878 	struct kaioinfo *ki;
879 	struct aio_liojob *lj;
880 	int notify;
881 
882 	cb = &aiocbe->uaiocb;
883 	fp = aiocbe->fd_file;
884 
885 	if (fp->f_type != DTYPE_VNODE)
886 		return (-1);
887 
888 	vp = (struct vnode *)fp->f_data;
889 
890 	/*
891 	 * If its not a disk, we don't want to return a positive error.
892 	 * It causes the aio code to not fall through to try the thread
893 	 * way when you're talking to a regular file.
894 	 */
895 	if (!vn_isdisk(vp, &error)) {
896 		if (error == ENOTBLK)
897 			return (-1);
898 		else
899 			return (error);
900 	}
901 
902  	if (cb->aio_nbytes % vp->v_rdev->si_bsize_phys)
903 		return (-1);
904 
905 	if (cb->aio_nbytes >
906 	    MAXPHYS - (((vm_offset_t) cb->aio_buf) & PAGE_MASK))
907 		return (-1);
908 
909 	ki = p->p_aioinfo;
910 	if (ki->kaio_buffer_count >= ki->kaio_ballowed_count)
911 		return (-1);
912 
913 	ki->kaio_buffer_count++;
914 
915 	lj = aiocbe->lio;
916 	if (lj)
917 		lj->lioj_buffer_count++;
918 
919 	/* Create and build a buffer header for a transfer. */
920 	bp = getpbuf(NULL);
921 	BUF_KERNPROC(bp);
922 
923 	/*
924 	 * Get a copy of the kva from the physical buffer.
925 	 */
926 	bp->b_bio1.bio_caller_info1.ptr = p;
927 	error = 0;
928 
929 	bp->b_cmd = (cb->aio_lio_opcode == LIO_WRITE) ?
930 		    BUF_CMD_WRITE : BUF_CMD_READ;
931 	bp->b_bio1.bio_done = aio_physwakeup;
932 	bp->b_bio1.bio_offset = cb->aio_offset;
933 
934 	/* Bring buffer into kernel space. */
935 	if (vmapbuf(bp, __DEVOLATILE(char *, cb->aio_buf), cb->aio_nbytes) < 0) {
936 		error = EFAULT;
937 		goto doerror;
938 	}
939 
940 	crit_enter();
941 
942 	aiocbe->bp = bp;
943 	bp->b_bio1.bio_caller_info2.ptr = aiocbe;
944 	TAILQ_INSERT_TAIL(&aio_bufjobs, aiocbe, list);
945 	TAILQ_INSERT_TAIL(&ki->kaio_bufqueue, aiocbe, plist);
946 	aiocbe->jobstate = JOBST_JOBQBUF;
947 	cb->_aiocb_private.status = cb->aio_nbytes;
948 	num_buf_aio++;
949 	bp->b_error = 0;
950 
951 	crit_exit();
952 
953 	/* Perform transfer. */
954 	dev_dstrategy(vp->v_rdev, &bp->b_bio1);
955 
956 	notify = 0;
957 	crit_enter();
958 
959 	/*
960 	 * If we had an error invoking the request, or an error in processing
961 	 * the request before we have returned, we process it as an error in
962 	 * transfer.  Note that such an I/O error is not indicated immediately,
963 	 * but is returned using the aio_error mechanism.  In this case,
964 	 * aio_suspend will return immediately.
965 	 */
966 	if (bp->b_error || (bp->b_flags & B_ERROR)) {
967 		struct aiocb *job = aiocbe->uuaiocb;
968 
969 		aiocbe->uaiocb._aiocb_private.status = 0;
970 		suword(&job->_aiocb_private.status, 0);
971 		aiocbe->uaiocb._aiocb_private.error = bp->b_error;
972 		suword(&job->_aiocb_private.error, bp->b_error);
973 
974 		ki->kaio_buffer_finished_count++;
975 
976 		if (aiocbe->jobstate != JOBST_JOBBFINISHED) {
977 			aiocbe->jobstate = JOBST_JOBBFINISHED;
978 			aiocbe->jobflags |= AIOCBLIST_DONE;
979 			TAILQ_REMOVE(&aio_bufjobs, aiocbe, list);
980 			TAILQ_REMOVE(&ki->kaio_bufqueue, aiocbe, plist);
981 			TAILQ_INSERT_TAIL(&ki->kaio_bufdone, aiocbe, plist);
982 			notify = 1;
983 		}
984 	}
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 	crit_enter();
1011 	while (bp->b_cmd != BUF_CMD_DONE) {
1012 		if (tsleep(bp, 0, "physstr", aiod_timeout)) {
1013 			if (bp->b_cmd != BUF_CMD_DONE) {
1014 				crit_exit();
1015 				return EINPROGRESS;
1016 			} else {
1017 				break;
1018 			}
1019 		}
1020 	}
1021 	crit_exit();
1022 
1023 	/* Release mapping into kernel space. */
1024 	vunmapbuf(bp);
1025 	iocb->bp = 0;
1026 
1027 	error = 0;
1028 
1029 	/* Check for an error. */
1030 	if (bp->b_flags & B_ERROR)
1031 		error = bp->b_error;
1032 
1033 	relpbuf(bp, NULL);
1034 	return (error);
1035 }
1036 #endif /* VFS_AIO */
1037 
1038 /*
1039  * Wake up aio requests that may be serviceable now.
1040  */
1041 void
1042 aio_swake(struct socket *so, struct signalsockbuf *ssb)
1043 {
1044 #ifndef VFS_AIO
1045 	return;
1046 #else
1047 	struct aiocblist *cb,*cbn;
1048 	struct proc *p;
1049 	struct kaioinfo *ki = NULL;
1050 	int opcode, wakecount = 0;
1051 	struct aioproclist *aiop;
1052 
1053 	if (ssb == &so->so_snd) {
1054 		opcode = LIO_WRITE;
1055 		so->so_snd.ssb_flags &= ~SSB_AIO;
1056 	} else {
1057 		opcode = LIO_READ;
1058 		so->so_rcv.ssb_flags &= ~SSB_AIO;
1059 	}
1060 
1061 	for (cb = TAILQ_FIRST(&so->so_aiojobq); cb; cb = cbn) {
1062 		cbn = TAILQ_NEXT(cb, list);
1063 		if (opcode == cb->uaiocb.aio_lio_opcode) {
1064 			p = cb->userproc;
1065 			ki = p->p_aioinfo;
1066 			TAILQ_REMOVE(&so->so_aiojobq, cb, list);
1067 			TAILQ_REMOVE(&ki->kaio_sockqueue, cb, plist);
1068 			TAILQ_INSERT_TAIL(&aio_jobs, cb, list);
1069 			TAILQ_INSERT_TAIL(&ki->kaio_jobqueue, cb, plist);
1070 			wakecount++;
1071 			if (cb->jobstate != JOBST_JOBQGLOBAL)
1072 				panic("invalid queue value");
1073 		}
1074 	}
1075 
1076 	while (wakecount--) {
1077 		if ((aiop = TAILQ_FIRST(&aio_freeproc)) != 0) {
1078 			TAILQ_REMOVE(&aio_freeproc, aiop, list);
1079 			TAILQ_INSERT_TAIL(&aio_activeproc, aiop, list);
1080 			aiop->aioprocflags &= ~AIOP_FREE;
1081 			wakeup(aiop->aioproc);
1082 		}
1083 	}
1084 #endif /* VFS_AIO */
1085 }
1086 
1087 #ifdef VFS_AIO
1088 /*
1089  * Queue a new AIO request.  Choosing either the threaded or direct physio VCHR
1090  * technique is done in this code.
1091  */
1092 static int
1093 _aio_aqueue(struct aiocb *job, struct aio_liojob *lj, int type)
1094 {
1095 	struct proc *p = curproc;
1096 	struct filedesc *fdp;
1097 	struct file *fp;
1098 	unsigned int fd;
1099 	struct socket *so;
1100 	int error;
1101 	int opcode, user_opcode;
1102 	struct aiocblist *aiocbe;
1103 	struct aioproclist *aiop;
1104 	struct kaioinfo *ki;
1105 	struct kevent kev;
1106 	struct kqueue *kq;
1107 	struct file *kq_fp;
1108 
1109 	if ((aiocbe = TAILQ_FIRST(&aio_freejobs)) != NULL)
1110 		TAILQ_REMOVE(&aio_freejobs, aiocbe, list);
1111 	else
1112 		aiocbe = zalloc (aiocb_zone);
1113 
1114 	aiocbe->inputcharge = 0;
1115 	aiocbe->outputcharge = 0;
1116 	callout_init(&aiocbe->timeout);
1117 	SLIST_INIT(&aiocbe->klist);
1118 
1119 	suword(&job->_aiocb_private.status, -1);
1120 	suword(&job->_aiocb_private.error, 0);
1121 	suword(&job->_aiocb_private.kernelinfo, -1);
1122 
1123 	error = copyin(job, &aiocbe->uaiocb, sizeof(aiocbe->uaiocb));
1124 	if (error) {
1125 		suword(&job->_aiocb_private.error, error);
1126 		TAILQ_INSERT_HEAD(&aio_freejobs, aiocbe, list);
1127 		return error;
1128 	}
1129 	if (aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_SIGNAL &&
1130 	    !_SIG_VALID(aiocbe->uaiocb.aio_sigevent.sigev_signo)) {
1131 		TAILQ_INSERT_HEAD(&aio_freejobs, aiocbe, list);
1132 		return EINVAL;
1133 	}
1134 
1135 	/* Save userspace address of the job info. */
1136 	aiocbe->uuaiocb = job;
1137 
1138 	/* Get the opcode. */
1139 	user_opcode = aiocbe->uaiocb.aio_lio_opcode;
1140 	if (type != LIO_NOP)
1141 		aiocbe->uaiocb.aio_lio_opcode = type;
1142 	opcode = aiocbe->uaiocb.aio_lio_opcode;
1143 
1144 	/* Get the fd info for process. */
1145 	fdp = p->p_fd;
1146 
1147 	/*
1148 	 * Range check file descriptor.
1149 	 */
1150 	fd = aiocbe->uaiocb.aio_fildes;
1151 	if (fd >= fdp->fd_nfiles) {
1152 		TAILQ_INSERT_HEAD(&aio_freejobs, aiocbe, list);
1153 		if (type == 0)
1154 			suword(&job->_aiocb_private.error, EBADF);
1155 		return EBADF;
1156 	}
1157 
1158 	fp = aiocbe->fd_file = fdp->fd_files[fd].fp;
1159 	if ((fp == NULL) || ((opcode == LIO_WRITE) && ((fp->f_flag & FWRITE) ==
1160 	    0))) {
1161 		TAILQ_INSERT_HEAD(&aio_freejobs, aiocbe, list);
1162 		if (type == 0)
1163 			suword(&job->_aiocb_private.error, EBADF);
1164 		return EBADF;
1165 	}
1166 	fhold(fp);
1167 
1168 	if (aiocbe->uaiocb.aio_offset == -1LL) {
1169 		error = EINVAL;
1170 		goto aqueue_fail;
1171 	}
1172 	error = suword(&job->_aiocb_private.kernelinfo, jobrefid);
1173 	if (error) {
1174 		error = EINVAL;
1175 		goto aqueue_fail;
1176 	}
1177 	aiocbe->uaiocb._aiocb_private.kernelinfo = (void *)(intptr_t)jobrefid;
1178 	if (jobrefid == LONG_MAX)
1179 		jobrefid = 1;
1180 	else
1181 		jobrefid++;
1182 
1183 	if (opcode == LIO_NOP) {
1184 		fdrop(fp);
1185 		TAILQ_INSERT_HEAD(&aio_freejobs, aiocbe, list);
1186 		if (type == 0) {
1187 			suword(&job->_aiocb_private.error, 0);
1188 			suword(&job->_aiocb_private.status, 0);
1189 			suword(&job->_aiocb_private.kernelinfo, 0);
1190 		}
1191 		return 0;
1192 	}
1193 	if ((opcode != LIO_READ) && (opcode != LIO_WRITE)) {
1194 		if (type == 0)
1195 			suword(&job->_aiocb_private.status, 0);
1196 		error = EINVAL;
1197 		goto aqueue_fail;
1198 	}
1199 
1200 	if (aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_KEVENT) {
1201 		kev.ident = aiocbe->uaiocb.aio_sigevent.sigev_notify_kqueue;
1202 		kev.udata = aiocbe->uaiocb.aio_sigevent.sigev_value.sigval_ptr;
1203 	}
1204 	else {
1205 		/*
1206 		 * This method for requesting kevent-based notification won't
1207 		 * work on the alpha, since we're passing in a pointer
1208 		 * via aio_lio_opcode, which is an int.  Use the SIGEV_KEVENT-
1209 		 * based method instead.
1210 		 */
1211 		if (user_opcode == LIO_NOP || user_opcode == LIO_READ ||
1212 		    user_opcode == LIO_WRITE)
1213 			goto no_kqueue;
1214 
1215 		error = copyin((struct kevent *)(uintptr_t)user_opcode,
1216 		    &kev, sizeof(kev));
1217 		if (error)
1218 			goto aqueue_fail;
1219 	}
1220 	if ((u_int)kev.ident >= fdp->fd_nfiles ||
1221 	    (kq_fp = fdp->fd_files[kev.ident].fp) == NULL ||
1222 	    (kq_fp->f_type != DTYPE_KQUEUE)) {
1223 		error = EBADF;
1224 		goto aqueue_fail;
1225 	}
1226 	kq = (struct kqueue *)kq_fp->f_data;
1227 	kev.ident = (uintptr_t)aiocbe->uuaiocb;
1228 	kev.filter = EVFILT_AIO;
1229 	kev.flags = EV_ADD | EV_ENABLE | EV_FLAG1;
1230 	kev.data = (intptr_t)aiocbe;
1231 	/* XXX lwp kqueue_register takes a thread, but only uses its proc */
1232 	error = kqueue_register(kq, &kev, FIRST_LWP_IN_PROC(p)->lwp_thread);
1233 aqueue_fail:
1234 	if (error) {
1235 		fdrop(fp);
1236 		TAILQ_INSERT_HEAD(&aio_freejobs, aiocbe, list);
1237 		if (type == 0)
1238 			suword(&job->_aiocb_private.error, error);
1239 		goto done;
1240 	}
1241 no_kqueue:
1242 
1243 	suword(&job->_aiocb_private.error, EINPROGRESS);
1244 	aiocbe->uaiocb._aiocb_private.error = EINPROGRESS;
1245 	aiocbe->userproc = p;
1246 	aiocbe->jobflags = 0;
1247 	aiocbe->lio = lj;
1248 	ki = p->p_aioinfo;
1249 
1250 	if (fp->f_type == DTYPE_SOCKET) {
1251 		/*
1252 		 * Alternate queueing for socket ops: Reach down into the
1253 		 * descriptor to get the socket data.  Then check to see if the
1254 		 * socket is ready to be read or written (based on the requested
1255 		 * operation).
1256 		 *
1257 		 * If it is not ready for io, then queue the aiocbe on the
1258 		 * socket, and set the flags so we get a call when ssb_notify()
1259 		 * happens.
1260 		 */
1261 		so = (struct socket *)fp->f_data;
1262 		crit_enter();
1263 		if (((opcode == LIO_READ) && (!soreadable(so))) || ((opcode ==
1264 		    LIO_WRITE) && (!sowriteable(so)))) {
1265 			TAILQ_INSERT_TAIL(&so->so_aiojobq, aiocbe, list);
1266 			TAILQ_INSERT_TAIL(&ki->kaio_sockqueue, aiocbe, plist);
1267 			if (opcode == LIO_READ)
1268 				so->so_rcv.ssb_flags |= SSB_AIO;
1269 			else
1270 				so->so_snd.ssb_flags |= SSB_AIO;
1271 			aiocbe->jobstate = JOBST_JOBQGLOBAL; /* XXX */
1272 			ki->kaio_queue_count++;
1273 			num_queue_count++;
1274 			crit_exit();
1275 			error = 0;
1276 			goto done;
1277 		}
1278 		crit_exit();
1279 	}
1280 
1281 	if ((error = aio_qphysio(p, aiocbe)) == 0)
1282 		goto done;
1283 	if (error > 0) {
1284 		suword(&job->_aiocb_private.status, 0);
1285 		aiocbe->uaiocb._aiocb_private.error = error;
1286 		suword(&job->_aiocb_private.error, error);
1287 		goto done;
1288 	}
1289 
1290 	/* No buffer for daemon I/O. */
1291 	aiocbe->bp = NULL;
1292 
1293 	ki->kaio_queue_count++;
1294 	if (lj)
1295 		lj->lioj_queue_count++;
1296 	crit_enter();
1297 	TAILQ_INSERT_TAIL(&ki->kaio_jobqueue, aiocbe, plist);
1298 	TAILQ_INSERT_TAIL(&aio_jobs, aiocbe, list);
1299 	crit_exit();
1300 	aiocbe->jobstate = JOBST_JOBQGLOBAL;
1301 
1302 	num_queue_count++;
1303 	error = 0;
1304 
1305 	/*
1306 	 * If we don't have a free AIO process, and we are below our quota, then
1307 	 * start one.  Otherwise, depend on the subsequent I/O completions to
1308 	 * pick-up this job.  If we don't successfully create the new process
1309 	 * (thread) due to resource issues, we return an error for now (EAGAIN),
1310 	 * which is likely not the correct thing to do.
1311 	 */
1312 	crit_enter();
1313 retryproc:
1314 	if ((aiop = TAILQ_FIRST(&aio_freeproc)) != NULL) {
1315 		TAILQ_REMOVE(&aio_freeproc, aiop, list);
1316 		TAILQ_INSERT_TAIL(&aio_activeproc, aiop, list);
1317 		aiop->aioprocflags &= ~AIOP_FREE;
1318 		wakeup(aiop->aioproc);
1319 	} else if (((num_aio_resv_start + num_aio_procs) < max_aio_procs) &&
1320 	    ((ki->kaio_active_count + num_aio_resv_start) <
1321 	    ki->kaio_maxactive_count)) {
1322 		num_aio_resv_start++;
1323 		if ((error = aio_newproc()) == 0) {
1324 			num_aio_resv_start--;
1325 			goto retryproc;
1326 		}
1327 		num_aio_resv_start--;
1328 	}
1329 	crit_exit();
1330 done:
1331 	return error;
1332 }
1333 
1334 /*
1335  * This routine queues an AIO request, checking for quotas.
1336  */
1337 static int
1338 aio_aqueue(struct aiocb *job, int type)
1339 {
1340 	struct proc *p = curproc;
1341 	struct kaioinfo *ki;
1342 
1343 	if (p->p_aioinfo == NULL)
1344 		aio_init_aioinfo(p);
1345 
1346 	if (num_queue_count >= max_queue_count)
1347 		return EAGAIN;
1348 
1349 	ki = p->p_aioinfo;
1350 	if (ki->kaio_queue_count >= ki->kaio_qallowed_count)
1351 		return EAGAIN;
1352 
1353 	return _aio_aqueue(job, NULL, type);
1354 }
1355 #endif /* VFS_AIO */
1356 
1357 /*
1358  * Support the aio_return system call, as a side-effect, kernel resources are
1359  * released.
1360  */
1361 int
1362 sys_aio_return(struct aio_return_args *uap)
1363 {
1364 #ifndef VFS_AIO
1365 	return ENOSYS;
1366 #else
1367 	struct proc *p = curproc;
1368 	struct lwp *lp = curthread->td_lwp;
1369 	long jobref;
1370 	struct aiocblist *cb, *ncb;
1371 	struct aiocb *ujob;
1372 	struct kaioinfo *ki;
1373 
1374 	ki = p->p_aioinfo;
1375 	if (ki == NULL)
1376 		return EINVAL;
1377 
1378 	ujob = uap->aiocbp;
1379 
1380 	jobref = fuword(&ujob->_aiocb_private.kernelinfo);
1381 	if (jobref == -1 || jobref == 0)
1382 		return EINVAL;
1383 
1384 	TAILQ_FOREACH(cb, &ki->kaio_jobdone, plist) {
1385 		if (((intptr_t) cb->uaiocb._aiocb_private.kernelinfo) ==
1386 		    jobref) {
1387 			if (ujob == cb->uuaiocb) {
1388 				uap->sysmsg_result =
1389 				    cb->uaiocb._aiocb_private.status;
1390 			} else
1391 				uap->sysmsg_result = EFAULT;
1392 			if (cb->uaiocb.aio_lio_opcode == LIO_WRITE) {
1393 				lp->lwp_ru.ru_oublock += cb->outputcharge;
1394 				cb->outputcharge = 0;
1395 			} else if (cb->uaiocb.aio_lio_opcode == LIO_READ) {
1396 				lp->lwp_ru.ru_inblock += cb->inputcharge;
1397 				cb->inputcharge = 0;
1398 			}
1399 			aio_free_entry(cb);
1400 			return 0;
1401 		}
1402 	}
1403 	crit_enter();
1404 	for (cb = TAILQ_FIRST(&ki->kaio_bufdone); cb; cb = ncb) {
1405 		ncb = TAILQ_NEXT(cb, plist);
1406 		if (((intptr_t) cb->uaiocb._aiocb_private.kernelinfo)
1407 		    == jobref) {
1408 			crit_exit();
1409 			if (ujob == cb->uuaiocb) {
1410 				uap->sysmsg_result =
1411 				    cb->uaiocb._aiocb_private.status;
1412 			} else
1413 				uap->sysmsg_result = EFAULT;
1414 			aio_free_entry(cb);
1415 			return 0;
1416 		}
1417 	}
1418 	crit_exit();
1419 
1420 	return (EINVAL);
1421 #endif /* VFS_AIO */
1422 }
1423 
1424 /*
1425  * Allow a process to wakeup when any of the I/O requests are completed.
1426  */
1427 int
1428 sys_aio_suspend(struct aio_suspend_args *uap)
1429 {
1430 #ifndef VFS_AIO
1431 	return ENOSYS;
1432 #else
1433 	struct proc *p = curproc;
1434 	struct timeval atv;
1435 	struct timespec ts;
1436 	struct aiocb *const *cbptr, *cbp;
1437 	struct kaioinfo *ki;
1438 	struct aiocblist *cb;
1439 	int i;
1440 	int njoblist;
1441 	int error, timo;
1442 	long *ijoblist;
1443 	struct aiocb **ujoblist;
1444 
1445 	if (uap->nent > AIO_LISTIO_MAX)
1446 		return EINVAL;
1447 
1448 	timo = 0;
1449 	if (uap->timeout) {
1450 		/* Get timespec struct. */
1451 		if ((error = copyin(uap->timeout, &ts, sizeof(ts))) != 0)
1452 			return error;
1453 
1454 		if (ts.tv_nsec < 0 || ts.tv_nsec >= 1000000000)
1455 			return (EINVAL);
1456 
1457 		TIMESPEC_TO_TIMEVAL(&atv, &ts);
1458 		if (itimerfix(&atv))
1459 			return (EINVAL);
1460 		timo = tvtohz_high(&atv);
1461 	}
1462 
1463 	ki = p->p_aioinfo;
1464 	if (ki == NULL)
1465 		return EAGAIN;
1466 
1467 	njoblist = 0;
1468 	ijoblist = zalloc(aiol_zone);
1469 	ujoblist = zalloc(aiol_zone);
1470 	cbptr = uap->aiocbp;
1471 
1472 	for (i = 0; i < uap->nent; i++) {
1473 		cbp = (struct aiocb *)(intptr_t)fuword(&cbptr[i]);
1474 		if (cbp == 0)
1475 			continue;
1476 		ujoblist[njoblist] = cbp;
1477 		ijoblist[njoblist] = fuword(&cbp->_aiocb_private.kernelinfo);
1478 		njoblist++;
1479 	}
1480 
1481 	if (njoblist == 0) {
1482 		zfree(aiol_zone, ijoblist);
1483 		zfree(aiol_zone, ujoblist);
1484 		return 0;
1485 	}
1486 
1487 	error = 0;
1488 	for (;;) {
1489 		TAILQ_FOREACH(cb, &ki->kaio_jobdone, plist) {
1490 			for (i = 0; i < njoblist; i++) {
1491 				if (((intptr_t)
1492 				    cb->uaiocb._aiocb_private.kernelinfo) ==
1493 				    ijoblist[i]) {
1494 					if (ujoblist[i] != cb->uuaiocb)
1495 						error = EINVAL;
1496 					zfree(aiol_zone, ijoblist);
1497 					zfree(aiol_zone, ujoblist);
1498 					return error;
1499 				}
1500 			}
1501 		}
1502 
1503 		crit_enter();
1504 		for (cb = TAILQ_FIRST(&ki->kaio_bufdone); cb; cb =
1505 		    TAILQ_NEXT(cb, plist)) {
1506 			for (i = 0; i < njoblist; i++) {
1507 				if (((intptr_t)
1508 				    cb->uaiocb._aiocb_private.kernelinfo) ==
1509 				    ijoblist[i]) {
1510 					crit_exit();
1511 					if (ujoblist[i] != cb->uuaiocb)
1512 						error = EINVAL;
1513 					zfree(aiol_zone, ijoblist);
1514 					zfree(aiol_zone, ujoblist);
1515 					return error;
1516 				}
1517 			}
1518 		}
1519 
1520 		ki->kaio_flags |= KAIO_WAKEUP;
1521 		error = tsleep(p, PCATCH, "aiospn", timo);
1522 		crit_exit();
1523 
1524 		if (error == ERESTART || error == EINTR) {
1525 			zfree(aiol_zone, ijoblist);
1526 			zfree(aiol_zone, ujoblist);
1527 			return EINTR;
1528 		} else if (error == EWOULDBLOCK) {
1529 			zfree(aiol_zone, ijoblist);
1530 			zfree(aiol_zone, ujoblist);
1531 			return EAGAIN;
1532 		}
1533 	}
1534 
1535 /* NOTREACHED */
1536 	return EINVAL;
1537 #endif /* VFS_AIO */
1538 }
1539 
1540 /*
1541  * aio_cancel cancels any non-physio aio operations not currently in
1542  * progress.
1543  */
1544 int
1545 sys_aio_cancel(struct aio_cancel_args *uap)
1546 {
1547 #ifndef VFS_AIO
1548 	return ENOSYS;
1549 #else
1550 	struct proc *p = curproc;
1551 	struct kaioinfo *ki;
1552 	struct aiocblist *cbe, *cbn;
1553 	struct file *fp;
1554 	struct filedesc *fdp;
1555 	struct socket *so;
1556 	struct proc *po;
1557 	int error;
1558 	int cancelled=0;
1559 	int notcancelled=0;
1560 	struct vnode *vp;
1561 
1562 	fdp = p->p_fd;
1563 	if ((u_int)uap->fd >= fdp->fd_nfiles ||
1564 	    (fp = fdp->fd_files[uap->fd].fp) == NULL)
1565 		return (EBADF);
1566 
1567         if (fp->f_type == DTYPE_VNODE) {
1568 		vp = (struct vnode *)fp->f_data;
1569 
1570 		if (vn_isdisk(vp,&error)) {
1571 			uap->sysmsg_result = AIO_NOTCANCELED;
1572         	        return 0;
1573 		}
1574 	} else if (fp->f_type == DTYPE_SOCKET) {
1575 		so = (struct socket *)fp->f_data;
1576 
1577 		crit_enter();
1578 
1579 		for (cbe = TAILQ_FIRST(&so->so_aiojobq); cbe; cbe = cbn) {
1580 			cbn = TAILQ_NEXT(cbe, list);
1581 			if ((uap->aiocbp == NULL) ||
1582 				(uap->aiocbp == cbe->uuaiocb) ) {
1583 				po = cbe->userproc;
1584 				ki = po->p_aioinfo;
1585 				TAILQ_REMOVE(&so->so_aiojobq, cbe, list);
1586 				TAILQ_REMOVE(&ki->kaio_sockqueue, cbe, plist);
1587 				TAILQ_INSERT_TAIL(&ki->kaio_jobdone, cbe, plist);
1588 				if (ki->kaio_flags & KAIO_WAKEUP) {
1589 					wakeup(po);
1590 				}
1591 				cbe->jobstate = JOBST_JOBFINISHED;
1592 				cbe->uaiocb._aiocb_private.status=-1;
1593 				cbe->uaiocb._aiocb_private.error=ECANCELED;
1594 				cancelled++;
1595 /* XXX cancelled, knote? */
1596 			        if (cbe->uaiocb.aio_sigevent.sigev_notify ==
1597 				    SIGEV_SIGNAL)
1598 					ksignal(cbe->userproc, cbe->uaiocb.aio_sigevent.sigev_signo);
1599 				if (uap->aiocbp)
1600 					break;
1601 			}
1602 		}
1603 		crit_exit();
1604 
1605 		if ((cancelled) && (uap->aiocbp)) {
1606 			uap->sysmsg_result = AIO_CANCELED;
1607 			return 0;
1608 		}
1609 	}
1610 	ki=p->p_aioinfo;
1611 	if (ki == NULL)
1612 		goto done;
1613 	crit_enter();
1614 
1615 	for (cbe = TAILQ_FIRST(&ki->kaio_jobqueue); cbe; cbe = cbn) {
1616 		cbn = TAILQ_NEXT(cbe, plist);
1617 
1618 		if ((uap->fd == cbe->uaiocb.aio_fildes) &&
1619 		    ((uap->aiocbp == NULL ) ||
1620 		     (uap->aiocbp == cbe->uuaiocb))) {
1621 
1622 			if (cbe->jobstate == JOBST_JOBQGLOBAL) {
1623 				TAILQ_REMOVE(&aio_jobs, cbe, list);
1624                                 TAILQ_REMOVE(&ki->kaio_jobqueue, cbe, plist);
1625                                 TAILQ_INSERT_TAIL(&ki->kaio_jobdone, cbe,
1626                                     plist);
1627 				cancelled++;
1628 				ki->kaio_queue_finished_count++;
1629 				cbe->jobstate = JOBST_JOBFINISHED;
1630 				cbe->uaiocb._aiocb_private.status = -1;
1631 				cbe->uaiocb._aiocb_private.error = ECANCELED;
1632 /* XXX cancelled, knote? */
1633 			        if (cbe->uaiocb.aio_sigevent.sigev_notify ==
1634 				    SIGEV_SIGNAL)
1635 					ksignal(cbe->userproc, cbe->uaiocb.aio_sigevent.sigev_signo);
1636 			} else {
1637 				notcancelled++;
1638 			}
1639 		}
1640 	}
1641 	crit_exit();
1642 done:
1643 	if (notcancelled) {
1644 		uap->sysmsg_result = AIO_NOTCANCELED;
1645 		return 0;
1646 	}
1647 	if (cancelled) {
1648 		uap->sysmsg_result = AIO_CANCELED;
1649 		return 0;
1650 	}
1651 	uap->sysmsg_result = AIO_ALLDONE;
1652 
1653 	return 0;
1654 #endif /* VFS_AIO */
1655 }
1656 
1657 /*
1658  * aio_error is implemented in the kernel level for compatibility purposes only.
1659  * For a user mode async implementation, it would be best to do it in a userland
1660  * subroutine.
1661  */
1662 int
1663 sys_aio_error(struct aio_error_args *uap)
1664 {
1665 #ifndef VFS_AIO
1666 	return ENOSYS;
1667 #else
1668 	struct proc *p = curproc;
1669 	struct aiocblist *cb;
1670 	struct kaioinfo *ki;
1671 	long jobref;
1672 
1673 	ki = p->p_aioinfo;
1674 	if (ki == NULL)
1675 		return EINVAL;
1676 
1677 	jobref = fuword(&uap->aiocbp->_aiocb_private.kernelinfo);
1678 	if ((jobref == -1) || (jobref == 0))
1679 		return EINVAL;
1680 
1681 	TAILQ_FOREACH(cb, &ki->kaio_jobdone, plist) {
1682 		if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1683 		    jobref) {
1684 			uap->sysmsg_result = cb->uaiocb._aiocb_private.error;
1685 			return 0;
1686 		}
1687 	}
1688 
1689 	crit_enter();
1690 
1691 	for (cb = TAILQ_FIRST(&ki->kaio_jobqueue); cb; cb = TAILQ_NEXT(cb,
1692 	    plist)) {
1693 		if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1694 		    jobref) {
1695 			uap->sysmsg_result = EINPROGRESS;
1696 			crit_exit();
1697 			return 0;
1698 		}
1699 	}
1700 
1701 	for (cb = TAILQ_FIRST(&ki->kaio_sockqueue); cb; cb = TAILQ_NEXT(cb,
1702 	    plist)) {
1703 		if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1704 		    jobref) {
1705 			uap->sysmsg_result = EINPROGRESS;
1706 			crit_exit();
1707 			return 0;
1708 		}
1709 	}
1710 	crit_exit();
1711 
1712 	crit_enter();
1713 	for (cb = TAILQ_FIRST(&ki->kaio_bufdone); cb; cb = TAILQ_NEXT(cb,
1714 	    plist)) {
1715 		if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1716 		    jobref) {
1717 			uap->sysmsg_result = cb->uaiocb._aiocb_private.error;
1718 			crit_exit();
1719 			return 0;
1720 		}
1721 	}
1722 
1723 	for (cb = TAILQ_FIRST(&ki->kaio_bufqueue); cb; cb = TAILQ_NEXT(cb,
1724 	    plist)) {
1725 		if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1726 		    jobref) {
1727 			uap->sysmsg_result = EINPROGRESS;
1728 			crit_exit();
1729 			return 0;
1730 		}
1731 	}
1732 	crit_exit();
1733 
1734 #if (0)
1735 	/*
1736 	 * Hack for lio.
1737 	 */
1738 	status = fuword(&uap->aiocbp->_aiocb_private.status);
1739 	if (status == -1)
1740 		return fuword(&uap->aiocbp->_aiocb_private.error);
1741 #endif
1742 	return EINVAL;
1743 #endif /* VFS_AIO */
1744 }
1745 
1746 /* syscall - asynchronous read from a file (REALTIME) */
1747 int
1748 sys_aio_read(struct aio_read_args *uap)
1749 {
1750 #ifndef VFS_AIO
1751 	return ENOSYS;
1752 #else
1753 	return aio_aqueue(uap->aiocbp, LIO_READ);
1754 #endif /* VFS_AIO */
1755 }
1756 
1757 /* syscall - asynchronous write to a file (REALTIME) */
1758 int
1759 sys_aio_write(struct aio_write_args *uap)
1760 {
1761 #ifndef VFS_AIO
1762 	return ENOSYS;
1763 #else
1764 	return aio_aqueue(uap->aiocbp, LIO_WRITE);
1765 #endif /* VFS_AIO */
1766 }
1767 
1768 /* syscall - XXX undocumented */
1769 int
1770 sys_lio_listio(struct lio_listio_args *uap)
1771 {
1772 #ifndef VFS_AIO
1773 	return ENOSYS;
1774 #else
1775 	struct proc *p = curproc;
1776 	struct lwp *lp = curthread->td_lwp;
1777 	int nent, nentqueued;
1778 	struct aiocb *iocb, * const *cbptr;
1779 	struct aiocblist *cb;
1780 	struct kaioinfo *ki;
1781 	struct aio_liojob *lj;
1782 	int error, runningcode;
1783 	int nerror;
1784 	int i;
1785 
1786 	if ((uap->mode != LIO_NOWAIT) && (uap->mode != LIO_WAIT))
1787 		return EINVAL;
1788 
1789 	nent = uap->nent;
1790 	if (nent > AIO_LISTIO_MAX)
1791 		return EINVAL;
1792 
1793 	if (p->p_aioinfo == NULL)
1794 		aio_init_aioinfo(p);
1795 
1796 	if ((nent + num_queue_count) > max_queue_count)
1797 		return EAGAIN;
1798 
1799 	ki = p->p_aioinfo;
1800 	if ((nent + ki->kaio_queue_count) > ki->kaio_qallowed_count)
1801 		return EAGAIN;
1802 
1803 	lj = zalloc(aiolio_zone);
1804 	if (!lj)
1805 		return EAGAIN;
1806 
1807 	lj->lioj_flags = 0;
1808 	lj->lioj_buffer_count = 0;
1809 	lj->lioj_buffer_finished_count = 0;
1810 	lj->lioj_queue_count = 0;
1811 	lj->lioj_queue_finished_count = 0;
1812 	lj->lioj_ki = ki;
1813 
1814 	/*
1815 	 * Setup signal.
1816 	 */
1817 	if (uap->sig && (uap->mode == LIO_NOWAIT)) {
1818 		error = copyin(uap->sig, &lj->lioj_signal,
1819 		    sizeof(lj->lioj_signal));
1820 		if (error) {
1821 			zfree(aiolio_zone, lj);
1822 			return error;
1823 		}
1824 		if (!_SIG_VALID(lj->lioj_signal.sigev_signo)) {
1825 			zfree(aiolio_zone, lj);
1826 			return EINVAL;
1827 		}
1828 		lj->lioj_flags |= LIOJ_SIGNAL;
1829 		lj->lioj_flags &= ~LIOJ_SIGNAL_POSTED;
1830 	} else
1831 		lj->lioj_flags &= ~LIOJ_SIGNAL;
1832 
1833 	TAILQ_INSERT_TAIL(&ki->kaio_liojoblist, lj, lioj_list);
1834 	/*
1835 	 * Get pointers to the list of I/O requests.
1836 	 */
1837 	nerror = 0;
1838 	nentqueued = 0;
1839 	cbptr = uap->acb_list;
1840 	for (i = 0; i < uap->nent; i++) {
1841 		iocb = (struct aiocb *)(intptr_t)fuword(&cbptr[i]);
1842 		if (((intptr_t)iocb != -1) && ((intptr_t)iocb != 0)) {
1843 			error = _aio_aqueue(iocb, lj, 0);
1844 			if (error == 0)
1845 				nentqueued++;
1846 			else
1847 				nerror++;
1848 		}
1849 	}
1850 
1851 	/*
1852 	 * If we haven't queued any, then just return error.
1853 	 */
1854 	if (nentqueued == 0)
1855 		return 0;
1856 
1857 	/*
1858 	 * Calculate the appropriate error return.
1859 	 */
1860 	runningcode = 0;
1861 	if (nerror)
1862 		runningcode = EIO;
1863 
1864 	if (uap->mode == LIO_WAIT) {
1865 		int command, found, jobref;
1866 
1867 		for (;;) {
1868 			found = 0;
1869 			for (i = 0; i < uap->nent; i++) {
1870 				/*
1871 				 * Fetch address of the control buf pointer in
1872 				 * user space.
1873 				 */
1874 				iocb = (struct aiocb *)
1875 				    (intptr_t)fuword(&cbptr[i]);
1876 				if (((intptr_t)iocb == -1) || ((intptr_t)iocb
1877 				    == 0))
1878 					continue;
1879 
1880 				/*
1881 				 * Fetch the associated command from user space.
1882 				 */
1883 				command = fuword(&iocb->aio_lio_opcode);
1884 				if (command == LIO_NOP) {
1885 					found++;
1886 					continue;
1887 				}
1888 
1889 				jobref = fuword(&iocb->_aiocb_private.kernelinfo);
1890 
1891 				TAILQ_FOREACH(cb, &ki->kaio_jobdone, plist) {
1892 					if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo)
1893 					    == jobref) {
1894 						if (cb->uaiocb.aio_lio_opcode
1895 						    == LIO_WRITE) {
1896 							lp->lwp_ru.ru_oublock +=
1897 							    cb->outputcharge;
1898 							cb->outputcharge = 0;
1899 						} else if (cb->uaiocb.aio_lio_opcode
1900 						    == LIO_READ) {
1901 							lp->lwp_ru.ru_inblock +=
1902 							    cb->inputcharge;
1903 							cb->inputcharge = 0;
1904 						}
1905 						found++;
1906 						break;
1907 					}
1908 				}
1909 
1910 				crit_enter();
1911 				TAILQ_FOREACH(cb, &ki->kaio_bufdone, plist) {
1912 					if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo)
1913 					    == jobref) {
1914 						found++;
1915 						break;
1916 					}
1917 				}
1918 				crit_exit();
1919 			}
1920 
1921 			/*
1922 			 * If all I/Os have been disposed of, then we can
1923 			 * return.
1924 			 */
1925 			if (found == nentqueued)
1926 				return runningcode;
1927 
1928 			ki->kaio_flags |= KAIO_WAKEUP;
1929 			error = tsleep(p, PCATCH, "aiospn", 0);
1930 
1931 			if (error == EINTR)
1932 				return EINTR;
1933 			else if (error == EWOULDBLOCK)
1934 				return EAGAIN;
1935 		}
1936 	}
1937 
1938 	return runningcode;
1939 #endif /* VFS_AIO */
1940 }
1941 
1942 #ifdef VFS_AIO
1943 /*
1944  * This is a weird hack so that we can post a signal.  It is safe to do so from
1945  * a timeout routine, but *not* from an interrupt routine.
1946  */
1947 static void
1948 process_signal(void *aioj)
1949 {
1950 	struct aiocblist *aiocbe = aioj;
1951 	struct aio_liojob *lj = aiocbe->lio;
1952 	struct aiocb *cb = &aiocbe->uaiocb;
1953 
1954 	if ((lj) && (lj->lioj_signal.sigev_notify == SIGEV_SIGNAL) &&
1955 	    (lj->lioj_queue_count == lj->lioj_queue_finished_count)) {
1956 		ksignal(lj->lioj_ki->kaio_p, lj->lioj_signal.sigev_signo);
1957 		lj->lioj_flags |= LIOJ_SIGNAL_POSTED;
1958 	}
1959 
1960 	if (cb->aio_sigevent.sigev_notify == SIGEV_SIGNAL)
1961 		ksignal(aiocbe->userproc, cb->aio_sigevent.sigev_signo);
1962 }
1963 
1964 /*
1965  * Interrupt handler for physio, performs the necessary process wakeups, and
1966  * signals.
1967  */
1968 static void
1969 aio_physwakeup(struct bio *bio)
1970 {
1971 	struct buf *bp = bio->bio_buf;
1972 	struct aiocblist *aiocbe;
1973 	struct proc *p;
1974 	struct kaioinfo *ki;
1975 	struct aio_liojob *lj;
1976 
1977 	aiocbe = bio->bio_caller_info2.ptr;
1978 
1979 	if (aiocbe) {
1980 		p = bio->bio_caller_info1.ptr;
1981 
1982 		aiocbe->jobstate = JOBST_JOBBFINISHED;
1983 		aiocbe->uaiocb._aiocb_private.status -= bp->b_resid;
1984 		aiocbe->uaiocb._aiocb_private.error = 0;
1985 		aiocbe->jobflags |= AIOCBLIST_DONE;
1986 
1987 		if (bp->b_flags & B_ERROR)
1988 			aiocbe->uaiocb._aiocb_private.error = bp->b_error;
1989 
1990 		lj = aiocbe->lio;
1991 		if (lj) {
1992 			lj->lioj_buffer_finished_count++;
1993 
1994 			/*
1995 			 * wakeup/signal if all of the interrupt jobs are done.
1996 			 */
1997 			if (lj->lioj_buffer_finished_count ==
1998 			    lj->lioj_buffer_count) {
1999 				/*
2000 				 * Post a signal if it is called for.
2001 				 */
2002 				if ((lj->lioj_flags &
2003 				    (LIOJ_SIGNAL|LIOJ_SIGNAL_POSTED)) ==
2004 				    LIOJ_SIGNAL) {
2005 					lj->lioj_flags |= LIOJ_SIGNAL_POSTED;
2006 					callout_reset(&aiocbe->timeout, 0,
2007 							process_signal, aiocbe);
2008 				}
2009 			}
2010 		}
2011 
2012 		ki = p->p_aioinfo;
2013 		if (ki) {
2014 			ki->kaio_buffer_finished_count++;
2015 			TAILQ_REMOVE(&aio_bufjobs, aiocbe, list);
2016 			TAILQ_REMOVE(&ki->kaio_bufqueue, aiocbe, plist);
2017 			TAILQ_INSERT_TAIL(&ki->kaio_bufdone, aiocbe, plist);
2018 
2019 			KNOTE(&aiocbe->klist, 0);
2020 			/* Do the wakeup. */
2021 			if (ki->kaio_flags & (KAIO_RUNDOWN|KAIO_WAKEUP)) {
2022 				ki->kaio_flags &= ~KAIO_WAKEUP;
2023 				wakeup(p);
2024 			}
2025 		}
2026 
2027 		if (aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_SIGNAL) {
2028 			callout_reset(&aiocbe->timeout, 0,
2029 					process_signal, aiocbe);
2030 		}
2031 	}
2032 	bp->b_cmd = BUF_CMD_DONE;
2033 	wakeup(bp);
2034 }
2035 #endif /* VFS_AIO */
2036 
2037 /* syscall - wait for the next completion of an aio request */
2038 int
2039 sys_aio_waitcomplete(struct aio_waitcomplete_args *uap)
2040 {
2041 #ifndef VFS_AIO
2042 	return ENOSYS;
2043 #else
2044 	struct proc *p = curproc;
2045 	struct lwp *lp = curthread->td_lwp;
2046 	struct timeval atv;
2047 	struct timespec ts;
2048 	struct kaioinfo *ki;
2049 	struct aiocblist *cb = NULL;
2050 	int error, timo;
2051 
2052 	suword(uap->aiocbp, (int)NULL);
2053 
2054 	timo = 0;
2055 	if (uap->timeout) {
2056 		/* Get timespec struct. */
2057 		error = copyin(uap->timeout, &ts, sizeof(ts));
2058 		if (error)
2059 			return error;
2060 
2061 		if ((ts.tv_nsec < 0) || (ts.tv_nsec >= 1000000000))
2062 			return (EINVAL);
2063 
2064 		TIMESPEC_TO_TIMEVAL(&atv, &ts);
2065 		if (itimerfix(&atv))
2066 			return (EINVAL);
2067 		timo = tvtohz_high(&atv);
2068 	}
2069 
2070 	ki = p->p_aioinfo;
2071 	if (ki == NULL)
2072 		return EAGAIN;
2073 
2074 	for (;;) {
2075 		if ((cb = TAILQ_FIRST(&ki->kaio_jobdone)) != 0) {
2076 			suword(uap->aiocbp, (uintptr_t)cb->uuaiocb);
2077 			uap->sysmsg_result = cb->uaiocb._aiocb_private.status;
2078 			if (cb->uaiocb.aio_lio_opcode == LIO_WRITE) {
2079 				lp->lwp_ru.ru_oublock +=
2080 				    cb->outputcharge;
2081 				cb->outputcharge = 0;
2082 			} else if (cb->uaiocb.aio_lio_opcode == LIO_READ) {
2083 				lp->lwp_ru.ru_inblock += cb->inputcharge;
2084 				cb->inputcharge = 0;
2085 			}
2086 			aio_free_entry(cb);
2087 			return cb->uaiocb._aiocb_private.error;
2088 		}
2089 
2090 		crit_enter();
2091  		if ((cb = TAILQ_FIRST(&ki->kaio_bufdone)) != 0 ) {
2092 			crit_exit();
2093 			suword(uap->aiocbp, (uintptr_t)cb->uuaiocb);
2094 			uap->sysmsg_result = cb->uaiocb._aiocb_private.status;
2095 			aio_free_entry(cb);
2096 			return cb->uaiocb._aiocb_private.error;
2097 		}
2098 
2099 		ki->kaio_flags |= KAIO_WAKEUP;
2100 		error = tsleep(p, PCATCH, "aiowc", timo);
2101 		crit_exit();
2102 
2103 		if (error == ERESTART)
2104 			return EINTR;
2105 		else if (error < 0)
2106 			return error;
2107 		else if (error == EINTR)
2108 			return EINTR;
2109 		else if (error == EWOULDBLOCK)
2110 			return EAGAIN;
2111 	}
2112 #endif /* VFS_AIO */
2113 }
2114 
2115 #ifndef VFS_AIO
2116 static int
2117 filt_aioattach(struct knote *kn)
2118 {
2119 
2120 	return (ENXIO);
2121 }
2122 
2123 struct filterops aio_filtops =
2124 	{ 0, filt_aioattach, NULL, NULL };
2125 
2126 #else
2127 /* kqueue attach function */
2128 static int
2129 filt_aioattach(struct knote *kn)
2130 {
2131 	struct aiocblist *aiocbe = (struct aiocblist *)kn->kn_sdata;
2132 
2133 	/*
2134 	 * The aiocbe pointer must be validated before using it, so
2135 	 * registration is restricted to the kernel; the user cannot
2136 	 * set EV_FLAG1.
2137 	 */
2138 	if ((kn->kn_flags & EV_FLAG1) == 0)
2139 		return (EPERM);
2140 	kn->kn_flags &= ~EV_FLAG1;
2141 
2142 	SLIST_INSERT_HEAD(&aiocbe->klist, kn, kn_selnext);
2143 
2144 	return (0);
2145 }
2146 
2147 /* kqueue detach function */
2148 static void
2149 filt_aiodetach(struct knote *kn)
2150 {
2151 	struct aiocblist *aiocbe = (struct aiocblist *)kn->kn_sdata;
2152 
2153 	SLIST_REMOVE(&aiocbe->klist, kn, knote, kn_selnext);
2154 }
2155 
2156 /* kqueue filter function */
2157 /*ARGSUSED*/
2158 static int
2159 filt_aio(struct knote *kn, long hint)
2160 {
2161 	struct aiocblist *aiocbe = (struct aiocblist *)kn->kn_sdata;
2162 
2163 	kn->kn_data = aiocbe->uaiocb._aiocb_private.error;
2164 	if (aiocbe->jobstate != JOBST_JOBFINISHED &&
2165 	    aiocbe->jobstate != JOBST_JOBBFINISHED)
2166 		return (0);
2167 	kn->kn_flags |= EV_EOF;
2168 	return (1);
2169 }
2170 
2171 struct filterops aio_filtops =
2172 	{ 0, filt_aioattach, filt_aiodetach, filt_aio };
2173 #endif /* VFS_AIO */
2174