2 * An async IO implementation for Linux
3 * Written by Benjamin LaHaise <bcrl@kvack.org>
5 * Implements an efficient asynchronous io interface.
7 * Copyright 2000, 2001, 2002 Red Hat, Inc. All Rights Reserved.
9 * See ../COPYING for licensing terms.
11 #define pr_fmt(fmt) "%s: " fmt, __func__
13 #include <linux/kernel.h>
14 #include <linux/init.h>
15 #include <linux/errno.h>
16 #include <linux/time.h>
17 #include <linux/aio_abi.h>
18 #include <linux/export.h>
19 #include <linux/syscalls.h>
20 #include <linux/backing-dev.h>
21 #include <linux/uio.h>
23 #include <linux/sched.h>
25 #include <linux/file.h>
27 #include <linux/mman.h>
28 #include <linux/mmu_context.h>
29 #include <linux/slab.h>
30 #include <linux/timer.h>
31 #include <linux/aio.h>
32 #include <linux/highmem.h>
33 #include <linux/workqueue.h>
34 #include <linux/security.h>
35 #include <linux/eventfd.h>
36 #include <linux/blkdev.h>
37 #include <linux/compat.h>
38 #include <linux/anon_inodes.h>
39 #include <linux/migrate.h>
40 #include <linux/ramfs.h>
42 #include <asm/kmap_types.h>
43 #include <asm/uaccess.h>
47 #define AIO_RING_MAGIC 0xa10a10a1
48 #define AIO_RING_COMPAT_FEATURES 1
49 #define AIO_RING_INCOMPAT_FEATURES 0
51 unsigned id
; /* kernel internal index number */
52 unsigned nr
; /* number of io_events */
57 unsigned compat_features
;
58 unsigned incompat_features
;
59 unsigned header_length
; /* size of aio_ring */
62 struct io_event io_events
[0];
63 }; /* 128 bytes + ring size */
65 #define AIO_RING_PAGES 8
71 /* This needs improving */
72 unsigned long user_id
;
73 struct hlist_node list
;
76 * This is what userspace passed to io_setup(), it's not used for
77 * anything but counting against the global max_reqs quota.
79 * The real limit is nr_events - 1, which will be larger (see
84 /* Size of ringbuffer, in units of struct io_event */
87 unsigned long mmap_base
;
88 unsigned long mmap_size
;
90 struct page
**ring_pages
;
93 struct rcu_head rcu_head
;
94 struct work_struct rcu_work
;
98 } ____cacheline_aligned_in_smp
;
102 struct list_head active_reqs
; /* used for cancellation */
103 } ____cacheline_aligned_in_smp
;
106 struct mutex ring_lock
;
107 wait_queue_head_t wait
;
108 } ____cacheline_aligned_in_smp
;
112 spinlock_t completion_lock
;
113 } ____cacheline_aligned_in_smp
;
115 struct page
*internal_pages
[AIO_RING_PAGES
];
116 struct file
*aio_ring_file
;
119 /*------ sysctl variables----*/
120 static DEFINE_SPINLOCK(aio_nr_lock
);
121 unsigned long aio_nr
; /* current system wide number of aio requests */
122 unsigned long aio_max_nr
= 0x10000; /* system wide maximum number of aio requests */
123 /*----end sysctl variables---*/
125 static struct kmem_cache
*kiocb_cachep
;
126 static struct kmem_cache
*kioctx_cachep
;
129 * Creates the slab caches used by the aio routines, panic on
130 * failure as this is done early during the boot sequence.
132 static int __init
aio_setup(void)
134 kiocb_cachep
= KMEM_CACHE(kiocb
, SLAB_HWCACHE_ALIGN
|SLAB_PANIC
);
135 kioctx_cachep
= KMEM_CACHE(kioctx
,SLAB_HWCACHE_ALIGN
|SLAB_PANIC
);
137 pr_debug("sizeof(struct page) = %zu\n", sizeof(struct page
));
141 __initcall(aio_setup
);
143 static void aio_free_ring(struct kioctx
*ctx
)
146 struct file
*aio_ring_file
= ctx
->aio_ring_file
;
148 for (i
= 0; i
< ctx
->nr_pages
; i
++) {
149 pr_debug("pid(%d) [%d] page->count=%d\n", current
->pid
, i
,
150 page_count(ctx
->ring_pages
[i
]));
151 put_page(ctx
->ring_pages
[i
]);
154 if (ctx
->ring_pages
&& ctx
->ring_pages
!= ctx
->internal_pages
)
155 kfree(ctx
->ring_pages
);
158 truncate_setsize(aio_ring_file
->f_inode
, 0);
159 pr_debug("pid(%d) i_nlink=%u d_count=%d d_unhashed=%d i_count=%d\n",
160 current
->pid
, aio_ring_file
->f_inode
->i_nlink
,
161 aio_ring_file
->f_path
.dentry
->d_count
,
162 d_unhashed(aio_ring_file
->f_path
.dentry
),
163 atomic_read(&aio_ring_file
->f_inode
->i_count
));
165 ctx
->aio_ring_file
= NULL
;
169 static int aio_ring_mmap(struct file
*file
, struct vm_area_struct
*vma
)
171 vma
->vm_ops
= &generic_file_vm_ops
;
175 static const struct file_operations aio_ring_fops
= {
176 .mmap
= aio_ring_mmap
,
179 static int aio_set_page_dirty(struct page
*page
)
184 static int aio_migratepage(struct address_space
*mapping
, struct page
*new,
185 struct page
*old
, enum migrate_mode mode
)
187 struct kioctx
*ctx
= mapping
->private_data
;
189 unsigned idx
= old
->index
;
192 /* Writeback must be complete */
193 BUG_ON(PageWriteback(old
));
196 rc
= migrate_page_move_mapping(mapping
, new, old
, NULL
, mode
);
197 if (rc
!= MIGRATEPAGE_SUCCESS
) {
204 spin_lock_irqsave(&ctx
->completion_lock
, flags
);
205 migrate_page_copy(new, old
);
206 ctx
->ring_pages
[idx
] = new;
207 spin_unlock_irqrestore(&ctx
->completion_lock
, flags
);
212 static const struct address_space_operations aio_ctx_aops
= {
213 .set_page_dirty
= aio_set_page_dirty
,
214 .migratepage
= aio_migratepage
,
217 static int aio_setup_ring(struct kioctx
*ctx
)
219 struct aio_ring
*ring
;
220 unsigned nr_events
= ctx
->max_reqs
;
221 struct mm_struct
*mm
= current
->mm
;
222 unsigned long size
, populate
;
227 /* Compensate for the ring buffer's head/tail overlap entry */
228 nr_events
+= 2; /* 1 is required, 2 for good luck */
230 size
= sizeof(struct aio_ring
);
231 size
+= sizeof(struct io_event
) * nr_events
;
233 nr_pages
= PFN_UP(size
);
237 file
= anon_inode_getfile_private("[aio]", &aio_ring_fops
, ctx
, O_RDWR
);
239 ctx
->aio_ring_file
= NULL
;
243 file
->f_inode
->i_mapping
->a_ops
= &aio_ctx_aops
;
244 file
->f_inode
->i_mapping
->private_data
= ctx
;
245 file
->f_inode
->i_size
= PAGE_SIZE
* (loff_t
)nr_pages
;
247 for (i
= 0; i
< nr_pages
; i
++) {
249 page
= find_or_create_page(file
->f_inode
->i_mapping
,
250 i
, GFP_HIGHUSER
| __GFP_ZERO
);
253 pr_debug("pid(%d) page[%d]->count=%d\n",
254 current
->pid
, i
, page_count(page
));
255 SetPageUptodate(page
);
259 ctx
->aio_ring_file
= file
;
260 nr_events
= (PAGE_SIZE
* nr_pages
- sizeof(struct aio_ring
))
261 / sizeof(struct io_event
);
263 ctx
->ring_pages
= ctx
->internal_pages
;
264 if (nr_pages
> AIO_RING_PAGES
) {
265 ctx
->ring_pages
= kcalloc(nr_pages
, sizeof(struct page
*),
267 if (!ctx
->ring_pages
)
271 ctx
->mmap_size
= nr_pages
* PAGE_SIZE
;
272 pr_debug("attempting mmap of %lu bytes\n", ctx
->mmap_size
);
274 down_write(&mm
->mmap_sem
);
275 ctx
->mmap_base
= do_mmap_pgoff(ctx
->aio_ring_file
, 0, ctx
->mmap_size
,
276 PROT_READ
| PROT_WRITE
,
277 MAP_SHARED
| MAP_POPULATE
, 0, &populate
);
278 if (IS_ERR((void *)ctx
->mmap_base
)) {
279 up_write(&mm
->mmap_sem
);
284 up_write(&mm
->mmap_sem
);
286 mm_populate(ctx
->mmap_base
, populate
);
288 pr_debug("mmap address: 0x%08lx\n", ctx
->mmap_base
);
289 ctx
->nr_pages
= get_user_pages(current
, mm
, ctx
->mmap_base
, nr_pages
,
290 1, 0, ctx
->ring_pages
, NULL
);
291 for (i
= 0; i
< ctx
->nr_pages
; i
++)
292 put_page(ctx
->ring_pages
[i
]);
294 if (unlikely(ctx
->nr_pages
!= nr_pages
)) {
299 ctx
->user_id
= ctx
->mmap_base
;
300 ctx
->nr_events
= nr_events
; /* trusted copy */
302 ring
= kmap_atomic(ctx
->ring_pages
[0]);
303 ring
->nr
= nr_events
; /* user copy */
304 ring
->id
= ctx
->user_id
;
305 ring
->head
= ring
->tail
= 0;
306 ring
->magic
= AIO_RING_MAGIC
;
307 ring
->compat_features
= AIO_RING_COMPAT_FEATURES
;
308 ring
->incompat_features
= AIO_RING_INCOMPAT_FEATURES
;
309 ring
->header_length
= sizeof(struct aio_ring
);
311 flush_dcache_page(ctx
->ring_pages
[0]);
316 #define AIO_EVENTS_PER_PAGE (PAGE_SIZE / sizeof(struct io_event))
317 #define AIO_EVENTS_FIRST_PAGE ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
318 #define AIO_EVENTS_OFFSET (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
320 void kiocb_set_cancel_fn(struct kiocb
*req
, kiocb_cancel_fn
*cancel
)
322 struct kioctx
*ctx
= req
->ki_ctx
;
325 spin_lock_irqsave(&ctx
->ctx_lock
, flags
);
327 if (!req
->ki_list
.next
)
328 list_add(&req
->ki_list
, &ctx
->active_reqs
);
330 req
->ki_cancel
= cancel
;
332 spin_unlock_irqrestore(&ctx
->ctx_lock
, flags
);
334 EXPORT_SYMBOL(kiocb_set_cancel_fn
);
336 static int kiocb_cancel(struct kioctx
*ctx
, struct kiocb
*kiocb
,
337 struct io_event
*res
)
339 kiocb_cancel_fn
*old
, *cancel
;
343 * Don't want to set kiocb->ki_cancel = KIOCB_CANCELLED unless it
344 * actually has a cancel function, hence the cmpxchg()
347 cancel
= ACCESS_ONCE(kiocb
->ki_cancel
);
349 if (!cancel
|| cancel
== KIOCB_CANCELLED
)
353 cancel
= cmpxchg(&kiocb
->ki_cancel
, old
, KIOCB_CANCELLED
);
354 } while (cancel
!= old
);
356 atomic_inc(&kiocb
->ki_users
);
357 spin_unlock_irq(&ctx
->ctx_lock
);
359 memset(res
, 0, sizeof(*res
));
360 res
->obj
= (u64
)(unsigned long)kiocb
->ki_obj
.user
;
361 res
->data
= kiocb
->ki_user_data
;
362 ret
= cancel(kiocb
, res
);
364 spin_lock_irq(&ctx
->ctx_lock
);
369 static void free_ioctx_rcu(struct rcu_head
*head
)
371 struct kioctx
*ctx
= container_of(head
, struct kioctx
, rcu_head
);
372 kmem_cache_free(kioctx_cachep
, ctx
);
376 * When this function runs, the kioctx has been removed from the "hash table"
377 * and ctx->users has dropped to 0, so we know no more kiocbs can be submitted -
378 * now it's safe to cancel any that need to be.
380 static void free_ioctx(struct kioctx
*ctx
)
382 struct aio_ring
*ring
;
385 unsigned head
, avail
;
387 spin_lock_irq(&ctx
->ctx_lock
);
389 while (!list_empty(&ctx
->active_reqs
)) {
390 req
= list_first_entry(&ctx
->active_reqs
,
391 struct kiocb
, ki_list
);
393 list_del_init(&req
->ki_list
);
394 kiocb_cancel(ctx
, req
, &res
);
397 spin_unlock_irq(&ctx
->ctx_lock
);
399 ring
= kmap_atomic(ctx
->ring_pages
[0]);
403 while (atomic_read(&ctx
->reqs_active
) > 0) {
404 wait_event(ctx
->wait
,
406 atomic_read(&ctx
->reqs_active
) <= 0);
408 avail
= (head
<= ctx
->tail
? ctx
->tail
: ctx
->nr_events
) - head
;
410 atomic_sub(avail
, &ctx
->reqs_active
);
412 head
%= ctx
->nr_events
;
415 WARN_ON(atomic_read(&ctx
->reqs_active
) < 0);
419 pr_debug("freeing %p\n", ctx
);
422 * Here the call_rcu() is between the wait_event() for reqs_active to
423 * hit 0, and freeing the ioctx.
425 * aio_complete() decrements reqs_active, but it has to touch the ioctx
426 * after to issue a wakeup so we use rcu.
428 call_rcu(&ctx
->rcu_head
, free_ioctx_rcu
);
431 static void put_ioctx(struct kioctx
*ctx
)
433 if (unlikely(atomic_dec_and_test(&ctx
->users
)))
438 * Allocates and initializes an ioctx. Returns an ERR_PTR if it failed.
440 static struct kioctx
*ioctx_alloc(unsigned nr_events
)
442 struct mm_struct
*mm
= current
->mm
;
446 /* Prevent overflows */
447 if ((nr_events
> (0x10000000U
/ sizeof(struct io_event
))) ||
448 (nr_events
> (0x10000000U
/ sizeof(struct kiocb
)))) {
449 pr_debug("ENOMEM: nr_events too high\n");
450 return ERR_PTR(-EINVAL
);
453 if (!nr_events
|| (unsigned long)nr_events
> aio_max_nr
)
454 return ERR_PTR(-EAGAIN
);
456 ctx
= kmem_cache_zalloc(kioctx_cachep
, GFP_KERNEL
);
458 return ERR_PTR(-ENOMEM
);
460 ctx
->max_reqs
= nr_events
;
462 atomic_set(&ctx
->users
, 2);
463 atomic_set(&ctx
->dead
, 0);
464 spin_lock_init(&ctx
->ctx_lock
);
465 spin_lock_init(&ctx
->completion_lock
);
466 mutex_init(&ctx
->ring_lock
);
467 init_waitqueue_head(&ctx
->wait
);
469 INIT_LIST_HEAD(&ctx
->active_reqs
);
471 if (aio_setup_ring(ctx
) < 0)
474 /* limit the number of system wide aios */
475 spin_lock(&aio_nr_lock
);
476 if (aio_nr
+ nr_events
> aio_max_nr
||
477 aio_nr
+ nr_events
< aio_nr
) {
478 spin_unlock(&aio_nr_lock
);
481 aio_nr
+= ctx
->max_reqs
;
482 spin_unlock(&aio_nr_lock
);
484 /* now link into global list. */
485 spin_lock(&mm
->ioctx_lock
);
486 hlist_add_head_rcu(&ctx
->list
, &mm
->ioctx_list
);
487 spin_unlock(&mm
->ioctx_lock
);
489 pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
490 ctx
, ctx
->user_id
, mm
, ctx
->nr_events
);
497 if (ctx
->aio_ring_file
)
498 fput(ctx
->aio_ring_file
);
499 kmem_cache_free(kioctx_cachep
, ctx
);
500 pr_debug("error allocating ioctx %d\n", err
);
504 static void kill_ioctx_work(struct work_struct
*work
)
506 struct kioctx
*ctx
= container_of(work
, struct kioctx
, rcu_work
);
508 wake_up_all(&ctx
->wait
);
512 static void kill_ioctx_rcu(struct rcu_head
*head
)
514 struct kioctx
*ctx
= container_of(head
, struct kioctx
, rcu_head
);
516 INIT_WORK(&ctx
->rcu_work
, kill_ioctx_work
);
517 schedule_work(&ctx
->rcu_work
);
521 * Cancels all outstanding aio requests on an aio context. Used
522 * when the processes owning a context have all exited to encourage
523 * the rapid destruction of the kioctx.
525 static void kill_ioctx(struct kioctx
*ctx
)
527 if (!atomic_xchg(&ctx
->dead
, 1)) {
528 hlist_del_rcu(&ctx
->list
);
531 * It'd be more correct to do this in free_ioctx(), after all
532 * the outstanding kiocbs have finished - but by then io_destroy
533 * has already returned, so io_setup() could potentially return
534 * -EAGAIN with no ioctxs actually in use (as far as userspace
537 spin_lock(&aio_nr_lock
);
538 BUG_ON(aio_nr
- ctx
->max_reqs
> aio_nr
);
539 aio_nr
-= ctx
->max_reqs
;
540 spin_unlock(&aio_nr_lock
);
543 vm_munmap(ctx
->mmap_base
, ctx
->mmap_size
);
545 /* Between hlist_del_rcu() and dropping the initial ref */
546 call_rcu(&ctx
->rcu_head
, kill_ioctx_rcu
);
550 /* wait_on_sync_kiocb:
551 * Waits on the given sync kiocb to complete.
553 ssize_t
wait_on_sync_kiocb(struct kiocb
*iocb
)
555 while (atomic_read(&iocb
->ki_users
)) {
556 set_current_state(TASK_UNINTERRUPTIBLE
);
557 if (!atomic_read(&iocb
->ki_users
))
561 __set_current_state(TASK_RUNNING
);
562 return iocb
->ki_user_data
;
564 EXPORT_SYMBOL(wait_on_sync_kiocb
);
567 * exit_aio: called when the last user of mm goes away. At this point, there is
568 * no way for any new requests to be submited or any of the io_* syscalls to be
569 * called on the context.
571 * There may be outstanding kiocbs, but free_ioctx() will explicitly wait on
574 void exit_aio(struct mm_struct
*mm
)
577 struct hlist_node
*n
;
579 hlist_for_each_entry_safe(ctx
, n
, &mm
->ioctx_list
, list
) {
580 if (1 != atomic_read(&ctx
->users
))
582 "exit_aio:ioctx still alive: %d %d %d\n",
583 atomic_read(&ctx
->users
),
584 atomic_read(&ctx
->dead
),
585 atomic_read(&ctx
->reqs_active
));
587 * We don't need to bother with munmap() here -
588 * exit_mmap(mm) is coming and it'll unmap everything.
589 * Since aio_free_ring() uses non-zero ->mmap_size
590 * as indicator that it needs to unmap the area,
591 * just set it to 0; aio_free_ring() is the only
592 * place that uses ->mmap_size, so it's safe.
601 * Allocate a slot for an aio request. Increments the ki_users count
602 * of the kioctx so that the kioctx stays around until all requests are
603 * complete. Returns NULL if no requests are free.
605 * Returns with kiocb->ki_users set to 2. The io submit code path holds
606 * an extra reference while submitting the i/o.
607 * This prevents races between the aio code path referencing the
608 * req (after submitting it) and aio_complete() freeing the req.
610 static inline struct kiocb
*aio_get_req(struct kioctx
*ctx
)
614 if (atomic_read(&ctx
->reqs_active
) >= ctx
->nr_events
)
617 if (atomic_inc_return(&ctx
->reqs_active
) > ctx
->nr_events
- 1)
620 req
= kmem_cache_alloc(kiocb_cachep
, GFP_KERNEL
|__GFP_ZERO
);
624 atomic_set(&req
->ki_users
, 2);
629 atomic_dec(&ctx
->reqs_active
);
633 static void kiocb_free(struct kiocb
*req
)
637 if (req
->ki_eventfd
!= NULL
)
638 eventfd_ctx_put(req
->ki_eventfd
);
641 if (req
->ki_iovec
!= &req
->ki_inline_vec
)
642 kfree(req
->ki_iovec
);
643 kmem_cache_free(kiocb_cachep
, req
);
646 void aio_put_req(struct kiocb
*req
)
648 if (atomic_dec_and_test(&req
->ki_users
))
651 EXPORT_SYMBOL(aio_put_req
);
653 static struct kioctx
*lookup_ioctx(unsigned long ctx_id
)
655 struct mm_struct
*mm
= current
->mm
;
656 struct kioctx
*ctx
, *ret
= NULL
;
660 hlist_for_each_entry_rcu(ctx
, &mm
->ioctx_list
, list
) {
661 if (ctx
->user_id
== ctx_id
) {
662 atomic_inc(&ctx
->users
);
673 * Called when the io request on the given iocb is complete.
675 void aio_complete(struct kiocb
*iocb
, long res
, long res2
)
677 struct kioctx
*ctx
= iocb
->ki_ctx
;
678 struct aio_ring
*ring
;
679 struct io_event
*ev_page
, *event
;
684 * Special case handling for sync iocbs:
685 * - events go directly into the iocb for fast handling
686 * - the sync task with the iocb in its stack holds the single iocb
687 * ref, no other paths have a way to get another ref
688 * - the sync task helpfully left a reference to itself in the iocb
690 if (is_sync_kiocb(iocb
)) {
691 BUG_ON(atomic_read(&iocb
->ki_users
) != 1);
692 iocb
->ki_user_data
= res
;
693 atomic_set(&iocb
->ki_users
, 0);
694 wake_up_process(iocb
->ki_obj
.tsk
);
699 * Take rcu_read_lock() in case the kioctx is being destroyed, as we
700 * need to issue a wakeup after decrementing reqs_active.
704 if (iocb
->ki_list
.next
) {
707 spin_lock_irqsave(&ctx
->ctx_lock
, flags
);
708 list_del(&iocb
->ki_list
);
709 spin_unlock_irqrestore(&ctx
->ctx_lock
, flags
);
713 * cancelled requests don't get events, userland was given one
714 * when the event got cancelled.
716 if (unlikely(xchg(&iocb
->ki_cancel
,
717 KIOCB_CANCELLED
) == KIOCB_CANCELLED
)) {
718 atomic_dec(&ctx
->reqs_active
);
719 /* Still need the wake_up in case free_ioctx is waiting */
724 * Add a completion event to the ring buffer. Must be done holding
725 * ctx->completion_lock to prevent other code from messing with the tail
726 * pointer since we might be called from irq context.
728 spin_lock_irqsave(&ctx
->completion_lock
, flags
);
731 pos
= tail
+ AIO_EVENTS_OFFSET
;
733 if (++tail
>= ctx
->nr_events
)
736 ev_page
= kmap_atomic(ctx
->ring_pages
[pos
/ AIO_EVENTS_PER_PAGE
]);
737 event
= ev_page
+ pos
% AIO_EVENTS_PER_PAGE
;
739 event
->obj
= (u64
)(unsigned long)iocb
->ki_obj
.user
;
740 event
->data
= iocb
->ki_user_data
;
744 kunmap_atomic(ev_page
);
745 flush_dcache_page(ctx
->ring_pages
[pos
/ AIO_EVENTS_PER_PAGE
]);
747 pr_debug("%p[%u]: %p: %p %Lx %lx %lx\n",
748 ctx
, tail
, iocb
, iocb
->ki_obj
.user
, iocb
->ki_user_data
,
751 /* after flagging the request as done, we
752 * must never even look at it again
754 smp_wmb(); /* make event visible before updating tail */
758 ring
= kmap_atomic(ctx
->ring_pages
[0]);
761 flush_dcache_page(ctx
->ring_pages
[0]);
763 spin_unlock_irqrestore(&ctx
->completion_lock
, flags
);
765 pr_debug("added to ring %p at [%u]\n", iocb
, tail
);
768 * Check if the user asked us to deliver the result through an
769 * eventfd. The eventfd_signal() function is safe to be called
772 if (iocb
->ki_eventfd
!= NULL
)
773 eventfd_signal(iocb
->ki_eventfd
, 1);
776 /* everything turned out well, dispose of the aiocb. */
780 * We have to order our ring_info tail store above and test
781 * of the wait list below outside the wait lock. This is
782 * like in wake_up_bit() where clearing a bit has to be
783 * ordered with the unlocked test.
787 if (waitqueue_active(&ctx
->wait
))
792 EXPORT_SYMBOL(aio_complete
);
795 * Pull an event off of the ioctx's event ring. Returns the number of
798 static long aio_read_events_ring(struct kioctx
*ctx
,
799 struct io_event __user
*event
, long nr
)
801 struct aio_ring
*ring
;
806 mutex_lock(&ctx
->ring_lock
);
808 ring
= kmap_atomic(ctx
->ring_pages
[0]);
812 pr_debug("h%u t%u m%u\n", head
, ctx
->tail
, ctx
->nr_events
);
814 if (head
== ctx
->tail
)
822 avail
= (head
<= ctx
->tail
? ctx
->tail
: ctx
->nr_events
) - head
;
823 if (head
== ctx
->tail
)
826 avail
= min(avail
, nr
- ret
);
827 avail
= min_t(long, avail
, AIO_EVENTS_PER_PAGE
-
828 ((head
+ AIO_EVENTS_OFFSET
) % AIO_EVENTS_PER_PAGE
));
830 pos
= head
+ AIO_EVENTS_OFFSET
;
831 page
= ctx
->ring_pages
[pos
/ AIO_EVENTS_PER_PAGE
];
832 pos
%= AIO_EVENTS_PER_PAGE
;
835 copy_ret
= copy_to_user(event
+ ret
, ev
+ pos
,
836 sizeof(*ev
) * avail
);
839 if (unlikely(copy_ret
)) {
846 head
%= ctx
->nr_events
;
849 ring
= kmap_atomic(ctx
->ring_pages
[0]);
852 flush_dcache_page(ctx
->ring_pages
[0]);
854 pr_debug("%li h%u t%u\n", ret
, head
, ctx
->tail
);
856 atomic_sub(ret
, &ctx
->reqs_active
);
858 mutex_unlock(&ctx
->ring_lock
);
863 static bool aio_read_events(struct kioctx
*ctx
, long min_nr
, long nr
,
864 struct io_event __user
*event
, long *i
)
866 long ret
= aio_read_events_ring(ctx
, event
+ *i
, nr
- *i
);
871 if (unlikely(atomic_read(&ctx
->dead
)))
877 return ret
< 0 || *i
>= min_nr
;
880 static long read_events(struct kioctx
*ctx
, long min_nr
, long nr
,
881 struct io_event __user
*event
,
882 struct timespec __user
*timeout
)
884 ktime_t until
= { .tv64
= KTIME_MAX
};
890 if (unlikely(copy_from_user(&ts
, timeout
, sizeof(ts
))))
893 until
= timespec_to_ktime(ts
);
897 * Note that aio_read_events() is being called as the conditional - i.e.
898 * we're calling it after prepare_to_wait() has set task state to
899 * TASK_INTERRUPTIBLE.
901 * But aio_read_events() can block, and if it blocks it's going to flip
902 * the task state back to TASK_RUNNING.
904 * This should be ok, provided it doesn't flip the state back to
905 * TASK_RUNNING and return 0 too much - that causes us to spin. That
906 * will only happen if the mutex_lock() call blocks, and we then find
907 * the ringbuffer empty. So in practice we should be ok, but it's
908 * something to be aware of when touching this code.
910 wait_event_interruptible_hrtimeout(ctx
->wait
,
911 aio_read_events(ctx
, min_nr
, nr
, event
, &ret
), until
);
913 if (!ret
&& signal_pending(current
))
920 * Create an aio_context capable of receiving at least nr_events.
921 * ctxp must not point to an aio_context that already exists, and
922 * must be initialized to 0 prior to the call. On successful
923 * creation of the aio_context, *ctxp is filled in with the resulting
924 * handle. May fail with -EINVAL if *ctxp is not initialized,
925 * if the specified nr_events exceeds internal limits. May fail
926 * with -EAGAIN if the specified nr_events exceeds the user's limit
927 * of available events. May fail with -ENOMEM if insufficient kernel
928 * resources are available. May fail with -EFAULT if an invalid
929 * pointer is passed for ctxp. Will fail with -ENOSYS if not
932 SYSCALL_DEFINE2(io_setup
, unsigned, nr_events
, aio_context_t __user
*, ctxp
)
934 struct kioctx
*ioctx
= NULL
;
938 ret
= get_user(ctx
, ctxp
);
943 if (unlikely(ctx
|| nr_events
== 0)) {
944 pr_debug("EINVAL: io_setup: ctx %lu nr_events %u\n",
949 ioctx
= ioctx_alloc(nr_events
);
950 ret
= PTR_ERR(ioctx
);
951 if (!IS_ERR(ioctx
)) {
952 ret
= put_user(ioctx
->user_id
, ctxp
);
963 * Destroy the aio_context specified. May cancel any outstanding
964 * AIOs and block on completion. Will fail with -ENOSYS if not
965 * implemented. May fail with -EINVAL if the context pointed to
968 SYSCALL_DEFINE1(io_destroy
, aio_context_t
, ctx
)
970 struct kioctx
*ioctx
= lookup_ioctx(ctx
);
971 if (likely(NULL
!= ioctx
)) {
976 pr_debug("EINVAL: io_destroy: invalid context id\n");
980 static void aio_advance_iovec(struct kiocb
*iocb
, ssize_t ret
)
982 struct iovec
*iov
= &iocb
->ki_iovec
[iocb
->ki_cur_seg
];
986 while (iocb
->ki_cur_seg
< iocb
->ki_nr_segs
&& ret
> 0) {
987 ssize_t
this = min((ssize_t
)iov
->iov_len
, ret
);
988 iov
->iov_base
+= this;
989 iov
->iov_len
-= this;
990 iocb
->ki_left
-= this;
992 if (iov
->iov_len
== 0) {
998 /* the caller should not have done more io than what fit in
999 * the remaining iovecs */
1000 BUG_ON(ret
> 0 && iocb
->ki_left
== 0);
1003 typedef ssize_t (aio_rw_op
)(struct kiocb
*, const struct iovec
*,
1004 unsigned long, loff_t
);
1006 static ssize_t
aio_rw_vect_retry(struct kiocb
*iocb
, int rw
, aio_rw_op
*rw_op
)
1008 struct file
*file
= iocb
->ki_filp
;
1009 struct address_space
*mapping
= file
->f_mapping
;
1010 struct inode
*inode
= mapping
->host
;
1013 /* This matches the pread()/pwrite() logic */
1014 if (iocb
->ki_pos
< 0)
1018 file_start_write(file
);
1020 ret
= rw_op(iocb
, &iocb
->ki_iovec
[iocb
->ki_cur_seg
],
1021 iocb
->ki_nr_segs
- iocb
->ki_cur_seg
,
1024 aio_advance_iovec(iocb
, ret
);
1026 /* retry all partial writes. retry partial reads as long as its a
1028 } while (ret
> 0 && iocb
->ki_left
> 0 &&
1030 (!S_ISFIFO(inode
->i_mode
) && !S_ISSOCK(inode
->i_mode
))));
1032 file_end_write(file
);
1034 /* This means we must have transferred all that we could */
1035 /* No need to retry anymore */
1036 if ((ret
== 0) || (iocb
->ki_left
== 0))
1037 ret
= iocb
->ki_nbytes
- iocb
->ki_left
;
1039 /* If we managed to write some out we return that, rather than
1040 * the eventual error. */
1042 && ret
< 0 && ret
!= -EIOCBQUEUED
1043 && iocb
->ki_nbytes
- iocb
->ki_left
)
1044 ret
= iocb
->ki_nbytes
- iocb
->ki_left
;
1049 static ssize_t
aio_setup_vectored_rw(int rw
, struct kiocb
*kiocb
, bool compat
)
1053 kiocb
->ki_nr_segs
= kiocb
->ki_nbytes
;
1055 #ifdef CONFIG_COMPAT
1057 ret
= compat_rw_copy_check_uvector(rw
,
1058 (struct compat_iovec __user
*)kiocb
->ki_buf
,
1059 kiocb
->ki_nr_segs
, 1, &kiocb
->ki_inline_vec
,
1063 ret
= rw_copy_check_uvector(rw
,
1064 (struct iovec __user
*)kiocb
->ki_buf
,
1065 kiocb
->ki_nr_segs
, 1, &kiocb
->ki_inline_vec
,
1070 /* ki_nbytes now reflect bytes instead of segs */
1071 kiocb
->ki_nbytes
= ret
;
1075 static ssize_t
aio_setup_single_vector(int rw
, struct kiocb
*kiocb
)
1077 if (unlikely(!access_ok(!rw
, kiocb
->ki_buf
, kiocb
->ki_nbytes
)))
1080 kiocb
->ki_iovec
= &kiocb
->ki_inline_vec
;
1081 kiocb
->ki_iovec
->iov_base
= kiocb
->ki_buf
;
1082 kiocb
->ki_iovec
->iov_len
= kiocb
->ki_nbytes
;
1083 kiocb
->ki_nr_segs
= 1;
1089 * Performs the initial checks and aio retry method
1090 * setup for the kiocb at the time of io submission.
1092 static ssize_t
aio_run_iocb(struct kiocb
*req
, bool compat
)
1094 struct file
*file
= req
->ki_filp
;
1100 switch (req
->ki_opcode
) {
1101 case IOCB_CMD_PREAD
:
1102 case IOCB_CMD_PREADV
:
1105 rw_op
= file
->f_op
->aio_read
;
1108 case IOCB_CMD_PWRITE
:
1109 case IOCB_CMD_PWRITEV
:
1112 rw_op
= file
->f_op
->aio_write
;
1115 if (unlikely(!(file
->f_mode
& mode
)))
1121 ret
= (req
->ki_opcode
== IOCB_CMD_PREADV
||
1122 req
->ki_opcode
== IOCB_CMD_PWRITEV
)
1123 ? aio_setup_vectored_rw(rw
, req
, compat
)
1124 : aio_setup_single_vector(rw
, req
);
1128 ret
= rw_verify_area(rw
, file
, &req
->ki_pos
, req
->ki_nbytes
);
1132 req
->ki_nbytes
= ret
;
1135 ret
= aio_rw_vect_retry(req
, rw
, rw_op
);
1138 case IOCB_CMD_FDSYNC
:
1139 if (!file
->f_op
->aio_fsync
)
1142 ret
= file
->f_op
->aio_fsync(req
, 1);
1145 case IOCB_CMD_FSYNC
:
1146 if (!file
->f_op
->aio_fsync
)
1149 ret
= file
->f_op
->aio_fsync(req
, 0);
1153 pr_debug("EINVAL: no operation provided\n");
1157 if (ret
!= -EIOCBQUEUED
) {
1159 * There's no easy way to restart the syscall since other AIO's
1160 * may be already running. Just fail this IO with EINTR.
1162 if (unlikely(ret
== -ERESTARTSYS
|| ret
== -ERESTARTNOINTR
||
1163 ret
== -ERESTARTNOHAND
||
1164 ret
== -ERESTART_RESTARTBLOCK
))
1166 aio_complete(req
, ret
, 0);
1172 static int io_submit_one(struct kioctx
*ctx
, struct iocb __user
*user_iocb
,
1173 struct iocb
*iocb
, bool compat
)
1178 /* enforce forwards compatibility on users */
1179 if (unlikely(iocb
->aio_reserved1
|| iocb
->aio_reserved2
)) {
1180 pr_debug("EINVAL: reserve field set\n");
1184 /* prevent overflows */
1186 (iocb
->aio_buf
!= (unsigned long)iocb
->aio_buf
) ||
1187 (iocb
->aio_nbytes
!= (size_t)iocb
->aio_nbytes
) ||
1188 ((ssize_t
)iocb
->aio_nbytes
< 0)
1190 pr_debug("EINVAL: io_submit: overflow check\n");
1194 req
= aio_get_req(ctx
);
1198 req
->ki_filp
= fget(iocb
->aio_fildes
);
1199 if (unlikely(!req
->ki_filp
)) {
1204 if (iocb
->aio_flags
& IOCB_FLAG_RESFD
) {
1206 * If the IOCB_FLAG_RESFD flag of aio_flags is set, get an
1207 * instance of the file* now. The file descriptor must be
1208 * an eventfd() fd, and will be signaled for each completed
1209 * event using the eventfd_signal() function.
1211 req
->ki_eventfd
= eventfd_ctx_fdget((int) iocb
->aio_resfd
);
1212 if (IS_ERR(req
->ki_eventfd
)) {
1213 ret
= PTR_ERR(req
->ki_eventfd
);
1214 req
->ki_eventfd
= NULL
;
1219 ret
= put_user(KIOCB_KEY
, &user_iocb
->aio_key
);
1220 if (unlikely(ret
)) {
1221 pr_debug("EFAULT: aio_key\n");
1225 req
->ki_obj
.user
= user_iocb
;
1226 req
->ki_user_data
= iocb
->aio_data
;
1227 req
->ki_pos
= iocb
->aio_offset
;
1229 req
->ki_buf
= (char __user
*)(unsigned long)iocb
->aio_buf
;
1230 req
->ki_left
= req
->ki_nbytes
= iocb
->aio_nbytes
;
1231 req
->ki_opcode
= iocb
->aio_lio_opcode
;
1233 ret
= aio_run_iocb(req
, compat
);
1237 aio_put_req(req
); /* drop extra ref to req */
1240 atomic_dec(&ctx
->reqs_active
);
1241 aio_put_req(req
); /* drop extra ref to req */
1242 aio_put_req(req
); /* drop i/o ref to req */
1246 long do_io_submit(aio_context_t ctx_id
, long nr
,
1247 struct iocb __user
*__user
*iocbpp
, bool compat
)
1252 struct blk_plug plug
;
1254 if (unlikely(nr
< 0))
1257 if (unlikely(nr
> LONG_MAX
/sizeof(*iocbpp
)))
1258 nr
= LONG_MAX
/sizeof(*iocbpp
);
1260 if (unlikely(!access_ok(VERIFY_READ
, iocbpp
, (nr
*sizeof(*iocbpp
)))))
1263 ctx
= lookup_ioctx(ctx_id
);
1264 if (unlikely(!ctx
)) {
1265 pr_debug("EINVAL: invalid context id\n");
1269 blk_start_plug(&plug
);
1272 * AKPM: should this return a partial result if some of the IOs were
1273 * successfully submitted?
1275 for (i
=0; i
<nr
; i
++) {
1276 struct iocb __user
*user_iocb
;
1279 if (unlikely(__get_user(user_iocb
, iocbpp
+ i
))) {
1284 if (unlikely(copy_from_user(&tmp
, user_iocb
, sizeof(tmp
)))) {
1289 ret
= io_submit_one(ctx
, user_iocb
, &tmp
, compat
);
1293 blk_finish_plug(&plug
);
1300 * Queue the nr iocbs pointed to by iocbpp for processing. Returns
1301 * the number of iocbs queued. May return -EINVAL if the aio_context
1302 * specified by ctx_id is invalid, if nr is < 0, if the iocb at
1303 * *iocbpp[0] is not properly initialized, if the operation specified
1304 * is invalid for the file descriptor in the iocb. May fail with
1305 * -EFAULT if any of the data structures point to invalid data. May
1306 * fail with -EBADF if the file descriptor specified in the first
1307 * iocb is invalid. May fail with -EAGAIN if insufficient resources
1308 * are available to queue any iocbs. Will return 0 if nr is 0. Will
1309 * fail with -ENOSYS if not implemented.
1311 SYSCALL_DEFINE3(io_submit
, aio_context_t
, ctx_id
, long, nr
,
1312 struct iocb __user
* __user
*, iocbpp
)
1314 return do_io_submit(ctx_id
, nr
, iocbpp
, 0);
1318 * Finds a given iocb for cancellation.
1320 static struct kiocb
*lookup_kiocb(struct kioctx
*ctx
, struct iocb __user
*iocb
,
1323 struct list_head
*pos
;
1325 assert_spin_locked(&ctx
->ctx_lock
);
1327 if (key
!= KIOCB_KEY
)
1330 /* TODO: use a hash or array, this sucks. */
1331 list_for_each(pos
, &ctx
->active_reqs
) {
1332 struct kiocb
*kiocb
= list_kiocb(pos
);
1333 if (kiocb
->ki_obj
.user
== iocb
)
1340 * Attempts to cancel an iocb previously passed to io_submit. If
1341 * the operation is successfully cancelled, the resulting event is
1342 * copied into the memory pointed to by result without being placed
1343 * into the completion queue and 0 is returned. May fail with
1344 * -EFAULT if any of the data structures pointed to are invalid.
1345 * May fail with -EINVAL if aio_context specified by ctx_id is
1346 * invalid. May fail with -EAGAIN if the iocb specified was not
1347 * cancelled. Will fail with -ENOSYS if not implemented.
1349 SYSCALL_DEFINE3(io_cancel
, aio_context_t
, ctx_id
, struct iocb __user
*, iocb
,
1350 struct io_event __user
*, result
)
1352 struct io_event res
;
1354 struct kiocb
*kiocb
;
1358 ret
= get_user(key
, &iocb
->aio_key
);
1362 ctx
= lookup_ioctx(ctx_id
);
1366 spin_lock_irq(&ctx
->ctx_lock
);
1368 kiocb
= lookup_kiocb(ctx
, iocb
, key
);
1370 ret
= kiocb_cancel(ctx
, kiocb
, &res
);
1374 spin_unlock_irq(&ctx
->ctx_lock
);
1377 /* Cancellation succeeded -- copy the result
1378 * into the user's buffer.
1380 if (copy_to_user(result
, &res
, sizeof(res
)))
1390 * Attempts to read at least min_nr events and up to nr events from
1391 * the completion queue for the aio_context specified by ctx_id. If
1392 * it succeeds, the number of read events is returned. May fail with
1393 * -EINVAL if ctx_id is invalid, if min_nr is out of range, if nr is
1394 * out of range, if timeout is out of range. May fail with -EFAULT
1395 * if any of the memory specified is invalid. May return 0 or
1396 * < min_nr if the timeout specified by timeout has elapsed
1397 * before sufficient events are available, where timeout == NULL
1398 * specifies an infinite timeout. Note that the timeout pointed to by
1399 * timeout is relative. Will fail with -ENOSYS if not implemented.
1401 SYSCALL_DEFINE5(io_getevents
, aio_context_t
, ctx_id
,
1404 struct io_event __user
*, events
,
1405 struct timespec __user
*, timeout
)
1407 struct kioctx
*ioctx
= lookup_ioctx(ctx_id
);
1410 if (likely(ioctx
)) {
1411 if (likely(min_nr
<= nr
&& min_nr
>= 0))
1412 ret
= read_events(ioctx
, min_nr
, nr
, events
, timeout
);