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