]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sys/kern/vfs_aio.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.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 "opt_compat.h"
25
26 #include <sys/param.h>
27 #include <sys/systm.h>
28 #include <sys/malloc.h>
29 #include <sys/bio.h>
30 #include <sys/buf.h>
31 #include <sys/eventhandler.h>
32 #include <sys/sysproto.h>
33 #include <sys/filedesc.h>
34 #include <sys/kernel.h>
35 #include <sys/module.h>
36 #include <sys/kthread.h>
37 #include <sys/fcntl.h>
38 #include <sys/file.h>
39 #include <sys/limits.h>
40 #include <sys/lock.h>
41 #include <sys/mutex.h>
42 #include <sys/unistd.h>
43 #include <sys/posix4.h>
44 #include <sys/proc.h>
45 #include <sys/resourcevar.h>
46 #include <sys/signalvar.h>
47 #include <sys/protosw.h>
48 #include <sys/sema.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/syscall.h>
52 #include <sys/sysent.h>
53 #include <sys/sysctl.h>
54 #include <sys/sx.h>
55 #include <sys/taskqueue.h>
56 #include <sys/vnode.h>
57 #include <sys/conf.h>
58 #include <sys/event.h>
59 #include <sys/mount.h>
60
61 #include <machine/atomic.h>
62
63 #include <vm/vm.h>
64 #include <vm/vm_extern.h>
65 #include <vm/pmap.h>
66 #include <vm/vm_map.h>
67 #include <vm/vm_object.h>
68 #include <vm/uma.h>
69 #include <sys/aio.h>
70
71 #include "opt_vfs_aio.h"
72
73 /*
74  * Counter for allocating reference ids to new jobs.  Wrapped to 1 on
75  * overflow. (XXX will be removed soon.)
76  */
77 static u_long jobrefid;
78
79 /*
80  * Counter for aio_fsync.
81  */
82 static uint64_t jobseqno;
83
84 #define JOBST_NULL              0
85 #define JOBST_JOBQSOCK          1
86 #define JOBST_JOBQGLOBAL        2
87 #define JOBST_JOBRUNNING        3
88 #define JOBST_JOBFINISHED       4
89 #define JOBST_JOBQBUF           5
90 #define JOBST_JOBQSYNC          6
91
92 #ifndef MAX_AIO_PER_PROC
93 #define MAX_AIO_PER_PROC        32
94 #endif
95
96 #ifndef MAX_AIO_QUEUE_PER_PROC
97 #define MAX_AIO_QUEUE_PER_PROC  256 /* Bigger than AIO_LISTIO_MAX */
98 #endif
99
100 #ifndef MAX_AIO_PROCS
101 #define MAX_AIO_PROCS           32
102 #endif
103
104 #ifndef MAX_AIO_QUEUE
105 #define MAX_AIO_QUEUE           1024 /* Bigger than AIO_LISTIO_MAX */
106 #endif
107
108 #ifndef TARGET_AIO_PROCS
109 #define TARGET_AIO_PROCS        4
110 #endif
111
112 #ifndef MAX_BUF_AIO
113 #define MAX_BUF_AIO             16
114 #endif
115
116 #ifndef AIOD_TIMEOUT_DEFAULT
117 #define AIOD_TIMEOUT_DEFAULT    (10 * hz)
118 #endif
119
120 #ifndef AIOD_LIFETIME_DEFAULT
121 #define AIOD_LIFETIME_DEFAULT   (30 * hz)
122 #endif
123
124 FEATURE(aio, "Asynchronous I/O");
125
126 static MALLOC_DEFINE(M_LIO, "lio", "listio aio control block list");
127
128 static SYSCTL_NODE(_vfs, OID_AUTO, aio, CTLFLAG_RW, 0, "Async IO management");
129
130 static int max_aio_procs = MAX_AIO_PROCS;
131 SYSCTL_INT(_vfs_aio, OID_AUTO, max_aio_procs,
132         CTLFLAG_RW, &max_aio_procs, 0,
133         "Maximum number of kernel threads to use for handling async IO ");
134
135 static int num_aio_procs = 0;
136 SYSCTL_INT(_vfs_aio, OID_AUTO, num_aio_procs,
137         CTLFLAG_RD, &num_aio_procs, 0,
138         "Number of presently active kernel threads for async IO");
139
140 /*
141  * The code will adjust the actual number of AIO processes towards this
142  * number when it gets a chance.
143  */
144 static int target_aio_procs = TARGET_AIO_PROCS;
145 SYSCTL_INT(_vfs_aio, OID_AUTO, target_aio_procs, CTLFLAG_RW, &target_aio_procs,
146         0, "Preferred number of ready kernel threads for async IO");
147
148 static int max_queue_count = MAX_AIO_QUEUE;
149 SYSCTL_INT(_vfs_aio, OID_AUTO, max_aio_queue, CTLFLAG_RW, &max_queue_count, 0,
150     "Maximum number of aio requests to queue, globally");
151
152 static int num_queue_count = 0;
153 SYSCTL_INT(_vfs_aio, OID_AUTO, num_queue_count, CTLFLAG_RD, &num_queue_count, 0,
154     "Number of queued aio requests");
155
156 static int num_buf_aio = 0;
157 SYSCTL_INT(_vfs_aio, OID_AUTO, num_buf_aio, CTLFLAG_RD, &num_buf_aio, 0,
158     "Number of aio requests presently handled by the buf subsystem");
159
160 /* Number of async I/O thread in the process of being started */
161 /* XXX This should be local to aio_aqueue() */
162 static int num_aio_resv_start = 0;
163
164 static int aiod_timeout;
165 SYSCTL_INT(_vfs_aio, OID_AUTO, aiod_timeout, CTLFLAG_RW, &aiod_timeout, 0,
166     "Timeout value for synchronous aio operations");
167
168 static int aiod_lifetime;
169 SYSCTL_INT(_vfs_aio, OID_AUTO, aiod_lifetime, CTLFLAG_RW, &aiod_lifetime, 0,
170     "Maximum lifetime for idle aiod");
171
172 static int unloadable = 0;
173 SYSCTL_INT(_vfs_aio, OID_AUTO, unloadable, CTLFLAG_RW, &unloadable, 0,
174     "Allow unload of aio (not recommended)");
175
176
177 static int max_aio_per_proc = MAX_AIO_PER_PROC;
178 SYSCTL_INT(_vfs_aio, OID_AUTO, max_aio_per_proc, CTLFLAG_RW, &max_aio_per_proc,
179     0, "Maximum active aio requests per process (stored in the process)");
180
181 static int max_aio_queue_per_proc = MAX_AIO_QUEUE_PER_PROC;
182 SYSCTL_INT(_vfs_aio, OID_AUTO, max_aio_queue_per_proc, CTLFLAG_RW,
183     &max_aio_queue_per_proc, 0,
184     "Maximum queued aio requests per process (stored in the process)");
185
186 static int max_buf_aio = MAX_BUF_AIO;
187 SYSCTL_INT(_vfs_aio, OID_AUTO, max_buf_aio, CTLFLAG_RW, &max_buf_aio, 0,
188     "Maximum buf aio requests per process (stored in the process)");
189
190 typedef struct oaiocb {
191         int     aio_fildes;             /* File descriptor */
192         off_t   aio_offset;             /* File offset for I/O */
193         volatile void *aio_buf;         /* I/O buffer in process space */
194         size_t  aio_nbytes;             /* Number of bytes for I/O */
195         struct  osigevent aio_sigevent; /* Signal to deliver */
196         int     aio_lio_opcode;         /* LIO opcode */
197         int     aio_reqprio;            /* Request priority -- ignored */
198         struct  __aiocb_private _aiocb_private;
199 } oaiocb_t;
200
201 /*
202  * Below is a key of locks used to protect each member of struct aiocblist
203  * aioliojob and kaioinfo and any backends.
204  *
205  * * - need not protected
206  * a - locked by kaioinfo lock
207  * b - locked by backend lock, the backend lock can be null in some cases,
208  *     for example, BIO belongs to this type, in this case, proc lock is
209  *     reused.
210  * c - locked by aio_job_mtx, the lock for the generic file I/O backend.
211  */
212
213 /*
214  * Current, there is only two backends: BIO and generic file I/O.
215  * socket I/O is served by generic file I/O, this is not a good idea, since
216  * disk file I/O and any other types without O_NONBLOCK flag can block daemon
217  * threads, if there is no thread to serve socket I/O, the socket I/O will be
218  * delayed too long or starved, we should create some threads dedicated to
219  * sockets to do non-blocking I/O, same for pipe and fifo, for these I/O
220  * systems we really need non-blocking interface, fiddling O_NONBLOCK in file
221  * structure is not safe because there is race between userland and aio
222  * daemons.
223  */
224
225 struct aiocblist {
226         TAILQ_ENTRY(aiocblist) list;    /* (b) internal list of for backend */
227         TAILQ_ENTRY(aiocblist) plist;   /* (a) list of jobs for each backend */
228         TAILQ_ENTRY(aiocblist) allist;  /* (a) list of all jobs in proc */
229         int     jobflags;               /* (a) job flags */
230         int     jobstate;               /* (b) job state */
231         int     inputcharge;            /* (*) input blockes */
232         int     outputcharge;           /* (*) output blockes */
233         struct  buf *bp;                /* (*) private to BIO backend,
234                                          * buffer pointer
235                                          */
236         struct  proc *userproc;         /* (*) user process */
237         struct  ucred *cred;            /* (*) active credential when created */
238         struct  file *fd_file;          /* (*) pointer to file structure */
239         struct  aioliojob *lio;         /* (*) optional lio job */
240         struct  aiocb *uuaiocb;         /* (*) pointer in userspace of aiocb */
241         struct  knlist klist;           /* (a) list of knotes */
242         struct  aiocb uaiocb;           /* (*) kernel I/O control block */
243         ksiginfo_t ksi;                 /* (a) realtime signal info */
244         struct  task biotask;           /* (*) private to BIO backend */
245         uint64_t seqno;                 /* (*) job number */
246         int     pending;                /* (a) number of pending I/O, aio_fsync only */
247 };
248
249 /* jobflags */
250 #define AIOCBLIST_DONE          0x01
251 #define AIOCBLIST_BUFDONE       0x02
252 #define AIOCBLIST_RUNDOWN       0x04
253 #define AIOCBLIST_CHECKSYNC     0x08
254
255 /*
256  * AIO process info
257  */
258 #define AIOP_FREE       0x1                     /* proc on free queue */
259
260 struct aiothreadlist {
261         int aiothreadflags;                     /* (c) AIO proc flags */
262         TAILQ_ENTRY(aiothreadlist) list;        /* (c) list of processes */
263         struct thread *aiothread;               /* (*) the AIO thread */
264 };
265
266 /*
267  * data-structure for lio signal management
268  */
269 struct aioliojob {
270         int     lioj_flags;                     /* (a) listio flags */
271         int     lioj_count;                     /* (a) listio flags */
272         int     lioj_finished_count;            /* (a) listio flags */
273         struct  sigevent lioj_signal;           /* (a) signal on all I/O done */
274         TAILQ_ENTRY(aioliojob) lioj_list;       /* (a) lio list */
275         struct  knlist klist;                   /* (a) list of knotes */
276         ksiginfo_t lioj_ksi;                    /* (a) Realtime signal info */
277 };
278
279 #define LIOJ_SIGNAL             0x1     /* signal on all done (lio) */
280 #define LIOJ_SIGNAL_POSTED      0x2     /* signal has been posted */
281 #define LIOJ_KEVENT_POSTED      0x4     /* kevent triggered */
282
283 /*
284  * per process aio data structure
285  */
286 struct kaioinfo {
287         struct mtx      kaio_mtx;       /* the lock to protect this struct */
288         int     kaio_flags;             /* (a) per process kaio flags */
289         int     kaio_maxactive_count;   /* (*) maximum number of AIOs */
290         int     kaio_active_count;      /* (c) number of currently used AIOs */
291         int     kaio_qallowed_count;    /* (*) maxiumu size of AIO queue */
292         int     kaio_count;             /* (a) size of AIO queue */
293         int     kaio_ballowed_count;    /* (*) maximum number of buffers */
294         int     kaio_buffer_count;      /* (a) number of physio buffers */
295         TAILQ_HEAD(,aiocblist) kaio_all;        /* (a) all AIOs in the process */
296         TAILQ_HEAD(,aiocblist) kaio_done;       /* (a) done queue for process */
297         TAILQ_HEAD(,aioliojob) kaio_liojoblist; /* (a) list of lio jobs */
298         TAILQ_HEAD(,aiocblist) kaio_jobqueue;   /* (a) job queue for process */
299         TAILQ_HEAD(,aiocblist) kaio_bufqueue;   /* (a) buffer job queue for process */
300         TAILQ_HEAD(,aiocblist) kaio_sockqueue;  /* (a) queue for aios waiting on sockets,
301                                                  *  NOT USED YET.
302                                                  */
303         TAILQ_HEAD(,aiocblist) kaio_syncqueue;  /* (a) queue for aio_fsync */
304         struct  task    kaio_task;      /* (*) task to kick aio threads */
305 };
306
307 #define AIO_LOCK(ki)            mtx_lock(&(ki)->kaio_mtx)
308 #define AIO_UNLOCK(ki)          mtx_unlock(&(ki)->kaio_mtx)
309 #define AIO_LOCK_ASSERT(ki, f)  mtx_assert(&(ki)->kaio_mtx, (f))
310 #define AIO_MTX(ki)             (&(ki)->kaio_mtx)
311
312 #define KAIO_RUNDOWN    0x1     /* process is being run down */
313 #define KAIO_WAKEUP     0x2     /* wakeup process when there is a significant event */
314
315 /*
316  * Operations used to interact with userland aio control blocks.
317  * Different ABIs provide their own operations.
318  */
319 struct aiocb_ops {
320         int     (*copyin)(struct aiocb *ujob, struct aiocb *kjob);
321         long    (*fetch_status)(struct aiocb *ujob);
322         long    (*fetch_error)(struct aiocb *ujob);
323         int     (*store_status)(struct aiocb *ujob, long status);
324         int     (*store_error)(struct aiocb *ujob, long error);
325         int     (*store_kernelinfo)(struct aiocb *ujob, long jobref);
326         int     (*store_aiocb)(struct aiocb **ujobp, struct aiocb *ujob);
327 };
328
329 static TAILQ_HEAD(,aiothreadlist) aio_freeproc;         /* (c) Idle daemons */
330 static struct sema aio_newproc_sem;
331 static struct mtx aio_job_mtx;
332 static struct mtx aio_sock_mtx;
333 static TAILQ_HEAD(,aiocblist) aio_jobs;                 /* (c) Async job list */
334 static struct unrhdr *aiod_unr;
335
336 void            aio_init_aioinfo(struct proc *p);
337 static void     aio_onceonly(void);
338 static int      aio_free_entry(struct aiocblist *aiocbe);
339 static void     aio_process(struct aiocblist *aiocbe);
340 static int      aio_newproc(int *);
341 int             aio_aqueue(struct thread *td, struct aiocb *job,
342                         struct aioliojob *lio, int type, struct aiocb_ops *ops);
343 static void     aio_physwakeup(struct buf *bp);
344 static void     aio_proc_rundown(void *arg, struct proc *p);
345 static void     aio_proc_rundown_exec(void *arg, struct proc *p, struct image_params *imgp);
346 static int      aio_qphysio(struct proc *p, struct aiocblist *iocb);
347 static void     biohelper(void *, int);
348 static void     aio_daemon(void *param);
349 static void     aio_swake_cb(struct socket *, struct sockbuf *);
350 static int      aio_unload(void);
351 static void     aio_bio_done_notify(struct proc *userp, struct aiocblist *aiocbe, int type);
352 #define DONE_BUF        1
353 #define DONE_QUEUE      2
354 static int      aio_kick(struct proc *userp);
355 static void     aio_kick_nowait(struct proc *userp);
356 static void     aio_kick_helper(void *context, int pending);
357 static int      filt_aioattach(struct knote *kn);
358 static void     filt_aiodetach(struct knote *kn);
359 static int      filt_aio(struct knote *kn, long hint);
360 static int      filt_lioattach(struct knote *kn);
361 static void     filt_liodetach(struct knote *kn);
362 static int      filt_lio(struct knote *kn, long hint);
363
364 /*
365  * Zones for:
366  *      kaio    Per process async io info
367  *      aiop    async io thread data
368  *      aiocb   async io jobs
369  *      aiol    list io job pointer - internal to aio_suspend XXX
370  *      aiolio  list io jobs
371  */
372 static uma_zone_t kaio_zone, aiop_zone, aiocb_zone, aiol_zone, aiolio_zone;
373
374 /* kqueue filters for aio */
375 static struct filterops aio_filtops =
376         { 0, filt_aioattach, filt_aiodetach, filt_aio };
377 static struct filterops lio_filtops =
378         { 0, filt_lioattach, filt_liodetach, filt_lio };
379
380 static eventhandler_tag exit_tag, exec_tag;
381
382 TASKQUEUE_DEFINE_THREAD(aiod_bio);
383
384 /*
385  * Main operations function for use as a kernel module.
386  */
387 static int
388 aio_modload(struct module *module, int cmd, void *arg)
389 {
390         int error = 0;
391
392         switch (cmd) {
393         case MOD_LOAD:
394                 aio_onceonly();
395                 break;
396         case MOD_UNLOAD:
397                 error = aio_unload();
398                 break;
399         case MOD_SHUTDOWN:
400                 break;
401         default:
402                 error = EINVAL;
403                 break;
404         }
405         return (error);
406 }
407
408 static moduledata_t aio_mod = {
409         "aio",
410         &aio_modload,
411         NULL
412 };
413
414 SYSCALL_MODULE_HELPER(aio_cancel);
415 SYSCALL_MODULE_HELPER(aio_error);
416 SYSCALL_MODULE_HELPER(aio_fsync);
417 SYSCALL_MODULE_HELPER(aio_read);
418 SYSCALL_MODULE_HELPER(aio_return);
419 SYSCALL_MODULE_HELPER(aio_suspend);
420 SYSCALL_MODULE_HELPER(aio_waitcomplete);
421 SYSCALL_MODULE_HELPER(aio_write);
422 SYSCALL_MODULE_HELPER(lio_listio);
423 SYSCALL_MODULE_HELPER(oaio_read);
424 SYSCALL_MODULE_HELPER(oaio_write);
425 SYSCALL_MODULE_HELPER(olio_listio);
426
427 DECLARE_MODULE(aio, aio_mod,
428         SI_SUB_VFS, SI_ORDER_ANY);
429 MODULE_VERSION(aio, 1);
430
431 /*
432  * Startup initialization
433  */
434 static void
435 aio_onceonly(void)
436 {
437
438         /* XXX: should probably just use so->callback */
439         aio_swake = &aio_swake_cb;
440         exit_tag = EVENTHANDLER_REGISTER(process_exit, aio_proc_rundown, NULL,
441             EVENTHANDLER_PRI_ANY);
442         exec_tag = EVENTHANDLER_REGISTER(process_exec, aio_proc_rundown_exec, NULL,
443             EVENTHANDLER_PRI_ANY);
444         kqueue_add_filteropts(EVFILT_AIO, &aio_filtops);
445         kqueue_add_filteropts(EVFILT_LIO, &lio_filtops);
446         TAILQ_INIT(&aio_freeproc);
447         sema_init(&aio_newproc_sem, 0, "aio_new_proc");
448         mtx_init(&aio_job_mtx, "aio_job", NULL, MTX_DEF);
449         mtx_init(&aio_sock_mtx, "aio_sock", NULL, MTX_DEF);
450         TAILQ_INIT(&aio_jobs);
451         aiod_unr = new_unrhdr(1, INT_MAX, NULL);
452         kaio_zone = uma_zcreate("AIO", sizeof(struct kaioinfo), NULL, NULL,
453             NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
454         aiop_zone = uma_zcreate("AIOP", sizeof(struct aiothreadlist), NULL,
455             NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
456         aiocb_zone = uma_zcreate("AIOCB", sizeof(struct aiocblist), NULL, NULL,
457             NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
458         aiol_zone = uma_zcreate("AIOL", AIO_LISTIO_MAX*sizeof(intptr_t) , NULL,
459             NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
460         aiolio_zone = uma_zcreate("AIOLIO", sizeof(struct aioliojob), NULL,
461             NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
462         aiod_timeout = AIOD_TIMEOUT_DEFAULT;
463         aiod_lifetime = AIOD_LIFETIME_DEFAULT;
464         jobrefid = 1;
465         async_io_version = _POSIX_VERSION;
466         p31b_setcfg(CTL_P1003_1B_AIO_LISTIO_MAX, AIO_LISTIO_MAX);
467         p31b_setcfg(CTL_P1003_1B_AIO_MAX, MAX_AIO_QUEUE);
468         p31b_setcfg(CTL_P1003_1B_AIO_PRIO_DELTA_MAX, 0);
469 }
470
471 /*
472  * Callback for unload of AIO when used as a module.
473  */
474 static int
475 aio_unload(void)
476 {
477         int error;
478
479         /*
480          * XXX: no unloads by default, it's too dangerous.
481          * perhaps we could do it if locked out callers and then
482          * did an aio_proc_rundown() on each process.
483          *
484          * jhb: aio_proc_rundown() needs to run on curproc though,
485          * so I don't think that would fly.
486          */
487         if (!unloadable)
488                 return (EOPNOTSUPP);
489
490         error = kqueue_del_filteropts(EVFILT_AIO);
491         if (error)
492                 return error;
493         error = kqueue_del_filteropts(EVFILT_LIO);
494         if (error)
495                 return error;
496         async_io_version = 0;
497         aio_swake = NULL;
498         taskqueue_free(taskqueue_aiod_bio);
499         delete_unrhdr(aiod_unr);
500         uma_zdestroy(kaio_zone);
501         uma_zdestroy(aiop_zone);
502         uma_zdestroy(aiocb_zone);
503         uma_zdestroy(aiol_zone);
504         uma_zdestroy(aiolio_zone);
505         EVENTHANDLER_DEREGISTER(process_exit, exit_tag);
506         EVENTHANDLER_DEREGISTER(process_exec, exec_tag);
507         mtx_destroy(&aio_job_mtx);
508         mtx_destroy(&aio_sock_mtx);
509         sema_destroy(&aio_newproc_sem);
510         p31b_setcfg(CTL_P1003_1B_AIO_LISTIO_MAX, -1);
511         p31b_setcfg(CTL_P1003_1B_AIO_MAX, -1);
512         p31b_setcfg(CTL_P1003_1B_AIO_PRIO_DELTA_MAX, -1);
513         return (0);
514 }
515
516 /*
517  * Init the per-process aioinfo structure.  The aioinfo limits are set
518  * per-process for user limit (resource) management.
519  */
520 void
521 aio_init_aioinfo(struct proc *p)
522 {
523         struct kaioinfo *ki;
524
525         ki = uma_zalloc(kaio_zone, M_WAITOK);
526         mtx_init(&ki->kaio_mtx, "aiomtx", NULL, MTX_DEF);
527         ki->kaio_flags = 0;
528         ki->kaio_maxactive_count = max_aio_per_proc;
529         ki->kaio_active_count = 0;
530         ki->kaio_qallowed_count = max_aio_queue_per_proc;
531         ki->kaio_count = 0;
532         ki->kaio_ballowed_count = max_buf_aio;
533         ki->kaio_buffer_count = 0;
534         TAILQ_INIT(&ki->kaio_all);
535         TAILQ_INIT(&ki->kaio_done);
536         TAILQ_INIT(&ki->kaio_jobqueue);
537         TAILQ_INIT(&ki->kaio_bufqueue);
538         TAILQ_INIT(&ki->kaio_liojoblist);
539         TAILQ_INIT(&ki->kaio_sockqueue);
540         TAILQ_INIT(&ki->kaio_syncqueue);
541         TASK_INIT(&ki->kaio_task, 0, aio_kick_helper, p);
542         PROC_LOCK(p);
543         if (p->p_aioinfo == NULL) {
544                 p->p_aioinfo = ki;
545                 PROC_UNLOCK(p);
546         } else {
547                 PROC_UNLOCK(p);
548                 mtx_destroy(&ki->kaio_mtx);
549                 uma_zfree(kaio_zone, ki);
550         }
551
552         while (num_aio_procs < target_aio_procs)
553                 aio_newproc(NULL);
554 }
555
556 static int
557 aio_sendsig(struct proc *p, struct sigevent *sigev, ksiginfo_t *ksi)
558 {
559         int ret = 0;
560
561         PROC_LOCK(p);
562         if (!KSI_ONQ(ksi)) {
563                 ksi->ksi_code = SI_ASYNCIO;
564                 ksi->ksi_flags |= KSI_EXT | KSI_INS;
565                 ret = psignal_event(p, sigev, ksi);
566         }
567         PROC_UNLOCK(p);
568         return (ret);
569 }
570
571 /*
572  * Free a job entry.  Wait for completion if it is currently active, but don't
573  * delay forever.  If we delay, we return a flag that says that we have to
574  * restart the queue scan.
575  */
576 static int
577 aio_free_entry(struct aiocblist *aiocbe)
578 {
579         struct kaioinfo *ki;
580         struct aioliojob *lj;
581         struct proc *p;
582
583         p = aiocbe->userproc;
584         MPASS(curproc == p);
585         ki = p->p_aioinfo;
586         MPASS(ki != NULL);
587
588         AIO_LOCK_ASSERT(ki, MA_OWNED);
589         MPASS(aiocbe->jobstate == JOBST_JOBFINISHED);
590
591         atomic_subtract_int(&num_queue_count, 1);
592
593         ki->kaio_count--;
594         MPASS(ki->kaio_count >= 0);
595
596         TAILQ_REMOVE(&ki->kaio_done, aiocbe, plist);
597         TAILQ_REMOVE(&ki->kaio_all, aiocbe, allist);
598
599         lj = aiocbe->lio;
600         if (lj) {
601                 lj->lioj_count--;
602                 lj->lioj_finished_count--;
603
604                 if (lj->lioj_count == 0) {
605                         TAILQ_REMOVE(&ki->kaio_liojoblist, lj, lioj_list);
606                         /* lio is going away, we need to destroy any knotes */
607                         knlist_delete(&lj->klist, curthread, 1);
608                         PROC_LOCK(p);
609                         sigqueue_take(&lj->lioj_ksi);
610                         PROC_UNLOCK(p);
611                         uma_zfree(aiolio_zone, lj);
612                 }
613         }
614
615         /* aiocbe is going away, we need to destroy any knotes */
616         knlist_delete(&aiocbe->klist, curthread, 1);
617         PROC_LOCK(p);
618         sigqueue_take(&aiocbe->ksi);
619         PROC_UNLOCK(p);
620
621         MPASS(aiocbe->bp == NULL);
622         aiocbe->jobstate = JOBST_NULL;
623         AIO_UNLOCK(ki);
624
625         /*
626          * The thread argument here is used to find the owning process
627          * and is also passed to fo_close() which may pass it to various
628          * places such as devsw close() routines.  Because of that, we
629          * need a thread pointer from the process owning the job that is
630          * persistent and won't disappear out from under us or move to
631          * another process.
632          *
633          * Currently, all the callers of this function call it to remove
634          * an aiocblist from the current process' job list either via a
635          * syscall or due to the current process calling exit() or
636          * execve().  Thus, we know that p == curproc.  We also know that
637          * curthread can't exit since we are curthread.
638          *
639          * Therefore, we use curthread as the thread to pass to
640          * knlist_delete().  This does mean that it is possible for the
641          * thread pointer at close time to differ from the thread pointer
642          * at open time, but this is already true of file descriptors in
643          * a multithreaded process.
644          */
645         fdrop(aiocbe->fd_file, curthread);
646         crfree(aiocbe->cred);
647         uma_zfree(aiocb_zone, aiocbe);
648         AIO_LOCK(ki);
649
650         return (0);
651 }
652
653 static void
654 aio_proc_rundown_exec(void *arg, struct proc *p, struct image_params *imgp __unused)
655 {
656         aio_proc_rundown(arg, p);
657 }
658
659 /*
660  * Rundown the jobs for a given process.
661  */
662 static void
663 aio_proc_rundown(void *arg, struct proc *p)
664 {
665         struct kaioinfo *ki;
666         struct aioliojob *lj;
667         struct aiocblist *cbe, *cbn;
668         struct file *fp;
669         struct socket *so;
670         int remove;
671
672         KASSERT(curthread->td_proc == p,
673             ("%s: called on non-curproc", __func__));
674         ki = p->p_aioinfo;
675         if (ki == NULL)
676                 return;
677
678         AIO_LOCK(ki);
679         ki->kaio_flags |= KAIO_RUNDOWN;
680
681 restart:
682
683         /*
684          * Try to cancel all pending requests. This code simulates
685          * aio_cancel on all pending I/O requests.
686          */
687         TAILQ_FOREACH_SAFE(cbe, &ki->kaio_jobqueue, plist, cbn) {
688                 remove = 0;
689                 mtx_lock(&aio_job_mtx);
690                 if (cbe->jobstate == JOBST_JOBQGLOBAL) {
691                         TAILQ_REMOVE(&aio_jobs, cbe, list);
692                         remove = 1;
693                 } else if (cbe->jobstate == JOBST_JOBQSOCK) {
694                         fp = cbe->fd_file;
695                         MPASS(fp->f_type == DTYPE_SOCKET);
696                         so = fp->f_data;
697                         TAILQ_REMOVE(&so->so_aiojobq, cbe, list);
698                         remove = 1;
699                 } else if (cbe->jobstate == JOBST_JOBQSYNC) {
700                         TAILQ_REMOVE(&ki->kaio_syncqueue, cbe, list);
701                         remove = 1;
702                 }
703                 mtx_unlock(&aio_job_mtx);
704
705                 if (remove) {
706                         cbe->jobstate = JOBST_JOBFINISHED;
707                         cbe->uaiocb._aiocb_private.status = -1;
708                         cbe->uaiocb._aiocb_private.error = ECANCELED;
709                         TAILQ_REMOVE(&ki->kaio_jobqueue, cbe, plist);
710                         aio_bio_done_notify(p, cbe, DONE_QUEUE);
711                 }
712         }
713
714         /* Wait for all running I/O to be finished */
715         if (TAILQ_FIRST(&ki->kaio_bufqueue) ||
716             TAILQ_FIRST(&ki->kaio_jobqueue)) {
717                 ki->kaio_flags |= KAIO_WAKEUP;
718                 msleep(&p->p_aioinfo, AIO_MTX(ki), PRIBIO, "aioprn", hz);
719                 goto restart;
720         }
721
722         /* Free all completed I/O requests. */
723         while ((cbe = TAILQ_FIRST(&ki->kaio_done)) != NULL)
724                 aio_free_entry(cbe);
725
726         while ((lj = TAILQ_FIRST(&ki->kaio_liojoblist)) != NULL) {
727                 if (lj->lioj_count == 0) {
728                         TAILQ_REMOVE(&ki->kaio_liojoblist, lj, lioj_list);
729                         knlist_delete(&lj->klist, curthread, 1);
730                         PROC_LOCK(p);
731                         sigqueue_take(&lj->lioj_ksi);
732                         PROC_UNLOCK(p);
733                         uma_zfree(aiolio_zone, lj);
734                 } else {
735                         panic("LIO job not cleaned up: C:%d, FC:%d\n",
736                             lj->lioj_count, lj->lioj_finished_count);
737                 }
738         }
739         AIO_UNLOCK(ki);
740         taskqueue_drain(taskqueue_aiod_bio, &ki->kaio_task);
741         mtx_destroy(&ki->kaio_mtx);
742         uma_zfree(kaio_zone, ki);
743         p->p_aioinfo = NULL;
744 }
745
746 /*
747  * Select a job to run (called by an AIO daemon).
748  */
749 static struct aiocblist *
750 aio_selectjob(struct aiothreadlist *aiop)
751 {
752         struct aiocblist *aiocbe;
753         struct kaioinfo *ki;
754         struct proc *userp;
755
756         mtx_assert(&aio_job_mtx, MA_OWNED);
757         TAILQ_FOREACH(aiocbe, &aio_jobs, list) {
758                 userp = aiocbe->userproc;
759                 ki = userp->p_aioinfo;
760
761                 if (ki->kaio_active_count < ki->kaio_maxactive_count) {
762                         TAILQ_REMOVE(&aio_jobs, aiocbe, list);
763                         /* Account for currently active jobs. */
764                         ki->kaio_active_count++;
765                         aiocbe->jobstate = JOBST_JOBRUNNING;
766                         break;
767                 }
768         }
769         return (aiocbe);
770 }
771
772 /*
773  *  Move all data to a permanent storage device, this code
774  *  simulates fsync syscall.
775  */
776 static int
777 aio_fsync_vnode(struct thread *td, struct vnode *vp)
778 {
779         struct mount *mp;
780         int vfslocked;
781         int error;
782
783         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
784         if ((error = vn_start_write(vp, &mp, V_WAIT | PCATCH)) != 0)
785                 goto drop;
786         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
787         if (vp->v_object != NULL) {
788                 VM_OBJECT_LOCK(vp->v_object);
789                 vm_object_page_clean(vp->v_object, 0, 0, 0);
790                 VM_OBJECT_UNLOCK(vp->v_object);
791         }
792         error = VOP_FSYNC(vp, MNT_WAIT, td);
793
794         VOP_UNLOCK(vp, 0, td);
795         vn_finished_write(mp);
796 drop:
797         VFS_UNLOCK_GIANT(vfslocked);
798         return (error);
799 }
800
801 /*
802  * The AIO processing activity.  This is the code that does the I/O request for
803  * the non-physio version of the operations.  The normal vn operations are used,
804  * and this code should work in all instances for every type of file, including
805  * pipes, sockets, fifos, and regular files.
806  *
807  * XXX I don't think it works well for socket, pipe, and fifo.
808  */
809 static void
810 aio_process(struct aiocblist *aiocbe)
811 {
812         struct ucred *td_savedcred;
813         struct thread *td;
814         struct aiocb *cb;
815         struct file *fp;
816         struct socket *so;
817         struct uio auio;
818         struct iovec aiov;
819         int cnt;
820         int error;
821         int oublock_st, oublock_end;
822         int inblock_st, inblock_end;
823
824         td = curthread;
825         td_savedcred = td->td_ucred;
826         td->td_ucred = aiocbe->cred;
827         cb = &aiocbe->uaiocb;
828         fp = aiocbe->fd_file;
829
830         if (cb->aio_lio_opcode == LIO_SYNC) {
831                 error = 0;
832                 cnt = 0;
833                 if (fp->f_vnode != NULL)
834                         error = aio_fsync_vnode(td, fp->f_vnode);
835                 cb->_aiocb_private.error = error;
836                 cb->_aiocb_private.status = 0;
837                 td->td_ucred = td_savedcred;
838                 return;
839         }
840
841         aiov.iov_base = (void *)(uintptr_t)cb->aio_buf;
842         aiov.iov_len = cb->aio_nbytes;
843
844         auio.uio_iov = &aiov;
845         auio.uio_iovcnt = 1;
846         auio.uio_offset = cb->aio_offset;
847         auio.uio_resid = cb->aio_nbytes;
848         cnt = cb->aio_nbytes;
849         auio.uio_segflg = UIO_USERSPACE;
850         auio.uio_td = td;
851
852         inblock_st = td->td_ru.ru_inblock;
853         oublock_st = td->td_ru.ru_oublock;
854         /*
855          * aio_aqueue() acquires a reference to the file that is
856          * released in aio_free_entry().
857          */
858         if (cb->aio_lio_opcode == LIO_READ) {
859                 auio.uio_rw = UIO_READ;
860                 if (auio.uio_resid == 0)
861                         error = 0;
862                 else
863                         error = fo_read(fp, &auio, fp->f_cred, FOF_OFFSET, td);
864         } else {
865                 if (fp->f_type == DTYPE_VNODE)
866                         bwillwrite();
867                 auio.uio_rw = UIO_WRITE;
868                 error = fo_write(fp, &auio, fp->f_cred, FOF_OFFSET, td);
869         }
870         inblock_end = td->td_ru.ru_inblock;
871         oublock_end = td->td_ru.ru_oublock;
872
873         aiocbe->inputcharge = inblock_end - inblock_st;
874         aiocbe->outputcharge = oublock_end - oublock_st;
875
876         if ((error) && (auio.uio_resid != cnt)) {
877                 if (error == ERESTART || error == EINTR || error == EWOULDBLOCK)
878                         error = 0;
879                 if ((error == EPIPE) && (cb->aio_lio_opcode == LIO_WRITE)) {
880                         int sigpipe = 1;
881                         if (fp->f_type == DTYPE_SOCKET) {
882                                 so = fp->f_data;
883                                 if (so->so_options & SO_NOSIGPIPE)
884                                         sigpipe = 0;
885                         }
886                         if (sigpipe) {
887                                 PROC_LOCK(aiocbe->userproc);
888                                 psignal(aiocbe->userproc, SIGPIPE);
889                                 PROC_UNLOCK(aiocbe->userproc);
890                         }
891                 }
892         }
893
894         cnt -= auio.uio_resid;
895         cb->_aiocb_private.error = error;
896         cb->_aiocb_private.status = cnt;
897         td->td_ucred = td_savedcred;
898 }
899
900 static void
901 aio_bio_done_notify(struct proc *userp, struct aiocblist *aiocbe, int type)
902 {
903         struct aioliojob *lj;
904         struct kaioinfo *ki;
905         struct aiocblist *scb, *scbn;
906         int lj_done;
907
908         ki = userp->p_aioinfo;
909         AIO_LOCK_ASSERT(ki, MA_OWNED);
910         lj = aiocbe->lio;
911         lj_done = 0;
912         if (lj) {
913                 lj->lioj_finished_count++;
914                 if (lj->lioj_count == lj->lioj_finished_count)
915                         lj_done = 1;
916         }
917         if (type == DONE_QUEUE) {
918                 aiocbe->jobflags |= AIOCBLIST_DONE;
919         } else {
920                 aiocbe->jobflags |= AIOCBLIST_BUFDONE;
921         }
922         TAILQ_INSERT_TAIL(&ki->kaio_done, aiocbe, plist);
923         aiocbe->jobstate = JOBST_JOBFINISHED;
924
925         if (ki->kaio_flags & KAIO_RUNDOWN)
926                 goto notification_done;
927
928         if (aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_SIGNAL ||
929             aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_THREAD_ID)
930                 aio_sendsig(userp, &aiocbe->uaiocb.aio_sigevent, &aiocbe->ksi);
931
932         KNOTE_LOCKED(&aiocbe->klist, 1);
933
934         if (lj_done) {
935                 if (lj->lioj_signal.sigev_notify == SIGEV_KEVENT) {
936                         lj->lioj_flags |= LIOJ_KEVENT_POSTED;
937                         KNOTE_LOCKED(&lj->klist, 1);
938                 }
939                 if ((lj->lioj_flags & (LIOJ_SIGNAL|LIOJ_SIGNAL_POSTED))
940                     == LIOJ_SIGNAL
941                     && (lj->lioj_signal.sigev_notify == SIGEV_SIGNAL ||
942                         lj->lioj_signal.sigev_notify == SIGEV_THREAD_ID)) {
943                         aio_sendsig(userp, &lj->lioj_signal, &lj->lioj_ksi);
944                         lj->lioj_flags |= LIOJ_SIGNAL_POSTED;
945                 }
946         }
947
948 notification_done:
949         if (aiocbe->jobflags & AIOCBLIST_CHECKSYNC) {
950                 TAILQ_FOREACH_SAFE(scb, &ki->kaio_syncqueue, list, scbn) {
951                         if (aiocbe->fd_file == scb->fd_file &&
952                             aiocbe->seqno < scb->seqno) {
953                                 if (--scb->pending == 0) {
954                                         mtx_lock(&aio_job_mtx);
955                                         scb->jobstate = JOBST_JOBQGLOBAL;
956                                         TAILQ_REMOVE(&ki->kaio_syncqueue, scb, list);
957                                         TAILQ_INSERT_TAIL(&aio_jobs, scb, list);
958                                         aio_kick_nowait(userp);
959                                         mtx_unlock(&aio_job_mtx);
960                                 }
961                         }
962                 }
963         }
964         if (ki->kaio_flags & KAIO_WAKEUP) {
965                 ki->kaio_flags &= ~KAIO_WAKEUP;
966                 wakeup(&userp->p_aioinfo);
967         }
968 }
969
970 /*
971  * The AIO daemon, most of the actual work is done in aio_process,
972  * but the setup (and address space mgmt) is done in this routine.
973  */
974 static void
975 aio_daemon(void *_id)
976 {
977         struct aiocblist *aiocbe;
978         struct aiothreadlist *aiop;
979         struct kaioinfo *ki;
980         struct proc *curcp, *mycp, *userp;
981         struct vmspace *myvm, *tmpvm;
982         struct thread *td = curthread;
983         int id = (intptr_t)_id;
984
985         /*
986          * Local copies of curproc (cp) and vmspace (myvm)
987          */
988         mycp = td->td_proc;
989         myvm = mycp->p_vmspace;
990
991         KASSERT(mycp->p_textvp == NULL, ("kthread has a textvp"));
992
993         /*
994          * Allocate and ready the aio control info.  There is one aiop structure
995          * per daemon.
996          */
997         aiop = uma_zalloc(aiop_zone, M_WAITOK);
998         aiop->aiothread = td;
999         aiop->aiothreadflags = 0;
1000
1001         /* The daemon resides in its own pgrp. */
1002         setsid(td, NULL);
1003
1004         /*
1005          * Wakeup parent process.  (Parent sleeps to keep from blasting away
1006          * and creating too many daemons.)
1007          */
1008         sema_post(&aio_newproc_sem);
1009
1010         mtx_lock(&aio_job_mtx);
1011         for (;;) {
1012                 /*
1013                  * curcp is the current daemon process context.
1014                  * userp is the current user process context.
1015                  */
1016                 curcp = mycp;
1017
1018                 /*
1019                  * Take daemon off of free queue
1020                  */
1021                 if (aiop->aiothreadflags & AIOP_FREE) {
1022                         TAILQ_REMOVE(&aio_freeproc, aiop, list);
1023                         aiop->aiothreadflags &= ~AIOP_FREE;
1024                 }
1025
1026                 /*
1027                  * Check for jobs.
1028                  */
1029                 while ((aiocbe = aio_selectjob(aiop)) != NULL) {
1030                         mtx_unlock(&aio_job_mtx);
1031                         userp = aiocbe->userproc;
1032
1033                         /*
1034                          * Connect to process address space for user program.
1035                          */
1036                         if (userp != curcp) {
1037                                 /*
1038                                  * Save the current address space that we are
1039                                  * connected to.
1040                                  */
1041                                 tmpvm = mycp->p_vmspace;
1042
1043                                 /*
1044                                  * Point to the new user address space, and
1045                                  * refer to it.
1046                                  */
1047                                 mycp->p_vmspace = userp->p_vmspace;
1048                                 atomic_add_int(&mycp->p_vmspace->vm_refcnt, 1);
1049
1050                                 /* Activate the new mapping. */
1051                                 pmap_activate(FIRST_THREAD_IN_PROC(mycp));
1052
1053                                 /*
1054                                  * If the old address space wasn't the daemons
1055                                  * own address space, then we need to remove the
1056                                  * daemon's reference from the other process
1057                                  * that it was acting on behalf of.
1058                                  */
1059                                 if (tmpvm != myvm) {
1060                                         vmspace_free(tmpvm);
1061                                 }
1062                                 curcp = userp;
1063                         }
1064
1065                         ki = userp->p_aioinfo;
1066
1067                         /* Do the I/O function. */
1068                         aio_process(aiocbe);
1069
1070                         mtx_lock(&aio_job_mtx);
1071                         /* Decrement the active job count. */
1072                         ki->kaio_active_count--;
1073                         mtx_unlock(&aio_job_mtx);
1074
1075                         AIO_LOCK(ki);
1076                         TAILQ_REMOVE(&ki->kaio_jobqueue, aiocbe, plist);
1077                         aio_bio_done_notify(userp, aiocbe, DONE_QUEUE);
1078                         AIO_UNLOCK(ki);
1079
1080                         mtx_lock(&aio_job_mtx);
1081                 }
1082
1083                 /*
1084                  * Disconnect from user address space.
1085                  */
1086                 if (curcp != mycp) {
1087
1088                         mtx_unlock(&aio_job_mtx);
1089
1090                         /* Get the user address space to disconnect from. */
1091                         tmpvm = mycp->p_vmspace;
1092
1093                         /* Get original address space for daemon. */
1094                         mycp->p_vmspace = myvm;
1095
1096                         /* Activate the daemon's address space. */
1097                         pmap_activate(FIRST_THREAD_IN_PROC(mycp));
1098 #ifdef DIAGNOSTIC
1099                         if (tmpvm == myvm) {
1100                                 printf("AIOD: vmspace problem -- %d\n",
1101                                     mycp->p_pid);
1102                         }
1103 #endif
1104                         /* Remove our vmspace reference. */
1105                         vmspace_free(tmpvm);
1106
1107                         curcp = mycp;
1108
1109                         mtx_lock(&aio_job_mtx);
1110                         /*
1111                          * We have to restart to avoid race, we only sleep if
1112                          * no job can be selected, that should be
1113                          * curcp == mycp.
1114                          */
1115                         continue;
1116                 }
1117
1118                 mtx_assert(&aio_job_mtx, MA_OWNED);
1119
1120                 TAILQ_INSERT_HEAD(&aio_freeproc, aiop, list);
1121                 aiop->aiothreadflags |= AIOP_FREE;
1122
1123                 /*
1124                  * If daemon is inactive for a long time, allow it to exit,
1125                  * thereby freeing resources.
1126                  */
1127                 if (msleep(aiop->aiothread, &aio_job_mtx, PRIBIO, "aiordy",
1128                     aiod_lifetime)) {
1129                         if (TAILQ_EMPTY(&aio_jobs)) {
1130                                 if ((aiop->aiothreadflags & AIOP_FREE) &&
1131                                     (num_aio_procs > target_aio_procs)) {
1132                                         TAILQ_REMOVE(&aio_freeproc, aiop, list);
1133                                         num_aio_procs--;
1134                                         mtx_unlock(&aio_job_mtx);
1135                                         uma_zfree(aiop_zone, aiop);
1136                                         free_unr(aiod_unr, id);
1137 #ifdef DIAGNOSTIC
1138                                         if (mycp->p_vmspace->vm_refcnt <= 1) {
1139                                                 printf("AIOD: bad vm refcnt for"
1140                                                     " exiting daemon: %d\n",
1141                                                     mycp->p_vmspace->vm_refcnt);
1142                                         }
1143 #endif
1144                                         kthread_exit(0);
1145                                 }
1146                         }
1147                 }
1148         }
1149         mtx_unlock(&aio_job_mtx);
1150         panic("shouldn't be here\n");
1151 }
1152
1153 /*
1154  * Create a new AIO daemon. This is mostly a kernel-thread fork routine. The
1155  * AIO daemon modifies its environment itself.
1156  */
1157 static int
1158 aio_newproc(int *start)
1159 {
1160         int error;
1161         struct proc *p;
1162         int id;
1163
1164         id = alloc_unr(aiod_unr);
1165         error = kthread_create(aio_daemon, (void *)(intptr_t)id, &p,
1166                 RFNOWAIT, 0, "aiod%d", id);
1167         if (error == 0) {
1168                 /*
1169                  * Wait until daemon is started.
1170                  */
1171                 sema_wait(&aio_newproc_sem);
1172                 mtx_lock(&aio_job_mtx);
1173                 num_aio_procs++;
1174                 if (start != NULL)
1175                         (*start)--;
1176                 mtx_unlock(&aio_job_mtx);
1177         } else {
1178                 free_unr(aiod_unr, id);
1179         }
1180         return (error);
1181 }
1182
1183 /*
1184  * Try the high-performance, low-overhead physio method for eligible
1185  * VCHR devices.  This method doesn't use an aio helper thread, and
1186  * thus has very low overhead.
1187  *
1188  * Assumes that the caller, aio_aqueue(), has incremented the file
1189  * structure's reference count, preventing its deallocation for the
1190  * duration of this call.
1191  */
1192 static int
1193 aio_qphysio(struct proc *p, struct aiocblist *aiocbe)
1194 {
1195         struct aiocb *cb;
1196         struct file *fp;
1197         struct buf *bp;
1198         struct vnode *vp;
1199         struct kaioinfo *ki;
1200         struct aioliojob *lj;
1201         int error;
1202
1203         cb = &aiocbe->uaiocb;
1204         fp = aiocbe->fd_file;
1205
1206         if (fp->f_type != DTYPE_VNODE)
1207                 return (-1);
1208
1209         vp = fp->f_vnode;
1210
1211         /*
1212          * If its not a disk, we don't want to return a positive error.
1213          * It causes the aio code to not fall through to try the thread
1214          * way when you're talking to a regular file.
1215          */
1216         if (!vn_isdisk(vp, &error)) {
1217                 if (error == ENOTBLK)
1218                         return (-1);
1219                 else
1220                         return (error);
1221         }
1222
1223         if (vp->v_bufobj.bo_bsize == 0)
1224                 return (-1);
1225
1226         if (cb->aio_nbytes % vp->v_bufobj.bo_bsize)
1227                 return (-1);
1228
1229         if (cb->aio_nbytes > vp->v_rdev->si_iosize_max)
1230                 return (-1);
1231
1232         if (cb->aio_nbytes >
1233             MAXPHYS - (((vm_offset_t) cb->aio_buf) & PAGE_MASK))
1234                 return (-1);
1235
1236         ki = p->p_aioinfo;
1237         if (ki->kaio_buffer_count >= ki->kaio_ballowed_count)
1238                 return (-1);
1239
1240         /* Create and build a buffer header for a transfer. */
1241         bp = (struct buf *)getpbuf(NULL);
1242         BUF_KERNPROC(bp);
1243
1244         AIO_LOCK(ki);
1245         ki->kaio_count++;
1246         ki->kaio_buffer_count++;
1247         lj = aiocbe->lio;
1248         if (lj)
1249                 lj->lioj_count++;
1250         AIO_UNLOCK(ki);
1251
1252         /*
1253          * Get a copy of the kva from the physical buffer.
1254          */
1255         error = 0;
1256
1257         bp->b_bcount = cb->aio_nbytes;
1258         bp->b_bufsize = cb->aio_nbytes;
1259         bp->b_iodone = aio_physwakeup;
1260         bp->b_saveaddr = bp->b_data;
1261         bp->b_data = (void *)(uintptr_t)cb->aio_buf;
1262         bp->b_offset = cb->aio_offset;
1263         bp->b_iooffset = cb->aio_offset;
1264         bp->b_blkno = btodb(cb->aio_offset);
1265         bp->b_iocmd = cb->aio_lio_opcode == LIO_WRITE ? BIO_WRITE : BIO_READ;
1266
1267         /*
1268          * Bring buffer into kernel space.
1269          */
1270         if (vmapbuf(bp) < 0) {
1271                 error = EFAULT;
1272                 goto doerror;
1273         }
1274
1275         AIO_LOCK(ki);
1276         aiocbe->bp = bp;
1277         bp->b_caller1 = (void *)aiocbe;
1278         TAILQ_INSERT_TAIL(&ki->kaio_bufqueue, aiocbe, plist);
1279         TAILQ_INSERT_TAIL(&ki->kaio_all, aiocbe, allist);
1280         aiocbe->jobstate = JOBST_JOBQBUF;
1281         cb->_aiocb_private.status = cb->aio_nbytes;
1282         AIO_UNLOCK(ki);
1283
1284         atomic_add_int(&num_queue_count, 1);
1285         atomic_add_int(&num_buf_aio, 1);
1286
1287         bp->b_error = 0;
1288
1289         TASK_INIT(&aiocbe->biotask, 0, biohelper, aiocbe);
1290
1291         /* Perform transfer. */
1292         dev_strategy(vp->v_rdev, bp);
1293         return (0);
1294
1295 doerror:
1296         AIO_LOCK(ki);
1297         ki->kaio_count--;
1298         ki->kaio_buffer_count--;
1299         if (lj)
1300                 lj->lioj_count--;
1301         aiocbe->bp = NULL;
1302         AIO_UNLOCK(ki);
1303         relpbuf(bp, NULL);
1304         return (error);
1305 }
1306
1307 /*
1308  * Wake up aio requests that may be serviceable now.
1309  */
1310 static void
1311 aio_swake_cb(struct socket *so, struct sockbuf *sb)
1312 {
1313         struct aiocblist *cb, *cbn;
1314         int opcode;
1315
1316         if (sb == &so->so_snd)
1317                 opcode = LIO_WRITE;
1318         else
1319                 opcode = LIO_READ;
1320
1321         SOCKBUF_LOCK(sb);
1322         sb->sb_flags &= ~SB_AIO;
1323         mtx_lock(&aio_job_mtx);
1324         TAILQ_FOREACH_SAFE(cb, &so->so_aiojobq, list, cbn) {
1325                 if (opcode == cb->uaiocb.aio_lio_opcode) {
1326                         if (cb->jobstate != JOBST_JOBQSOCK)
1327                                 panic("invalid queue value");
1328                         /* XXX
1329                          * We don't have actual sockets backend yet,
1330                          * so we simply move the requests to the generic
1331                          * file I/O backend.
1332                          */
1333                         TAILQ_REMOVE(&so->so_aiojobq, cb, list);
1334                         TAILQ_INSERT_TAIL(&aio_jobs, cb, list);
1335                         aio_kick_nowait(cb->userproc);
1336                 }
1337         }
1338         mtx_unlock(&aio_job_mtx);
1339         SOCKBUF_UNLOCK(sb);
1340 }
1341
1342 static int
1343 convert_old_sigevent(struct osigevent *osig, struct sigevent *nsig)
1344 {
1345
1346         /*
1347          * Only SIGEV_NONE, SIGEV_SIGNAL, and SIGEV_KEVENT are
1348          * supported by AIO with the old sigevent structure.
1349          */
1350         nsig->sigev_notify = osig->sigev_notify;
1351         switch (nsig->sigev_notify) {
1352         case SIGEV_NONE:
1353                 break;
1354         case SIGEV_SIGNAL:
1355                 nsig->sigev_signo = osig->__sigev_u.__sigev_signo;
1356                 break;
1357         case SIGEV_KEVENT:
1358                 nsig->sigev_notify_kqueue =
1359                     osig->__sigev_u.__sigev_notify_kqueue;
1360                 nsig->sigev_value.sival_ptr = osig->sigev_value.sival_ptr;
1361                 break;
1362         default:
1363                 return (EINVAL);
1364         }
1365         return (0);
1366 }
1367
1368 static int
1369 aiocb_copyin_old_sigevent(struct aiocb *ujob, struct aiocb *kjob)
1370 {
1371         struct oaiocb *ojob;
1372         int error;
1373
1374         bzero(kjob, sizeof(struct aiocb));
1375         error = copyin(ujob, kjob, sizeof(struct oaiocb));
1376         if (error)
1377                 return (error);
1378         ojob = (struct oaiocb *)kjob;
1379         return (convert_old_sigevent(&ojob->aio_sigevent, &kjob->aio_sigevent));
1380 }
1381
1382 static int
1383 aiocb_copyin(struct aiocb *ujob, struct aiocb *kjob)
1384 {
1385
1386         return (copyin(ujob, kjob, sizeof(struct aiocb)));
1387 }
1388
1389 static long
1390 aiocb_fetch_status(struct aiocb *ujob)
1391 {
1392
1393         return (fuword(&ujob->_aiocb_private.status));
1394 }
1395
1396 static long
1397 aiocb_fetch_error(struct aiocb *ujob)
1398 {
1399
1400         return (fuword(&ujob->_aiocb_private.error));
1401 }
1402
1403 static int
1404 aiocb_store_status(struct aiocb *ujob, long status)
1405 {
1406
1407         return (suword(&ujob->_aiocb_private.status, status));
1408 }
1409
1410 static int
1411 aiocb_store_error(struct aiocb *ujob, long error)
1412 {
1413
1414         return (suword(&ujob->_aiocb_private.error, error));
1415 }
1416
1417 static int
1418 aiocb_store_kernelinfo(struct aiocb *ujob, long jobref)
1419 {
1420
1421         return (suword(&ujob->_aiocb_private.kernelinfo, jobref));
1422 }
1423
1424 static int
1425 aiocb_store_aiocb(struct aiocb **ujobp, struct aiocb *ujob)
1426 {
1427
1428         return (suword(ujobp, (long)ujob));
1429 }
1430
1431 static struct aiocb_ops aiocb_ops = {
1432         .copyin = aiocb_copyin,
1433         .fetch_status = aiocb_fetch_status,
1434         .fetch_error = aiocb_fetch_error,
1435         .store_status = aiocb_store_status,
1436         .store_error = aiocb_store_error,
1437         .store_kernelinfo = aiocb_store_kernelinfo,
1438         .store_aiocb = aiocb_store_aiocb,
1439 };
1440
1441 static struct aiocb_ops aiocb_ops_osigevent = {
1442         .copyin = aiocb_copyin_old_sigevent,
1443         .fetch_status = aiocb_fetch_status,
1444         .fetch_error = aiocb_fetch_error,
1445         .store_status = aiocb_store_status,
1446         .store_error = aiocb_store_error,
1447         .store_kernelinfo = aiocb_store_kernelinfo,
1448         .store_aiocb = aiocb_store_aiocb,
1449 };
1450
1451 /*
1452  * Queue a new AIO request.  Choosing either the threaded or direct physio VCHR
1453  * technique is done in this code.
1454  */
1455 int
1456 aio_aqueue(struct thread *td, struct aiocb *job, struct aioliojob *lj,
1457         int type, struct aiocb_ops *ops)
1458 {
1459         struct proc *p = td->td_proc;
1460         struct file *fp;
1461         struct socket *so;
1462         struct aiocblist *aiocbe, *cb;
1463         struct kaioinfo *ki;
1464         struct kevent kev;
1465         struct sockbuf *sb;
1466         int opcode;
1467         int error;
1468         int fd, kqfd;
1469         int jid;
1470
1471         if (p->p_aioinfo == NULL)
1472                 aio_init_aioinfo(p);
1473
1474         ki = p->p_aioinfo;
1475
1476         ops->store_status(job, -1);
1477         ops->store_error(job, 0);
1478         ops->store_kernelinfo(job, -1);
1479
1480         if (num_queue_count >= max_queue_count ||
1481             ki->kaio_count >= ki->kaio_qallowed_count) {
1482                 ops->store_error(job, EAGAIN);
1483                 return (EAGAIN);
1484         }
1485
1486         aiocbe = uma_zalloc(aiocb_zone, M_WAITOK | M_ZERO);
1487         aiocbe->inputcharge = 0;
1488         aiocbe->outputcharge = 0;
1489         knlist_init(&aiocbe->klist, AIO_MTX(ki), NULL, NULL, NULL);
1490
1491         error = ops->copyin(job, &aiocbe->uaiocb);
1492         if (error) {
1493                 ops->store_error(job, error);
1494                 uma_zfree(aiocb_zone, aiocbe);
1495                 return (error);
1496         }
1497
1498         if (aiocbe->uaiocb.aio_sigevent.sigev_notify != SIGEV_KEVENT &&
1499             aiocbe->uaiocb.aio_sigevent.sigev_notify != SIGEV_SIGNAL &&
1500             aiocbe->uaiocb.aio_sigevent.sigev_notify != SIGEV_THREAD_ID &&
1501             aiocbe->uaiocb.aio_sigevent.sigev_notify != SIGEV_NONE) {
1502                 ops->store_error(job, EINVAL);
1503                 uma_zfree(aiocb_zone, aiocbe);
1504                 return (EINVAL);
1505         }
1506
1507         if ((aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_SIGNAL ||
1508              aiocbe->uaiocb.aio_sigevent.sigev_notify == SIGEV_THREAD_ID) &&
1509                 !_SIG_VALID(aiocbe->uaiocb.aio_sigevent.sigev_signo)) {
1510                 uma_zfree(aiocb_zone, aiocbe);
1511                 return (EINVAL);
1512         }
1513
1514         ksiginfo_init(&aiocbe->ksi);
1515
1516         /* Save userspace address of the job info. */
1517         aiocbe->uuaiocb = job;
1518
1519         /* Get the opcode. */
1520         if (type != LIO_NOP)
1521                 aiocbe->uaiocb.aio_lio_opcode = type;
1522         opcode = aiocbe->uaiocb.aio_lio_opcode;
1523
1524         /* Fetch the file object for the specified file descriptor. */
1525         fd = aiocbe->uaiocb.aio_fildes;
1526         switch (opcode) {
1527         case LIO_WRITE:
1528                 error = fget_write(td, fd, &fp);
1529                 break;
1530         case LIO_READ:
1531                 error = fget_read(td, fd, &fp);
1532                 break;
1533         default:
1534                 error = fget(td, fd, &fp);
1535         }
1536         if (error) {
1537                 uma_zfree(aiocb_zone, aiocbe);
1538                 ops->store_error(job, error);
1539                 return (error);
1540         }
1541
1542         if (opcode == LIO_SYNC && fp->f_vnode == NULL) {
1543                 error = EINVAL;
1544                 goto aqueue_fail;
1545         }
1546
1547         if (opcode != LIO_SYNC && aiocbe->uaiocb.aio_offset == -1LL) {
1548                 error = EINVAL;
1549                 goto aqueue_fail;
1550         }
1551
1552         aiocbe->fd_file = fp;
1553
1554         mtx_lock(&aio_job_mtx);
1555         jid = jobrefid++;
1556         aiocbe->seqno = jobseqno++;
1557         mtx_unlock(&aio_job_mtx);
1558         error = ops->store_kernelinfo(job, jid);
1559         if (error) {
1560                 error = EINVAL;
1561                 goto aqueue_fail;
1562         }
1563         aiocbe->uaiocb._aiocb_private.kernelinfo = (void *)(intptr_t)jid;
1564
1565         if (opcode == LIO_NOP) {
1566                 fdrop(fp, td);
1567                 uma_zfree(aiocb_zone, aiocbe);
1568                 return (0);
1569         }
1570         if ((opcode != LIO_READ) && (opcode != LIO_WRITE) &&
1571             (opcode != LIO_SYNC)) {
1572                 error = EINVAL;
1573                 goto aqueue_fail;
1574         }
1575
1576         if (aiocbe->uaiocb.aio_sigevent.sigev_notify != SIGEV_KEVENT)
1577                 goto no_kqueue;
1578         kqfd = aiocbe->uaiocb.aio_sigevent.sigev_notify_kqueue;
1579         kev.ident = (uintptr_t)aiocbe->uuaiocb;
1580         kev.filter = EVFILT_AIO;
1581         kev.flags = EV_ADD | EV_ENABLE | EV_FLAG1;
1582         kev.data = (intptr_t)aiocbe;
1583         kev.udata = aiocbe->uaiocb.aio_sigevent.sigev_value.sival_ptr;
1584         error = kqfd_register(kqfd, &kev, td, 1);
1585 aqueue_fail:
1586         if (error) {
1587                 fdrop(fp, td);
1588                 uma_zfree(aiocb_zone, aiocbe);
1589                 ops->store_error(job, error);
1590                 goto done;
1591         }
1592 no_kqueue:
1593
1594         ops->store_error(job, EINPROGRESS);
1595         aiocbe->uaiocb._aiocb_private.error = EINPROGRESS;
1596         aiocbe->userproc = p;
1597         aiocbe->cred = crhold(td->td_ucred);
1598         aiocbe->jobflags = 0;
1599         aiocbe->lio = lj;
1600
1601         if (opcode == LIO_SYNC)
1602                 goto queueit;
1603
1604         if (fp->f_type == DTYPE_SOCKET) {
1605                 /*
1606                  * Alternate queueing for socket ops: Reach down into the
1607                  * descriptor to get the socket data.  Then check to see if the
1608                  * socket is ready to be read or written (based on the requested
1609                  * operation).
1610                  *
1611                  * If it is not ready for io, then queue the aiocbe on the
1612                  * socket, and set the flags so we get a call when sbnotify()
1613                  * happens.
1614                  *
1615                  * Note if opcode is neither LIO_WRITE nor LIO_READ we lock
1616                  * and unlock the snd sockbuf for no reason.
1617                  */
1618                 so = fp->f_data;
1619                 sb = (opcode == LIO_READ) ? &so->so_rcv : &so->so_snd;
1620                 SOCKBUF_LOCK(sb);
1621                 if (((opcode == LIO_READ) && (!soreadable(so))) || ((opcode ==
1622                     LIO_WRITE) && (!sowriteable(so)))) {
1623                         sb->sb_flags |= SB_AIO;
1624
1625                         mtx_lock(&aio_job_mtx);
1626                         TAILQ_INSERT_TAIL(&so->so_aiojobq, aiocbe, list);
1627                         mtx_unlock(&aio_job_mtx);
1628
1629                         AIO_LOCK(ki);
1630                         TAILQ_INSERT_TAIL(&ki->kaio_all, aiocbe, allist);
1631                         TAILQ_INSERT_TAIL(&ki->kaio_jobqueue, aiocbe, plist);
1632                         aiocbe->jobstate = JOBST_JOBQSOCK;
1633                         ki->kaio_count++;
1634                         if (lj)
1635                                 lj->lioj_count++;
1636                         AIO_UNLOCK(ki);
1637                         SOCKBUF_UNLOCK(sb);
1638                         atomic_add_int(&num_queue_count, 1);
1639                         error = 0;
1640                         goto done;
1641                 }
1642                 SOCKBUF_UNLOCK(sb);
1643         }
1644
1645         if ((error = aio_qphysio(p, aiocbe)) == 0)
1646                 goto done;
1647 #if 0
1648         if (error > 0) {
1649                 aiocbe->uaiocb._aiocb_private.error = error;
1650                 ops->store_error(job, error);
1651                 goto done;
1652         }
1653 #endif
1654 queueit:
1655         /* No buffer for daemon I/O. */
1656         aiocbe->bp = NULL;
1657         atomic_add_int(&num_queue_count, 1);
1658
1659         AIO_LOCK(ki);
1660         ki->kaio_count++;
1661         if (lj)
1662                 lj->lioj_count++;
1663         TAILQ_INSERT_TAIL(&ki->kaio_jobqueue, aiocbe, plist);
1664         TAILQ_INSERT_TAIL(&ki->kaio_all, aiocbe, allist);
1665         if (opcode == LIO_SYNC) {
1666                 TAILQ_FOREACH(cb, &ki->kaio_jobqueue, plist) {
1667                         if (cb->fd_file == aiocbe->fd_file &&
1668                             cb->uaiocb.aio_lio_opcode != LIO_SYNC &&
1669                             cb->seqno < aiocbe->seqno) {
1670                                 cb->jobflags |= AIOCBLIST_CHECKSYNC;
1671                                 aiocbe->pending++;
1672                         }
1673                 }
1674                 TAILQ_FOREACH(cb, &ki->kaio_bufqueue, plist) {
1675                         if (cb->fd_file == aiocbe->fd_file &&
1676                             cb->uaiocb.aio_lio_opcode != LIO_SYNC &&
1677                             cb->seqno < aiocbe->seqno) {
1678                                 cb->jobflags |= AIOCBLIST_CHECKSYNC;
1679                                 aiocbe->pending++;
1680                         }
1681                 }
1682                 if (aiocbe->pending != 0) {
1683                         TAILQ_INSERT_TAIL(&ki->kaio_syncqueue, aiocbe, list);
1684                         aiocbe->jobstate = JOBST_JOBQSYNC;
1685                         AIO_UNLOCK(ki);
1686                         goto done;
1687                 }
1688         }
1689         mtx_lock(&aio_job_mtx);
1690         TAILQ_INSERT_TAIL(&aio_jobs, aiocbe, list);
1691         aiocbe->jobstate = JOBST_JOBQGLOBAL;
1692         aio_kick_nowait(p);
1693         mtx_unlock(&aio_job_mtx);
1694         AIO_UNLOCK(ki);
1695         error = 0;
1696 done:
1697         return (error);
1698 }
1699
1700 static void
1701 aio_kick_nowait(struct proc *userp)
1702 {
1703         struct kaioinfo *ki = userp->p_aioinfo;
1704         struct aiothreadlist *aiop;
1705
1706         mtx_assert(&aio_job_mtx, MA_OWNED);
1707         if ((aiop = TAILQ_FIRST(&aio_freeproc)) != NULL) {
1708                 TAILQ_REMOVE(&aio_freeproc, aiop, list);
1709                 aiop->aiothreadflags &= ~AIOP_FREE;
1710                 wakeup(aiop->aiothread);
1711         } else if (((num_aio_resv_start + num_aio_procs) < max_aio_procs) &&
1712             ((ki->kaio_active_count + num_aio_resv_start) <
1713             ki->kaio_maxactive_count)) {
1714                 taskqueue_enqueue(taskqueue_aiod_bio, &ki->kaio_task);
1715         }
1716 }
1717
1718 static int
1719 aio_kick(struct proc *userp)
1720 {
1721         struct kaioinfo *ki = userp->p_aioinfo;
1722         struct aiothreadlist *aiop;
1723         int error, ret = 0;
1724
1725         mtx_assert(&aio_job_mtx, MA_OWNED);
1726 retryproc:
1727         if ((aiop = TAILQ_FIRST(&aio_freeproc)) != NULL) {
1728                 TAILQ_REMOVE(&aio_freeproc, aiop, list);
1729                 aiop->aiothreadflags &= ~AIOP_FREE;
1730                 wakeup(aiop->aiothread);
1731         } else if (((num_aio_resv_start + num_aio_procs) < max_aio_procs) &&
1732             ((ki->kaio_active_count + num_aio_resv_start) <
1733             ki->kaio_maxactive_count)) {
1734                 num_aio_resv_start++;
1735                 mtx_unlock(&aio_job_mtx);
1736                 error = aio_newproc(&num_aio_resv_start);
1737                 mtx_lock(&aio_job_mtx);
1738                 if (error) {
1739                         num_aio_resv_start--;
1740                         goto retryproc;
1741                 }
1742         } else {
1743                 ret = -1;
1744         }
1745         return (ret);
1746 }
1747
1748 static void
1749 aio_kick_helper(void *context, int pending)
1750 {
1751         struct proc *userp = context;
1752
1753         mtx_lock(&aio_job_mtx);
1754         while (--pending >= 0) {
1755                 if (aio_kick(userp))
1756                         break;
1757         }
1758         mtx_unlock(&aio_job_mtx);
1759 }
1760
1761 /*
1762  * Support the aio_return system call, as a side-effect, kernel resources are
1763  * released.
1764  */
1765 static int
1766 kern_aio_return(struct thread *td, struct aiocb *uaiocb, struct aiocb_ops *ops)
1767 {
1768         struct proc *p = td->td_proc;
1769         struct aiocblist *cb;
1770         struct kaioinfo *ki;
1771         int status, error;
1772
1773         ki = p->p_aioinfo;
1774         if (ki == NULL)
1775                 return (EINVAL);
1776         AIO_LOCK(ki);
1777         TAILQ_FOREACH(cb, &ki->kaio_done, plist) {
1778                 if (cb->uuaiocb == uaiocb)
1779                         break;
1780         }
1781         if (cb != NULL) {
1782                 MPASS(cb->jobstate == JOBST_JOBFINISHED);
1783                 status = cb->uaiocb._aiocb_private.status;
1784                 error = cb->uaiocb._aiocb_private.error;
1785                 td->td_retval[0] = status;
1786                 if (cb->uaiocb.aio_lio_opcode == LIO_WRITE) {
1787                         td->td_ru.ru_oublock += cb->outputcharge;
1788                         cb->outputcharge = 0;
1789                 } else if (cb->uaiocb.aio_lio_opcode == LIO_READ) {
1790                         td->td_ru.ru_inblock += cb->inputcharge;
1791                         cb->inputcharge = 0;
1792                 }
1793                 aio_free_entry(cb);
1794                 AIO_UNLOCK(ki);
1795                 ops->store_error(uaiocb, error);
1796                 ops->store_status(uaiocb, status);
1797         } else {
1798                 error = EINVAL;
1799                 AIO_UNLOCK(ki);
1800         }
1801         return (error);
1802 }
1803
1804 int
1805 aio_return(struct thread *td, struct aio_return_args *uap)
1806 {
1807
1808         return (kern_aio_return(td, uap->aiocbp, &aiocb_ops));
1809 }
1810
1811 /*
1812  * Allow a process to wakeup when any of the I/O requests are completed.
1813  */
1814 static int
1815 kern_aio_suspend(struct thread *td, int njoblist, struct aiocb **ujoblist,
1816     struct timespec *ts)
1817 {
1818         struct proc *p = td->td_proc;
1819         struct timeval atv;
1820         struct kaioinfo *ki;
1821         struct aiocblist *cb, *cbfirst;
1822         int error, i, timo;
1823
1824         timo = 0;
1825         if (ts) {
1826                 if (ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
1827                         return (EINVAL);
1828
1829                 TIMESPEC_TO_TIMEVAL(&atv, ts);
1830                 if (itimerfix(&atv))
1831                         return (EINVAL);
1832                 timo = tvtohz(&atv);
1833         }
1834
1835         ki = p->p_aioinfo;
1836         if (ki == NULL)
1837                 return (EAGAIN);
1838
1839         if (njoblist == 0)
1840                 return (0);
1841
1842         AIO_LOCK(ki);
1843         for (;;) {
1844                 cbfirst = NULL;
1845                 error = 0;
1846                 TAILQ_FOREACH(cb, &ki->kaio_all, allist) {
1847                         for (i = 0; i < njoblist; i++) {
1848                                 if (cb->uuaiocb == ujoblist[i]) {
1849                                         if (cbfirst == NULL)
1850                                                 cbfirst = cb;
1851                                         if (cb->jobstate == JOBST_JOBFINISHED)
1852                                                 goto RETURN;
1853                                 }
1854                         }
1855                 }
1856                 /* All tasks were finished. */
1857                 if (cbfirst == NULL)
1858                         break;
1859
1860                 ki->kaio_flags |= KAIO_WAKEUP;
1861                 error = msleep(&p->p_aioinfo, AIO_MTX(ki), PRIBIO | PCATCH,
1862                     "aiospn", timo);
1863                 if (error == ERESTART)
1864                         error = EINTR;
1865                 if (error)
1866                         break;
1867         }
1868 RETURN:
1869         AIO_UNLOCK(ki);
1870         return (error);
1871 }
1872
1873 int
1874 aio_suspend(struct thread *td, struct aio_suspend_args *uap)
1875 {
1876         struct timespec ts, *tsp;
1877         struct aiocb **ujoblist;
1878         int error;
1879
1880         if (uap->nent < 0 || uap->nent > AIO_LISTIO_MAX)
1881                 return (EINVAL);
1882
1883         if (uap->timeout) {
1884                 /* Get timespec struct. */
1885                 if ((error = copyin(uap->timeout, &ts, sizeof(ts))) != 0)
1886                         return (error);
1887                 tsp = &ts;
1888         } else
1889                 tsp = NULL;
1890
1891         ujoblist = uma_zalloc(aiol_zone, M_WAITOK);
1892         error = copyin(uap->aiocbp, ujoblist, uap->nent * sizeof(ujoblist[0]));
1893         if (error == 0)
1894                 error = kern_aio_suspend(td, uap->nent, ujoblist, tsp);
1895         uma_zfree(aiol_zone, ujoblist);
1896         return (error);
1897 }
1898
1899 /*
1900  * aio_cancel cancels any non-physio aio operations not currently in
1901  * progress.
1902  */
1903 int
1904 aio_cancel(struct thread *td, struct aio_cancel_args *uap)
1905 {
1906         struct proc *p = td->td_proc;
1907         struct kaioinfo *ki;
1908         struct aiocblist *cbe, *cbn;
1909         struct file *fp;
1910         struct socket *so;
1911         int error;
1912         int remove;
1913         int cancelled = 0;
1914         int notcancelled = 0;
1915         struct vnode *vp;
1916
1917         /* Lookup file object. */
1918         error = fget(td, uap->fd, &fp);
1919         if (error)
1920                 return (error);
1921
1922         ki = p->p_aioinfo;
1923         if (ki == NULL)
1924                 goto done;
1925
1926         if (fp->f_type == DTYPE_VNODE) {
1927                 vp = fp->f_vnode;
1928                 if (vn_isdisk(vp, &error)) {
1929                         fdrop(fp, td);
1930                         td->td_retval[0] = AIO_NOTCANCELED;
1931                         return (0);
1932                 }
1933         }
1934
1935         AIO_LOCK(ki);
1936         TAILQ_FOREACH_SAFE(cbe, &ki->kaio_jobqueue, plist, cbn) {
1937                 if ((uap->fd == cbe->uaiocb.aio_fildes) &&
1938                     ((uap->aiocbp == NULL) ||
1939                      (uap->aiocbp == cbe->uuaiocb))) {
1940                         remove = 0;
1941
1942                         mtx_lock(&aio_job_mtx);
1943                         if (cbe->jobstate == JOBST_JOBQGLOBAL) {
1944                                 TAILQ_REMOVE(&aio_jobs, cbe, list);
1945                                 remove = 1;
1946                         } else if (cbe->jobstate == JOBST_JOBQSOCK) {
1947                                 MPASS(fp->f_type == DTYPE_SOCKET);
1948                                 so = fp->f_data;
1949                                 TAILQ_REMOVE(&so->so_aiojobq, cbe, list);
1950                                 remove = 1;
1951                         } else if (cbe->jobstate == JOBST_JOBQSYNC) {
1952                                 TAILQ_REMOVE(&ki->kaio_syncqueue, cbe, list);
1953                                 remove = 1;
1954                         }
1955                         mtx_unlock(&aio_job_mtx);
1956
1957                         if (remove) {
1958                                 TAILQ_REMOVE(&ki->kaio_jobqueue, cbe, plist);
1959                                 cbe->uaiocb._aiocb_private.status = -1;
1960                                 cbe->uaiocb._aiocb_private.error = ECANCELED;
1961                                 aio_bio_done_notify(p, cbe, DONE_QUEUE);
1962                                 cancelled++;
1963                         } else {
1964                                 notcancelled++;
1965                         }
1966                         if (uap->aiocbp != NULL)
1967                                 break;
1968                 }
1969         }
1970         AIO_UNLOCK(ki);
1971
1972 done:
1973         fdrop(fp, td);
1974
1975         if (uap->aiocbp != NULL) {
1976                 if (cancelled) {
1977                         td->td_retval[0] = AIO_CANCELED;
1978                         return (0);
1979                 }
1980         }
1981
1982         if (notcancelled) {
1983                 td->td_retval[0] = AIO_NOTCANCELED;
1984                 return (0);
1985         }
1986
1987         if (cancelled) {
1988                 td->td_retval[0] = AIO_CANCELED;
1989                 return (0);
1990         }
1991
1992         td->td_retval[0] = AIO_ALLDONE;
1993
1994         return (0);
1995 }
1996
1997 /*
1998  * aio_error is implemented in the kernel level for compatibility purposes
1999  * only.  For a user mode async implementation, it would be best to do it in
2000  * a userland subroutine.
2001  */
2002 static int
2003 kern_aio_error(struct thread *td, struct aiocb *aiocbp, struct aiocb_ops *ops)
2004 {
2005         struct proc *p = td->td_proc;
2006         struct aiocblist *cb;
2007         struct kaioinfo *ki;
2008         int status;
2009
2010         ki = p->p_aioinfo;
2011         if (ki == NULL) {
2012                 td->td_retval[0] = EINVAL;
2013                 return (0);
2014         }
2015
2016         AIO_LOCK(ki);
2017         TAILQ_FOREACH(cb, &ki->kaio_all, allist) {
2018                 if (cb->uuaiocb == aiocbp) {
2019                         if (cb->jobstate == JOBST_JOBFINISHED)
2020                                 td->td_retval[0] =
2021                                         cb->uaiocb._aiocb_private.error;
2022                         else
2023                                 td->td_retval[0] = EINPROGRESS;
2024                         AIO_UNLOCK(ki);
2025                         return (0);
2026                 }
2027         }
2028         AIO_UNLOCK(ki);
2029
2030         /*
2031          * Hack for failure of aio_aqueue.
2032          */
2033         status = ops->fetch_status(aiocbp);
2034         if (status == -1) {
2035                 td->td_retval[0] = ops->fetch_error(aiocbp);
2036                 return (0);
2037         }
2038
2039         td->td_retval[0] = EINVAL;
2040         return (0);
2041 }
2042
2043 int
2044 aio_error(struct thread *td, struct aio_error_args *uap)
2045 {
2046
2047         return (kern_aio_error(td, uap->aiocbp, &aiocb_ops));
2048 }
2049
2050 /* syscall - asynchronous read from a file (REALTIME) */
2051 int
2052 oaio_read(struct thread *td, struct oaio_read_args *uap)
2053 {
2054
2055         return (aio_aqueue(td, (struct aiocb *)uap->aiocbp, NULL, LIO_READ,
2056             &aiocb_ops_osigevent));
2057 }
2058
2059 int
2060 aio_read(struct thread *td, struct aio_read_args *uap)
2061 {
2062
2063         return (aio_aqueue(td, uap->aiocbp, NULL, LIO_READ, &aiocb_ops));
2064 }
2065
2066 /* syscall - asynchronous write to a file (REALTIME) */
2067 int
2068 oaio_write(struct thread *td, struct oaio_write_args *uap)
2069 {
2070
2071         return (aio_aqueue(td, (struct aiocb *)uap->aiocbp, NULL, LIO_WRITE,
2072             &aiocb_ops_osigevent));
2073 }
2074
2075 int
2076 aio_write(struct thread *td, struct aio_write_args *uap)
2077 {
2078
2079         return (aio_aqueue(td, uap->aiocbp, NULL, LIO_WRITE, &aiocb_ops));
2080 }
2081
2082 static int
2083 kern_lio_listio(struct thread *td, int mode, struct aiocb * const *uacb_list,
2084     struct aiocb **acb_list, int nent, struct sigevent *sig,
2085     struct aiocb_ops *ops)
2086 {
2087         struct proc *p = td->td_proc;
2088         struct aiocb *iocb;
2089         struct kaioinfo *ki;
2090         struct aioliojob *lj;
2091         struct kevent kev;
2092         int error;
2093         int nerror;
2094         int i;
2095
2096         if ((mode != LIO_NOWAIT) && (mode != LIO_WAIT))
2097                 return (EINVAL);
2098
2099         if (nent < 0 || nent > AIO_LISTIO_MAX)
2100                 return (EINVAL);
2101
2102         if (p->p_aioinfo == NULL)
2103                 aio_init_aioinfo(p);
2104
2105         ki = p->p_aioinfo;
2106
2107         lj = uma_zalloc(aiolio_zone, M_WAITOK);
2108         lj->lioj_flags = 0;
2109         lj->lioj_count = 0;
2110         lj->lioj_finished_count = 0;
2111         knlist_init(&lj->klist, AIO_MTX(ki), NULL, NULL, NULL);
2112         ksiginfo_init(&lj->lioj_ksi);
2113
2114         /*
2115          * Setup signal.
2116          */
2117         if (sig && (mode == LIO_NOWAIT)) {
2118                 bcopy(sig, &lj->lioj_signal, sizeof(lj->lioj_signal));
2119                 if (lj->lioj_signal.sigev_notify == SIGEV_KEVENT) {
2120                         /* Assume only new style KEVENT */
2121                         kev.filter = EVFILT_LIO;
2122                         kev.flags = EV_ADD | EV_ENABLE | EV_FLAG1;
2123                         kev.ident = (uintptr_t)uacb_list; /* something unique */
2124                         kev.data = (intptr_t)lj;
2125                         /* pass user defined sigval data */
2126                         kev.udata = lj->lioj_signal.sigev_value.sival_ptr;
2127                         error = kqfd_register(
2128                             lj->lioj_signal.sigev_notify_kqueue, &kev, td, 1);
2129                         if (error) {
2130                                 uma_zfree(aiolio_zone, lj);
2131                                 return (error);
2132                         }
2133                 } else if (lj->lioj_signal.sigev_notify == SIGEV_NONE) {
2134                         ;
2135                 } else if (lj->lioj_signal.sigev_notify == SIGEV_SIGNAL ||
2136                            lj->lioj_signal.sigev_notify == SIGEV_THREAD_ID) {
2137                                 if (!_SIG_VALID(lj->lioj_signal.sigev_signo)) {
2138                                         uma_zfree(aiolio_zone, lj);
2139                                         return EINVAL;
2140                                 }
2141                                 lj->lioj_flags |= LIOJ_SIGNAL;
2142                 } else {
2143                         uma_zfree(aiolio_zone, lj);
2144                         return EINVAL;
2145                 }
2146         }
2147
2148         AIO_LOCK(ki);
2149         TAILQ_INSERT_TAIL(&ki->kaio_liojoblist, lj, lioj_list);
2150         /*
2151          * Add extra aiocb count to avoid the lio to be freed
2152          * by other threads doing aio_waitcomplete or aio_return,
2153          * and prevent event from being sent until we have queued
2154          * all tasks.
2155          */
2156         lj->lioj_count = 1;
2157         AIO_UNLOCK(ki);
2158
2159         /*
2160          * Get pointers to the list of I/O requests.
2161          */
2162         nerror = 0;
2163         for (i = 0; i < nent; i++) {
2164                 iocb = acb_list[i];
2165                 if (iocb != NULL) {
2166                         error = aio_aqueue(td, iocb, lj, LIO_NOP, ops);
2167                         if (error != 0)
2168                                 nerror++;
2169                 }
2170         }
2171
2172         error = 0;
2173         AIO_LOCK(ki);
2174         if (mode == LIO_WAIT) {
2175                 while (lj->lioj_count - 1 != lj->lioj_finished_count) {
2176                         ki->kaio_flags |= KAIO_WAKEUP;
2177                         error = msleep(&p->p_aioinfo, AIO_MTX(ki),
2178                             PRIBIO | PCATCH, "aiospn", 0);
2179                         if (error == ERESTART)
2180                                 error = EINTR;
2181                         if (error)
2182                                 break;
2183                 }
2184         } else {
2185                 if (lj->lioj_count - 1 == lj->lioj_finished_count) {
2186                         if (lj->lioj_signal.sigev_notify == SIGEV_KEVENT) {
2187                                 lj->lioj_flags |= LIOJ_KEVENT_POSTED;
2188                                 KNOTE_LOCKED(&lj->klist, 1);
2189                         }
2190                         if ((lj->lioj_flags & (LIOJ_SIGNAL|LIOJ_SIGNAL_POSTED))
2191                             == LIOJ_SIGNAL
2192                             && (lj->lioj_signal.sigev_notify == SIGEV_SIGNAL ||
2193                             lj->lioj_signal.sigev_notify == SIGEV_THREAD_ID)) {
2194                                 aio_sendsig(p, &lj->lioj_signal,
2195                                             &lj->lioj_ksi);
2196                                 lj->lioj_flags |= LIOJ_SIGNAL_POSTED;
2197                         }
2198                 }
2199         }
2200         lj->lioj_count--;
2201         if (lj->lioj_count == 0) {
2202                 TAILQ_REMOVE(&ki->kaio_liojoblist, lj, lioj_list);
2203                 knlist_delete(&lj->klist, curthread, 1);
2204                 PROC_LOCK(p);
2205                 sigqueue_take(&lj->lioj_ksi);
2206                 PROC_UNLOCK(p);
2207                 AIO_UNLOCK(ki);
2208                 uma_zfree(aiolio_zone, lj);
2209         } else
2210                 AIO_UNLOCK(ki);
2211
2212         if (nerror)
2213                 return (EIO);
2214         return (error);
2215 }
2216
2217 /* syscall - list directed I/O (REALTIME) */
2218 int
2219 olio_listio(struct thread *td, struct olio_listio_args *uap)
2220 {
2221         struct aiocb **acb_list;
2222         struct sigevent *sigp, sig;
2223         struct osigevent osig;
2224         int error, nent;
2225
2226         if ((uap->mode != LIO_NOWAIT) && (uap->mode != LIO_WAIT))
2227                 return (EINVAL);
2228
2229         nent = uap->nent;
2230         if (nent < 0 || nent > AIO_LISTIO_MAX)
2231                 return (EINVAL);
2232
2233         if (uap->sig && (uap->mode == LIO_NOWAIT)) {
2234                 error = copyin(uap->sig, &osig, sizeof(osig));
2235                 if (error)
2236                         return (error);
2237                 error = convert_old_sigevent(&osig, &sig);
2238                 if (error)
2239                         return (error);
2240                 sigp = &sig;
2241         } else
2242                 sigp = NULL;
2243
2244         acb_list = malloc(sizeof(struct aiocb *) * nent, M_LIO, M_WAITOK);
2245         error = copyin(uap->acb_list, acb_list, nent * sizeof(acb_list[0]));
2246         if (error == 0)
2247                 error = kern_lio_listio(td, uap->mode,
2248                     (struct aiocb * const *)uap->acb_list, acb_list, nent, sigp,
2249                     &aiocb_ops_osigevent);
2250         free(acb_list, M_LIO);
2251         return (error);
2252 }
2253
2254 /* syscall - list directed I/O (REALTIME) */
2255 int
2256 lio_listio(struct thread *td, struct lio_listio_args *uap)
2257 {
2258         struct aiocb **acb_list;
2259         struct sigevent *sigp, sig;
2260         int error, nent;
2261
2262         if ((uap->mode != LIO_NOWAIT) && (uap->mode != LIO_WAIT))
2263                 return (EINVAL);
2264
2265         nent = uap->nent;
2266         if (nent < 0 || nent > AIO_LISTIO_MAX)
2267                 return (EINVAL);
2268
2269         if (uap->sig && (uap->mode == LIO_NOWAIT)) {
2270                 error = copyin(uap->sig, &sig, sizeof(sig));
2271                 if (error)
2272                         return (error);
2273                 sigp = &sig;
2274         } else
2275                 sigp = NULL;
2276
2277         acb_list = malloc(sizeof(struct aiocb *) * nent, M_LIO, M_WAITOK);
2278         error = copyin(uap->acb_list, acb_list, nent * sizeof(acb_list[0]));
2279         if (error == 0)
2280                 error = kern_lio_listio(td, uap->mode, uap->acb_list, acb_list,
2281                     nent, sigp, &aiocb_ops);
2282         free(acb_list, M_LIO);
2283         return (error);
2284 }
2285
2286 /*
2287  * Called from interrupt thread for physio, we should return as fast
2288  * as possible, so we schedule a biohelper task.
2289  */
2290 static void
2291 aio_physwakeup(struct buf *bp)
2292 {
2293         struct aiocblist *aiocbe;
2294
2295         aiocbe = (struct aiocblist *)bp->b_caller1;
2296         taskqueue_enqueue(taskqueue_aiod_bio, &aiocbe->biotask);
2297 }
2298
2299 /*
2300  * Task routine to perform heavy tasks, process wakeup, and signals.
2301  */
2302 static void
2303 biohelper(void *context, int pending)
2304 {
2305         struct aiocblist *aiocbe = context;
2306         struct buf *bp;
2307         struct proc *userp;
2308         struct kaioinfo *ki;
2309         int nblks;
2310
2311         bp = aiocbe->bp;
2312         userp = aiocbe->userproc;
2313         ki = userp->p_aioinfo;
2314         AIO_LOCK(ki);
2315         aiocbe->uaiocb._aiocb_private.status -= bp->b_resid;
2316         aiocbe->uaiocb._aiocb_private.error = 0;
2317         if (bp->b_ioflags & BIO_ERROR)
2318                 aiocbe->uaiocb._aiocb_private.error = bp->b_error;
2319         nblks = btodb(aiocbe->uaiocb.aio_nbytes);
2320         if (aiocbe->uaiocb.aio_lio_opcode == LIO_WRITE)
2321                 aiocbe->outputcharge += nblks;
2322         else
2323                 aiocbe->inputcharge += nblks;
2324         aiocbe->bp = NULL;
2325         TAILQ_REMOVE(&userp->p_aioinfo->kaio_bufqueue, aiocbe, plist);
2326         ki->kaio_buffer_count--;
2327         aio_bio_done_notify(userp, aiocbe, DONE_BUF);
2328         AIO_UNLOCK(ki);
2329
2330         /* Release mapping into kernel space. */
2331         vunmapbuf(bp);
2332         relpbuf(bp, NULL);
2333         atomic_subtract_int(&num_buf_aio, 1);
2334 }
2335
2336 /* syscall - wait for the next completion of an aio request */
2337 static int
2338 kern_aio_waitcomplete(struct thread *td, struct aiocb **aiocbp,
2339     struct timespec *ts, struct aiocb_ops *ops)
2340 {
2341         struct proc *p = td->td_proc;
2342         struct timeval atv;
2343         struct kaioinfo *ki;
2344         struct aiocblist *cb;
2345         struct aiocb *uuaiocb;
2346         int error, status, timo;
2347
2348         ops->store_aiocb(aiocbp, NULL);
2349
2350         timo = 0;
2351         if (ts) {
2352                 if ((ts->tv_nsec < 0) || (ts->tv_nsec >= 1000000000))
2353                         return (EINVAL);
2354
2355                 TIMESPEC_TO_TIMEVAL(&atv, ts);
2356                 if (itimerfix(&atv))
2357                         return (EINVAL);
2358                 timo = tvtohz(&atv);
2359         }
2360
2361         if (p->p_aioinfo == NULL)
2362                 aio_init_aioinfo(p);
2363         ki = p->p_aioinfo;
2364
2365         error = 0;
2366         cb = NULL;
2367         AIO_LOCK(ki);
2368         while ((cb = TAILQ_FIRST(&ki->kaio_done)) == NULL) {
2369                 ki->kaio_flags |= KAIO_WAKEUP;
2370                 error = msleep(&p->p_aioinfo, AIO_MTX(ki), PRIBIO | PCATCH,
2371                     "aiowc", timo);
2372                 if (timo && error == ERESTART)
2373                         error = EINTR;
2374                 if (error)
2375                         break;
2376         }
2377
2378         if (cb != NULL) {
2379                 MPASS(cb->jobstate == JOBST_JOBFINISHED);
2380                 uuaiocb = cb->uuaiocb;
2381                 status = cb->uaiocb._aiocb_private.status;
2382                 error = cb->uaiocb._aiocb_private.error;
2383                 td->td_retval[0] = status;
2384                 if (cb->uaiocb.aio_lio_opcode == LIO_WRITE) {
2385                         td->td_ru.ru_oublock += cb->outputcharge;
2386                         cb->outputcharge = 0;
2387                 } else if (cb->uaiocb.aio_lio_opcode == LIO_READ) {
2388                         td->td_ru.ru_inblock += cb->inputcharge;
2389                         cb->inputcharge = 0;
2390                 }
2391                 aio_free_entry(cb);
2392                 AIO_UNLOCK(ki);
2393                 ops->store_aiocb(aiocbp, uuaiocb);
2394                 ops->store_error(uuaiocb, error);
2395                 ops->store_status(uuaiocb, status);
2396         } else
2397                 AIO_UNLOCK(ki);
2398
2399         return (error);
2400 }
2401
2402 int
2403 aio_waitcomplete(struct thread *td, struct aio_waitcomplete_args *uap)
2404 {
2405         struct timespec ts, *tsp;
2406         int error;
2407
2408         if (uap->timeout) {
2409                 /* Get timespec struct. */
2410                 error = copyin(uap->timeout, &ts, sizeof(ts));
2411                 if (error)
2412                         return (error);
2413                 tsp = &ts;
2414         } else
2415                 tsp = NULL;
2416
2417         return (kern_aio_waitcomplete(td, uap->aiocbp, tsp, &aiocb_ops));
2418 }
2419
2420 static int
2421 kern_aio_fsync(struct thread *td, int op, struct aiocb *aiocbp,
2422     struct aiocb_ops *ops)
2423 {
2424         struct proc *p = td->td_proc;
2425         struct kaioinfo *ki;
2426
2427         if (op != O_SYNC) /* XXX lack of O_DSYNC */
2428                 return (EINVAL);
2429         ki = p->p_aioinfo;
2430         if (ki == NULL)
2431                 aio_init_aioinfo(p);
2432         return (aio_aqueue(td, aiocbp, NULL, LIO_SYNC, ops));
2433 }
2434
2435 int
2436 aio_fsync(struct thread *td, struct aio_fsync_args *uap)
2437 {
2438
2439         return (kern_aio_fsync(td, uap->op, uap->aiocbp, &aiocb_ops));
2440 }
2441
2442 /* kqueue attach function */
2443 static int
2444 filt_aioattach(struct knote *kn)
2445 {
2446         struct aiocblist *aiocbe = (struct aiocblist *)kn->kn_sdata;
2447
2448         /*
2449          * The aiocbe pointer must be validated before using it, so
2450          * registration is restricted to the kernel; the user cannot
2451          * set EV_FLAG1.
2452          */
2453         if ((kn->kn_flags & EV_FLAG1) == 0)
2454                 return (EPERM);
2455         kn->kn_ptr.p_aio = aiocbe;
2456         kn->kn_flags &= ~EV_FLAG1;
2457
2458         knlist_add(&aiocbe->klist, kn, 0);
2459
2460         return (0);
2461 }
2462
2463 /* kqueue detach function */
2464 static void
2465 filt_aiodetach(struct knote *kn)
2466 {
2467         struct aiocblist *aiocbe = kn->kn_ptr.p_aio;
2468
2469         if (!knlist_empty(&aiocbe->klist))
2470                 knlist_remove(&aiocbe->klist, kn, 0);
2471 }
2472
2473 /* kqueue filter function */
2474 /*ARGSUSED*/
2475 static int
2476 filt_aio(struct knote *kn, long hint)
2477 {
2478         struct aiocblist *aiocbe = kn->kn_ptr.p_aio;
2479
2480         kn->kn_data = aiocbe->uaiocb._aiocb_private.error;
2481         if (aiocbe->jobstate != JOBST_JOBFINISHED)
2482                 return (0);
2483         kn->kn_flags |= EV_EOF;
2484         return (1);
2485 }
2486
2487 /* kqueue attach function */
2488 static int
2489 filt_lioattach(struct knote *kn)
2490 {
2491         struct aioliojob * lj = (struct aioliojob *)kn->kn_sdata;
2492
2493         /*
2494          * The aioliojob pointer must be validated before using it, so
2495          * registration is restricted to the kernel; the user cannot
2496          * set EV_FLAG1.
2497          */
2498         if ((kn->kn_flags & EV_FLAG1) == 0)
2499                 return (EPERM);
2500         kn->kn_ptr.p_lio = lj;
2501         kn->kn_flags &= ~EV_FLAG1;
2502
2503         knlist_add(&lj->klist, kn, 0);
2504
2505         return (0);
2506 }
2507
2508 /* kqueue detach function */
2509 static void
2510 filt_liodetach(struct knote *kn)
2511 {
2512         struct aioliojob * lj = kn->kn_ptr.p_lio;
2513
2514         if (!knlist_empty(&lj->klist))
2515                 knlist_remove(&lj->klist, kn, 0);
2516 }
2517
2518 /* kqueue filter function */
2519 /*ARGSUSED*/
2520 static int
2521 filt_lio(struct knote *kn, long hint)
2522 {
2523         struct aioliojob * lj = kn->kn_ptr.p_lio;
2524
2525         return (lj->lioj_flags & LIOJ_KEVENT_POSTED);
2526 }
2527
2528 #ifdef COMPAT_IA32
2529 #include <sys/mount.h>
2530 #include <sys/socket.h>
2531 #include <compat/freebsd32/freebsd32.h>
2532 #include <compat/freebsd32/freebsd32_proto.h>
2533 #include <compat/freebsd32/freebsd32_signal.h>
2534 #include <compat/freebsd32/freebsd32_syscall.h>
2535 #include <compat/freebsd32/freebsd32_util.h>
2536
2537 struct __aiocb_private32 {
2538         int32_t status;
2539         int32_t error;
2540         uint32_t kernelinfo;
2541 };
2542
2543 typedef struct oaiocb32 {
2544         int     aio_fildes;             /* File descriptor */
2545         uint64_t aio_offset __packed;   /* File offset for I/O */
2546         uint32_t aio_buf;               /* I/O buffer in process space */
2547         uint32_t aio_nbytes;            /* Number of bytes for I/O */
2548         struct  osigevent32 aio_sigevent; /* Signal to deliver */
2549         int     aio_lio_opcode;         /* LIO opcode */
2550         int     aio_reqprio;            /* Request priority -- ignored */
2551         struct  __aiocb_private32 _aiocb_private;
2552 } oaiocb32_t;
2553
2554 typedef struct aiocb32 {
2555         int32_t aio_fildes;             /* File descriptor */
2556         uint64_t aio_offset __packed;   /* File offset for I/O */
2557         uint32_t aio_buf;               /* I/O buffer in process space */
2558         uint32_t aio_nbytes;            /* Number of bytes for I/O */
2559         int     __spare__[2];
2560         uint32_t __spare2__;
2561         int     aio_lio_opcode;         /* LIO opcode */
2562         int     aio_reqprio;            /* Request priority -- ignored */
2563         struct __aiocb_private32 _aiocb_private;
2564         struct sigevent32 aio_sigevent; /* Signal to deliver */
2565 } aiocb32_t;
2566
2567 static int
2568 convert_old_sigevent32(struct osigevent32 *osig, struct sigevent *nsig)
2569 {
2570
2571         /*
2572          * Only SIGEV_NONE, SIGEV_SIGNAL, and SIGEV_KEVENT are
2573          * supported by AIO with the old sigevent structure.
2574          */
2575         CP(*osig, *nsig, sigev_notify);
2576         switch (nsig->sigev_notify) {
2577         case SIGEV_NONE:
2578                 break;
2579         case SIGEV_SIGNAL:
2580                 nsig->sigev_signo = osig->__sigev_u.__sigev_signo;
2581                 break;
2582         case SIGEV_KEVENT:
2583                 nsig->sigev_notify_kqueue =
2584                     osig->__sigev_u.__sigev_notify_kqueue;
2585                 PTRIN_CP(*osig, *nsig, sigev_value.sival_ptr);
2586                 break;
2587         default:
2588                 return (EINVAL);
2589         }
2590         return (0);
2591 }
2592
2593 static int
2594 aiocb32_copyin_old_sigevent(struct aiocb *ujob, struct aiocb *kjob)
2595 {
2596         struct oaiocb32 job32;
2597         int error;
2598
2599         bzero(kjob, sizeof(struct aiocb));
2600         error = copyin(ujob, &job32, sizeof(job32));
2601         if (error)
2602                 return (error);
2603
2604         CP(job32, *kjob, aio_fildes);
2605         CP(job32, *kjob, aio_offset);
2606         PTRIN_CP(job32, *kjob, aio_buf);
2607         CP(job32, *kjob, aio_nbytes);
2608         CP(job32, *kjob, aio_lio_opcode);
2609         CP(job32, *kjob, aio_reqprio);
2610         CP(job32, *kjob, _aiocb_private.status);
2611         CP(job32, *kjob, _aiocb_private.error);
2612         PTRIN_CP(job32, *kjob, _aiocb_private.kernelinfo);
2613         return (convert_old_sigevent32(&job32.aio_sigevent,
2614             &kjob->aio_sigevent));
2615 }
2616
2617 static int
2618 convert_sigevent32(struct sigevent32 *sig32, struct sigevent *sig)
2619 {
2620
2621         CP(*sig32, *sig, sigev_notify);
2622         switch (sig->sigev_notify) {
2623         case SIGEV_NONE:
2624                 break;
2625         case SIGEV_THREAD_ID:
2626                 CP(*sig32, *sig, sigev_notify_thread_id);
2627                 /* FALLTHROUGH */
2628         case SIGEV_SIGNAL:
2629                 CP(*sig32, *sig, sigev_signo);
2630                 break;
2631         case SIGEV_KEVENT:
2632                 CP(*sig32, *sig, sigev_notify_kqueue);
2633                 PTRIN_CP(*sig32, *sig, sigev_value.sival_ptr);
2634                 break;
2635         default:
2636                 return (EINVAL);
2637         }
2638         return (0);
2639 }
2640
2641 static int
2642 aiocb32_copyin(struct aiocb *ujob, struct aiocb *kjob)
2643 {
2644         struct aiocb32 job32;
2645         int error;
2646
2647         error = copyin(ujob, &job32, sizeof(job32));
2648         if (error)
2649                 return (error);
2650         CP(job32, *kjob, aio_fildes);
2651         CP(job32, *kjob, aio_offset);
2652         PTRIN_CP(job32, *kjob, aio_buf);
2653         CP(job32, *kjob, aio_nbytes);
2654         CP(job32, *kjob, aio_lio_opcode);
2655         CP(job32, *kjob, aio_reqprio);
2656         CP(job32, *kjob, _aiocb_private.status);
2657         CP(job32, *kjob, _aiocb_private.error);
2658         PTRIN_CP(job32, *kjob, _aiocb_private.kernelinfo);
2659         return (convert_sigevent32(&job32.aio_sigevent, &kjob->aio_sigevent));
2660 }
2661
2662 static long
2663 aiocb32_fetch_status(struct aiocb *ujob)
2664 {
2665         struct aiocb32 *ujob32;
2666
2667         ujob32 = (struct aiocb32 *)ujob;
2668         return (fuword32(&ujob32->_aiocb_private.status));
2669 }
2670
2671 static long
2672 aiocb32_fetch_error(struct aiocb *ujob)
2673 {
2674         struct aiocb32 *ujob32;
2675
2676         ujob32 = (struct aiocb32 *)ujob;
2677         return (fuword32(&ujob32->_aiocb_private.error));
2678 }
2679
2680 static int
2681 aiocb32_store_status(struct aiocb *ujob, long status)
2682 {
2683         struct aiocb32 *ujob32;
2684
2685         ujob32 = (struct aiocb32 *)ujob;
2686         return (suword32(&ujob32->_aiocb_private.status, status));
2687 }
2688
2689 static int
2690 aiocb32_store_error(struct aiocb *ujob, long error)
2691 {
2692         struct aiocb32 *ujob32;
2693
2694         ujob32 = (struct aiocb32 *)ujob;
2695         return (suword32(&ujob32->_aiocb_private.error, error));
2696 }
2697
2698 static int
2699 aiocb32_store_kernelinfo(struct aiocb *ujob, long jobref)
2700 {
2701         struct aiocb32 *ujob32;
2702
2703         ujob32 = (struct aiocb32 *)ujob;
2704         return (suword32(&ujob32->_aiocb_private.kernelinfo, jobref));
2705 }
2706
2707 static int
2708 aiocb32_store_aiocb(struct aiocb **ujobp, struct aiocb *ujob)
2709 {
2710
2711         return (suword32(ujobp, (long)ujob));
2712 }
2713
2714 static struct aiocb_ops aiocb32_ops = {
2715         .copyin = aiocb32_copyin,
2716         .fetch_status = aiocb32_fetch_status,
2717         .fetch_error = aiocb32_fetch_error,
2718         .store_status = aiocb32_store_status,
2719         .store_error = aiocb32_store_error,
2720         .store_kernelinfo = aiocb32_store_kernelinfo,
2721         .store_aiocb = aiocb32_store_aiocb,
2722 };
2723
2724 static struct aiocb_ops aiocb32_ops_osigevent = {
2725         .copyin = aiocb32_copyin_old_sigevent,
2726         .fetch_status = aiocb32_fetch_status,
2727         .fetch_error = aiocb32_fetch_error,
2728         .store_status = aiocb32_store_status,
2729         .store_error = aiocb32_store_error,
2730         .store_kernelinfo = aiocb32_store_kernelinfo,
2731         .store_aiocb = aiocb32_store_aiocb,
2732 };
2733
2734 int
2735 freebsd32_aio_return(struct thread *td, struct freebsd32_aio_return_args *uap)
2736 {
2737
2738         return (kern_aio_return(td, (struct aiocb *)uap->aiocbp, &aiocb32_ops));
2739 }
2740
2741 int
2742 freebsd32_aio_suspend(struct thread *td, struct freebsd32_aio_suspend_args *uap)
2743 {
2744         struct timespec32 ts32;
2745         struct timespec ts, *tsp;
2746         struct aiocb **ujoblist;
2747         uint32_t *ujoblist32;
2748         int error, i;
2749
2750         if (uap->nent < 0 || uap->nent > AIO_LISTIO_MAX)
2751                 return (EINVAL);
2752
2753         if (uap->timeout) {
2754                 /* Get timespec struct. */
2755                 if ((error = copyin(uap->timeout, &ts32, sizeof(ts32))) != 0)
2756                         return (error);
2757                 CP(ts32, ts, tv_sec);
2758                 CP(ts32, ts, tv_nsec);
2759                 tsp = &ts;
2760         } else
2761                 tsp = NULL;
2762
2763         ujoblist = uma_zalloc(aiol_zone, M_WAITOK);
2764         ujoblist32 = (uint32_t *)ujoblist;
2765         error = copyin(uap->aiocbp, ujoblist32, uap->nent *
2766             sizeof(ujoblist32[0]));
2767         if (error == 0) {
2768                 for (i = uap->nent; i > 0; i--)
2769                         ujoblist[i] = PTRIN(ujoblist32[i]);
2770
2771                 error = kern_aio_suspend(td, uap->nent, ujoblist, tsp);
2772         }
2773         uma_zfree(aiol_zone, ujoblist);
2774         return (error);
2775 }
2776
2777 int
2778 freebsd32_aio_cancel(struct thread *td, struct freebsd32_aio_cancel_args *uap)
2779 {
2780
2781         return (aio_cancel(td, (struct aio_cancel_args *)uap));
2782 }
2783
2784 int
2785 freebsd32_aio_error(struct thread *td, struct freebsd32_aio_error_args *uap)
2786 {
2787
2788         return (kern_aio_error(td, (struct aiocb *)uap->aiocbp, &aiocb32_ops));
2789 }
2790
2791 int
2792 freebsd32_oaio_read(struct thread *td, struct freebsd32_oaio_read_args *uap)
2793 {
2794
2795         return (aio_aqueue(td, (struct aiocb *)uap->aiocbp, NULL, LIO_READ,
2796             &aiocb32_ops_osigevent));
2797 }
2798
2799 int
2800 freebsd32_aio_read(struct thread *td, struct freebsd32_aio_read_args *uap)
2801 {
2802
2803         return (aio_aqueue(td, (struct aiocb *)uap->aiocbp, NULL, LIO_READ,
2804             &aiocb32_ops));
2805 }
2806
2807 int
2808 freebsd32_oaio_write(struct thread *td, struct freebsd32_oaio_write_args *uap)
2809 {
2810
2811         return (aio_aqueue(td, (struct aiocb *)uap->aiocbp, NULL, LIO_WRITE,
2812             &aiocb32_ops_osigevent));
2813 }
2814
2815 int
2816 freebsd32_aio_write(struct thread *td, struct freebsd32_aio_write_args *uap)
2817 {
2818
2819         return (aio_aqueue(td, (struct aiocb *)uap->aiocbp, NULL, LIO_WRITE,
2820             &aiocb32_ops));
2821 }
2822
2823 int
2824 freebsd32_aio_waitcomplete(struct thread *td,
2825     struct freebsd32_aio_waitcomplete_args *uap)
2826 {
2827         struct timespec32 ts32;
2828         struct timespec ts, *tsp;
2829         int error;
2830
2831         if (uap->timeout) {
2832                 /* Get timespec struct. */
2833                 error = copyin(uap->timeout, &ts32, sizeof(ts32));
2834                 if (error)
2835                         return (error);
2836                 CP(ts32, ts, tv_sec);
2837                 CP(ts32, ts, tv_nsec);
2838                 tsp = &ts;
2839         } else
2840                 tsp = NULL;
2841
2842         return (kern_aio_waitcomplete(td, (struct aiocb **)uap->aiocbp, tsp,
2843             &aiocb32_ops));
2844 }
2845
2846 int
2847 freebsd32_aio_fsync(struct thread *td, struct freebsd32_aio_fsync_args *uap)
2848 {
2849
2850         return (kern_aio_fsync(td, uap->op, (struct aiocb *)uap->aiocbp,
2851             &aiocb32_ops));
2852 }
2853
2854 int
2855 freebsd32_olio_listio(struct thread *td, struct freebsd32_olio_listio_args *uap)
2856 {
2857         struct aiocb **acb_list;
2858         struct sigevent *sigp, sig;
2859         struct osigevent32 osig;
2860         uint32_t *acb_list32;
2861         int error, i, nent;
2862
2863         if ((uap->mode != LIO_NOWAIT) && (uap->mode != LIO_WAIT))
2864                 return (EINVAL);
2865
2866         nent = uap->nent;
2867         if (nent < 0 || nent > AIO_LISTIO_MAX)
2868                 return (EINVAL);
2869
2870         if (uap->sig && (uap->mode == LIO_NOWAIT)) {
2871                 error = copyin(uap->sig, &osig, sizeof(osig));
2872                 if (error)
2873                         return (error);
2874                 error = convert_old_sigevent32(&osig, &sig);
2875                 if (error)
2876                         return (error);
2877                 sigp = &sig;
2878         } else
2879                 sigp = NULL;
2880
2881         acb_list32 = malloc(sizeof(uint32_t) * nent, M_LIO, M_WAITOK);
2882         error = copyin(uap->acb_list, acb_list32, nent * sizeof(uint32_t));
2883         if (error) {
2884                 free(acb_list32, M_LIO);
2885                 return (error);
2886         }
2887         acb_list = malloc(sizeof(struct aiocb *) * nent, M_LIO, M_WAITOK);
2888         for (i = 0; i < nent; i++)
2889                 acb_list[i] = PTRIN(acb_list32[i]);
2890         free(acb_list32, M_LIO);
2891
2892         error = kern_lio_listio(td, uap->mode,
2893             (struct aiocb * const *)uap->acb_list, acb_list, nent, sigp,
2894             &aiocb32_ops_osigevent);
2895         free(acb_list, M_LIO);
2896         return (error);
2897 }
2898
2899 int
2900 freebsd32_lio_listio(struct thread *td, struct freebsd32_lio_listio_args *uap)
2901 {
2902         struct aiocb **acb_list;
2903         struct sigevent *sigp, sig;
2904         struct sigevent32 sig32;
2905         uint32_t *acb_list32;
2906         int error, i, nent;
2907
2908         if ((uap->mode != LIO_NOWAIT) && (uap->mode != LIO_WAIT))
2909                 return (EINVAL);
2910
2911         nent = uap->nent;
2912         if (nent < 0 || nent > AIO_LISTIO_MAX)
2913                 return (EINVAL);
2914
2915         if (uap->sig && (uap->mode == LIO_NOWAIT)) {
2916                 error = copyin(uap->sig, &sig32, sizeof(sig32));
2917                 if (error)
2918                         return (error);
2919                 error = convert_sigevent32(&sig32, &sig);
2920                 if (error)
2921                         return (error);
2922                 sigp = &sig;
2923         } else
2924                 sigp = NULL;
2925
2926         acb_list32 = malloc(sizeof(uint32_t) * nent, M_LIO, M_WAITOK);
2927         error = copyin(uap->acb_list, acb_list32, nent * sizeof(uint32_t));
2928         if (error) {
2929                 free(acb_list32, M_LIO);
2930                 return (error);
2931         }
2932         acb_list = malloc(sizeof(struct aiocb *) * nent, M_LIO, M_WAITOK);
2933         for (i = 0; i < nent; i++)
2934                 acb_list[i] = PTRIN(acb_list32[i]);
2935         free(acb_list32, M_LIO);
2936
2937         error = kern_lio_listio(td, uap->mode,
2938             (struct aiocb * const *)uap->acb_list, acb_list, nent, sigp,
2939             &aiocb32_ops);
2940         free(acb_list, M_LIO);
2941         return (error);
2942 }
2943
2944 SYSCALL32_MODULE_HELPER(freebsd32_aio_return);
2945 SYSCALL32_MODULE_HELPER(freebsd32_aio_suspend);
2946 SYSCALL32_MODULE_HELPER(freebsd32_aio_cancel);
2947 SYSCALL32_MODULE_HELPER(freebsd32_aio_error);
2948 SYSCALL32_MODULE_HELPER(freebsd32_aio_fsync);
2949 SYSCALL32_MODULE_HELPER(freebsd32_aio_read);
2950 SYSCALL32_MODULE_HELPER(freebsd32_aio_write);
2951 SYSCALL32_MODULE_HELPER(freebsd32_aio_waitcomplete);
2952 SYSCALL32_MODULE_HELPER(freebsd32_lio_listio);
2953 SYSCALL32_MODULE_HELPER(freebsd32_oaio_read);
2954 SYSCALL32_MODULE_HELPER(freebsd32_oaio_write);
2955 SYSCALL32_MODULE_HELPER(freebsd32_olio_listio);
2956 #endif