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