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