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