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