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