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