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