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