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