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