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