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