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