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