Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[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.2 2003/06/17 04:28:41 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 proc *p, 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
626         /*
627          * Local copies of curproc (cp) and vmspace (myvm)
628          */
629         mycp = curproc;
630         myvm = mycp->p_vmspace;
631
632         if (mycp->p_textvp) {
633                 vrele(mycp->p_textvp);
634                 mycp->p_textvp = NULL;
635         }
636
637         /*
638          * Allocate and ready the aio control info.  There is one aiop structure
639          * per daemon.
640          */
641         aiop = zalloc(aiop_zone);
642         aiop->aioproc = mycp;
643         aiop->aioprocflags |= AIOP_FREE;
644
645         s = splnet();
646
647         /*
648          * Place thread (lightweight process) onto the AIO free thread list.
649          */
650         if (TAILQ_EMPTY(&aio_freeproc))
651                 wakeup(&aio_freeproc);
652         TAILQ_INSERT_HEAD(&aio_freeproc, aiop, list);
653
654         splx(s);
655
656         /* Make up a name for the daemon. */
657         strcpy(mycp->p_comm, "aiod");
658
659         /*
660          * Get rid of our current filedescriptors.  AIOD's don't need any
661          * filedescriptors, except as temporarily inherited from the client.
662          * Credentials are also cloned, and made equivalent to "root".
663          */
664         fdfree(mycp);
665         mycp->p_fd = NULL;
666         mycp->p_ucred = crcopy(mycp->p_ucred);
667         mycp->p_ucred->cr_uid = 0;
668         uifree(mycp->p_ucred->cr_uidinfo);
669         mycp->p_ucred->cr_uidinfo = uifind(0);
670         mycp->p_ucred->cr_ngroups = 1;
671         mycp->p_ucred->cr_groups[0] = 1;
672
673         /* The daemon resides in its own pgrp. */
674         enterpgrp(mycp, mycp->p_pid, 1);
675
676         /* Mark special process type. */
677         mycp->p_flag |= P_SYSTEM | P_KTHREADP;
678
679         /*
680          * Wakeup parent process.  (Parent sleeps to keep from blasting away
681          * and creating too many daemons.)
682          */
683         wakeup(mycp);
684
685         for (;;) {
686                 /*
687                  * curcp is the current daemon process context.
688                  * userp is the current user process context.
689                  */
690                 curcp = mycp;
691
692                 /*
693                  * Take daemon off of free queue
694                  */
695                 if (aiop->aioprocflags & AIOP_FREE) {
696                         s = splnet();
697                         TAILQ_REMOVE(&aio_freeproc, aiop, list);
698                         TAILQ_INSERT_TAIL(&aio_activeproc, aiop, list);
699                         aiop->aioprocflags &= ~AIOP_FREE;
700                         splx(s);
701                 }
702                 aiop->aioprocflags &= ~AIOP_SCHED;
703
704                 /*
705                  * Check for jobs.
706                  */
707                 while ((aiocbe = aio_selectjob(aiop)) != NULL) {
708                         cb = &aiocbe->uaiocb;
709                         userp = aiocbe->userproc;
710
711                         aiocbe->jobstate = JOBST_JOBRUNNING;
712
713                         /*
714                          * Connect to process address space for user program.
715                          */
716                         if (userp != curcp) {
717                                 /*
718                                  * Save the current address space that we are
719                                  * connected to.
720                                  */
721                                 tmpvm = mycp->p_vmspace;
722                                 
723                                 /*
724                                  * Point to the new user address space, and
725                                  * refer to it.
726                                  */
727                                 mycp->p_vmspace = userp->p_vmspace;
728                                 mycp->p_vmspace->vm_refcnt++;
729                                 
730                                 /* Activate the new mapping. */
731                                 pmap_activate(mycp);
732                                 
733                                 /*
734                                  * If the old address space wasn't the daemons
735                                  * own address space, then we need to remove the
736                                  * daemon's reference from the other process
737                                  * that it was acting on behalf of.
738                                  */
739                                 if (tmpvm != myvm) {
740                                         vmspace_free(tmpvm);
741                                 }
742                                 curcp = userp;
743                         }
744
745                         ki = userp->p_aioinfo;
746                         lj = aiocbe->lio;
747
748                         /* Account for currently active jobs. */
749                         ki->kaio_active_count++;
750
751                         /* Do the I/O function. */
752                         aio_process(aiocbe);
753
754                         /* Decrement the active job count. */
755                         ki->kaio_active_count--;
756
757                         /*
758                          * Increment the completion count for wakeup/signal
759                          * comparisons.
760                          */
761                         aiocbe->jobflags |= AIOCBLIST_DONE;
762                         ki->kaio_queue_finished_count++;
763                         if (lj)
764                                 lj->lioj_queue_finished_count++;
765                         if ((ki->kaio_flags & KAIO_WAKEUP) || ((ki->kaio_flags
766                             & KAIO_RUNDOWN) && (ki->kaio_active_count == 0))) {
767                                 ki->kaio_flags &= ~KAIO_WAKEUP;
768                                 wakeup(userp);
769                         }
770
771                         s = splbio();
772                         if (lj && (lj->lioj_flags &
773                             (LIOJ_SIGNAL|LIOJ_SIGNAL_POSTED)) == LIOJ_SIGNAL) {
774                                 if ((lj->lioj_queue_finished_count ==
775                                     lj->lioj_queue_count) &&
776                                     (lj->lioj_buffer_finished_count ==
777                                     lj->lioj_buffer_count)) {
778                                                 psignal(userp,
779                                                     lj->lioj_signal.sigev_signo);
780                                                 lj->lioj_flags |=
781                                                     LIOJ_SIGNAL_POSTED;
782                                 }
783                         }
784                         splx(s);
785
786                         aiocbe->jobstate = JOBST_JOBFINISHED;
787
788                         s = splnet();
789                         TAILQ_REMOVE(&ki->kaio_jobqueue, aiocbe, plist);
790                         TAILQ_INSERT_TAIL(&ki->kaio_jobdone, aiocbe, plist);
791                         splx(s);
792                         KNOTE(&aiocbe->klist, 0);
793
794                         if (aiocbe->jobflags & AIOCBLIST_RUNDOWN) {
795                                 wakeup(aiocbe);
796                                 aiocbe->jobflags &= ~AIOCBLIST_RUNDOWN;
797                         }
798
799                         if (cb->aio_sigevent.sigev_notify == SIGEV_SIGNAL) {
800                                 psignal(userp, cb->aio_sigevent.sigev_signo);
801                         }
802                 }
803
804                 /*
805                  * Disconnect from user address space.
806                  */
807                 if (curcp != mycp) {
808                         /* Get the user address space to disconnect from. */
809                         tmpvm = mycp->p_vmspace;
810                         
811                         /* Get original address space for daemon. */
812                         mycp->p_vmspace = myvm;
813                         
814                         /* Activate the daemon's address space. */
815                         pmap_activate(mycp);
816 #ifdef DIAGNOSTIC
817                         if (tmpvm == myvm) {
818                                 printf("AIOD: vmspace problem -- %d\n",
819                                     mycp->p_pid);
820                         }
821 #endif
822                         /* Remove our vmspace reference. */
823                         vmspace_free(tmpvm);
824
825                         curcp = mycp;
826                 }
827
828                 /*
829                  * If we are the first to be put onto the free queue, wakeup
830                  * anyone waiting for a daemon.
831                  */
832                 s = splnet();
833                 TAILQ_REMOVE(&aio_activeproc, aiop, list);
834                 if (TAILQ_EMPTY(&aio_freeproc))
835                         wakeup(&aio_freeproc);
836                 TAILQ_INSERT_HEAD(&aio_freeproc, aiop, list);
837                 aiop->aioprocflags |= AIOP_FREE;
838                 splx(s);
839
840                 /*
841                  * If daemon is inactive for a long time, allow it to exit,
842                  * thereby freeing resources.
843                  */
844                 if (((aiop->aioprocflags & AIOP_SCHED) == 0) && tsleep(mycp,
845                     PRIBIO, "aiordy", aiod_lifetime)) {
846                         s = splnet();
847                         if (TAILQ_EMPTY(&aio_jobs)) {
848                                 if ((aiop->aioprocflags & AIOP_FREE) &&
849                                     (num_aio_procs > target_aio_procs)) {
850                                         TAILQ_REMOVE(&aio_freeproc, aiop, list);
851                                         splx(s);
852                                         zfree(aiop_zone, aiop);
853                                         num_aio_procs--;
854 #ifdef DIAGNOSTIC
855                                         if (mycp->p_vmspace->vm_refcnt <= 1) {
856                                                 printf("AIOD: bad vm refcnt for"
857                                                     " exiting daemon: %d\n",
858                                                     mycp->p_vmspace->vm_refcnt);
859                                         }
860 #endif
861                                         exit1(mycp, 0);
862                                 }
863                         }
864                         splx(s);
865                 }
866         }
867 }
868
869 /*
870  * Create a new AIO daemon.  This is mostly a kernel-thread fork routine.  The
871  * AIO daemon modifies its environment itself.
872  */
873 static int
874 aio_newproc()
875 {
876         int error;
877         struct proc *p, *np;
878
879         p = &proc0;
880         error = fork1(p, RFPROC|RFMEM|RFNOWAIT, &np);
881         if (error)
882                 return error;
883         cpu_set_fork_handler(np, aio_daemon, curproc);
884
885         /*
886          * Wait until daemon is started, but continue on just in case to
887          * handle error conditions.
888          */
889         error = tsleep(np, PZERO, "aiosta", aiod_timeout);
890         num_aio_procs++;
891
892         return error;
893 }
894
895 /*
896  * Try the high-performance, low-overhead physio method for eligible
897  * VCHR devices.  This method doesn't use an aio helper thread, and
898  * thus has very low overhead. 
899  *
900  * Assumes that the caller, _aio_aqueue(), has incremented the file
901  * structure's reference count, preventing its deallocation for the
902  * duration of this call. 
903  */
904 static int
905 aio_qphysio(struct proc *p, struct aiocblist *aiocbe)
906 {
907         int error;
908         struct aiocb *cb;
909         struct file *fp;
910         struct buf *bp;
911         struct vnode *vp;
912         struct kaioinfo *ki;
913         struct aio_liojob *lj;
914         int s;
915         int notify;
916
917         cb = &aiocbe->uaiocb;
918         fp = aiocbe->fd_file;
919
920         if (fp->f_type != DTYPE_VNODE) 
921                 return (-1);
922
923         vp = (struct vnode *)fp->f_data;
924
925         /*
926          * If its not a disk, we don't want to return a positive error.
927          * It causes the aio code to not fall through to try the thread
928          * way when you're talking to a regular file.
929          */
930         if (!vn_isdisk(vp, &error)) {
931                 if (error == ENOTBLK)
932                         return (-1);
933                 else
934                         return (error);
935         }
936
937         if (cb->aio_nbytes % vp->v_rdev->si_bsize_phys)
938                 return (-1);
939
940         if (cb->aio_nbytes >
941             MAXPHYS - (((vm_offset_t) cb->aio_buf) & PAGE_MASK))
942                 return (-1);
943
944         ki = p->p_aioinfo;
945         if (ki->kaio_buffer_count >= ki->kaio_ballowed_count) 
946                 return (-1);
947
948         ki->kaio_buffer_count++;
949
950         lj = aiocbe->lio;
951         if (lj)
952                 lj->lioj_buffer_count++;
953
954         /* Create and build a buffer header for a transfer. */
955         bp = (struct buf *)getpbuf(NULL);
956         BUF_KERNPROC(bp);
957
958         /*
959          * Get a copy of the kva from the physical buffer.
960          */
961         bp->b_caller1 = p;
962         bp->b_dev = vp->v_rdev;
963         error = 0;
964
965         bp->b_bcount = cb->aio_nbytes;
966         bp->b_bufsize = cb->aio_nbytes;
967         bp->b_flags = B_PHYS | B_CALL | (cb->aio_lio_opcode == LIO_WRITE ?
968             B_WRITE : B_READ);
969         bp->b_iodone = aio_physwakeup;
970         bp->b_saveaddr = bp->b_data;
971         bp->b_data = (void *)(uintptr_t)cb->aio_buf;
972         bp->b_blkno = btodb(cb->aio_offset);
973
974         /* Bring buffer into kernel space. */
975         if (vmapbuf(bp) < 0) {
976                 error = EFAULT;
977                 goto doerror;
978         }
979
980         s = splbio();
981         aiocbe->bp = bp;
982         bp->b_spc = (void *)aiocbe;
983         TAILQ_INSERT_TAIL(&aio_bufjobs, aiocbe, list);
984         TAILQ_INSERT_TAIL(&ki->kaio_bufqueue, aiocbe, plist);
985         aiocbe->jobstate = JOBST_JOBQBUF;
986         cb->_aiocb_private.status = cb->aio_nbytes;
987         num_buf_aio++;
988         bp->b_error = 0;
989
990         splx(s);
991         
992         /* Perform transfer. */
993         BUF_STRATEGY(bp, 0);
994
995         notify = 0;
996         s = splbio();
997         
998         /*
999          * If we had an error invoking the request, or an error in processing
1000          * the request before we have returned, we process it as an error in
1001          * transfer.  Note that such an I/O error is not indicated immediately,
1002          * but is returned using the aio_error mechanism.  In this case,
1003          * aio_suspend will return immediately.
1004          */
1005         if (bp->b_error || (bp->b_flags & B_ERROR)) {
1006                 struct aiocb *job = aiocbe->uuaiocb;
1007
1008                 aiocbe->uaiocb._aiocb_private.status = 0;
1009                 suword(&job->_aiocb_private.status, 0);
1010                 aiocbe->uaiocb._aiocb_private.error = bp->b_error;
1011                 suword(&job->_aiocb_private.error, bp->b_error);
1012
1013                 ki->kaio_buffer_finished_count++;
1014
1015                 if (aiocbe->jobstate != JOBST_JOBBFINISHED) {
1016                         aiocbe->jobstate = JOBST_JOBBFINISHED;
1017                         aiocbe->jobflags |= AIOCBLIST_DONE;
1018                         TAILQ_REMOVE(&aio_bufjobs, aiocbe, list);
1019                         TAILQ_REMOVE(&ki->kaio_bufqueue, aiocbe, plist);
1020                         TAILQ_INSERT_TAIL(&ki->kaio_bufdone, aiocbe, plist);
1021                         notify = 1;
1022                 }
1023         }
1024         splx(s);
1025         if (notify)
1026                 KNOTE(&aiocbe->klist, 0);
1027         return 0;
1028
1029 doerror:
1030         ki->kaio_buffer_count--;
1031         if (lj)
1032                 lj->lioj_buffer_count--;
1033         aiocbe->bp = NULL;
1034         relpbuf(bp, NULL);
1035         return error;
1036 }
1037
1038 /*
1039  * This waits/tests physio completion.
1040  */
1041 static int
1042 aio_fphysio(struct aiocblist *iocb)
1043 {
1044         int s;
1045         struct buf *bp;
1046         int error;
1047
1048         bp = iocb->bp;
1049
1050         s = splbio();
1051         while ((bp->b_flags & B_DONE) == 0) {
1052                 if (tsleep(bp, PRIBIO, "physstr", aiod_timeout)) {
1053                         if ((bp->b_flags & B_DONE) == 0) {
1054                                 splx(s);
1055                                 return EINPROGRESS;
1056                         } else
1057                                 break;
1058                 }
1059         }
1060         splx(s);
1061
1062         /* Release mapping into kernel space. */
1063         vunmapbuf(bp);
1064         iocb->bp = 0;
1065
1066         error = 0;
1067         
1068         /* Check for an error. */
1069         if (bp->b_flags & B_ERROR)
1070                 error = bp->b_error;
1071
1072         relpbuf(bp, NULL);
1073         return (error);
1074 }
1075 #endif /* VFS_AIO */
1076
1077 /*
1078  * Wake up aio requests that may be serviceable now.
1079  */
1080 void
1081 aio_swake(struct socket *so, struct sockbuf *sb)
1082 {
1083 #ifndef VFS_AIO
1084         return;
1085 #else
1086         struct aiocblist *cb,*cbn;
1087         struct proc *p;
1088         struct kaioinfo *ki = NULL;
1089         int opcode, wakecount = 0;
1090         struct aioproclist *aiop;
1091
1092         if (sb == &so->so_snd) {
1093                 opcode = LIO_WRITE;
1094                 so->so_snd.sb_flags &= ~SB_AIO;
1095         } else {
1096                 opcode = LIO_READ;
1097                 so->so_rcv.sb_flags &= ~SB_AIO;
1098         }
1099
1100         for (cb = TAILQ_FIRST(&so->so_aiojobq); cb; cb = cbn) {
1101                 cbn = TAILQ_NEXT(cb, list);
1102                 if (opcode == cb->uaiocb.aio_lio_opcode) {
1103                         p = cb->userproc;
1104                         ki = p->p_aioinfo;
1105                         TAILQ_REMOVE(&so->so_aiojobq, cb, list);
1106                         TAILQ_REMOVE(&ki->kaio_sockqueue, cb, plist);
1107                         TAILQ_INSERT_TAIL(&aio_jobs, cb, list);
1108                         TAILQ_INSERT_TAIL(&ki->kaio_jobqueue, cb, plist);
1109                         wakecount++;
1110                         if (cb->jobstate != JOBST_JOBQGLOBAL)
1111                                 panic("invalid queue value");
1112                 }
1113         }
1114
1115         while (wakecount--) {
1116                 if ((aiop = TAILQ_FIRST(&aio_freeproc)) != 0) {
1117                         TAILQ_REMOVE(&aio_freeproc, aiop, list);
1118                         TAILQ_INSERT_TAIL(&aio_activeproc, aiop, list);
1119                         aiop->aioprocflags &= ~AIOP_FREE;
1120                         wakeup(aiop->aioproc);
1121                 }
1122         }
1123 #endif /* VFS_AIO */
1124 }
1125
1126 #ifdef VFS_AIO
1127 /*
1128  * Queue a new AIO request.  Choosing either the threaded or direct physio VCHR
1129  * technique is done in this code.
1130  */
1131 static int
1132 _aio_aqueue(struct proc *p, struct aiocb *job, struct aio_liojob *lj, int type)
1133 {
1134         struct filedesc *fdp;
1135         struct file *fp;
1136         unsigned int fd;
1137         struct socket *so;
1138         int s;
1139         int error;
1140         int opcode, user_opcode;
1141         struct aiocblist *aiocbe;
1142         struct aioproclist *aiop;
1143         struct kaioinfo *ki;
1144         struct kevent kev;
1145         struct kqueue *kq;
1146         struct file *kq_fp;
1147
1148         if ((aiocbe = TAILQ_FIRST(&aio_freejobs)) != NULL)
1149                 TAILQ_REMOVE(&aio_freejobs, aiocbe, list);
1150         else
1151                 aiocbe = zalloc (aiocb_zone);
1152
1153         aiocbe->inputcharge = 0;
1154         aiocbe->outputcharge = 0;
1155         callout_handle_init(&aiocbe->timeouthandle);
1156         SLIST_INIT(&aiocbe->klist);
1157
1158         suword(&job->_aiocb_private.status, -1);
1159         suword(&job->_aiocb_private.error, 0);
1160         suword(&job->_aiocb_private.kernelinfo, -1);
1161
1162         error = copyin(job, &aiocbe->uaiocb, sizeof(aiocbe->uaiocb));
1163         if (error) {
1164                 suword(&job->_aiocb_private.error, error);
1165                 TAILQ_INSERT_HEAD(&aio_freejobs, aiocbe, list);
1166                 return error;
1167         }
1168         if (aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_SIGNAL &&
1169             !_SIG_VALID(aiocbe->uaiocb.aio_sigevent.sigev_signo)) {
1170                 TAILQ_INSERT_HEAD(&aio_freejobs, aiocbe, list);
1171                 return EINVAL;
1172         }
1173
1174         /* Save userspace address of the job info. */
1175         aiocbe->uuaiocb = job;
1176
1177         /* Get the opcode. */
1178         user_opcode = aiocbe->uaiocb.aio_lio_opcode;
1179         if (type != LIO_NOP)
1180                 aiocbe->uaiocb.aio_lio_opcode = type;
1181         opcode = aiocbe->uaiocb.aio_lio_opcode;
1182
1183         /* Get the fd info for process. */
1184         fdp = p->p_fd;
1185
1186         /*
1187          * Range check file descriptor.
1188          */
1189         fd = aiocbe->uaiocb.aio_fildes;
1190         if (fd >= fdp->fd_nfiles) {
1191                 TAILQ_INSERT_HEAD(&aio_freejobs, aiocbe, list);
1192                 if (type == 0)
1193                         suword(&job->_aiocb_private.error, EBADF);
1194                 return EBADF;
1195         }
1196
1197         fp = aiocbe->fd_file = fdp->fd_ofiles[fd];
1198         if ((fp == NULL) || ((opcode == LIO_WRITE) && ((fp->f_flag & FWRITE) ==
1199             0))) {
1200                 TAILQ_INSERT_HEAD(&aio_freejobs, aiocbe, list);
1201                 if (type == 0)
1202                         suword(&job->_aiocb_private.error, EBADF);
1203                 return EBADF;
1204         }
1205         fhold(fp);
1206
1207         if (aiocbe->uaiocb.aio_offset == -1LL) {
1208                 error = EINVAL;
1209                 goto aqueue_fail;
1210         }
1211         error = suword(&job->_aiocb_private.kernelinfo, jobrefid);
1212         if (error) {
1213                 error = EINVAL;
1214                 goto aqueue_fail;
1215         }
1216         aiocbe->uaiocb._aiocb_private.kernelinfo = (void *)(intptr_t)jobrefid;
1217         if (jobrefid == LONG_MAX)
1218                 jobrefid = 1;
1219         else
1220                 jobrefid++;
1221         
1222         if (opcode == LIO_NOP) {
1223                 fdrop(fp, p);
1224                 TAILQ_INSERT_HEAD(&aio_freejobs, aiocbe, list);
1225                 if (type == 0) {
1226                         suword(&job->_aiocb_private.error, 0);
1227                         suword(&job->_aiocb_private.status, 0);
1228                         suword(&job->_aiocb_private.kernelinfo, 0);
1229                 }
1230                 return 0;
1231         }
1232         if ((opcode != LIO_READ) && (opcode != LIO_WRITE)) {
1233                 if (type == 0)
1234                         suword(&job->_aiocb_private.status, 0);
1235                 error = EINVAL;
1236                 goto aqueue_fail;
1237         }
1238
1239         if (aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_KEVENT) {
1240                 kev.ident = aiocbe->uaiocb.aio_sigevent.sigev_notify_kqueue;
1241                 kev.udata = aiocbe->uaiocb.aio_sigevent.sigev_value.sigval_ptr;
1242         }
1243         else {
1244                 /*
1245                  * This method for requesting kevent-based notification won't
1246                  * work on the alpha, since we're passing in a pointer
1247                  * via aio_lio_opcode, which is an int.  Use the SIGEV_KEVENT-
1248                  * based method instead.
1249                  */
1250                 if (user_opcode == LIO_NOP || user_opcode == LIO_READ ||
1251                     user_opcode == LIO_WRITE)
1252                         goto no_kqueue;
1253
1254                 error = copyin((struct kevent *)(uintptr_t)user_opcode,
1255                     &kev, sizeof(kev));
1256                 if (error)
1257                         goto aqueue_fail;
1258         }
1259         if ((u_int)kev.ident >= fdp->fd_nfiles ||
1260             (kq_fp = fdp->fd_ofiles[kev.ident]) == NULL ||
1261             (kq_fp->f_type != DTYPE_KQUEUE)) {
1262                 error = EBADF;
1263                 goto aqueue_fail;
1264         }
1265         kq = (struct kqueue *)kq_fp->f_data;
1266         kev.ident = (uintptr_t)aiocbe->uuaiocb;
1267         kev.filter = EVFILT_AIO;
1268         kev.flags = EV_ADD | EV_ENABLE | EV_FLAG1;
1269         kev.data = (intptr_t)aiocbe;
1270         error = kqueue_register(kq, &kev, p);
1271 aqueue_fail:
1272         if (error) {
1273                 fdrop(fp, p);
1274                 TAILQ_INSERT_HEAD(&aio_freejobs, aiocbe, list);
1275                 if (type == 0)
1276                         suword(&job->_aiocb_private.error, error);
1277                 goto done;
1278         }
1279 no_kqueue:
1280
1281         suword(&job->_aiocb_private.error, EINPROGRESS);
1282         aiocbe->uaiocb._aiocb_private.error = EINPROGRESS;
1283         aiocbe->userproc = p;
1284         aiocbe->jobflags = 0;
1285         aiocbe->lio = lj;
1286         ki = p->p_aioinfo;
1287
1288         if (fp->f_type == DTYPE_SOCKET) {
1289                 /*
1290                  * Alternate queueing for socket ops: Reach down into the
1291                  * descriptor to get the socket data.  Then check to see if the
1292                  * socket is ready to be read or written (based on the requested
1293                  * operation).
1294                  *
1295                  * If it is not ready for io, then queue the aiocbe on the
1296                  * socket, and set the flags so we get a call when sbnotify()
1297                  * happens.
1298                  */
1299                 so = (struct socket *)fp->f_data;
1300                 s = splnet();
1301                 if (((opcode == LIO_READ) && (!soreadable(so))) || ((opcode ==
1302                     LIO_WRITE) && (!sowriteable(so)))) {
1303                         TAILQ_INSERT_TAIL(&so->so_aiojobq, aiocbe, list);
1304                         TAILQ_INSERT_TAIL(&ki->kaio_sockqueue, aiocbe, plist);
1305                         if (opcode == LIO_READ)
1306                                 so->so_rcv.sb_flags |= SB_AIO;
1307                         else
1308                                 so->so_snd.sb_flags |= SB_AIO;
1309                         aiocbe->jobstate = JOBST_JOBQGLOBAL; /* XXX */
1310                         ki->kaio_queue_count++;
1311                         num_queue_count++;
1312                         splx(s);
1313                         error = 0;
1314                         goto done;
1315                 }
1316                 splx(s);
1317         }
1318
1319         if ((error = aio_qphysio(p, aiocbe)) == 0)
1320                 goto done;
1321         if (error > 0) {
1322                 suword(&job->_aiocb_private.status, 0);
1323                 aiocbe->uaiocb._aiocb_private.error = error;
1324                 suword(&job->_aiocb_private.error, error);
1325                 goto done;
1326         }
1327
1328         /* No buffer for daemon I/O. */
1329         aiocbe->bp = NULL;
1330
1331         ki->kaio_queue_count++;
1332         if (lj)
1333                 lj->lioj_queue_count++;
1334         s = splnet();
1335         TAILQ_INSERT_TAIL(&ki->kaio_jobqueue, aiocbe, plist);
1336         TAILQ_INSERT_TAIL(&aio_jobs, aiocbe, list);
1337         splx(s);
1338         aiocbe->jobstate = JOBST_JOBQGLOBAL;
1339
1340         num_queue_count++;
1341         error = 0;
1342
1343         /*
1344          * If we don't have a free AIO process, and we are below our quota, then
1345          * start one.  Otherwise, depend on the subsequent I/O completions to
1346          * pick-up this job.  If we don't sucessfully create the new process
1347          * (thread) due to resource issues, we return an error for now (EAGAIN),
1348          * which is likely not the correct thing to do.
1349          */
1350         s = splnet();
1351 retryproc:
1352         if ((aiop = TAILQ_FIRST(&aio_freeproc)) != NULL) {
1353                 TAILQ_REMOVE(&aio_freeproc, aiop, list);
1354                 TAILQ_INSERT_TAIL(&aio_activeproc, aiop, list);
1355                 aiop->aioprocflags &= ~AIOP_FREE;
1356                 wakeup(aiop->aioproc);
1357         } else if (((num_aio_resv_start + num_aio_procs) < max_aio_procs) &&
1358             ((ki->kaio_active_count + num_aio_resv_start) <
1359             ki->kaio_maxactive_count)) {
1360                 num_aio_resv_start++;
1361                 if ((error = aio_newproc()) == 0) {
1362                         num_aio_resv_start--;
1363                         goto retryproc;
1364                 }
1365                 num_aio_resv_start--;
1366         }
1367         splx(s);
1368 done:
1369         return error;
1370 }
1371
1372 /*
1373  * This routine queues an AIO request, checking for quotas.
1374  */
1375 static int
1376 aio_aqueue(struct proc *p, struct aiocb *job, int type)
1377 {
1378         struct kaioinfo *ki;
1379
1380         if (p->p_aioinfo == NULL)
1381                 aio_init_aioinfo(p);
1382
1383         if (num_queue_count >= max_queue_count)
1384                 return EAGAIN;
1385
1386         ki = p->p_aioinfo;
1387         if (ki->kaio_queue_count >= ki->kaio_qallowed_count)
1388                 return EAGAIN;
1389
1390         return _aio_aqueue(p, job, NULL, type);
1391 }
1392 #endif /* VFS_AIO */
1393
1394 /*
1395  * Support the aio_return system call, as a side-effect, kernel resources are
1396  * released.
1397  */
1398 int
1399 aio_return(struct proc *p, struct aio_return_args *uap)
1400 {
1401 #ifndef VFS_AIO
1402         return ENOSYS;
1403 #else
1404         int s;
1405         long jobref;
1406         struct aiocblist *cb, *ncb;
1407         struct aiocb *ujob;
1408         struct kaioinfo *ki;
1409
1410         ki = p->p_aioinfo;
1411         if (ki == NULL)
1412                 return EINVAL;
1413
1414         ujob = uap->aiocbp;
1415
1416         jobref = fuword(&ujob->_aiocb_private.kernelinfo);
1417         if (jobref == -1 || jobref == 0)
1418                 return EINVAL;
1419
1420         TAILQ_FOREACH(cb, &ki->kaio_jobdone, plist) {
1421                 if (((intptr_t) cb->uaiocb._aiocb_private.kernelinfo) ==
1422                     jobref) {
1423                         if (ujob == cb->uuaiocb) {
1424                                 p->p_retval[0] =
1425                                     cb->uaiocb._aiocb_private.status;
1426                         } else
1427                                 p->p_retval[0] = EFAULT;
1428                         if (cb->uaiocb.aio_lio_opcode == LIO_WRITE) {
1429                                 p->p_stats->p_ru.ru_oublock +=
1430                                     cb->outputcharge;
1431                                 cb->outputcharge = 0;
1432                         } else if (cb->uaiocb.aio_lio_opcode == LIO_READ) {
1433                                 p->p_stats->p_ru.ru_inblock += cb->inputcharge;
1434                                 cb->inputcharge = 0;
1435                         }
1436                         aio_free_entry(cb);
1437                         return 0;
1438                 }
1439         }
1440         s = splbio();
1441         for (cb = TAILQ_FIRST(&ki->kaio_bufdone); cb; cb = ncb) {
1442                 ncb = TAILQ_NEXT(cb, plist);
1443                 if (((intptr_t) cb->uaiocb._aiocb_private.kernelinfo)
1444                     == jobref) {
1445                         splx(s);
1446                         if (ujob == cb->uuaiocb) {
1447                                 p->p_retval[0] =
1448                                     cb->uaiocb._aiocb_private.status;
1449                         } else
1450                                 p->p_retval[0] = EFAULT;
1451                         aio_free_entry(cb);
1452                         return 0;
1453                 }
1454         }
1455         splx(s);
1456
1457         return (EINVAL);
1458 #endif /* VFS_AIO */
1459 }
1460
1461 /*
1462  * Allow a process to wakeup when any of the I/O requests are completed.
1463  */
1464 int
1465 aio_suspend(struct proc *p, struct aio_suspend_args *uap)
1466 {
1467 #ifndef VFS_AIO
1468         return ENOSYS;
1469 #else
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, s, 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(&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                 s = splbio();
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                                         splx(s);
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, PRIBIO | PCATCH, "aiospn", timo);
1558                 splx(s);
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 proc *p, struct aio_cancel_args *uap)
1582 {
1583 #ifndef VFS_AIO
1584         return ENOSYS;
1585 #else
1586         struct kaioinfo *ki;
1587         struct aiocblist *cbe, *cbn;
1588         struct file *fp;
1589         struct filedesc *fdp;
1590         struct socket *so;
1591         struct proc *po;
1592         int s,error;
1593         int cancelled=0;
1594         int notcancelled=0;
1595         struct vnode *vp;
1596
1597         fdp = p->p_fd;
1598         if ((u_int)uap->fd >= fdp->fd_nfiles ||
1599             (fp = fdp->fd_ofiles[uap->fd]) == NULL)
1600                 return (EBADF);
1601
1602         if (fp->f_type == DTYPE_VNODE) {
1603                 vp = (struct vnode *)fp->f_data;
1604                 
1605                 if (vn_isdisk(vp,&error)) {
1606                         p->p_retval[0] = AIO_NOTCANCELED;
1607                         return 0;
1608                 }
1609         } else if (fp->f_type == DTYPE_SOCKET) {
1610                 so = (struct socket *)fp->f_data;
1611
1612                 s = splnet();
1613
1614                 for (cbe = TAILQ_FIRST(&so->so_aiojobq); cbe; cbe = cbn) {
1615                         cbn = TAILQ_NEXT(cbe, list);
1616                         if ((uap->aiocbp == NULL) ||
1617                                 (uap->aiocbp == cbe->uuaiocb) ) {
1618                                 po = cbe->userproc;
1619                                 ki = po->p_aioinfo;
1620                                 TAILQ_REMOVE(&so->so_aiojobq, cbe, list);
1621                                 TAILQ_REMOVE(&ki->kaio_sockqueue, cbe, plist);
1622                                 TAILQ_INSERT_TAIL(&ki->kaio_jobdone, cbe, plist);
1623                                 if (ki->kaio_flags & KAIO_WAKEUP) {
1624                                         wakeup(po);
1625                                 }
1626                                 cbe->jobstate = JOBST_JOBFINISHED;
1627                                 cbe->uaiocb._aiocb_private.status=-1;
1628                                 cbe->uaiocb._aiocb_private.error=ECANCELED;
1629                                 cancelled++;
1630 /* XXX cancelled, knote? */
1631                                 if (cbe->uaiocb.aio_sigevent.sigev_notify ==
1632                                     SIGEV_SIGNAL)
1633                                         psignal(cbe->userproc, cbe->uaiocb.aio_sigevent.sigev_signo);
1634                                 if (uap->aiocbp) 
1635                                         break;
1636                         }
1637                 }
1638                 splx(s);
1639
1640                 if ((cancelled) && (uap->aiocbp)) {
1641                         p->p_retval[0] = AIO_CANCELED;
1642                         return 0;
1643                 }
1644         }
1645         ki=p->p_aioinfo;
1646         if (ki == NULL)
1647                 goto done;
1648         s = splnet();
1649
1650         for (cbe = TAILQ_FIRST(&ki->kaio_jobqueue); cbe; cbe = cbn) {
1651                 cbn = TAILQ_NEXT(cbe, plist);
1652
1653                 if ((uap->fd == cbe->uaiocb.aio_fildes) &&
1654                     ((uap->aiocbp == NULL ) || 
1655                      (uap->aiocbp == cbe->uuaiocb))) {
1656                         
1657                         if (cbe->jobstate == JOBST_JOBQGLOBAL) {
1658                                 TAILQ_REMOVE(&aio_jobs, cbe, list);
1659                                 TAILQ_REMOVE(&ki->kaio_jobqueue, cbe, plist);
1660                                 TAILQ_INSERT_TAIL(&ki->kaio_jobdone, cbe,
1661                                     plist);
1662                                 cancelled++;
1663                                 ki->kaio_queue_finished_count++;
1664                                 cbe->jobstate = JOBST_JOBFINISHED;
1665                                 cbe->uaiocb._aiocb_private.status = -1;
1666                                 cbe->uaiocb._aiocb_private.error = ECANCELED;
1667 /* XXX cancelled, knote? */
1668                                 if (cbe->uaiocb.aio_sigevent.sigev_notify ==
1669                                     SIGEV_SIGNAL)
1670                                         psignal(cbe->userproc, cbe->uaiocb.aio_sigevent.sigev_signo);
1671                         } else {
1672                                 notcancelled++;
1673                         }
1674                 }
1675         }
1676         splx(s);
1677 done:
1678         if (notcancelled) {
1679                 p->p_retval[0] = AIO_NOTCANCELED;
1680                 return 0;
1681         }
1682         if (cancelled) {
1683                 p->p_retval[0] = AIO_CANCELED;
1684                 return 0;
1685         }
1686         p->p_retval[0] = AIO_ALLDONE;
1687
1688         return 0;
1689 #endif /* VFS_AIO */
1690 }
1691
1692 /*
1693  * aio_error is implemented in the kernel level for compatibility purposes only.
1694  * For a user mode async implementation, it would be best to do it in a userland
1695  * subroutine.
1696  */
1697 int
1698 aio_error(struct proc *p, struct aio_error_args *uap)
1699 {
1700 #ifndef VFS_AIO
1701         return ENOSYS;
1702 #else
1703         int s;
1704         struct aiocblist *cb;
1705         struct kaioinfo *ki;
1706         long jobref;
1707
1708         ki = p->p_aioinfo;
1709         if (ki == NULL)
1710                 return EINVAL;
1711
1712         jobref = fuword(&uap->aiocbp->_aiocb_private.kernelinfo);
1713         if ((jobref == -1) || (jobref == 0))
1714                 return EINVAL;
1715
1716         TAILQ_FOREACH(cb, &ki->kaio_jobdone, plist) {
1717                 if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1718                     jobref) {
1719                         p->p_retval[0] = cb->uaiocb._aiocb_private.error;
1720                         return 0;
1721                 }
1722         }
1723
1724         s = splnet();
1725
1726         for (cb = TAILQ_FIRST(&ki->kaio_jobqueue); cb; cb = TAILQ_NEXT(cb,
1727             plist)) {
1728                 if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1729                     jobref) {
1730                         p->p_retval[0] = EINPROGRESS;
1731                         splx(s);
1732                         return 0;
1733                 }
1734         }
1735
1736         for (cb = TAILQ_FIRST(&ki->kaio_sockqueue); cb; cb = TAILQ_NEXT(cb,
1737             plist)) {
1738                 if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1739                     jobref) {
1740                         p->p_retval[0] = EINPROGRESS;
1741                         splx(s);
1742                         return 0;
1743                 }
1744         }
1745         splx(s);
1746
1747         s = splbio();
1748         for (cb = TAILQ_FIRST(&ki->kaio_bufdone); cb; cb = TAILQ_NEXT(cb,
1749             plist)) {
1750                 if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1751                     jobref) {
1752                         p->p_retval[0] = cb->uaiocb._aiocb_private.error;
1753                         splx(s);
1754                         return 0;
1755                 }
1756         }
1757
1758         for (cb = TAILQ_FIRST(&ki->kaio_bufqueue); cb; cb = TAILQ_NEXT(cb,
1759             plist)) {
1760                 if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo) ==
1761                     jobref) {
1762                         p->p_retval[0] = EINPROGRESS;
1763                         splx(s);
1764                         return 0;
1765                 }
1766         }
1767         splx(s);
1768
1769 #if (0)
1770         /*
1771          * Hack for lio.
1772          */
1773         status = fuword(&uap->aiocbp->_aiocb_private.status);
1774         if (status == -1)
1775                 return fuword(&uap->aiocbp->_aiocb_private.error);
1776 #endif
1777         return EINVAL;
1778 #endif /* VFS_AIO */
1779 }
1780
1781 /* syscall - asynchronous read from a file (REALTIME) */
1782 int
1783 aio_read(struct proc *p, struct aio_read_args *uap)
1784 {
1785 #ifndef VFS_AIO
1786         return ENOSYS;
1787 #else
1788         return aio_aqueue(p, uap->aiocbp, LIO_READ);
1789 #endif /* VFS_AIO */
1790 }
1791
1792 /* syscall - asynchronous write to a file (REALTIME) */
1793 int
1794 aio_write(struct proc *p, struct aio_write_args *uap)
1795 {
1796 #ifndef VFS_AIO
1797         return ENOSYS;
1798 #else
1799         return aio_aqueue(p, uap->aiocbp, LIO_WRITE);
1800 #endif /* VFS_AIO */
1801 }
1802
1803 /* syscall - XXX undocumented */
1804 int
1805 lio_listio(struct proc *p, struct lio_listio_args *uap)
1806 {
1807 #ifndef VFS_AIO
1808         return ENOSYS;
1809 #else
1810         int nent, nentqueued;
1811         struct aiocb *iocb, * const *cbptr;
1812         struct aiocblist *cb;
1813         struct kaioinfo *ki;
1814         struct aio_liojob *lj;
1815         int error, runningcode;
1816         int nerror;
1817         int i;
1818         int s;
1819
1820         if ((uap->mode != LIO_NOWAIT) && (uap->mode != LIO_WAIT))
1821                 return EINVAL;
1822
1823         nent = uap->nent;
1824         if (nent > AIO_LISTIO_MAX)
1825                 return EINVAL;
1826
1827         if (p->p_aioinfo == NULL)
1828                 aio_init_aioinfo(p);
1829
1830         if ((nent + num_queue_count) > max_queue_count)
1831                 return EAGAIN;
1832
1833         ki = p->p_aioinfo;
1834         if ((nent + ki->kaio_queue_count) > ki->kaio_qallowed_count)
1835                 return EAGAIN;
1836
1837         lj = zalloc(aiolio_zone);
1838         if (!lj)
1839                 return EAGAIN;
1840
1841         lj->lioj_flags = 0;
1842         lj->lioj_buffer_count = 0;
1843         lj->lioj_buffer_finished_count = 0;
1844         lj->lioj_queue_count = 0;
1845         lj->lioj_queue_finished_count = 0;
1846         lj->lioj_ki = ki;
1847
1848         /*
1849          * Setup signal.
1850          */
1851         if (uap->sig && (uap->mode == LIO_NOWAIT)) {
1852                 error = copyin(uap->sig, &lj->lioj_signal,
1853                     sizeof(lj->lioj_signal));
1854                 if (error) {
1855                         zfree(aiolio_zone, lj);
1856                         return error;
1857                 }
1858                 if (!_SIG_VALID(lj->lioj_signal.sigev_signo)) {
1859                         zfree(aiolio_zone, lj);
1860                         return EINVAL;
1861                 }
1862                 lj->lioj_flags |= LIOJ_SIGNAL;
1863                 lj->lioj_flags &= ~LIOJ_SIGNAL_POSTED;
1864         } else
1865                 lj->lioj_flags &= ~LIOJ_SIGNAL;
1866
1867         TAILQ_INSERT_TAIL(&ki->kaio_liojoblist, lj, lioj_list);
1868         /*
1869          * Get pointers to the list of I/O requests.
1870          */
1871         nerror = 0;
1872         nentqueued = 0;
1873         cbptr = uap->acb_list;
1874         for (i = 0; i < uap->nent; i++) {
1875                 iocb = (struct aiocb *)(intptr_t)fuword(&cbptr[i]);
1876                 if (((intptr_t)iocb != -1) && ((intptr_t)iocb != 0)) {
1877                         error = _aio_aqueue(p, iocb, lj, 0);
1878                         if (error == 0)
1879                                 nentqueued++;
1880                         else
1881                                 nerror++;
1882                 }
1883         }
1884
1885         /*
1886          * If we haven't queued any, then just return error.
1887          */
1888         if (nentqueued == 0)
1889                 return 0;
1890
1891         /*
1892          * Calculate the appropriate error return.
1893          */
1894         runningcode = 0;
1895         if (nerror)
1896                 runningcode = EIO;
1897
1898         if (uap->mode == LIO_WAIT) {
1899                 int command, found, jobref;
1900                 
1901                 for (;;) {
1902                         found = 0;
1903                         for (i = 0; i < uap->nent; i++) {
1904                                 /*
1905                                  * Fetch address of the control buf pointer in
1906                                  * user space.
1907                                  */
1908                                 iocb = (struct aiocb *)
1909                                     (intptr_t)fuword(&cbptr[i]);
1910                                 if (((intptr_t)iocb == -1) || ((intptr_t)iocb
1911                                     == 0))
1912                                         continue;
1913
1914                                 /*
1915                                  * Fetch the associated command from user space.
1916                                  */
1917                                 command = fuword(&iocb->aio_lio_opcode);
1918                                 if (command == LIO_NOP) {
1919                                         found++;
1920                                         continue;
1921                                 }
1922
1923                                 jobref = fuword(&iocb->_aiocb_private.kernelinfo);
1924
1925                                 TAILQ_FOREACH(cb, &ki->kaio_jobdone, plist) {
1926                                         if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo)
1927                                             == jobref) {
1928                                                 if (cb->uaiocb.aio_lio_opcode
1929                                                     == LIO_WRITE) {
1930                                                         p->p_stats->p_ru.ru_oublock
1931                                                             +=
1932                                                             cb->outputcharge;
1933                                                         cb->outputcharge = 0;
1934                                                 } else if (cb->uaiocb.aio_lio_opcode
1935                                                     == LIO_READ) {
1936                                                         p->p_stats->p_ru.ru_inblock
1937                                                             += cb->inputcharge;
1938                                                         cb->inputcharge = 0;
1939                                                 }
1940                                                 found++;
1941                                                 break;
1942                                         }
1943                                 }
1944
1945                                 s = splbio();
1946                                 TAILQ_FOREACH(cb, &ki->kaio_bufdone, plist) {
1947                                         if (((intptr_t)cb->uaiocb._aiocb_private.kernelinfo)
1948                                             == jobref) {
1949                                                 found++;
1950                                                 break;
1951                                         }
1952                                 }
1953                                 splx(s);
1954                         }
1955
1956                         /*
1957                          * If all I/Os have been disposed of, then we can
1958                          * return.
1959                          */
1960                         if (found == nentqueued)
1961                                 return runningcode;
1962                         
1963                         ki->kaio_flags |= KAIO_WAKEUP;
1964                         error = tsleep(p, PRIBIO | PCATCH, "aiospn", 0);
1965
1966                         if (error == EINTR)
1967                                 return EINTR;
1968                         else if (error == EWOULDBLOCK)
1969                                 return EAGAIN;
1970                 }
1971         }
1972
1973         return runningcode;
1974 #endif /* VFS_AIO */
1975 }
1976
1977 #ifdef VFS_AIO
1978 /*
1979  * This is a weird hack so that we can post a signal.  It is safe to do so from
1980  * a timeout routine, but *not* from an interrupt routine.
1981  */
1982 static void
1983 process_signal(void *aioj)
1984 {
1985         struct aiocblist *aiocbe = aioj;
1986         struct aio_liojob *lj = aiocbe->lio;
1987         struct aiocb *cb = &aiocbe->uaiocb;
1988
1989         if ((lj) && (lj->lioj_signal.sigev_notify == SIGEV_SIGNAL) &&
1990             (lj->lioj_queue_count == lj->lioj_queue_finished_count)) {
1991                 psignal(lj->lioj_ki->kaio_p, lj->lioj_signal.sigev_signo);
1992                 lj->lioj_flags |= LIOJ_SIGNAL_POSTED;
1993         }
1994
1995         if (cb->aio_sigevent.sigev_notify == SIGEV_SIGNAL)
1996                 psignal(aiocbe->userproc, cb->aio_sigevent.sigev_signo);
1997 }
1998
1999 /*
2000  * Interrupt handler for physio, performs the necessary process wakeups, and
2001  * signals.
2002  */
2003 static void
2004 aio_physwakeup(struct buf *bp)
2005 {
2006         struct aiocblist *aiocbe;
2007         struct proc *p;
2008         struct kaioinfo *ki;
2009         struct aio_liojob *lj;
2010
2011         wakeup(bp);
2012
2013         aiocbe = (struct aiocblist *)bp->b_spc;
2014         if (aiocbe) {
2015                 p = bp->b_caller1;
2016
2017                 aiocbe->jobstate = JOBST_JOBBFINISHED;
2018                 aiocbe->uaiocb._aiocb_private.status -= bp->b_resid;
2019                 aiocbe->uaiocb._aiocb_private.error = 0;
2020                 aiocbe->jobflags |= AIOCBLIST_DONE;
2021
2022                 if (bp->b_flags & B_ERROR)
2023                         aiocbe->uaiocb._aiocb_private.error = bp->b_error;
2024
2025                 lj = aiocbe->lio;
2026                 if (lj) {
2027                         lj->lioj_buffer_finished_count++;
2028                         
2029                         /*
2030                          * wakeup/signal if all of the interrupt jobs are done.
2031                          */
2032                         if (lj->lioj_buffer_finished_count ==
2033                             lj->lioj_buffer_count) {
2034                                 /*
2035                                  * Post a signal if it is called for.
2036                                  */
2037                                 if ((lj->lioj_flags &
2038                                     (LIOJ_SIGNAL|LIOJ_SIGNAL_POSTED)) ==
2039                                     LIOJ_SIGNAL) {
2040                                         lj->lioj_flags |= LIOJ_SIGNAL_POSTED;
2041                                         aiocbe->timeouthandle =
2042                                                 timeout(process_signal,
2043                                                         aiocbe, 0);
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                         aiocbe->timeouthandle =
2065                                 timeout(process_signal, aiocbe, 0);
2066         }
2067 }
2068 #endif /* VFS_AIO */
2069
2070 /* syscall - wait for the next completion of an aio request */
2071 int
2072 aio_waitcomplete(struct proc *p, struct aio_waitcomplete_args *uap)
2073 {
2074 #ifndef VFS_AIO
2075         return ENOSYS;
2076 #else
2077         struct timeval atv;
2078         struct timespec ts;
2079         struct kaioinfo *ki;
2080         struct aiocblist *cb = NULL;
2081         int error, s, timo;
2082         
2083         suword(uap->aiocbp, (int)NULL);
2084
2085         timo = 0;
2086         if (uap->timeout) {
2087                 /* Get timespec struct. */
2088                 error = copyin(uap->timeout, &ts, sizeof(ts));
2089                 if (error)
2090                         return error;
2091
2092                 if ((ts.tv_nsec < 0) || (ts.tv_nsec >= 1000000000))
2093                         return (EINVAL);
2094
2095                 TIMESPEC_TO_TIMEVAL(&atv, &ts);
2096                 if (itimerfix(&atv))
2097                         return (EINVAL);
2098                 timo = tvtohz(&atv);
2099         }
2100
2101         ki = p->p_aioinfo;
2102         if (ki == NULL)
2103                 return EAGAIN;
2104
2105         for (;;) {
2106                 if ((cb = TAILQ_FIRST(&ki->kaio_jobdone)) != 0) {
2107                         suword(uap->aiocbp, (uintptr_t)cb->uuaiocb);
2108                         p->p_retval[0] = cb->uaiocb._aiocb_private.status;
2109                         if (cb->uaiocb.aio_lio_opcode == LIO_WRITE) {
2110                                 p->p_stats->p_ru.ru_oublock +=
2111                                     cb->outputcharge;
2112                                 cb->outputcharge = 0;
2113                         } else if (cb->uaiocb.aio_lio_opcode == LIO_READ) {
2114                                 p->p_stats->p_ru.ru_inblock += cb->inputcharge;
2115                                 cb->inputcharge = 0;
2116                         }
2117                         aio_free_entry(cb);
2118                         return cb->uaiocb._aiocb_private.error;
2119                 }
2120
2121                 s = splbio();
2122                 if ((cb = TAILQ_FIRST(&ki->kaio_bufdone)) != 0 ) {
2123                         splx(s);
2124                         suword(uap->aiocbp, (uintptr_t)cb->uuaiocb);
2125                         p->p_retval[0] = cb->uaiocb._aiocb_private.status;
2126                         aio_free_entry(cb);
2127                         return cb->uaiocb._aiocb_private.error;
2128                 }
2129
2130                 ki->kaio_flags |= KAIO_WAKEUP;
2131                 error = tsleep(p, PRIBIO | PCATCH, "aiowc", timo);
2132                 splx(s);
2133
2134                 if (error == ERESTART)
2135                         return EINTR;
2136                 else if (error < 0)
2137                         return error;
2138                 else if (error == EINTR)
2139                         return EINTR;
2140                 else if (error == EWOULDBLOCK)
2141                         return EAGAIN;
2142         }
2143 #endif /* VFS_AIO */
2144 }
2145
2146 #ifndef VFS_AIO
2147 static int
2148 filt_aioattach(struct knote *kn)
2149 {
2150
2151         return (ENXIO);
2152 }
2153
2154 struct filterops aio_filtops =
2155         { 0, filt_aioattach, NULL, NULL };
2156
2157 #else
2158 /* kqueue attach function */
2159 static int
2160 filt_aioattach(struct knote *kn)
2161 {
2162         struct aiocblist *aiocbe = (struct aiocblist *)kn->kn_sdata;
2163
2164         /*
2165          * The aiocbe pointer must be validated before using it, so
2166          * registration is restricted to the kernel; the user cannot
2167          * set EV_FLAG1.
2168          */
2169         if ((kn->kn_flags & EV_FLAG1) == 0)
2170                 return (EPERM);
2171         kn->kn_flags &= ~EV_FLAG1;
2172
2173         SLIST_INSERT_HEAD(&aiocbe->klist, kn, kn_selnext);
2174
2175         return (0);
2176 }
2177
2178 /* kqueue detach function */
2179 static void
2180 filt_aiodetach(struct knote *kn)
2181 {
2182         struct aiocblist *aiocbe = (struct aiocblist *)kn->kn_sdata;
2183
2184         SLIST_REMOVE(&aiocbe->klist, kn, knote, kn_selnext);
2185 }
2186
2187 /* kqueue filter function */
2188 /*ARGSUSED*/
2189 static int
2190 filt_aio(struct knote *kn, long hint)
2191 {
2192         struct aiocblist *aiocbe = (struct aiocblist *)kn->kn_sdata;
2193
2194         kn->kn_data = aiocbe->uaiocb._aiocb_private.error;
2195         if (aiocbe->jobstate != JOBST_JOBFINISHED &&
2196             aiocbe->jobstate != JOBST_JOBBFINISHED)
2197                 return (0);
2198         kn->kn_flags |= EV_EOF; 
2199         return (1);
2200 }
2201
2202 struct filterops aio_filtops =
2203         { 0, filt_aioattach, filt_aiodetach, filt_aio };
2204 #endif /* VFS_AIO */