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