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