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