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