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