vfs_aio.c revision 106998
1/*
2 * Copyright (c) 1997 John S. Dyson.  All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 * 2. John S. Dyson's name may not be used to endorse or promote products
10 *    derived from this software without specific prior written permission.
11 *
12 * DISCLAIMER:  This code isn't warranted to do anything useful.  Anything
13 * bad that happens because of using this software isn't the responsibility
14 * of the author.  This software is distributed AS-IS.
15 *
16 * $FreeBSD: head/sys/kern/vfs_aio.c 106998 2002-11-17 04:15:34Z alfred $
17 */
18
19/*
20 * This file contains support for the POSIX 1003.1B AIO/LIO facility.
21 */
22
23#include <sys/param.h>
24#include <sys/systm.h>
25#include <sys/malloc.h>
26#include <sys/bio.h>
27#include <sys/buf.h>
28#include <sys/sysproto.h>
29#include <sys/filedesc.h>
30#include <sys/kernel.h>
31#include <sys/kthread.h>
32#include <sys/fcntl.h>
33#include <sys/file.h>
34#include <sys/lock.h>
35#include <sys/mutex.h>
36#include <sys/unistd.h>
37#include <sys/proc.h>
38#include <sys/resourcevar.h>
39#include <sys/signalvar.h>
40#include <sys/protosw.h>
41#include <sys/socketvar.h>
42#include <sys/syscall.h>
43#include <sys/sysent.h>
44#include <sys/sysctl.h>
45#include <sys/sx.h>
46#include <sys/vnode.h>
47#include <sys/conf.h>
48#include <sys/event.h>
49
50#include <posix4/posix4.h>
51#include <vm/vm.h>
52#include <vm/vm_extern.h>
53#include <vm/pmap.h>
54#include <vm/vm_map.h>
55#include <vm/uma.h>
56#include <sys/aio.h>
57
58#include <machine/limits.h>
59
60#include "opt_vfs_aio.h"
61
62/*
63 * Counter for allocating reference ids to new jobs.  Wrapped to 1 on
64 * overflow.
65 */
66static	long jobrefid;
67
68#define JOBST_NULL		0x0
69#define JOBST_JOBQGLOBAL	0x2
70#define JOBST_JOBRUNNING	0x3
71#define JOBST_JOBFINISHED	0x4
72#define	JOBST_JOBQBUF		0x5
73#define	JOBST_JOBBFINISHED	0x6
74
75#ifndef MAX_AIO_PER_PROC
76#define MAX_AIO_PER_PROC	32
77#endif
78
79#ifndef MAX_AIO_QUEUE_PER_PROC
80#define MAX_AIO_QUEUE_PER_PROC	256 /* Bigger than AIO_LISTIO_MAX */
81#endif
82
83#ifndef MAX_AIO_PROCS
84#define MAX_AIO_PROCS		32
85#endif
86
87#ifndef MAX_AIO_QUEUE
88#define	MAX_AIO_QUEUE		1024 /* Bigger than AIO_LISTIO_MAX */
89#endif
90
91#ifndef TARGET_AIO_PROCS
92#define TARGET_AIO_PROCS	4
93#endif
94
95#ifndef MAX_BUF_AIO
96#define MAX_BUF_AIO		16
97#endif
98
99#ifndef AIOD_TIMEOUT_DEFAULT
100#define	AIOD_TIMEOUT_DEFAULT	(10 * hz)
101#endif
102
103#ifndef AIOD_LIFETIME_DEFAULT
104#define AIOD_LIFETIME_DEFAULT	(30 * hz)
105#endif
106
107SYSCTL_NODE(_vfs, OID_AUTO, aio, CTLFLAG_RW, 0, "Async IO management");
108
109static int max_aio_procs = MAX_AIO_PROCS;
110SYSCTL_INT(_vfs_aio, OID_AUTO, max_aio_procs,
111	CTLFLAG_RW, &max_aio_procs, 0,
112	"Maximum number of kernel threads to use for handling async IO ");
113
114static int num_aio_procs = 0;
115SYSCTL_INT(_vfs_aio, OID_AUTO, num_aio_procs,
116	CTLFLAG_RD, &num_aio_procs, 0,
117	"Number of presently active kernel threads for async IO");
118
119/*
120 * The code will adjust the actual number of AIO processes towards this
121 * number when it gets a chance.
122 */
123static int target_aio_procs = TARGET_AIO_PROCS;
124SYSCTL_INT(_vfs_aio, OID_AUTO, target_aio_procs, CTLFLAG_RW, &target_aio_procs,
125	0, "Preferred number of ready kernel threads for async IO");
126
127static int max_queue_count = MAX_AIO_QUEUE;
128SYSCTL_INT(_vfs_aio, OID_AUTO, max_aio_queue, CTLFLAG_RW, &max_queue_count, 0,
129    "Maximum number of aio requests to queue, globally");
130
131static int num_queue_count = 0;
132SYSCTL_INT(_vfs_aio, OID_AUTO, num_queue_count, CTLFLAG_RD, &num_queue_count, 0,
133    "Number of queued aio requests");
134
135static int num_buf_aio = 0;
136SYSCTL_INT(_vfs_aio, OID_AUTO, num_buf_aio, CTLFLAG_RD, &num_buf_aio, 0,
137    "Number of aio requests presently handled by the buf subsystem");
138
139/* Number of async I/O thread in the process of being started */
140/* XXX This should be local to _aio_aqueue() */
141static int num_aio_resv_start = 0;
142
143static int aiod_timeout;
144SYSCTL_INT(_vfs_aio, OID_AUTO, aiod_timeout, CTLFLAG_RW, &aiod_timeout, 0,
145    "Timeout value for synchronous aio operations");
146
147static int aiod_lifetime;
148SYSCTL_INT(_vfs_aio, OID_AUTO, aiod_lifetime, CTLFLAG_RW, &aiod_lifetime, 0,
149    "Maximum lifetime for idle aiod");
150
151static int unloadable = 0;
152SYSCTL_INT(_vfs_aio, OID_AUTO, unloadable, CTLFLAG_RW, &unloadable, 0,
153    "Allow unload of aio (not recommended)");
154
155
156static int max_aio_per_proc = MAX_AIO_PER_PROC;
157SYSCTL_INT(_vfs_aio, OID_AUTO, max_aio_per_proc, CTLFLAG_RW, &max_aio_per_proc,
158    0, "Maximum active aio requests per process (stored in the process)");
159
160static int max_aio_queue_per_proc = MAX_AIO_QUEUE_PER_PROC;
161SYSCTL_INT(_vfs_aio, OID_AUTO, max_aio_queue_per_proc, CTLFLAG_RW,
162    &max_aio_queue_per_proc, 0,
163    "Maximum queued aio requests per process (stored in the process)");
164
165static int max_buf_aio = MAX_BUF_AIO;
166SYSCTL_INT(_vfs_aio, OID_AUTO, max_buf_aio, CTLFLAG_RW, &max_buf_aio, 0,
167    "Maximum buf aio requests per process (stored in the process)");
168
169struct aiocblist {
170        TAILQ_ENTRY(aiocblist) list;	/* List of jobs */
171        TAILQ_ENTRY(aiocblist) plist;	/* List of jobs for proc */
172        int	jobflags;
173        int	jobstate;
174	int	inputcharge;
175	int	outputcharge;
176	struct	callout_handle timeouthandle;
177        struct	buf *bp;		/* Buffer pointer */
178        struct	proc *userproc;		/* User process */ /* Not td! */
179	struct  ucred *cred;		/* Active credential when created */
180        struct	file *fd_file;		/* Pointer to file structure */
181        struct	aio_liojob *lio;	/* Optional lio job */
182        struct	aiocb *uuaiocb;		/* Pointer in userspace of aiocb */
183	struct	klist klist;		/* list of knotes */
184        struct	aiocb uaiocb;		/* Kernel I/O control block */
185};
186
187/* jobflags */
188#define AIOCBLIST_RUNDOWN       0x4
189#define AIOCBLIST_DONE          0x10
190
191/*
192 * AIO process info
193 */
194#define AIOP_FREE	0x1			/* proc on free queue */
195#define AIOP_SCHED	0x2			/* proc explicitly scheduled */
196
197struct aiothreadlist {
198	int aiothreadflags;			/* AIO proc flags */
199	TAILQ_ENTRY(aiothreadlist) list;	/* List of processes */
200	struct thread *aiothread;		/* The AIO thread */
201};
202
203/*
204 * data-structure for lio signal management
205 */
206struct aio_liojob {
207	int	lioj_flags;
208	int	lioj_buffer_count;
209	int	lioj_buffer_finished_count;
210	int	lioj_queue_count;
211	int	lioj_queue_finished_count;
212	struct	sigevent lioj_signal;	/* signal on all I/O done */
213	TAILQ_ENTRY(aio_liojob) lioj_list;
214	struct	kaioinfo *lioj_ki;
215};
216#define	LIOJ_SIGNAL		0x1	/* signal on all done (lio) */
217#define	LIOJ_SIGNAL_POSTED	0x2	/* signal has been posted */
218
219/*
220 * per process aio data structure
221 */
222struct kaioinfo {
223	int	kaio_flags;		/* per process kaio flags */
224	int	kaio_maxactive_count;	/* maximum number of AIOs */
225	int	kaio_active_count;	/* number of currently used AIOs */
226	int	kaio_qallowed_count;	/* maxiumu size of AIO queue */
227	int	kaio_queue_count;	/* size of AIO queue */
228	int	kaio_ballowed_count;	/* maximum number of buffers */
229	int	kaio_queue_finished_count; /* number of daemon jobs finished */
230	int	kaio_buffer_count;	/* number of physio buffers */
231	int	kaio_buffer_finished_count; /* count of I/O done */
232	struct 	proc *kaio_p;		/* process that uses this kaio block */
233	TAILQ_HEAD(,aio_liojob) kaio_liojoblist; /* list of lio jobs */
234	TAILQ_HEAD(,aiocblist) kaio_jobqueue;	/* job queue for process */
235	TAILQ_HEAD(,aiocblist) kaio_jobdone;	/* done queue for process */
236	TAILQ_HEAD(,aiocblist) kaio_bufqueue;	/* buffer job queue for process */
237	TAILQ_HEAD(,aiocblist) kaio_bufdone;	/* buffer done queue for process */
238	TAILQ_HEAD(,aiocblist) kaio_sockqueue;	/* queue for aios waiting on sockets */
239};
240
241#define KAIO_RUNDOWN	0x1	/* process is being run down */
242#define KAIO_WAKEUP	0x2	/* wakeup process when there is a significant event */
243
244static TAILQ_HEAD(,aiothreadlist) aio_activeproc;	/* Active daemons */
245static TAILQ_HEAD(,aiothreadlist) aio_freeproc;		/* Idle daemons */
246static TAILQ_HEAD(,aiocblist) aio_jobs;			/* Async job list */
247static TAILQ_HEAD(,aiocblist) aio_bufjobs;		/* Phys I/O job list */
248
249static void	aio_init_aioinfo(struct proc *p);
250static void	aio_onceonly(void);
251static int	aio_free_entry(struct aiocblist *aiocbe);
252static void	aio_process(struct aiocblist *aiocbe);
253static int	aio_newproc(void);
254static int	aio_aqueue(struct thread *td, struct aiocb *job, int type);
255static void	aio_physwakeup(struct buf *bp);
256static void	aio_proc_rundown(struct proc *p);
257static int	aio_fphysio(struct aiocblist *aiocbe);
258static int	aio_qphysio(struct proc *p, struct aiocblist *iocb);
259static void	aio_daemon(void *uproc);
260static void	aio_swake_cb(struct socket *, struct sockbuf *);
261static int	aio_unload(void);
262static void	process_signal(void *aioj);
263static int	filt_aioattach(struct knote *kn);
264static void	filt_aiodetach(struct knote *kn);
265static int	filt_aio(struct knote *kn, long hint);
266
267/*
268 * Zones for:
269 * 	kaio	Per process async io info
270 *	aiop	async io thread data
271 *	aiocb	async io jobs
272 *	aiol	list io job pointer - internal to aio_suspend XXX
273 *	aiolio	list io jobs
274 */
275static uma_zone_t kaio_zone, aiop_zone, aiocb_zone, aiol_zone, aiolio_zone;
276
277/* kqueue filters for aio */
278static struct filterops aio_filtops =
279	{ 0, filt_aioattach, filt_aiodetach, filt_aio };
280
281/*
282 * Main operations function for use as a kernel module.
283 */
284static int
285aio_modload(struct module *module, int cmd, void *arg)
286{
287	int error = 0;
288
289	switch (cmd) {
290	case MOD_LOAD:
291		aio_onceonly();
292		break;
293	case MOD_UNLOAD:
294		error = aio_unload();
295		break;
296	case MOD_SHUTDOWN:
297		break;
298	default:
299		error = EINVAL;
300		break;
301	}
302	return (error);
303}
304
305static moduledata_t aio_mod = {
306	"aio",
307	&aio_modload,
308	NULL
309};
310
311SYSCALL_MODULE_HELPER(aio_return);
312SYSCALL_MODULE_HELPER(aio_suspend);
313SYSCALL_MODULE_HELPER(aio_cancel);
314SYSCALL_MODULE_HELPER(aio_error);
315SYSCALL_MODULE_HELPER(aio_read);
316SYSCALL_MODULE_HELPER(aio_write);
317SYSCALL_MODULE_HELPER(aio_waitcomplete);
318SYSCALL_MODULE_HELPER(lio_listio);
319
320DECLARE_MODULE(aio, aio_mod,
321	SI_SUB_VFS, SI_ORDER_ANY);
322MODULE_VERSION(aio, 1);
323
324/*
325 * Startup initialization
326 */
327static void
328aio_onceonly(void)
329{
330
331	/* XXX: should probably just use so->callback */
332	aio_swake = &aio_swake_cb;
333	at_exit(aio_proc_rundown);
334	at_exec(aio_proc_rundown);
335	kqueue_add_filteropts(EVFILT_AIO, &aio_filtops);
336	TAILQ_INIT(&aio_freeproc);
337	TAILQ_INIT(&aio_activeproc);
338	TAILQ_INIT(&aio_jobs);
339	TAILQ_INIT(&aio_bufjobs);
340	kaio_zone = uma_zcreate("AIO", sizeof(struct kaioinfo), NULL, NULL,
341	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
342	aiop_zone = uma_zcreate("AIOP", sizeof(struct aiothreadlist), NULL,
343	    NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
344	aiocb_zone = uma_zcreate("AIOCB", sizeof(struct aiocblist), NULL, NULL,
345	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
346	aiol_zone = uma_zcreate("AIOL", AIO_LISTIO_MAX*sizeof(intptr_t) , NULL,
347	    NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
348	aiolio_zone = uma_zcreate("AIOLIO", sizeof(struct aio_liojob), NULL,
349	    NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
350	aiod_timeout = AIOD_TIMEOUT_DEFAULT;
351	aiod_lifetime = AIOD_LIFETIME_DEFAULT;
352	jobrefid = 1;
353	async_io_version = _POSIX_VERSION;
354	p31b_setcfg(CTL_P1003_1B_AIO_LISTIO_MAX, AIO_LISTIO_MAX);
355	p31b_setcfg(CTL_P1003_1B_AIO_MAX, MAX_AIO_QUEUE);
356	p31b_setcfg(CTL_P1003_1B_AIO_PRIO_DELTA_MAX, 0);
357}
358
359/*
360 * Callback for unload of AIO when used as a module.
361 */
362static int
363aio_unload(void)
364{
365
366	/*
367	 * XXX: no unloads by default, it's too dangerous.
368	 * perhaps we could do it if locked out callers and then
369	 * did an aio_proc_rundown() on each process.
370	 */
371	if (!unloadable)
372		return (EOPNOTSUPP);
373
374	async_io_version = 0;
375	aio_swake = NULL;
376	rm_at_exit(aio_proc_rundown);
377	rm_at_exec(aio_proc_rundown);
378	kqueue_del_filteropts(EVFILT_AIO);
379	p31b_setcfg(CTL_P1003_1B_AIO_LISTIO_MAX, -1);
380	p31b_setcfg(CTL_P1003_1B_AIO_MAX, -1);
381	p31b_setcfg(CTL_P1003_1B_AIO_PRIO_DELTA_MAX, -1);
382	return (0);
383}
384
385/*
386 * Init the per-process aioinfo structure.  The aioinfo limits are set
387 * per-process for user limit (resource) management.
388 */
389static void
390aio_init_aioinfo(struct proc *p)
391{
392	struct kaioinfo *ki;
393	if (p->p_aioinfo == NULL) {
394		ki = uma_zalloc(kaio_zone, M_WAITOK);
395		p->p_aioinfo = ki;
396		ki->kaio_flags = 0;
397		ki->kaio_maxactive_count = max_aio_per_proc;
398		ki->kaio_active_count = 0;
399		ki->kaio_qallowed_count = max_aio_queue_per_proc;
400		ki->kaio_queue_count = 0;
401		ki->kaio_ballowed_count = max_buf_aio;
402		ki->kaio_buffer_count = 0;
403		ki->kaio_buffer_finished_count = 0;
404		ki->kaio_p = p;
405		TAILQ_INIT(&ki->kaio_jobdone);
406		TAILQ_INIT(&ki->kaio_jobqueue);
407		TAILQ_INIT(&ki->kaio_bufdone);
408		TAILQ_INIT(&ki->kaio_bufqueue);
409		TAILQ_INIT(&ki->kaio_liojoblist);
410		TAILQ_INIT(&ki->kaio_sockqueue);
411	}
412
413	while (num_aio_procs < target_aio_procs)
414		aio_newproc();
415}
416
417/*
418 * Free a job entry.  Wait for completion if it is currently active, but don't
419 * delay forever.  If we delay, we return a flag that says that we have to
420 * restart the queue scan.
421 */
422static int
423aio_free_entry(struct aiocblist *aiocbe)
424{
425	struct kaioinfo *ki;
426	struct aio_liojob *lj;
427	struct proc *p;
428	int error;
429	int s;
430
431	if (aiocbe->jobstate == JOBST_NULL)
432		panic("aio_free_entry: freeing already free job");
433
434	p = aiocbe->userproc;
435	ki = p->p_aioinfo;
436	lj = aiocbe->lio;
437	if (ki == NULL)
438		panic("aio_free_entry: missing p->p_aioinfo");
439
440	while (aiocbe->jobstate == JOBST_JOBRUNNING) {
441		aiocbe->jobflags |= AIOCBLIST_RUNDOWN;
442		tsleep(aiocbe, PRIBIO, "jobwai", 0);
443	}
444	if (aiocbe->bp == NULL) {
445		if (ki->kaio_queue_count <= 0)
446			panic("aio_free_entry: process queue size <= 0");
447		if (num_queue_count <= 0)
448			panic("aio_free_entry: system wide queue size <= 0");
449
450		if (lj) {
451			lj->lioj_queue_count--;
452			if (aiocbe->jobflags & AIOCBLIST_DONE)
453				lj->lioj_queue_finished_count--;
454		}
455		ki->kaio_queue_count--;
456		if (aiocbe->jobflags & AIOCBLIST_DONE)
457			ki->kaio_queue_finished_count--;
458		num_queue_count--;
459	} else {
460		if (lj) {
461			lj->lioj_buffer_count--;
462			if (aiocbe->jobflags & AIOCBLIST_DONE)
463				lj->lioj_buffer_finished_count--;
464		}
465		if (aiocbe->jobflags & AIOCBLIST_DONE)
466			ki->kaio_buffer_finished_count--;
467		ki->kaio_buffer_count--;
468		num_buf_aio--;
469	}
470
471	/* aiocbe is going away, we need to destroy any knotes */
472	/* XXXKSE Note the thread here is used to eventually find the
473	 * owning process again, but it is also used to do a fo_close
474	 * and that requires the thread. (but does it require the
475	 * OWNING thread? (or maybe the running thread?)
476	 * There is a semantic problem here...
477	 */
478	knote_remove(FIRST_THREAD_IN_PROC(p), &aiocbe->klist); /* XXXKSE */
479
480	if ((ki->kaio_flags & KAIO_WAKEUP) || ((ki->kaio_flags & KAIO_RUNDOWN)
481	    && ((ki->kaio_buffer_count == 0) && (ki->kaio_queue_count == 0)))) {
482		ki->kaio_flags &= ~KAIO_WAKEUP;
483		wakeup(p);
484	}
485
486	if (aiocbe->jobstate == JOBST_JOBQBUF) {
487		if ((error = aio_fphysio(aiocbe)) != 0)
488			return error;
489		if (aiocbe->jobstate != JOBST_JOBBFINISHED)
490			panic("aio_free_entry: invalid physio finish-up state");
491		s = splbio();
492		TAILQ_REMOVE(&ki->kaio_bufdone, aiocbe, plist);
493		splx(s);
494	} else if (aiocbe->jobstate == JOBST_JOBQGLOBAL) {
495		s = splnet();
496		TAILQ_REMOVE(&aio_jobs, aiocbe, list);
497		TAILQ_REMOVE(&ki->kaio_jobqueue, aiocbe, plist);
498		splx(s);
499	} else if (aiocbe->jobstate == JOBST_JOBFINISHED)
500		TAILQ_REMOVE(&ki->kaio_jobdone, aiocbe, plist);
501	else if (aiocbe->jobstate == JOBST_JOBBFINISHED) {
502		s = splbio();
503		TAILQ_REMOVE(&ki->kaio_bufdone, aiocbe, plist);
504		splx(s);
505		if (aiocbe->bp) {
506			vunmapbuf(aiocbe->bp);
507			relpbuf(aiocbe->bp, NULL);
508			aiocbe->bp = NULL;
509		}
510	}
511	if (lj && (lj->lioj_buffer_count == 0) && (lj->lioj_queue_count == 0)) {
512		TAILQ_REMOVE(&ki->kaio_liojoblist, lj, lioj_list);
513		uma_zfree(aiolio_zone, lj);
514	}
515	aiocbe->jobstate = JOBST_NULL;
516	untimeout(process_signal, aiocbe, aiocbe->timeouthandle);
517	fdrop(aiocbe->fd_file, curthread);
518	crfree(aiocbe->cred);
519	uma_zfree(aiocb_zone, aiocbe);
520	return 0;
521}
522
523/*
524 * Rundown the jobs for a given process.
525 */
526static void
527aio_proc_rundown(struct proc *p)
528{
529	int s;
530	struct kaioinfo *ki;
531	struct aio_liojob *lj, *ljn;
532	struct aiocblist *aiocbe, *aiocbn;
533	struct file *fp;
534	struct socket *so;
535
536	ki = p->p_aioinfo;
537	if (ki == NULL)
538		return;
539
540	ki->kaio_flags |= LIOJ_SIGNAL_POSTED;
541	while ((ki->kaio_active_count > 0) || (ki->kaio_buffer_count >
542	    ki->kaio_buffer_finished_count)) {
543		ki->kaio_flags |= KAIO_RUNDOWN;
544		if (tsleep(p, PRIBIO, "kaiowt", aiod_timeout))
545			break;
546	}
547
548	/*
549	 * Move any aio ops that are waiting on socket I/O to the normal job
550	 * queues so they are cleaned up with any others.
551	 */
552	s = splnet();
553	for (aiocbe = TAILQ_FIRST(&ki->kaio_sockqueue); aiocbe; aiocbe =
554	    aiocbn) {
555		aiocbn = TAILQ_NEXT(aiocbe, plist);
556		fp = aiocbe->fd_file;
557		if (fp != NULL) {
558			so = (struct socket *)fp->f_data;
559			TAILQ_REMOVE(&so->so_aiojobq, aiocbe, list);
560			if (TAILQ_EMPTY(&so->so_aiojobq)) {
561				so->so_snd.sb_flags &= ~SB_AIO;
562				so->so_rcv.sb_flags &= ~SB_AIO;
563			}
564		}
565		TAILQ_REMOVE(&ki->kaio_sockqueue, aiocbe, plist);
566		TAILQ_INSERT_HEAD(&aio_jobs, aiocbe, list);
567		TAILQ_INSERT_HEAD(&ki->kaio_jobqueue, aiocbe, plist);
568	}
569	splx(s);
570
571restart1:
572	for (aiocbe = TAILQ_FIRST(&ki->kaio_jobdone); aiocbe; aiocbe = aiocbn) {
573		aiocbn = TAILQ_NEXT(aiocbe, plist);
574		if (aio_free_entry(aiocbe))
575			goto restart1;
576	}
577
578restart2:
579	for (aiocbe = TAILQ_FIRST(&ki->kaio_jobqueue); aiocbe; aiocbe =
580	    aiocbn) {
581		aiocbn = TAILQ_NEXT(aiocbe, plist);
582		if (aio_free_entry(aiocbe))
583			goto restart2;
584	}
585
586/*
587 * Note the use of lots of splbio here, trying to avoid splbio for long chains
588 * of I/O.  Probably unnecessary.
589 */
590restart3:
591	s = splbio();
592	while (TAILQ_FIRST(&ki->kaio_bufqueue)) {
593		ki->kaio_flags |= KAIO_WAKEUP;
594		tsleep(p, PRIBIO, "aioprn", 0);
595		splx(s);
596		goto restart3;
597	}
598	splx(s);
599
600restart4:
601	s = splbio();
602	for (aiocbe = TAILQ_FIRST(&ki->kaio_bufdone); aiocbe; aiocbe = aiocbn) {
603		aiocbn = TAILQ_NEXT(aiocbe, plist);
604		if (aio_free_entry(aiocbe)) {
605			splx(s);
606			goto restart4;
607		}
608	}
609	splx(s);
610
611        /*
612         * If we've slept, jobs might have moved from one queue to another.
613         * Retry rundown if we didn't manage to empty the queues.
614         */
615        if (TAILQ_FIRST(&ki->kaio_jobdone) != NULL ||
616	    TAILQ_FIRST(&ki->kaio_jobqueue) != NULL ||
617	    TAILQ_FIRST(&ki->kaio_bufqueue) != NULL ||
618	    TAILQ_FIRST(&ki->kaio_bufdone) != NULL)
619		goto restart1;
620
621	for (lj = TAILQ_FIRST(&ki->kaio_liojoblist); lj; lj = ljn) {
622		ljn = TAILQ_NEXT(lj, lioj_list);
623		if ((lj->lioj_buffer_count == 0) && (lj->lioj_queue_count ==
624		    0)) {
625			TAILQ_REMOVE(&ki->kaio_liojoblist, lj, lioj_list);
626			uma_zfree(aiolio_zone, lj);
627		} else {
628#ifdef DIAGNOSTIC
629			printf("LIO job not cleaned up: B:%d, BF:%d, Q:%d, "
630			    "QF:%d\n", lj->lioj_buffer_count,
631			    lj->lioj_buffer_finished_count,
632			    lj->lioj_queue_count,
633			    lj->lioj_queue_finished_count);
634#endif
635		}
636	}
637
638	uma_zfree(kaio_zone, ki);
639	p->p_aioinfo = NULL;
640}
641
642/*
643 * Select a job to run (called by an AIO daemon).
644 */
645static struct aiocblist *
646aio_selectjob(struct aiothreadlist *aiop)
647{
648	int s;
649	struct aiocblist *aiocbe;
650	struct kaioinfo *ki;
651	struct proc *userp;
652
653	s = splnet();
654	for (aiocbe = TAILQ_FIRST(&aio_jobs); aiocbe; aiocbe =
655	    TAILQ_NEXT(aiocbe, list)) {
656		userp = aiocbe->userproc;
657		ki = userp->p_aioinfo;
658
659		if (ki->kaio_active_count < ki->kaio_maxactive_count) {
660			TAILQ_REMOVE(&aio_jobs, aiocbe, list);
661			splx(s);
662			return aiocbe;
663		}
664	}
665	splx(s);
666
667	return NULL;
668}
669
670/*
671 * The AIO processing activity.  This is the code that does the I/O request for
672 * the non-physio version of the operations.  The normal vn operations are used,
673 * and this code should work in all instances for every type of file, including
674 * pipes, sockets, fifos, and regular files.
675 */
676static void
677aio_process(struct aiocblist *aiocbe)
678{
679	struct ucred *td_savedcred;
680	struct thread *td;
681	struct proc *mycp;
682	struct aiocb *cb;
683	struct file *fp;
684	struct uio auio;
685	struct iovec aiov;
686	int cnt;
687	int error;
688	int oublock_st, oublock_end;
689	int inblock_st, inblock_end;
690
691	td = curthread;
692	td_savedcred = td->td_ucred;
693	td->td_ucred = aiocbe->cred;
694	mycp = td->td_proc;
695	cb = &aiocbe->uaiocb;
696	fp = aiocbe->fd_file;
697
698	aiov.iov_base = (void *)(uintptr_t)cb->aio_buf;
699	aiov.iov_len = cb->aio_nbytes;
700
701	auio.uio_iov = &aiov;
702	auio.uio_iovcnt = 1;
703	auio.uio_offset = cb->aio_offset;
704	auio.uio_resid = cb->aio_nbytes;
705	cnt = cb->aio_nbytes;
706	auio.uio_segflg = UIO_USERSPACE;
707	auio.uio_td = td;
708
709	inblock_st = mycp->p_stats->p_ru.ru_inblock;
710	oublock_st = mycp->p_stats->p_ru.ru_oublock;
711	/*
712	 * _aio_aqueue() acquires a reference to the file that is
713	 * released in aio_free_entry().
714	 */
715	if (cb->aio_lio_opcode == LIO_READ) {
716		auio.uio_rw = UIO_READ;
717		error = fo_read(fp, &auio, fp->f_cred, FOF_OFFSET, td);
718	} else {
719		auio.uio_rw = UIO_WRITE;
720		error = fo_write(fp, &auio, fp->f_cred, FOF_OFFSET, td);
721	}
722	inblock_end = mycp->p_stats->p_ru.ru_inblock;
723	oublock_end = mycp->p_stats->p_ru.ru_oublock;
724
725	aiocbe->inputcharge = inblock_end - inblock_st;
726	aiocbe->outputcharge = oublock_end - oublock_st;
727
728	if ((error) && (auio.uio_resid != cnt)) {
729		if (error == ERESTART || error == EINTR || error == EWOULDBLOCK)
730			error = 0;
731		if ((error == EPIPE) && (cb->aio_lio_opcode == LIO_WRITE)) {
732			PROC_LOCK(aiocbe->userproc);
733			psignal(aiocbe->userproc, SIGPIPE);
734			PROC_UNLOCK(aiocbe->userproc);
735		}
736	}
737
738	cnt -= auio.uio_resid;
739	cb->_aiocb_private.error = error;
740	cb->_aiocb_private.status = cnt;
741	td->td_ucred = td_savedcred;
742}
743
744/*
745 * The AIO daemon, most of the actual work is done in aio_process,
746 * but the setup (and address space mgmt) is done in this routine.
747 */
748static void
749aio_daemon(void *uproc)
750{
751	int s;
752	struct aio_liojob *lj;
753	struct aiocb *cb;
754	struct aiocblist *aiocbe;
755	struct aiothreadlist *aiop;
756	struct kaioinfo *ki;
757	struct proc *curcp, *mycp, *userp;
758	struct vmspace *myvm, *tmpvm;
759	struct thread *td = curthread;
760	struct pgrp *newpgrp;
761	struct session *newsess;
762
763	mtx_lock(&Giant);
764	/*
765	 * Local copies of curproc (cp) and vmspace (myvm)
766	 */
767	mycp = td->td_proc;
768	myvm = mycp->p_vmspace;
769
770	if (mycp->p_textvp) {
771		vrele(mycp->p_textvp);
772		mycp->p_textvp = NULL;
773	}
774
775	/*
776	 * Allocate and ready the aio control info.  There is one aiop structure
777	 * per daemon.
778	 */
779	aiop = uma_zalloc(aiop_zone, M_WAITOK);
780	aiop->aiothread = td;
781	aiop->aiothreadflags |= AIOP_FREE;
782
783	s = splnet();
784
785	/*
786	 * Place thread (lightweight process) onto the AIO free thread list.
787	 */
788	if (TAILQ_EMPTY(&aio_freeproc))
789		wakeup(&aio_freeproc);
790	TAILQ_INSERT_HEAD(&aio_freeproc, aiop, list);
791
792	splx(s);
793
794	/*
795	 * Get rid of our current filedescriptors.  AIOD's don't need any
796	 * filedescriptors, except as temporarily inherited from the client.
797	 */
798	fdfree(td);
799
800	mtx_unlock(&Giant);
801	/* The daemon resides in its own pgrp. */
802	MALLOC(newpgrp, struct pgrp *, sizeof(struct pgrp), M_PGRP,
803		M_WAITOK | M_ZERO);
804	MALLOC(newsess, struct session *, sizeof(struct session), M_SESSION,
805		M_WAITOK | M_ZERO);
806
807	sx_xlock(&proctree_lock);
808	enterpgrp(mycp, mycp->p_pid, newpgrp, newsess);
809	sx_xunlock(&proctree_lock);
810	mtx_lock(&Giant);
811
812	/* Mark special process type. */
813	mycp->p_flag |= P_SYSTEM;
814
815	/*
816	 * Wakeup parent process.  (Parent sleeps to keep from blasting away
817	 * and creating too many daemons.)
818	 */
819	wakeup(mycp);
820
821	for (;;) {
822		/*
823		 * curcp is the current daemon process context.
824		 * userp is the current user process context.
825		 */
826		curcp = mycp;
827
828		/*
829		 * Take daemon off of free queue
830		 */
831		if (aiop->aiothreadflags & AIOP_FREE) {
832			s = splnet();
833			TAILQ_REMOVE(&aio_freeproc, aiop, list);
834			TAILQ_INSERT_TAIL(&aio_activeproc, aiop, list);
835			aiop->aiothreadflags &= ~AIOP_FREE;
836			splx(s);
837		}
838		aiop->aiothreadflags &= ~AIOP_SCHED;
839
840		/*
841		 * Check for jobs.
842		 */
843		while ((aiocbe = aio_selectjob(aiop)) != NULL) {
844			cb = &aiocbe->uaiocb;
845			userp = aiocbe->userproc;
846
847			aiocbe->jobstate = JOBST_JOBRUNNING;
848
849			/*
850			 * Connect to process address space for user program.
851			 */
852			if (userp != curcp) {
853				/*
854				 * Save the current address space that we are
855				 * connected to.
856				 */
857				tmpvm = mycp->p_vmspace;
858
859				/*
860				 * Point to the new user address space, and
861				 * refer to it.
862				 */
863				mycp->p_vmspace = userp->p_vmspace;
864				mycp->p_vmspace->vm_refcnt++;
865
866				/* Activate the new mapping. */
867				pmap_activate(FIRST_THREAD_IN_PROC(mycp));
868
869				/*
870				 * If the old address space wasn't the daemons
871				 * own address space, then we need to remove the
872				 * daemon's reference from the other process
873				 * that it was acting on behalf of.
874				 */
875				if (tmpvm != myvm) {
876					vmspace_free(tmpvm);
877				}
878				curcp = userp;
879			}
880
881			ki = userp->p_aioinfo;
882			lj = aiocbe->lio;
883
884			/* Account for currently active jobs. */
885			ki->kaio_active_count++;
886
887			/* Do the I/O function. */
888			aio_process(aiocbe);
889
890			/* Decrement the active job count. */
891			ki->kaio_active_count--;
892
893			/*
894			 * Increment the completion count for wakeup/signal
895			 * comparisons.
896			 */
897			aiocbe->jobflags |= AIOCBLIST_DONE;
898			ki->kaio_queue_finished_count++;
899			if (lj)
900				lj->lioj_queue_finished_count++;
901			if ((ki->kaio_flags & KAIO_WAKEUP) || ((ki->kaio_flags
902			    & KAIO_RUNDOWN) && (ki->kaio_active_count == 0))) {
903				ki->kaio_flags &= ~KAIO_WAKEUP;
904				wakeup(userp);
905			}
906
907			s = splbio();
908			if (lj && (lj->lioj_flags &
909			    (LIOJ_SIGNAL|LIOJ_SIGNAL_POSTED)) == LIOJ_SIGNAL) {
910				if ((lj->lioj_queue_finished_count ==
911				    lj->lioj_queue_count) &&
912				    (lj->lioj_buffer_finished_count ==
913				    lj->lioj_buffer_count)) {
914					PROC_LOCK(userp);
915					psignal(userp,
916					    lj->lioj_signal.sigev_signo);
917					PROC_UNLOCK(userp);
918					lj->lioj_flags |= LIOJ_SIGNAL_POSTED;
919				}
920			}
921			splx(s);
922
923			aiocbe->jobstate = JOBST_JOBFINISHED;
924
925			s = splnet();
926			TAILQ_REMOVE(&ki->kaio_jobqueue, aiocbe, plist);
927			TAILQ_INSERT_TAIL(&ki->kaio_jobdone, aiocbe, plist);
928			splx(s);
929			KNOTE(&aiocbe->klist, 0);
930
931			if (aiocbe->jobflags & AIOCBLIST_RUNDOWN) {
932				wakeup(aiocbe);
933				aiocbe->jobflags &= ~AIOCBLIST_RUNDOWN;
934			}
935
936			if (cb->aio_sigevent.sigev_notify == SIGEV_SIGNAL) {
937				PROC_LOCK(userp);
938				psignal(userp, cb->aio_sigevent.sigev_signo);
939				PROC_UNLOCK(userp);
940			}
941		}
942
943		/*
944		 * Disconnect from user address space.
945		 */
946		if (curcp != mycp) {
947			/* Get the user address space to disconnect from. */
948			tmpvm = mycp->p_vmspace;
949
950			/* Get original address space for daemon. */
951			mycp->p_vmspace = myvm;
952
953			/* Activate the daemon's address space. */
954			pmap_activate(FIRST_THREAD_IN_PROC(mycp));
955#ifdef DIAGNOSTIC
956			if (tmpvm == myvm) {
957				printf("AIOD: vmspace problem -- %d\n",
958				    mycp->p_pid);
959			}
960#endif
961			/* Remove our vmspace reference. */
962			vmspace_free(tmpvm);
963
964			curcp = mycp;
965		}
966
967		/*
968		 * If we are the first to be put onto the free queue, wakeup
969		 * anyone waiting for a daemon.
970		 */
971		s = splnet();
972		TAILQ_REMOVE(&aio_activeproc, aiop, list);
973		if (TAILQ_EMPTY(&aio_freeproc))
974			wakeup(&aio_freeproc);
975		TAILQ_INSERT_HEAD(&aio_freeproc, aiop, list);
976		aiop->aiothreadflags |= AIOP_FREE;
977		splx(s);
978
979		/*
980		 * If daemon is inactive for a long time, allow it to exit,
981		 * thereby freeing resources.
982		 */
983		if ((aiop->aiothreadflags & AIOP_SCHED) == 0 &&
984		    tsleep(aiop->aiothread, PRIBIO, "aiordy", aiod_lifetime)) {
985			s = splnet();
986			if (TAILQ_EMPTY(&aio_jobs)) {
987				if ((aiop->aiothreadflags & AIOP_FREE) &&
988				    (num_aio_procs > target_aio_procs)) {
989					TAILQ_REMOVE(&aio_freeproc, aiop, list);
990					splx(s);
991					uma_zfree(aiop_zone, aiop);
992					num_aio_procs--;
993#ifdef DIAGNOSTIC
994					if (mycp->p_vmspace->vm_refcnt <= 1) {
995						printf("AIOD: bad vm refcnt for"
996						    " exiting daemon: %d\n",
997						    mycp->p_vmspace->vm_refcnt);
998					}
999#endif
1000					kthread_exit(0);
1001				}
1002			}
1003			splx(s);
1004		}
1005	}
1006}
1007
1008/*
1009 * Create a new AIO daemon.  This is mostly a kernel-thread fork routine.  The
1010 * AIO daemon modifies its environment itself.
1011 */
1012static int
1013aio_newproc()
1014{
1015	int error;
1016	struct proc *p;
1017
1018	error = kthread_create(aio_daemon, curproc, &p, RFNOWAIT, 0, "aiod%d",
1019			       num_aio_procs);
1020	if (error)
1021		return error;
1022
1023	/*
1024	 * Wait until daemon is started, but continue on just in case to
1025	 * handle error conditions.
1026	 */
1027	error = tsleep(p, PZERO, "aiosta", aiod_timeout);
1028
1029	num_aio_procs++;
1030
1031	return error;
1032}
1033
1034/*
1035 * Try the high-performance, low-overhead physio method for eligible
1036 * VCHR devices.  This method doesn't use an aio helper thread, and
1037 * thus has very low overhead.
1038 *
1039 * Assumes that the caller, _aio_aqueue(), has incremented the file
1040 * structure's reference count, preventing its deallocation for the
1041 * duration of this call.
1042 */
1043static int
1044aio_qphysio(struct proc *p, struct aiocblist *aiocbe)
1045{
1046	int error;
1047	struct aiocb *cb;
1048	struct file *fp;
1049	struct buf *bp;
1050	struct vnode *vp;
1051	struct kaioinfo *ki;
1052	struct aio_liojob *lj;
1053	int s;
1054	int notify;
1055
1056	cb = &aiocbe->uaiocb;
1057	fp = aiocbe->fd_file;
1058
1059	if (fp->f_type != DTYPE_VNODE)
1060		return (-1);
1061
1062	vp = (struct vnode *)fp->f_data;
1063
1064	/*
1065	 * If its not a disk, we don't want to return a positive error.
1066	 * It causes the aio code to not fall through to try the thread
1067	 * way when you're talking to a regular file.
1068	 */
1069	if (!vn_isdisk(vp, &error)) {
1070		if (error == ENOTBLK)
1071			return (-1);
1072		else
1073			return (error);
1074	}
1075
1076 	if (cb->aio_nbytes % vp->v_rdev->si_bsize_phys)
1077		return (-1);
1078
1079	if (cb->aio_nbytes >
1080	    MAXPHYS - (((vm_offset_t) cb->aio_buf) & PAGE_MASK))
1081		return (-1);
1082
1083	ki = p->p_aioinfo;
1084	if (ki->kaio_buffer_count >= ki->kaio_ballowed_count)
1085		return (-1);
1086
1087	ki->kaio_buffer_count++;
1088
1089	lj = aiocbe->lio;
1090	if (lj)
1091		lj->lioj_buffer_count++;
1092
1093	/* Create and build a buffer header for a transfer. */
1094	bp = (struct buf *)getpbuf(NULL);
1095	BUF_KERNPROC(bp);
1096
1097	/*
1098	 * Get a copy of the kva from the physical buffer.
1099	 */
1100	bp->b_caller1 = p;
1101	bp->b_dev = vp->v_rdev;
1102	error = bp->b_error = 0;
1103
1104	bp->b_bcount = cb->aio_nbytes;
1105	bp->b_bufsize = cb->aio_nbytes;
1106	bp->b_flags = B_PHYS;
1107	bp->b_iodone = aio_physwakeup;
1108	bp->b_saveaddr = bp->b_data;
1109	bp->b_data = (void *)(uintptr_t)cb->aio_buf;
1110	bp->b_blkno = btodb(cb->aio_offset);
1111
1112	if (cb->aio_lio_opcode == LIO_WRITE) {
1113		bp->b_iocmd = BIO_WRITE;
1114		if (!useracc(bp->b_data, bp->b_bufsize, VM_PROT_READ)) {
1115			error = EFAULT;
1116			goto doerror;
1117		}
1118	} else {
1119		bp->b_iocmd = BIO_READ;
1120		if (!useracc(bp->b_data, bp->b_bufsize, VM_PROT_WRITE)) {
1121			error = EFAULT;
1122			goto doerror;
1123		}
1124	}
1125
1126	/* Bring buffer into kernel space. */
1127	vmapbuf(bp);
1128
1129	s = splbio();
1130	aiocbe->bp = bp;
1131	bp->b_spc = (void *)aiocbe;
1132	TAILQ_INSERT_TAIL(&aio_bufjobs, aiocbe, list);
1133	TAILQ_INSERT_TAIL(&ki->kaio_bufqueue, aiocbe, plist);
1134	aiocbe->jobstate = JOBST_JOBQBUF;
1135	cb->_aiocb_private.status = cb->aio_nbytes;
1136	num_buf_aio++;
1137	bp->b_error = 0;
1138
1139	splx(s);
1140
1141	/* Perform transfer. */
1142	DEV_STRATEGY(bp, 0);
1143
1144	notify = 0;
1145	s = splbio();
1146
1147	/*
1148	 * If we had an error invoking the request, or an error in processing
1149	 * the request before we have returned, we process it as an error in
1150	 * transfer.  Note that such an I/O error is not indicated immediately,
1151	 * but is returned using the aio_error mechanism.  In this case,
1152	 * aio_suspend will return immediately.
1153	 */
1154	if (bp->b_error || (bp->b_ioflags & BIO_ERROR)) {
1155		struct aiocb *job = aiocbe->uuaiocb;
1156
1157		aiocbe->uaiocb._aiocb_private.status = 0;
1158		suword(&job->_aiocb_private.status, 0);
1159		aiocbe->uaiocb._aiocb_private.error = bp->b_error;
1160		suword(&job->_aiocb_private.error, bp->b_error);
1161
1162		ki->kaio_buffer_finished_count++;
1163
1164		if (aiocbe->jobstate != JOBST_JOBBFINISHED) {
1165			aiocbe->jobstate = JOBST_JOBBFINISHED;
1166			aiocbe->jobflags |= AIOCBLIST_DONE;
1167			TAILQ_REMOVE(&aio_bufjobs, aiocbe, list);
1168			TAILQ_REMOVE(&ki->kaio_bufqueue, aiocbe, plist);
1169			TAILQ_INSERT_TAIL(&ki->kaio_bufdone, aiocbe, plist);
1170			notify = 1;
1171		}
1172	}
1173	splx(s);
1174	if (notify)
1175		KNOTE(&aiocbe->klist, 0);
1176	return 0;
1177
1178doerror:
1179	ki->kaio_buffer_count--;
1180	if (lj)
1181		lj->lioj_buffer_count--;
1182	aiocbe->bp = NULL;
1183	relpbuf(bp, NULL);
1184	return error;
1185}
1186
1187/*
1188 * This waits/tests physio completion.
1189 */
1190static int
1191aio_fphysio(struct aiocblist *iocb)
1192{
1193	int s;
1194	struct buf *bp;
1195	int error;
1196
1197	bp = iocb->bp;
1198
1199	s = splbio();
1200	while ((bp->b_flags & B_DONE) == 0) {
1201		if (tsleep(bp, PRIBIO, "physstr", aiod_timeout)) {
1202			if ((bp->b_flags & B_DONE) == 0) {
1203				splx(s);
1204				return EINPROGRESS;
1205			} else
1206				break;
1207		}
1208	}
1209	splx(s);
1210
1211	/* Release mapping into kernel space. */
1212	vunmapbuf(bp);
1213	iocb->bp = 0;
1214
1215	error = 0;
1216
1217	/* Check for an error. */
1218	if (bp->b_ioflags & BIO_ERROR)
1219		error = bp->b_error;
1220
1221	relpbuf(bp, NULL);
1222	return (error);
1223}
1224
1225/*
1226 * Wake up aio requests that may be serviceable now.
1227 */
1228static void
1229aio_swake_cb(struct socket *so, struct sockbuf *sb)
1230{
1231	struct aiocblist *cb,*cbn;
1232	struct proc *p;
1233	struct kaioinfo *ki = NULL;
1234	int opcode, wakecount = 0;
1235	struct aiothreadlist *aiop;
1236
1237	if (sb == &so->so_snd) {
1238		opcode = LIO_WRITE;
1239		so->so_snd.sb_flags &= ~SB_AIO;
1240	} else {
1241		opcode = LIO_READ;
1242		so->so_rcv.sb_flags &= ~SB_AIO;
1243	}
1244
1245	for (cb = TAILQ_FIRST(&so->so_aiojobq); cb; cb = cbn) {
1246		cbn = TAILQ_NEXT(cb, list);
1247		if (opcode == cb->uaiocb.aio_lio_opcode) {
1248			p = cb->userproc;
1249			ki = p->p_aioinfo;
1250			TAILQ_REMOVE(&so->so_aiojobq, cb, list);
1251			TAILQ_REMOVE(&ki->kaio_sockqueue, cb, plist);
1252			TAILQ_INSERT_TAIL(&aio_jobs, cb, list);
1253			TAILQ_INSERT_TAIL(&ki->kaio_jobqueue, cb, plist);
1254			wakecount++;
1255			if (cb->jobstate != JOBST_JOBQGLOBAL)
1256				panic("invalid queue value");
1257		}
1258	}
1259
1260	while (wakecount--) {
1261		if ((aiop = TAILQ_FIRST(&aio_freeproc)) != 0) {
1262			TAILQ_REMOVE(&aio_freeproc, aiop, list);
1263			TAILQ_INSERT_TAIL(&aio_activeproc, aiop, list);
1264			aiop->aiothreadflags &= ~AIOP_FREE;
1265			wakeup(aiop->aiothread);
1266		}
1267	}
1268}
1269
1270/*
1271 * Queue a new AIO request.  Choosing either the threaded or direct physio VCHR
1272 * technique is done in this code.
1273 */
1274static int
1275_aio_aqueue(struct thread *td, struct aiocb *job, struct aio_liojob *lj, int type)
1276{
1277	struct proc *p = td->td_proc;
1278	struct filedesc *fdp;
1279	struct file *fp;
1280	unsigned int fd;
1281	struct socket *so;
1282	int s;
1283	int error;
1284	int opcode, user_opcode;
1285	struct aiocblist *aiocbe;
1286	struct aiothreadlist *aiop;
1287	struct kaioinfo *ki;
1288	struct kevent kev;
1289	struct kqueue *kq;
1290	struct file *kq_fp;
1291
1292	aiocbe = uma_zalloc(aiocb_zone, M_WAITOK);
1293	aiocbe->inputcharge = 0;
1294	aiocbe->outputcharge = 0;
1295	callout_handle_init(&aiocbe->timeouthandle);
1296	SLIST_INIT(&aiocbe->klist);
1297
1298	suword(&job->_aiocb_private.status, -1);
1299	suword(&job->_aiocb_private.error, 0);
1300	suword(&job->_aiocb_private.kernelinfo, -1);
1301
1302	error = copyin(job, &aiocbe->uaiocb, sizeof(aiocbe->uaiocb));
1303	if (error) {
1304		suword(&job->_aiocb_private.error, error);
1305		uma_zfree(aiocb_zone, aiocbe);
1306		return error;
1307	}
1308	if (aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_SIGNAL &&
1309		!_SIG_VALID(aiocbe->uaiocb.aio_sigevent.sigev_signo)) {
1310		uma_zfree(aiocb_zone, aiocbe);
1311		return EINVAL;
1312	}
1313
1314	/* Save userspace address of the job info. */
1315	aiocbe->uuaiocb = job;
1316
1317	/* Get the opcode. */
1318	user_opcode = aiocbe->uaiocb.aio_lio_opcode;
1319	if (type != LIO_NOP)
1320		aiocbe->uaiocb.aio_lio_opcode = type;
1321	opcode = aiocbe->uaiocb.aio_lio_opcode;
1322
1323	/* Get the fd info for process. */
1324	fdp = p->p_fd;
1325
1326	/*
1327	 * Range check file descriptor.
1328	 */
1329	fd = aiocbe->uaiocb.aio_fildes;
1330	if (fd >= fdp->fd_nfiles) {
1331		uma_zfree(aiocb_zone, aiocbe);
1332		if (type == 0)
1333			suword(&job->_aiocb_private.error, EBADF);
1334		return EBADF;
1335	}
1336
1337	fp = aiocbe->fd_file = fdp->fd_ofiles[fd];
1338	if ((fp == NULL) || ((opcode == LIO_WRITE) && ((fp->f_flag & FWRITE) ==
1339	    0))) {
1340		uma_zfree(aiocb_zone, aiocbe);
1341		if (type == 0)
1342			suword(&job->_aiocb_private.error, EBADF);
1343		return EBADF;
1344	}
1345	fhold(fp);
1346
1347	if (aiocbe->uaiocb.aio_offset == -1LL) {
1348		error = EINVAL;
1349		goto aqueue_fail;
1350	}
1351	error = suword(&job->_aiocb_private.kernelinfo, jobrefid);
1352	if (error) {
1353		error = EINVAL;
1354		goto aqueue_fail;
1355	}
1356	aiocbe->uaiocb._aiocb_private.kernelinfo = (void *)(intptr_t)jobrefid;
1357	if (jobrefid == LONG_MAX)
1358		jobrefid = 1;
1359	else
1360		jobrefid++;
1361
1362	if (opcode == LIO_NOP) {
1363		fdrop(fp, td);
1364		uma_zfree(aiocb_zone, aiocbe);
1365		if (type == 0) {
1366			suword(&job->_aiocb_private.error, 0);
1367			suword(&job->_aiocb_private.status, 0);
1368			suword(&job->_aiocb_private.kernelinfo, 0);
1369		}
1370		return 0;
1371	}
1372	if ((opcode != LIO_READ) && (opcode != LIO_WRITE)) {
1373		if (type == 0)
1374			suword(&job->_aiocb_private.status, 0);
1375		error = EINVAL;
1376		goto aqueue_fail;
1377	}
1378
1379	if (aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_KEVENT) {
1380		kev.ident = aiocbe->uaiocb.aio_sigevent.sigev_notify_kqueue;
1381		kev.udata = aiocbe->uaiocb.aio_sigevent.sigev_value.sigval_ptr;
1382	}
1383	else {
1384		/*
1385		 * This method for requesting kevent-based notification won't
1386		 * work on the alpha, since we're passing in a pointer
1387		 * via aio_lio_opcode, which is an int.  Use the SIGEV_KEVENT-
1388		 * based method instead.
1389		 */
1390		if (user_opcode == LIO_NOP || user_opcode == LIO_READ ||
1391		    user_opcode == LIO_WRITE)
1392			goto no_kqueue;
1393
1394		error = copyin((struct kevent *)(uintptr_t)user_opcode,
1395		    &kev, sizeof(kev));
1396		if (error)
1397			goto aqueue_fail;
1398	}
1399	if ((u_int)kev.ident >= fdp->fd_nfiles ||
1400	    (kq_fp = fdp->fd_ofiles[kev.ident]) == NULL ||
1401	    (kq_fp->f_type != DTYPE_KQUEUE)) {
1402		error = EBADF;
1403		goto aqueue_fail;
1404	}
1405	kq = (struct kqueue *)kq_fp->f_data;
1406	kev.ident = (uintptr_t)aiocbe->uuaiocb;
1407	kev.filter = EVFILT_AIO;
1408	kev.flags = EV_ADD | EV_ENABLE | EV_FLAG1;
1409	kev.data = (intptr_t)aiocbe;
1410	error = kqueue_register(kq, &kev, td);
1411aqueue_fail:
1412	if (error) {
1413		fdrop(fp, td);
1414		uma_zfree(aiocb_zone, aiocbe);
1415		if (type == 0)
1416			suword(&job->_aiocb_private.error, error);
1417		goto done;
1418	}
1419no_kqueue:
1420
1421	suword(&job->_aiocb_private.error, EINPROGRESS);
1422	aiocbe->uaiocb._aiocb_private.error = EINPROGRESS;
1423	aiocbe->userproc = p;
1424	aiocbe->cred = crhold(td->td_ucred);
1425	aiocbe->jobflags = 0;
1426	aiocbe->lio = lj;
1427	ki = p->p_aioinfo;
1428
1429	if (fp->f_type == DTYPE_SOCKET) {
1430		/*
1431		 * Alternate queueing for socket ops: Reach down into the
1432		 * descriptor to get the socket data.  Then check to see if the
1433		 * socket is ready to be read or written (based on the requested
1434		 * operation).
1435		 *
1436		 * If it is not ready for io, then queue the aiocbe on the
1437		 * socket, and set the flags so we get a call when sbnotify()
1438		 * happens.
1439		 */
1440		so = (struct socket *)fp->f_data;
1441		s = splnet();
1442		if (((opcode == LIO_READ) && (!soreadable(so))) || ((opcode ==
1443		    LIO_WRITE) && (!sowriteable(so)))) {
1444			TAILQ_INSERT_TAIL(&so->so_aiojobq, aiocbe, list);
1445			TAILQ_INSERT_TAIL(&ki->kaio_sockqueue, aiocbe, plist);
1446			if (opcode == LIO_READ)
1447				so->so_rcv.sb_flags |= SB_AIO;
1448			else
1449				so->so_snd.sb_flags |= SB_AIO;
1450			aiocbe->jobstate = JOBST_JOBQGLOBAL; /* XXX */
1451			ki->kaio_queue_count++;
1452			num_queue_count++;
1453			splx(s);
1454			error = 0;
1455			goto done;
1456		}
1457		splx(s);
1458	}
1459
1460	if ((error = aio_qphysio(p, aiocbe)) == 0)
1461		goto done;
1462	if (error > 0) {
1463		suword(&job->_aiocb_private.status, 0);
1464		aiocbe->uaiocb._aiocb_private.error = error;
1465		suword(&job->_aiocb_private.error, error);
1466		goto done;
1467	}
1468
1469	/* No buffer for daemon I/O. */
1470	aiocbe->bp = NULL;
1471
1472	ki->kaio_queue_count++;
1473	if (lj)
1474		lj->lioj_queue_count++;
1475	s = splnet();
1476	TAILQ_INSERT_TAIL(&ki->kaio_jobqueue, aiocbe, plist);
1477	TAILQ_INSERT_TAIL(&aio_jobs, aiocbe, list);
1478	splx(s);
1479	aiocbe->jobstate = JOBST_JOBQGLOBAL;
1480
1481	num_queue_count++;
1482	error = 0;
1483
1484	/*
1485	 * If we don't have a free AIO process, and we are below our quota, then
1486	 * start one.  Otherwise, depend on the subsequent I/O completions to
1487	 * pick-up this job.  If we don't sucessfully create the new process
1488	 * (thread) due to resource issues, we return an error for now (EAGAIN),
1489	 * which is likely not the correct thing to do.
1490	 */
1491	s = splnet();
1492retryproc:
1493	if ((aiop = TAILQ_FIRST(&aio_freeproc)) != NULL) {
1494		TAILQ_REMOVE(&aio_freeproc, aiop, list);
1495		TAILQ_INSERT_TAIL(&aio_activeproc, aiop, list);
1496		aiop->aiothreadflags &= ~AIOP_FREE;
1497		wakeup(aiop->aiothread);
1498	} else if (((num_aio_resv_start + num_aio_procs) < max_aio_procs) &&
1499	    ((ki->kaio_active_count + num_aio_resv_start) <
1500	    ki->kaio_maxactive_count)) {
1501		num_aio_resv_start++;
1502		if ((error = aio_newproc()) == 0) {
1503			num_aio_resv_start--;
1504			goto retryproc;
1505		}
1506		num_aio_resv_start--;
1507	}
1508	splx(s);
1509done:
1510	return error;
1511}
1512
1513/*
1514 * This routine queues an AIO request, checking for quotas.
1515 */
1516static int
1517aio_aqueue(struct thread *td, struct aiocb *job, int type)
1518{
1519	struct proc *p = td->td_proc;
1520	struct kaioinfo *ki;
1521
1522	if (p->p_aioinfo == NULL)
1523		aio_init_aioinfo(p);
1524
1525	if (num_queue_count >= max_queue_count)
1526		return EAGAIN;
1527
1528	ki = p->p_aioinfo;
1529	if (ki->kaio_queue_count >= ki->kaio_qallowed_count)
1530		return EAGAIN;
1531
1532	return _aio_aqueue(td, job, NULL, type);
1533}
1534
1535/*
1536 * Support the aio_return system call, as a side-effect, kernel resources are
1537 * released.
1538 */
1539int
1540aio_return(struct thread *td, struct aio_return_args *uap)
1541{
1542	struct proc *p = td->td_proc;
1543	int s;
1544	long jobref;
1545	struct aiocblist *cb, *ncb;
1546	struct aiocb *ujob;
1547	struct kaioinfo *ki;
1548
1549	ujob = uap->aiocbp;
1550	jobref = fuword(&ujob->_aiocb_private.kernelinfo);
1551	if (jobref == -1 || jobref == 0)
1552		return EINVAL;
1553
1554	ki = p->p_aioinfo;
1555	if (ki == NULL)
1556		return EINVAL;
1557	TAILQ_FOREACH(cb, &ki->kaio_jobdone, plist) {
1558		if (((intptr_t) cb->uaiocb._aiocb_private.kernelinfo) ==
1559		    jobref) {
1560			if (cb->uaiocb.aio_lio_opcode == LIO_WRITE) {
1561				p->p_stats->p_ru.ru_oublock +=
1562				    cb->outputcharge;
1563				cb->outputcharge = 0;
1564			} else if (cb->uaiocb.aio_lio_opcode == LIO_READ) {
1565				p->p_stats->p_ru.ru_inblock += cb->inputcharge;
1566				cb->inputcharge = 0;
1567			}
1568			goto done;
1569		}
1570	}
1571	s = splbio();
1572	for (cb = TAILQ_FIRST(&ki->kaio_bufdone); cb; cb = ncb) {
1573		ncb = TAILQ_NEXT(cb, plist);
1574		if (((intptr_t) cb->uaiocb._aiocb_private.kernelinfo)
1575		    == jobref) {
1576			break;
1577		}
1578	}
1579	splx(s);
1580 done:
1581	if (cb != NULL) {
1582		if (ujob == cb->uuaiocb) {
1583			td->td_retval[0] =
1584			    cb->uaiocb._aiocb_private.status;
1585		} else
1586			td->td_retval[0] = EFAULT;
1587		aio_free_entry(cb);
1588		return (0);
1589	}
1590	return (EINVAL);
1591}
1592
1593/*
1594 * Allow a process to wakeup when any of the I/O requests are completed.
1595 */
1596int
1597aio_suspend(struct thread *td, struct aio_suspend_args *uap)
1598{
1599	struct proc *p = td->td_proc;
1600	struct timeval atv;
1601	struct timespec ts;
1602	struct aiocb *const *cbptr, *cbp;
1603	struct kaioinfo *ki;
1604	struct aiocblist *cb;
1605	int i;
1606	int njoblist;
1607	int error, s, timo;
1608	long *ijoblist;
1609	struct aiocb **ujoblist;
1610
1611	if (uap->nent > AIO_LISTIO_MAX)
1612		return EINVAL;
1613
1614	timo = 0;
1615	if (uap->timeout) {
1616		/* Get timespec struct. */
1617		if ((error = copyin(uap->timeout, &ts, sizeof(ts))) != 0)
1618			return error;
1619
1620		if (ts.tv_nsec < 0 || ts.tv_nsec >= 1000000000)
1621			return (EINVAL);
1622
1623		TIMESPEC_TO_TIMEVAL(&atv, &ts);
1624		if (itimerfix(&atv))
1625			return (EINVAL);
1626		timo = tvtohz(&atv);
1627	}
1628
1629	ki = p->p_aioinfo;
1630	if (ki == NULL)
1631		return EAGAIN;
1632
1633	njoblist = 0;
1634	ijoblist = uma_zalloc(aiol_zone, M_WAITOK);
1635	ujoblist = uma_zalloc(aiol_zone, M_WAITOK);
1636	cbptr = uap->aiocbp;
1637
1638	for (i = 0; i < uap->nent; i++) {
1639		cbp = (struct aiocb *)(intptr_t)fuword(&cbptr[i]);
1640		if (cbp == 0)
1641			continue;
1642		ujoblist[njoblist] = cbp;
1643		ijoblist[njoblist] = fuword(&cbp->_aiocb_private.kernelinfo);
1644		njoblist++;
1645	}
1646
1647	if (njoblist == 0) {
1648		uma_zfree(aiol_zone, ijoblist);
1649		uma_zfree(aiol_zone, ujoblist);
1650		return 0;
1651	}
1652
1653	error = 0;
1654	for (;;) {
1655		TAILQ_FOREACH(cb, &ki->kaio_jobdone, plist) {
1656			for (i = 0; i < njoblist; i++) {
1657				if (((intptr_t)
1658				    cb->uaiocb._aiocb_private.kernelinfo) ==
1659				    ijoblist[i]) {
1660					if (ujoblist[i] != cb->uuaiocb)
1661						error = EINVAL;
1662					uma_zfree(aiol_zone, ijoblist);
1663					uma_zfree(aiol_zone, ujoblist);
1664					return error;
1665				}
1666			}
1667		}
1668
1669		s = splbio();
1670		for (cb = TAILQ_FIRST(&ki->kaio_bufdone); cb; cb =
1671		    TAILQ_NEXT(cb, plist)) {
1672			for (i = 0; i < njoblist; i++) {
1673				if (((intptr_t)
1674				    cb->uaiocb._aiocb_private.kernelinfo) ==
1675				    ijoblist[i]) {
1676					splx(s);
1677					if (ujoblist[i] != cb->uuaiocb)
1678						error = EINVAL;
1679					uma_zfree(aiol_zone, ijoblist);
1680					uma_zfree(aiol_zone, ujoblist);
1681					return error;
1682				}
1683			}
1684		}
1685
1686		ki->kaio_flags |= KAIO_WAKEUP;
1687		error = tsleep(p, PRIBIO | PCATCH, "aiospn", timo);
1688		splx(s);
1689
1690		if (error == ERESTART || error == EINTR) {
1691			uma_zfree(aiol_zone, ijoblist);
1692			uma_zfree(aiol_zone, ujoblist);
1693			return EINTR;
1694		} else if (error == EWOULDBLOCK) {
1695			uma_zfree(aiol_zone, ijoblist);
1696			uma_zfree(aiol_zone, ujoblist);
1697			return EAGAIN;
1698		}
1699	}
1700
1701/* NOTREACHED */
1702	return EINVAL;
1703}
1704
1705/*
1706 * aio_cancel cancels any non-physio aio operations not currently in
1707 * progress.
1708 */
1709int
1710aio_cancel(struct thread *td, struct aio_cancel_args *uap)
1711{
1712	struct proc *p = td->td_proc;
1713	struct kaioinfo *ki;
1714	struct aiocblist *cbe, *cbn;
1715	struct file *fp;
1716	struct filedesc *fdp;
1717	struct socket *so;
1718	struct proc *po;
1719	int s,error;
1720	int cancelled=0;
1721	int notcancelled=0;
1722	struct vnode *vp;
1723
1724	fdp = p->p_fd;
1725	if ((u_int)uap->fd >= fdp->fd_nfiles ||
1726	    (fp = fdp->fd_ofiles[uap->fd]) == NULL)
1727		return (EBADF);
1728
1729        if (fp->f_type == DTYPE_VNODE) {
1730		vp = (struct vnode *)fp->f_data;
1731
1732		if (vn_isdisk(vp,&error)) {
1733			td->td_retval[0] = AIO_NOTCANCELED;
1734        	        return 0;
1735		}
1736	} else if (fp->f_type == DTYPE_SOCKET) {
1737		so = (struct socket *)fp->f_data;
1738
1739		s = splnet();
1740
1741		for (cbe = TAILQ_FIRST(&so->so_aiojobq); cbe; cbe = cbn) {
1742			cbn = TAILQ_NEXT(cbe, list);
1743			if ((uap->aiocbp == NULL) ||
1744				(uap->aiocbp == cbe->uuaiocb) ) {
1745				po = cbe->userproc;
1746				ki = po->p_aioinfo;
1747				TAILQ_REMOVE(&so->so_aiojobq, cbe, list);
1748				TAILQ_REMOVE(&ki->kaio_sockqueue, cbe, plist);
1749				TAILQ_INSERT_TAIL(&ki->kaio_jobdone, cbe, plist);
1750				if (ki->kaio_flags & KAIO_WAKEUP) {
1751					wakeup(po);
1752				}
1753				cbe->jobstate = JOBST_JOBFINISHED;
1754				cbe->uaiocb._aiocb_private.status=-1;
1755				cbe->uaiocb._aiocb_private.error=ECANCELED;
1756				cancelled++;
1757/* XXX cancelled, knote? */
1758			        if (cbe->uaiocb.aio_sigevent.sigev_notify ==
1759				    SIGEV_SIGNAL) {
1760					PROC_LOCK(cbe->userproc);
1761					psignal(cbe->userproc, cbe->uaiocb.aio_sigevent.sigev_signo);
1762					PROC_UNLOCK(cbe->userproc);
1763				}
1764				if (uap->aiocbp)
1765					break;
1766			}
1767		}
1768		splx(s);
1769
1770		if ((cancelled) && (uap->aiocbp)) {
1771			td->td_retval[0] = AIO_CANCELED;
1772			return 0;
1773		}
1774	}
1775	ki=p->p_aioinfo;
1776	if (ki == NULL)
1777		goto done;
1778	s = splnet();
1779
1780	for (cbe = TAILQ_FIRST(&ki->kaio_jobqueue); cbe; cbe = cbn) {
1781		cbn = TAILQ_NEXT(cbe, plist);
1782
1783		if ((uap->fd == cbe->uaiocb.aio_fildes) &&
1784		    ((uap->aiocbp == NULL ) ||
1785		     (uap->aiocbp == cbe->uuaiocb))) {
1786
1787			if (cbe->jobstate == JOBST_JOBQGLOBAL) {
1788				TAILQ_REMOVE(&aio_jobs, cbe, list);
1789                                TAILQ_REMOVE(&ki->kaio_jobqueue, cbe, plist);
1790                                TAILQ_INSERT_TAIL(&ki->kaio_jobdone, cbe,
1791                                    plist);
1792				cancelled++;
1793				ki->kaio_queue_finished_count++;
1794				cbe->jobstate = JOBST_JOBFINISHED;
1795				cbe->uaiocb._aiocb_private.status = -1;
1796				cbe->uaiocb._aiocb_private.error = ECANCELED;
1797/* XXX cancelled, knote? */
1798			        if (cbe->uaiocb.aio_sigevent.sigev_notify ==
1799				    SIGEV_SIGNAL) {
1800					PROC_LOCK(cbe->userproc);
1801					psignal(cbe->userproc, cbe->uaiocb.aio_sigevent.sigev_signo);
1802					PROC_UNLOCK(cbe->userproc);
1803				}
1804			} else {
1805				notcancelled++;
1806			}
1807		}
1808	}
1809	splx(s);
1810done:
1811	if (notcancelled) {
1812		td->td_retval[0] = AIO_NOTCANCELED;
1813		return 0;
1814	}
1815	if (cancelled) {
1816		td->td_retval[0] = AIO_CANCELED;
1817		return 0;
1818	}
1819	td->td_retval[0] = AIO_ALLDONE;
1820
1821	return 0;
1822}
1823
1824/*
1825 * aio_error is implemented in the kernel level for compatibility purposes only.
1826 * For a user mode async implementation, it would be best to do it in a userland
1827 * subroutine.
1828 */
1829int
1830aio_error(struct thread *td, struct aio_error_args *uap)
1831{
1832	struct proc *p = td->td_proc;
1833	int s;
1834	struct aiocblist *cb;
1835	struct kaioinfo *ki;
1836	long jobref;
1837
1838	ki = p->p_aioinfo;
1839	if (ki == NULL)
1840		return EINVAL;
1841
1842	jobref = fuword(&uap->aiocbp->_aiocb_private.kernelinfo);
1843	if ((jobref == -1) || (jobref == 0))
1844		return EINVAL;
1845
1846	TAILQ_FOREACH(cb, &ki->kaio_jobdone, plist) {
1847		if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1848		    jobref) {
1849			td->td_retval[0] = cb->uaiocb._aiocb_private.error;
1850			return 0;
1851		}
1852	}
1853
1854	s = splnet();
1855
1856	for (cb = TAILQ_FIRST(&ki->kaio_jobqueue); cb; cb = TAILQ_NEXT(cb,
1857	    plist)) {
1858		if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1859		    jobref) {
1860			td->td_retval[0] = EINPROGRESS;
1861			splx(s);
1862			return 0;
1863		}
1864	}
1865
1866	for (cb = TAILQ_FIRST(&ki->kaio_sockqueue); cb; cb = TAILQ_NEXT(cb,
1867	    plist)) {
1868		if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1869		    jobref) {
1870			td->td_retval[0] = EINPROGRESS;
1871			splx(s);
1872			return 0;
1873		}
1874	}
1875	splx(s);
1876
1877	s = splbio();
1878	for (cb = TAILQ_FIRST(&ki->kaio_bufdone); cb; cb = TAILQ_NEXT(cb,
1879	    plist)) {
1880		if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1881		    jobref) {
1882			td->td_retval[0] = cb->uaiocb._aiocb_private.error;
1883			splx(s);
1884			return 0;
1885		}
1886	}
1887
1888	for (cb = TAILQ_FIRST(&ki->kaio_bufqueue); cb; cb = TAILQ_NEXT(cb,
1889	    plist)) {
1890		if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1891		    jobref) {
1892			td->td_retval[0] = EINPROGRESS;
1893			splx(s);
1894			return 0;
1895		}
1896	}
1897	splx(s);
1898
1899#if (0)
1900	/*
1901	 * Hack for lio.
1902	 */
1903	status = fuword(&uap->aiocbp->_aiocb_private.status);
1904	if (status == -1)
1905		return fuword(&uap->aiocbp->_aiocb_private.error);
1906#endif
1907	return EINVAL;
1908}
1909
1910/* syscall - asynchronous read from a file (REALTIME) */
1911int
1912aio_read(struct thread *td, struct aio_read_args *uap)
1913{
1914
1915	return aio_aqueue(td, uap->aiocbp, LIO_READ);
1916}
1917
1918/* syscall - asynchronous write to a file (REALTIME) */
1919int
1920aio_write(struct thread *td, struct aio_write_args *uap)
1921{
1922
1923	return aio_aqueue(td, uap->aiocbp, LIO_WRITE);
1924}
1925
1926/* syscall - XXX undocumented */
1927int
1928lio_listio(struct thread *td, struct lio_listio_args *uap)
1929{
1930	struct proc *p = td->td_proc;
1931	int nent, nentqueued;
1932	struct aiocb *iocb, * const *cbptr;
1933	struct aiocblist *cb;
1934	struct kaioinfo *ki;
1935	struct aio_liojob *lj;
1936	int error, runningcode;
1937	int nerror;
1938	int i;
1939	int s;
1940
1941	if ((uap->mode != LIO_NOWAIT) && (uap->mode != LIO_WAIT))
1942		return EINVAL;
1943
1944	nent = uap->nent;
1945	if (nent > AIO_LISTIO_MAX)
1946		return EINVAL;
1947
1948	if (p->p_aioinfo == NULL)
1949		aio_init_aioinfo(p);
1950
1951	if ((nent + num_queue_count) > max_queue_count)
1952		return EAGAIN;
1953
1954	ki = p->p_aioinfo;
1955	if ((nent + ki->kaio_queue_count) > ki->kaio_qallowed_count)
1956		return EAGAIN;
1957
1958	lj = uma_zalloc(aiolio_zone, M_WAITOK);
1959	if (!lj)
1960		return EAGAIN;
1961
1962	lj->lioj_flags = 0;
1963	lj->lioj_buffer_count = 0;
1964	lj->lioj_buffer_finished_count = 0;
1965	lj->lioj_queue_count = 0;
1966	lj->lioj_queue_finished_count = 0;
1967	lj->lioj_ki = ki;
1968
1969	/*
1970	 * Setup signal.
1971	 */
1972	if (uap->sig && (uap->mode == LIO_NOWAIT)) {
1973		error = copyin(uap->sig, &lj->lioj_signal,
1974			       sizeof(lj->lioj_signal));
1975		if (error) {
1976			uma_zfree(aiolio_zone, lj);
1977			return error;
1978		}
1979		if (!_SIG_VALID(lj->lioj_signal.sigev_signo)) {
1980			uma_zfree(aiolio_zone, lj);
1981			return EINVAL;
1982		}
1983		lj->lioj_flags |= LIOJ_SIGNAL;
1984	}
1985	TAILQ_INSERT_TAIL(&ki->kaio_liojoblist, lj, lioj_list);
1986	/*
1987	 * Get pointers to the list of I/O requests.
1988	 */
1989	nerror = 0;
1990	nentqueued = 0;
1991	cbptr = uap->acb_list;
1992	for (i = 0; i < uap->nent; i++) {
1993		iocb = (struct aiocb *)(intptr_t)fuword(&cbptr[i]);
1994		if (((intptr_t)iocb != -1) && ((intptr_t)iocb != 0)) {
1995			error = _aio_aqueue(td, iocb, lj, 0);
1996			if (error == 0)
1997				nentqueued++;
1998			else
1999				nerror++;
2000		}
2001	}
2002
2003	/*
2004	 * If we haven't queued any, then just return error.
2005	 */
2006	if (nentqueued == 0)
2007		return 0;
2008
2009	/*
2010	 * Calculate the appropriate error return.
2011	 */
2012	runningcode = 0;
2013	if (nerror)
2014		runningcode = EIO;
2015
2016	if (uap->mode == LIO_WAIT) {
2017		int command, found, jobref;
2018
2019		for (;;) {
2020			found = 0;
2021			for (i = 0; i < uap->nent; i++) {
2022				/*
2023				 * Fetch address of the control buf pointer in
2024				 * user space.
2025				 */
2026				iocb = (struct aiocb *)
2027				    (intptr_t)fuword(&cbptr[i]);
2028				if (((intptr_t)iocb == -1) || ((intptr_t)iocb
2029				    == 0))
2030					continue;
2031
2032				/*
2033				 * Fetch the associated command from user space.
2034				 */
2035				command = fuword(&iocb->aio_lio_opcode);
2036				if (command == LIO_NOP) {
2037					found++;
2038					continue;
2039				}
2040
2041				jobref = fuword(&iocb->_aiocb_private.kernelinfo);
2042
2043				TAILQ_FOREACH(cb, &ki->kaio_jobdone, plist) {
2044					if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo)
2045					    == jobref) {
2046						if (cb->uaiocb.aio_lio_opcode
2047						    == LIO_WRITE) {
2048							p->p_stats->p_ru.ru_oublock
2049							    +=
2050							    cb->outputcharge;
2051							cb->outputcharge = 0;
2052						} else if (cb->uaiocb.aio_lio_opcode
2053						    == LIO_READ) {
2054							p->p_stats->p_ru.ru_inblock
2055							    += cb->inputcharge;
2056							cb->inputcharge = 0;
2057						}
2058						found++;
2059						break;
2060					}
2061				}
2062
2063				s = splbio();
2064				TAILQ_FOREACH(cb, &ki->kaio_bufdone, plist) {
2065					if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo)
2066					    == jobref) {
2067						found++;
2068						break;
2069					}
2070				}
2071				splx(s);
2072			}
2073
2074			/*
2075			 * If all I/Os have been disposed of, then we can
2076			 * return.
2077			 */
2078			if (found == nentqueued)
2079				return runningcode;
2080
2081			ki->kaio_flags |= KAIO_WAKEUP;
2082			error = tsleep(p, PRIBIO | PCATCH, "aiospn", 0);
2083
2084			if (error == EINTR)
2085				return EINTR;
2086			else if (error == EWOULDBLOCK)
2087				return EAGAIN;
2088		}
2089	}
2090
2091	return runningcode;
2092}
2093
2094/*
2095 * This is a weird hack so that we can post a signal.  It is safe to do so from
2096 * a timeout routine, but *not* from an interrupt routine.
2097 */
2098static void
2099process_signal(void *aioj)
2100{
2101	struct aiocblist *aiocbe = aioj;
2102	struct aio_liojob *lj = aiocbe->lio;
2103	struct aiocb *cb = &aiocbe->uaiocb;
2104
2105	if ((lj) && (lj->lioj_signal.sigev_notify == SIGEV_SIGNAL) &&
2106		(lj->lioj_queue_count == lj->lioj_queue_finished_count)) {
2107		PROC_LOCK(lj->lioj_ki->kaio_p);
2108		psignal(lj->lioj_ki->kaio_p, lj->lioj_signal.sigev_signo);
2109		PROC_UNLOCK(lj->lioj_ki->kaio_p);
2110		lj->lioj_flags |= LIOJ_SIGNAL_POSTED;
2111	}
2112
2113	if (cb->aio_sigevent.sigev_notify == SIGEV_SIGNAL) {
2114		PROC_LOCK(aiocbe->userproc);
2115		psignal(aiocbe->userproc, cb->aio_sigevent.sigev_signo);
2116		PROC_UNLOCK(aiocbe->userproc);
2117	}
2118}
2119
2120/*
2121 * Interrupt handler for physio, performs the necessary process wakeups, and
2122 * signals.
2123 */
2124static void
2125aio_physwakeup(struct buf *bp)
2126{
2127	struct aiocblist *aiocbe;
2128	struct proc *p;
2129	struct kaioinfo *ki;
2130	struct aio_liojob *lj;
2131
2132	wakeup(bp);
2133
2134	aiocbe = (struct aiocblist *)bp->b_spc;
2135	if (aiocbe) {
2136		p = bp->b_caller1;
2137
2138		aiocbe->jobstate = JOBST_JOBBFINISHED;
2139		aiocbe->uaiocb._aiocb_private.status -= bp->b_resid;
2140		aiocbe->uaiocb._aiocb_private.error = 0;
2141		aiocbe->jobflags |= AIOCBLIST_DONE;
2142
2143		if (bp->b_ioflags & BIO_ERROR)
2144			aiocbe->uaiocb._aiocb_private.error = bp->b_error;
2145
2146		lj = aiocbe->lio;
2147		if (lj) {
2148			lj->lioj_buffer_finished_count++;
2149
2150			/*
2151			 * wakeup/signal if all of the interrupt jobs are done.
2152			 */
2153			if (lj->lioj_buffer_finished_count ==
2154			    lj->lioj_buffer_count) {
2155				/*
2156				 * Post a signal if it is called for.
2157				 */
2158				if ((lj->lioj_flags &
2159				    (LIOJ_SIGNAL|LIOJ_SIGNAL_POSTED)) ==
2160				    LIOJ_SIGNAL) {
2161					lj->lioj_flags |= LIOJ_SIGNAL_POSTED;
2162					aiocbe->timeouthandle =
2163						timeout(process_signal,
2164							aiocbe, 0);
2165				}
2166			}
2167		}
2168
2169		ki = p->p_aioinfo;
2170		if (ki) {
2171			ki->kaio_buffer_finished_count++;
2172			TAILQ_REMOVE(&aio_bufjobs, aiocbe, list);
2173			TAILQ_REMOVE(&ki->kaio_bufqueue, aiocbe, plist);
2174			TAILQ_INSERT_TAIL(&ki->kaio_bufdone, aiocbe, plist);
2175
2176			KNOTE(&aiocbe->klist, 0);
2177			/* Do the wakeup. */
2178			if (ki->kaio_flags & (KAIO_RUNDOWN|KAIO_WAKEUP)) {
2179				ki->kaio_flags &= ~KAIO_WAKEUP;
2180				wakeup(p);
2181			}
2182		}
2183
2184		if (aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_SIGNAL)
2185			aiocbe->timeouthandle =
2186				timeout(process_signal, aiocbe, 0);
2187	}
2188}
2189
2190/* syscall - wait for the next completion of an aio request */
2191int
2192aio_waitcomplete(struct thread *td, struct aio_waitcomplete_args *uap)
2193{
2194	struct proc *p = td->td_proc;
2195	struct timeval atv;
2196	struct timespec ts;
2197	struct kaioinfo *ki;
2198	struct aiocblist *cb = NULL;
2199	int error, s, timo;
2200
2201	suword(uap->aiocbp, (int)NULL);
2202
2203	timo = 0;
2204	if (uap->timeout) {
2205		/* Get timespec struct. */
2206		error = copyin(uap->timeout, &ts, sizeof(ts));
2207		if (error)
2208			return error;
2209
2210		if ((ts.tv_nsec < 0) || (ts.tv_nsec >= 1000000000))
2211			return (EINVAL);
2212
2213		TIMESPEC_TO_TIMEVAL(&atv, &ts);
2214		if (itimerfix(&atv))
2215			return (EINVAL);
2216		timo = tvtohz(&atv);
2217	}
2218
2219	ki = p->p_aioinfo;
2220	if (ki == NULL)
2221		return EAGAIN;
2222
2223	for (;;) {
2224		if ((cb = TAILQ_FIRST(&ki->kaio_jobdone)) != 0) {
2225			suword(uap->aiocbp, (uintptr_t)cb->uuaiocb);
2226			td->td_retval[0] = cb->uaiocb._aiocb_private.status;
2227			if (cb->uaiocb.aio_lio_opcode == LIO_WRITE) {
2228				p->p_stats->p_ru.ru_oublock +=
2229				    cb->outputcharge;
2230				cb->outputcharge = 0;
2231			} else if (cb->uaiocb.aio_lio_opcode == LIO_READ) {
2232				p->p_stats->p_ru.ru_inblock += cb->inputcharge;
2233				cb->inputcharge = 0;
2234			}
2235			aio_free_entry(cb);
2236			return cb->uaiocb._aiocb_private.error;
2237		}
2238
2239		s = splbio();
2240 		if ((cb = TAILQ_FIRST(&ki->kaio_bufdone)) != 0 ) {
2241			splx(s);
2242			suword(uap->aiocbp, (uintptr_t)cb->uuaiocb);
2243			td->td_retval[0] = cb->uaiocb._aiocb_private.status;
2244			aio_free_entry(cb);
2245			return cb->uaiocb._aiocb_private.error;
2246		}
2247
2248		ki->kaio_flags |= KAIO_WAKEUP;
2249		error = tsleep(p, PRIBIO | PCATCH, "aiowc", timo);
2250		splx(s);
2251
2252		if (error == ERESTART)
2253			return EINTR;
2254		else if (error < 0)
2255			return error;
2256		else if (error == EINTR)
2257			return EINTR;
2258		else if (error == EWOULDBLOCK)
2259			return EAGAIN;
2260	}
2261}
2262
2263/* kqueue attach function */
2264static int
2265filt_aioattach(struct knote *kn)
2266{
2267	struct aiocblist *aiocbe = (struct aiocblist *)kn->kn_sdata;
2268
2269	/*
2270	 * The aiocbe pointer must be validated before using it, so
2271	 * registration is restricted to the kernel; the user cannot
2272	 * set EV_FLAG1.
2273	 */
2274	if ((kn->kn_flags & EV_FLAG1) == 0)
2275		return (EPERM);
2276	kn->kn_flags &= ~EV_FLAG1;
2277
2278	SLIST_INSERT_HEAD(&aiocbe->klist, kn, kn_selnext);
2279
2280	return (0);
2281}
2282
2283/* kqueue detach function */
2284static void
2285filt_aiodetach(struct knote *kn)
2286{
2287	struct aiocblist *aiocbe = (struct aiocblist *)kn->kn_sdata;
2288
2289	SLIST_REMOVE(&aiocbe->klist, kn, knote, kn_selnext);
2290}
2291
2292/* kqueue filter function */
2293/*ARGSUSED*/
2294static int
2295filt_aio(struct knote *kn, long hint)
2296{
2297	struct aiocblist *aiocbe = (struct aiocblist *)kn->kn_sdata;
2298
2299	kn->kn_data = aiocbe->uaiocb._aiocb_private.error;
2300	if (aiocbe->jobstate != JOBST_JOBFINISHED &&
2301	    aiocbe->jobstate != JOBST_JOBBFINISHED)
2302		return (0);
2303	kn->kn_flags |= EV_EOF;
2304	return (1);
2305}
2306