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