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