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