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