aio: implement request batching
[safe/jmp/linux-2.6] / fs / aio.c
1 /*
2  *      An async IO implementation for Linux
3  *      Written by Benjamin LaHaise <bcrl@kvack.org>
4  *
5  *      Implements an efficient asynchronous io interface.
6  *
7  *      Copyright 2000, 2001, 2002 Red Hat, Inc.  All Rights Reserved.
8  *
9  *      See ../COPYING for licensing terms.
10  */
11 #include <linux/kernel.h>
12 #include <linux/init.h>
13 #include <linux/errno.h>
14 #include <linux/time.h>
15 #include <linux/aio_abi.h>
16 #include <linux/module.h>
17 #include <linux/syscalls.h>
18 #include <linux/uio.h>
19
20 #define DEBUG 0
21
22 #include <linux/sched.h>
23 #include <linux/fs.h>
24 #include <linux/file.h>
25 #include <linux/mm.h>
26 #include <linux/mman.h>
27 #include <linux/mmu_context.h>
28 #include <linux/slab.h>
29 #include <linux/timer.h>
30 #include <linux/aio.h>
31 #include <linux/highmem.h>
32 #include <linux/workqueue.h>
33 #include <linux/security.h>
34 #include <linux/eventfd.h>
35 #include <linux/blkdev.h>
36 #include <linux/mempool.h>
37 #include <linux/hash.h>
38
39 #include <asm/kmap_types.h>
40 #include <asm/uaccess.h>
41
42 #if DEBUG > 1
43 #define dprintk         printk
44 #else
45 #define dprintk(x...)   do { ; } while (0)
46 #endif
47
48 /*------ sysctl variables----*/
49 static DEFINE_SPINLOCK(aio_nr_lock);
50 unsigned long aio_nr;           /* current system wide number of aio requests */
51 unsigned long aio_max_nr = 0x10000; /* system wide maximum number of aio requests */
52 /*----end sysctl variables---*/
53
54 static struct kmem_cache        *kiocb_cachep;
55 static struct kmem_cache        *kioctx_cachep;
56
57 static struct workqueue_struct *aio_wq;
58
59 /* Used for rare fput completion. */
60 static void aio_fput_routine(struct work_struct *);
61 static DECLARE_WORK(fput_work, aio_fput_routine);
62
63 static DEFINE_SPINLOCK(fput_lock);
64 static LIST_HEAD(fput_head);
65
66 #define AIO_BATCH_HASH_BITS     3 /* allocated on-stack, so don't go crazy */
67 #define AIO_BATCH_HASH_SIZE     (1 << AIO_BATCH_HASH_BITS)
68 struct aio_batch_entry {
69         struct hlist_node list;
70         struct address_space *mapping;
71 };
72 mempool_t *abe_pool;
73
74 static void aio_kick_handler(struct work_struct *);
75 static void aio_queue_work(struct kioctx *);
76
77 /* aio_setup
78  *      Creates the slab caches used by the aio routines, panic on
79  *      failure as this is done early during the boot sequence.
80  */
81 static int __init aio_setup(void)
82 {
83         kiocb_cachep = KMEM_CACHE(kiocb, SLAB_HWCACHE_ALIGN|SLAB_PANIC);
84         kioctx_cachep = KMEM_CACHE(kioctx,SLAB_HWCACHE_ALIGN|SLAB_PANIC);
85
86         aio_wq = create_workqueue("aio");
87         abe_pool = mempool_create_kmalloc_pool(1, sizeof(struct aio_batch_entry));
88         BUG_ON(!abe_pool);
89
90         pr_debug("aio_setup: sizeof(struct page) = %d\n", (int)sizeof(struct page));
91
92         return 0;
93 }
94 __initcall(aio_setup);
95
96 static void aio_free_ring(struct kioctx *ctx)
97 {
98         struct aio_ring_info *info = &ctx->ring_info;
99         long i;
100
101         for (i=0; i<info->nr_pages; i++)
102                 put_page(info->ring_pages[i]);
103
104         if (info->mmap_size) {
105                 down_write(&ctx->mm->mmap_sem);
106                 do_munmap(ctx->mm, info->mmap_base, info->mmap_size);
107                 up_write(&ctx->mm->mmap_sem);
108         }
109
110         if (info->ring_pages && info->ring_pages != info->internal_pages)
111                 kfree(info->ring_pages);
112         info->ring_pages = NULL;
113         info->nr = 0;
114 }
115
116 static int aio_setup_ring(struct kioctx *ctx)
117 {
118         struct aio_ring *ring;
119         struct aio_ring_info *info = &ctx->ring_info;
120         unsigned nr_events = ctx->max_reqs;
121         unsigned long size;
122         int nr_pages;
123
124         /* Compensate for the ring buffer's head/tail overlap entry */
125         nr_events += 2; /* 1 is required, 2 for good luck */
126
127         size = sizeof(struct aio_ring);
128         size += sizeof(struct io_event) * nr_events;
129         nr_pages = (size + PAGE_SIZE-1) >> PAGE_SHIFT;
130
131         if (nr_pages < 0)
132                 return -EINVAL;
133
134         nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring)) / sizeof(struct io_event);
135
136         info->nr = 0;
137         info->ring_pages = info->internal_pages;
138         if (nr_pages > AIO_RING_PAGES) {
139                 info->ring_pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);
140                 if (!info->ring_pages)
141                         return -ENOMEM;
142         }
143
144         info->mmap_size = nr_pages * PAGE_SIZE;
145         dprintk("attempting mmap of %lu bytes\n", info->mmap_size);
146         down_write(&ctx->mm->mmap_sem);
147         info->mmap_base = do_mmap(NULL, 0, info->mmap_size, 
148                                   PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE,
149                                   0);
150         if (IS_ERR((void *)info->mmap_base)) {
151                 up_write(&ctx->mm->mmap_sem);
152                 info->mmap_size = 0;
153                 aio_free_ring(ctx);
154                 return -EAGAIN;
155         }
156
157         dprintk("mmap address: 0x%08lx\n", info->mmap_base);
158         info->nr_pages = get_user_pages(current, ctx->mm,
159                                         info->mmap_base, nr_pages, 
160                                         1, 0, info->ring_pages, NULL);
161         up_write(&ctx->mm->mmap_sem);
162
163         if (unlikely(info->nr_pages != nr_pages)) {
164                 aio_free_ring(ctx);
165                 return -EAGAIN;
166         }
167
168         ctx->user_id = info->mmap_base;
169
170         info->nr = nr_events;           /* trusted copy */
171
172         ring = kmap_atomic(info->ring_pages[0], KM_USER0);
173         ring->nr = nr_events;   /* user copy */
174         ring->id = ctx->user_id;
175         ring->head = ring->tail = 0;
176         ring->magic = AIO_RING_MAGIC;
177         ring->compat_features = AIO_RING_COMPAT_FEATURES;
178         ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
179         ring->header_length = sizeof(struct aio_ring);
180         kunmap_atomic(ring, KM_USER0);
181
182         return 0;
183 }
184
185
186 /* aio_ring_event: returns a pointer to the event at the given index from
187  * kmap_atomic(, km).  Release the pointer with put_aio_ring_event();
188  */
189 #define AIO_EVENTS_PER_PAGE     (PAGE_SIZE / sizeof(struct io_event))
190 #define AIO_EVENTS_FIRST_PAGE   ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
191 #define AIO_EVENTS_OFFSET       (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
192
193 #define aio_ring_event(info, nr, km) ({                                 \
194         unsigned pos = (nr) + AIO_EVENTS_OFFSET;                        \
195         struct io_event *__event;                                       \
196         __event = kmap_atomic(                                          \
197                         (info)->ring_pages[pos / AIO_EVENTS_PER_PAGE], km); \
198         __event += pos % AIO_EVENTS_PER_PAGE;                           \
199         __event;                                                        \
200 })
201
202 #define put_aio_ring_event(event, km) do {      \
203         struct io_event *__event = (event);     \
204         (void)__event;                          \
205         kunmap_atomic((void *)((unsigned long)__event & PAGE_MASK), km); \
206 } while(0)
207
208 static void ctx_rcu_free(struct rcu_head *head)
209 {
210         struct kioctx *ctx = container_of(head, struct kioctx, rcu_head);
211         unsigned nr_events = ctx->max_reqs;
212
213         kmem_cache_free(kioctx_cachep, ctx);
214
215         if (nr_events) {
216                 spin_lock(&aio_nr_lock);
217                 BUG_ON(aio_nr - nr_events > aio_nr);
218                 aio_nr -= nr_events;
219                 spin_unlock(&aio_nr_lock);
220         }
221 }
222
223 /* __put_ioctx
224  *      Called when the last user of an aio context has gone away,
225  *      and the struct needs to be freed.
226  */
227 static void __put_ioctx(struct kioctx *ctx)
228 {
229         BUG_ON(ctx->reqs_active);
230
231         cancel_delayed_work(&ctx->wq);
232         cancel_work_sync(&ctx->wq.work);
233         aio_free_ring(ctx);
234         mmdrop(ctx->mm);
235         ctx->mm = NULL;
236         pr_debug("__put_ioctx: freeing %p\n", ctx);
237         call_rcu(&ctx->rcu_head, ctx_rcu_free);
238 }
239
240 #define get_ioctx(kioctx) do {                                          \
241         BUG_ON(atomic_read(&(kioctx)->users) <= 0);                     \
242         atomic_inc(&(kioctx)->users);                                   \
243 } while (0)
244 #define put_ioctx(kioctx) do {                                          \
245         BUG_ON(atomic_read(&(kioctx)->users) <= 0);                     \
246         if (unlikely(atomic_dec_and_test(&(kioctx)->users)))            \
247                 __put_ioctx(kioctx);                                    \
248 } while (0)
249
250 /* ioctx_alloc
251  *      Allocates and initializes an ioctx.  Returns an ERR_PTR if it failed.
252  */
253 static struct kioctx *ioctx_alloc(unsigned nr_events)
254 {
255         struct mm_struct *mm;
256         struct kioctx *ctx;
257         int did_sync = 0;
258
259         /* Prevent overflows */
260         if ((nr_events > (0x10000000U / sizeof(struct io_event))) ||
261             (nr_events > (0x10000000U / sizeof(struct kiocb)))) {
262                 pr_debug("ENOMEM: nr_events too high\n");
263                 return ERR_PTR(-EINVAL);
264         }
265
266         if ((unsigned long)nr_events > aio_max_nr)
267                 return ERR_PTR(-EAGAIN);
268
269         ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
270         if (!ctx)
271                 return ERR_PTR(-ENOMEM);
272
273         ctx->max_reqs = nr_events;
274         mm = ctx->mm = current->mm;
275         atomic_inc(&mm->mm_count);
276
277         atomic_set(&ctx->users, 1);
278         spin_lock_init(&ctx->ctx_lock);
279         spin_lock_init(&ctx->ring_info.ring_lock);
280         init_waitqueue_head(&ctx->wait);
281
282         INIT_LIST_HEAD(&ctx->active_reqs);
283         INIT_LIST_HEAD(&ctx->run_list);
284         INIT_DELAYED_WORK(&ctx->wq, aio_kick_handler);
285
286         if (aio_setup_ring(ctx) < 0)
287                 goto out_freectx;
288
289         /* limit the number of system wide aios */
290         do {
291                 spin_lock_bh(&aio_nr_lock);
292                 if (aio_nr + nr_events > aio_max_nr ||
293                     aio_nr + nr_events < aio_nr)
294                         ctx->max_reqs = 0;
295                 else
296                         aio_nr += ctx->max_reqs;
297                 spin_unlock_bh(&aio_nr_lock);
298                 if (ctx->max_reqs || did_sync)
299                         break;
300
301                 /* wait for rcu callbacks to have completed before giving up */
302                 synchronize_rcu();
303                 did_sync = 1;
304                 ctx->max_reqs = nr_events;
305         } while (1);
306
307         if (ctx->max_reqs == 0)
308                 goto out_cleanup;
309
310         /* now link into global list. */
311         spin_lock(&mm->ioctx_lock);
312         hlist_add_head_rcu(&ctx->list, &mm->ioctx_list);
313         spin_unlock(&mm->ioctx_lock);
314
315         dprintk("aio: allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
316                 ctx, ctx->user_id, current->mm, ctx->ring_info.nr);
317         return ctx;
318
319 out_cleanup:
320         __put_ioctx(ctx);
321         return ERR_PTR(-EAGAIN);
322
323 out_freectx:
324         mmdrop(mm);
325         kmem_cache_free(kioctx_cachep, ctx);
326         ctx = ERR_PTR(-ENOMEM);
327
328         dprintk("aio: error allocating ioctx %p\n", ctx);
329         return ctx;
330 }
331
332 /* aio_cancel_all
333  *      Cancels all outstanding aio requests on an aio context.  Used 
334  *      when the processes owning a context have all exited to encourage 
335  *      the rapid destruction of the kioctx.
336  */
337 static void aio_cancel_all(struct kioctx *ctx)
338 {
339         int (*cancel)(struct kiocb *, struct io_event *);
340         struct io_event res;
341         spin_lock_irq(&ctx->ctx_lock);
342         ctx->dead = 1;
343         while (!list_empty(&ctx->active_reqs)) {
344                 struct list_head *pos = ctx->active_reqs.next;
345                 struct kiocb *iocb = list_kiocb(pos);
346                 list_del_init(&iocb->ki_list);
347                 cancel = iocb->ki_cancel;
348                 kiocbSetCancelled(iocb);
349                 if (cancel) {
350                         iocb->ki_users++;
351                         spin_unlock_irq(&ctx->ctx_lock);
352                         cancel(iocb, &res);
353                         spin_lock_irq(&ctx->ctx_lock);
354                 }
355         }
356         spin_unlock_irq(&ctx->ctx_lock);
357 }
358
359 static void wait_for_all_aios(struct kioctx *ctx)
360 {
361         struct task_struct *tsk = current;
362         DECLARE_WAITQUEUE(wait, tsk);
363
364         spin_lock_irq(&ctx->ctx_lock);
365         if (!ctx->reqs_active)
366                 goto out;
367
368         add_wait_queue(&ctx->wait, &wait);
369         set_task_state(tsk, TASK_UNINTERRUPTIBLE);
370         while (ctx->reqs_active) {
371                 spin_unlock_irq(&ctx->ctx_lock);
372                 io_schedule();
373                 set_task_state(tsk, TASK_UNINTERRUPTIBLE);
374                 spin_lock_irq(&ctx->ctx_lock);
375         }
376         __set_task_state(tsk, TASK_RUNNING);
377         remove_wait_queue(&ctx->wait, &wait);
378
379 out:
380         spin_unlock_irq(&ctx->ctx_lock);
381 }
382
383 /* wait_on_sync_kiocb:
384  *      Waits on the given sync kiocb to complete.
385  */
386 ssize_t wait_on_sync_kiocb(struct kiocb *iocb)
387 {
388         while (iocb->ki_users) {
389                 set_current_state(TASK_UNINTERRUPTIBLE);
390                 if (!iocb->ki_users)
391                         break;
392                 io_schedule();
393         }
394         __set_current_state(TASK_RUNNING);
395         return iocb->ki_user_data;
396 }
397 EXPORT_SYMBOL(wait_on_sync_kiocb);
398
399 /* exit_aio: called when the last user of mm goes away.  At this point, 
400  * there is no way for any new requests to be submited or any of the 
401  * io_* syscalls to be called on the context.  However, there may be 
402  * outstanding requests which hold references to the context; as they 
403  * go away, they will call put_ioctx and release any pinned memory
404  * associated with the request (held via struct page * references).
405  */
406 void exit_aio(struct mm_struct *mm)
407 {
408         struct kioctx *ctx;
409
410         while (!hlist_empty(&mm->ioctx_list)) {
411                 ctx = hlist_entry(mm->ioctx_list.first, struct kioctx, list);
412                 hlist_del_rcu(&ctx->list);
413
414                 aio_cancel_all(ctx);
415
416                 wait_for_all_aios(ctx);
417                 /*
418                  * Ensure we don't leave the ctx on the aio_wq
419                  */
420                 cancel_work_sync(&ctx->wq.work);
421
422                 if (1 != atomic_read(&ctx->users))
423                         printk(KERN_DEBUG
424                                 "exit_aio:ioctx still alive: %d %d %d\n",
425                                 atomic_read(&ctx->users), ctx->dead,
426                                 ctx->reqs_active);
427                 put_ioctx(ctx);
428         }
429 }
430
431 /* aio_get_req
432  *      Allocate a slot for an aio request.  Increments the users count
433  * of the kioctx so that the kioctx stays around until all requests are
434  * complete.  Returns NULL if no requests are free.
435  *
436  * Returns with kiocb->users set to 2.  The io submit code path holds
437  * an extra reference while submitting the i/o.
438  * This prevents races between the aio code path referencing the
439  * req (after submitting it) and aio_complete() freeing the req.
440  */
441 static struct kiocb *__aio_get_req(struct kioctx *ctx)
442 {
443         struct kiocb *req = NULL;
444         struct aio_ring *ring;
445         int okay = 0;
446
447         req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL);
448         if (unlikely(!req))
449                 return NULL;
450
451         req->ki_flags = 0;
452         req->ki_users = 2;
453         req->ki_key = 0;
454         req->ki_ctx = ctx;
455         req->ki_cancel = NULL;
456         req->ki_retry = NULL;
457         req->ki_dtor = NULL;
458         req->private = NULL;
459         req->ki_iovec = NULL;
460         INIT_LIST_HEAD(&req->ki_run_list);
461         req->ki_eventfd = NULL;
462
463         /* Check if the completion queue has enough free space to
464          * accept an event from this io.
465          */
466         spin_lock_irq(&ctx->ctx_lock);
467         ring = kmap_atomic(ctx->ring_info.ring_pages[0], KM_USER0);
468         if (ctx->reqs_active < aio_ring_avail(&ctx->ring_info, ring)) {
469                 list_add(&req->ki_list, &ctx->active_reqs);
470                 ctx->reqs_active++;
471                 okay = 1;
472         }
473         kunmap_atomic(ring, KM_USER0);
474         spin_unlock_irq(&ctx->ctx_lock);
475
476         if (!okay) {
477                 kmem_cache_free(kiocb_cachep, req);
478                 req = NULL;
479         }
480
481         return req;
482 }
483
484 static inline struct kiocb *aio_get_req(struct kioctx *ctx)
485 {
486         struct kiocb *req;
487         /* Handle a potential starvation case -- should be exceedingly rare as 
488          * requests will be stuck on fput_head only if the aio_fput_routine is 
489          * delayed and the requests were the last user of the struct file.
490          */
491         req = __aio_get_req(ctx);
492         if (unlikely(NULL == req)) {
493                 aio_fput_routine(NULL);
494                 req = __aio_get_req(ctx);
495         }
496         return req;
497 }
498
499 static inline void really_put_req(struct kioctx *ctx, struct kiocb *req)
500 {
501         assert_spin_locked(&ctx->ctx_lock);
502
503         if (req->ki_eventfd != NULL)
504                 eventfd_ctx_put(req->ki_eventfd);
505         if (req->ki_dtor)
506                 req->ki_dtor(req);
507         if (req->ki_iovec != &req->ki_inline_vec)
508                 kfree(req->ki_iovec);
509         kmem_cache_free(kiocb_cachep, req);
510         ctx->reqs_active--;
511
512         if (unlikely(!ctx->reqs_active && ctx->dead))
513                 wake_up(&ctx->wait);
514 }
515
516 static void aio_fput_routine(struct work_struct *data)
517 {
518         spin_lock_irq(&fput_lock);
519         while (likely(!list_empty(&fput_head))) {
520                 struct kiocb *req = list_kiocb(fput_head.next);
521                 struct kioctx *ctx = req->ki_ctx;
522
523                 list_del(&req->ki_list);
524                 spin_unlock_irq(&fput_lock);
525
526                 /* Complete the fput(s) */
527                 if (req->ki_filp != NULL)
528                         __fput(req->ki_filp);
529
530                 /* Link the iocb into the context's free list */
531                 spin_lock_irq(&ctx->ctx_lock);
532                 really_put_req(ctx, req);
533                 spin_unlock_irq(&ctx->ctx_lock);
534
535                 put_ioctx(ctx);
536                 spin_lock_irq(&fput_lock);
537         }
538         spin_unlock_irq(&fput_lock);
539 }
540
541 /* __aio_put_req
542  *      Returns true if this put was the last user of the request.
543  */
544 static int __aio_put_req(struct kioctx *ctx, struct kiocb *req)
545 {
546         dprintk(KERN_DEBUG "aio_put(%p): f_count=%ld\n",
547                 req, atomic_long_read(&req->ki_filp->f_count));
548
549         assert_spin_locked(&ctx->ctx_lock);
550
551         req->ki_users--;
552         BUG_ON(req->ki_users < 0);
553         if (likely(req->ki_users))
554                 return 0;
555         list_del(&req->ki_list);                /* remove from active_reqs */
556         req->ki_cancel = NULL;
557         req->ki_retry = NULL;
558
559         /*
560          * Try to optimize the aio and eventfd file* puts, by avoiding to
561          * schedule work in case it is not __fput() time. In normal cases,
562          * we would not be holding the last reference to the file*, so
563          * this function will be executed w/out any aio kthread wakeup.
564          */
565         if (unlikely(atomic_long_dec_and_test(&req->ki_filp->f_count))) {
566                 get_ioctx(ctx);
567                 spin_lock(&fput_lock);
568                 list_add(&req->ki_list, &fput_head);
569                 spin_unlock(&fput_lock);
570                 queue_work(aio_wq, &fput_work);
571         } else {
572                 req->ki_filp = NULL;
573                 really_put_req(ctx, req);
574         }
575         return 1;
576 }
577
578 /* aio_put_req
579  *      Returns true if this put was the last user of the kiocb,
580  *      false if the request is still in use.
581  */
582 int aio_put_req(struct kiocb *req)
583 {
584         struct kioctx *ctx = req->ki_ctx;
585         int ret;
586         spin_lock_irq(&ctx->ctx_lock);
587         ret = __aio_put_req(ctx, req);
588         spin_unlock_irq(&ctx->ctx_lock);
589         return ret;
590 }
591 EXPORT_SYMBOL(aio_put_req);
592
593 static struct kioctx *lookup_ioctx(unsigned long ctx_id)
594 {
595         struct mm_struct *mm = current->mm;
596         struct kioctx *ctx, *ret = NULL;
597         struct hlist_node *n;
598
599         rcu_read_lock();
600
601         hlist_for_each_entry_rcu(ctx, n, &mm->ioctx_list, list) {
602                 if (ctx->user_id == ctx_id && !ctx->dead) {
603                         get_ioctx(ctx);
604                         ret = ctx;
605                         break;
606                 }
607         }
608
609         rcu_read_unlock();
610         return ret;
611 }
612
613 /*
614  * Queue up a kiocb to be retried. Assumes that the kiocb
615  * has already been marked as kicked, and places it on
616  * the retry run list for the corresponding ioctx, if it
617  * isn't already queued. Returns 1 if it actually queued
618  * the kiocb (to tell the caller to activate the work
619  * queue to process it), or 0, if it found that it was
620  * already queued.
621  */
622 static inline int __queue_kicked_iocb(struct kiocb *iocb)
623 {
624         struct kioctx *ctx = iocb->ki_ctx;
625
626         assert_spin_locked(&ctx->ctx_lock);
627
628         if (list_empty(&iocb->ki_run_list)) {
629                 list_add_tail(&iocb->ki_run_list,
630                         &ctx->run_list);
631                 return 1;
632         }
633         return 0;
634 }
635
636 /* aio_run_iocb
637  *      This is the core aio execution routine. It is
638  *      invoked both for initial i/o submission and
639  *      subsequent retries via the aio_kick_handler.
640  *      Expects to be invoked with iocb->ki_ctx->lock
641  *      already held. The lock is released and reacquired
642  *      as needed during processing.
643  *
644  * Calls the iocb retry method (already setup for the
645  * iocb on initial submission) for operation specific
646  * handling, but takes care of most of common retry
647  * execution details for a given iocb. The retry method
648  * needs to be non-blocking as far as possible, to avoid
649  * holding up other iocbs waiting to be serviced by the
650  * retry kernel thread.
651  *
652  * The trickier parts in this code have to do with
653  * ensuring that only one retry instance is in progress
654  * for a given iocb at any time. Providing that guarantee
655  * simplifies the coding of individual aio operations as
656  * it avoids various potential races.
657  */
658 static ssize_t aio_run_iocb(struct kiocb *iocb)
659 {
660         struct kioctx   *ctx = iocb->ki_ctx;
661         ssize_t (*retry)(struct kiocb *);
662         ssize_t ret;
663
664         if (!(retry = iocb->ki_retry)) {
665                 printk("aio_run_iocb: iocb->ki_retry = NULL\n");
666                 return 0;
667         }
668
669         /*
670          * We don't want the next retry iteration for this
671          * operation to start until this one has returned and
672          * updated the iocb state. However, wait_queue functions
673          * can trigger a kick_iocb from interrupt context in the
674          * meantime, indicating that data is available for the next
675          * iteration. We want to remember that and enable the
676          * next retry iteration _after_ we are through with
677          * this one.
678          *
679          * So, in order to be able to register a "kick", but
680          * prevent it from being queued now, we clear the kick
681          * flag, but make the kick code *think* that the iocb is
682          * still on the run list until we are actually done.
683          * When we are done with this iteration, we check if
684          * the iocb was kicked in the meantime and if so, queue
685          * it up afresh.
686          */
687
688         kiocbClearKicked(iocb);
689
690         /*
691          * This is so that aio_complete knows it doesn't need to
692          * pull the iocb off the run list (We can't just call
693          * INIT_LIST_HEAD because we don't want a kick_iocb to
694          * queue this on the run list yet)
695          */
696         iocb->ki_run_list.next = iocb->ki_run_list.prev = NULL;
697         spin_unlock_irq(&ctx->ctx_lock);
698
699         /* Quit retrying if the i/o has been cancelled */
700         if (kiocbIsCancelled(iocb)) {
701                 ret = -EINTR;
702                 aio_complete(iocb, ret, 0);
703                 /* must not access the iocb after this */
704                 goto out;
705         }
706
707         /*
708          * Now we are all set to call the retry method in async
709          * context.
710          */
711         ret = retry(iocb);
712
713         if (ret != -EIOCBRETRY && ret != -EIOCBQUEUED) {
714                 BUG_ON(!list_empty(&iocb->ki_wait.task_list));
715                 aio_complete(iocb, ret, 0);
716         }
717 out:
718         spin_lock_irq(&ctx->ctx_lock);
719
720         if (-EIOCBRETRY == ret) {
721                 /*
722                  * OK, now that we are done with this iteration
723                  * and know that there is more left to go,
724                  * this is where we let go so that a subsequent
725                  * "kick" can start the next iteration
726                  */
727
728                 /* will make __queue_kicked_iocb succeed from here on */
729                 INIT_LIST_HEAD(&iocb->ki_run_list);
730                 /* we must queue the next iteration ourselves, if it
731                  * has already been kicked */
732                 if (kiocbIsKicked(iocb)) {
733                         __queue_kicked_iocb(iocb);
734
735                         /*
736                          * __queue_kicked_iocb will always return 1 here, because
737                          * iocb->ki_run_list is empty at this point so it should
738                          * be safe to unconditionally queue the context into the
739                          * work queue.
740                          */
741                         aio_queue_work(ctx);
742                 }
743         }
744         return ret;
745 }
746
747 /*
748  * __aio_run_iocbs:
749  *      Process all pending retries queued on the ioctx
750  *      run list.
751  * Assumes it is operating within the aio issuer's mm
752  * context.
753  */
754 static int __aio_run_iocbs(struct kioctx *ctx)
755 {
756         struct kiocb *iocb;
757         struct list_head run_list;
758
759         assert_spin_locked(&ctx->ctx_lock);
760
761         list_replace_init(&ctx->run_list, &run_list);
762         while (!list_empty(&run_list)) {
763                 iocb = list_entry(run_list.next, struct kiocb,
764                         ki_run_list);
765                 list_del(&iocb->ki_run_list);
766                 /*
767                  * Hold an extra reference while retrying i/o.
768                  */
769                 iocb->ki_users++;       /* grab extra reference */
770                 aio_run_iocb(iocb);
771                 __aio_put_req(ctx, iocb);
772         }
773         if (!list_empty(&ctx->run_list))
774                 return 1;
775         return 0;
776 }
777
778 static void aio_queue_work(struct kioctx * ctx)
779 {
780         unsigned long timeout;
781         /*
782          * if someone is waiting, get the work started right
783          * away, otherwise, use a longer delay
784          */
785         smp_mb();
786         if (waitqueue_active(&ctx->wait))
787                 timeout = 1;
788         else
789                 timeout = HZ/10;
790         queue_delayed_work(aio_wq, &ctx->wq, timeout);
791 }
792
793
794 /*
795  * aio_run_iocbs:
796  *      Process all pending retries queued on the ioctx
797  *      run list.
798  * Assumes it is operating within the aio issuer's mm
799  * context.
800  */
801 static inline void aio_run_iocbs(struct kioctx *ctx)
802 {
803         int requeue;
804
805         spin_lock_irq(&ctx->ctx_lock);
806
807         requeue = __aio_run_iocbs(ctx);
808         spin_unlock_irq(&ctx->ctx_lock);
809         if (requeue)
810                 aio_queue_work(ctx);
811 }
812
813 /*
814  * just like aio_run_iocbs, but keeps running them until
815  * the list stays empty
816  */
817 static inline void aio_run_all_iocbs(struct kioctx *ctx)
818 {
819         spin_lock_irq(&ctx->ctx_lock);
820         while (__aio_run_iocbs(ctx))
821                 ;
822         spin_unlock_irq(&ctx->ctx_lock);
823 }
824
825 /*
826  * aio_kick_handler:
827  *      Work queue handler triggered to process pending
828  *      retries on an ioctx. Takes on the aio issuer's
829  *      mm context before running the iocbs, so that
830  *      copy_xxx_user operates on the issuer's address
831  *      space.
832  * Run on aiod's context.
833  */
834 static void aio_kick_handler(struct work_struct *work)
835 {
836         struct kioctx *ctx = container_of(work, struct kioctx, wq.work);
837         mm_segment_t oldfs = get_fs();
838         struct mm_struct *mm;
839         int requeue;
840
841         set_fs(USER_DS);
842         use_mm(ctx->mm);
843         spin_lock_irq(&ctx->ctx_lock);
844         requeue =__aio_run_iocbs(ctx);
845         mm = ctx->mm;
846         spin_unlock_irq(&ctx->ctx_lock);
847         unuse_mm(mm);
848         set_fs(oldfs);
849         /*
850          * we're in a worker thread already, don't use queue_delayed_work,
851          */
852         if (requeue)
853                 queue_delayed_work(aio_wq, &ctx->wq, 0);
854 }
855
856
857 /*
858  * Called by kick_iocb to queue the kiocb for retry
859  * and if required activate the aio work queue to process
860  * it
861  */
862 static void try_queue_kicked_iocb(struct kiocb *iocb)
863 {
864         struct kioctx   *ctx = iocb->ki_ctx;
865         unsigned long flags;
866         int run = 0;
867
868         /* We're supposed to be the only path putting the iocb back on the run
869          * list.  If we find that the iocb is *back* on a wait queue already
870          * than retry has happened before we could queue the iocb.  This also
871          * means that the retry could have completed and freed our iocb, no
872          * good. */
873         BUG_ON((!list_empty(&iocb->ki_wait.task_list)));
874
875         spin_lock_irqsave(&ctx->ctx_lock, flags);
876         /* set this inside the lock so that we can't race with aio_run_iocb()
877          * testing it and putting the iocb on the run list under the lock */
878         if (!kiocbTryKick(iocb))
879                 run = __queue_kicked_iocb(iocb);
880         spin_unlock_irqrestore(&ctx->ctx_lock, flags);
881         if (run)
882                 aio_queue_work(ctx);
883 }
884
885 /*
886  * kick_iocb:
887  *      Called typically from a wait queue callback context
888  *      (aio_wake_function) to trigger a retry of the iocb.
889  *      The retry is usually executed by aio workqueue
890  *      threads (See aio_kick_handler).
891  */
892 void kick_iocb(struct kiocb *iocb)
893 {
894         /* sync iocbs are easy: they can only ever be executing from a 
895          * single context. */
896         if (is_sync_kiocb(iocb)) {
897                 kiocbSetKicked(iocb);
898                 wake_up_process(iocb->ki_obj.tsk);
899                 return;
900         }
901
902         try_queue_kicked_iocb(iocb);
903 }
904 EXPORT_SYMBOL(kick_iocb);
905
906 /* aio_complete
907  *      Called when the io request on the given iocb is complete.
908  *      Returns true if this is the last user of the request.  The 
909  *      only other user of the request can be the cancellation code.
910  */
911 int aio_complete(struct kiocb *iocb, long res, long res2)
912 {
913         struct kioctx   *ctx = iocb->ki_ctx;
914         struct aio_ring_info    *info;
915         struct aio_ring *ring;
916         struct io_event *event;
917         unsigned long   flags;
918         unsigned long   tail;
919         int             ret;
920
921         /*
922          * Special case handling for sync iocbs:
923          *  - events go directly into the iocb for fast handling
924          *  - the sync task with the iocb in its stack holds the single iocb
925          *    ref, no other paths have a way to get another ref
926          *  - the sync task helpfully left a reference to itself in the iocb
927          */
928         if (is_sync_kiocb(iocb)) {
929                 BUG_ON(iocb->ki_users != 1);
930                 iocb->ki_user_data = res;
931                 iocb->ki_users = 0;
932                 wake_up_process(iocb->ki_obj.tsk);
933                 return 1;
934         }
935
936         info = &ctx->ring_info;
937
938         /* add a completion event to the ring buffer.
939          * must be done holding ctx->ctx_lock to prevent
940          * other code from messing with the tail
941          * pointer since we might be called from irq
942          * context.
943          */
944         spin_lock_irqsave(&ctx->ctx_lock, flags);
945
946         if (iocb->ki_run_list.prev && !list_empty(&iocb->ki_run_list))
947                 list_del_init(&iocb->ki_run_list);
948
949         /*
950          * cancelled requests don't get events, userland was given one
951          * when the event got cancelled.
952          */
953         if (kiocbIsCancelled(iocb))
954                 goto put_rq;
955
956         ring = kmap_atomic(info->ring_pages[0], KM_IRQ1);
957
958         tail = info->tail;
959         event = aio_ring_event(info, tail, KM_IRQ0);
960         if (++tail >= info->nr)
961                 tail = 0;
962
963         event->obj = (u64)(unsigned long)iocb->ki_obj.user;
964         event->data = iocb->ki_user_data;
965         event->res = res;
966         event->res2 = res2;
967
968         dprintk("aio_complete: %p[%lu]: %p: %p %Lx %lx %lx\n",
969                 ctx, tail, iocb, iocb->ki_obj.user, iocb->ki_user_data,
970                 res, res2);
971
972         /* after flagging the request as done, we
973          * must never even look at it again
974          */
975         smp_wmb();      /* make event visible before updating tail */
976
977         info->tail = tail;
978         ring->tail = tail;
979
980         put_aio_ring_event(event, KM_IRQ0);
981         kunmap_atomic(ring, KM_IRQ1);
982
983         pr_debug("added to ring %p at [%lu]\n", iocb, tail);
984
985         /*
986          * Check if the user asked us to deliver the result through an
987          * eventfd. The eventfd_signal() function is safe to be called
988          * from IRQ context.
989          */
990         if (iocb->ki_eventfd != NULL)
991                 eventfd_signal(iocb->ki_eventfd, 1);
992
993 put_rq:
994         /* everything turned out well, dispose of the aiocb. */
995         ret = __aio_put_req(ctx, iocb);
996
997         /*
998          * We have to order our ring_info tail store above and test
999          * of the wait list below outside the wait lock.  This is
1000          * like in wake_up_bit() where clearing a bit has to be
1001          * ordered with the unlocked test.
1002          */
1003         smp_mb();
1004
1005         if (waitqueue_active(&ctx->wait))
1006                 wake_up(&ctx->wait);
1007
1008         spin_unlock_irqrestore(&ctx->ctx_lock, flags);
1009         return ret;
1010 }
1011 EXPORT_SYMBOL(aio_complete);
1012
1013 /* aio_read_evt
1014  *      Pull an event off of the ioctx's event ring.  Returns the number of 
1015  *      events fetched (0 or 1 ;-)
1016  *      FIXME: make this use cmpxchg.
1017  *      TODO: make the ringbuffer user mmap()able (requires FIXME).
1018  */
1019 static int aio_read_evt(struct kioctx *ioctx, struct io_event *ent)
1020 {
1021         struct aio_ring_info *info = &ioctx->ring_info;
1022         struct aio_ring *ring;
1023         unsigned long head;
1024         int ret = 0;
1025
1026         ring = kmap_atomic(info->ring_pages[0], KM_USER0);
1027         dprintk("in aio_read_evt h%lu t%lu m%lu\n",
1028                  (unsigned long)ring->head, (unsigned long)ring->tail,
1029                  (unsigned long)ring->nr);
1030
1031         if (ring->head == ring->tail)
1032                 goto out;
1033
1034         spin_lock(&info->ring_lock);
1035
1036         head = ring->head % info->nr;
1037         if (head != ring->tail) {
1038                 struct io_event *evp = aio_ring_event(info, head, KM_USER1);
1039                 *ent = *evp;
1040                 head = (head + 1) % info->nr;
1041                 smp_mb(); /* finish reading the event before updatng the head */
1042                 ring->head = head;
1043                 ret = 1;
1044                 put_aio_ring_event(evp, KM_USER1);
1045         }
1046         spin_unlock(&info->ring_lock);
1047
1048 out:
1049         kunmap_atomic(ring, KM_USER0);
1050         dprintk("leaving aio_read_evt: %d  h%lu t%lu\n", ret,
1051                  (unsigned long)ring->head, (unsigned long)ring->tail);
1052         return ret;
1053 }
1054
1055 struct aio_timeout {
1056         struct timer_list       timer;
1057         int                     timed_out;
1058         struct task_struct      *p;
1059 };
1060
1061 static void timeout_func(unsigned long data)
1062 {
1063         struct aio_timeout *to = (struct aio_timeout *)data;
1064
1065         to->timed_out = 1;
1066         wake_up_process(to->p);
1067 }
1068
1069 static inline void init_timeout(struct aio_timeout *to)
1070 {
1071         setup_timer_on_stack(&to->timer, timeout_func, (unsigned long) to);
1072         to->timed_out = 0;
1073         to->p = current;
1074 }
1075
1076 static inline void set_timeout(long start_jiffies, struct aio_timeout *to,
1077                                const struct timespec *ts)
1078 {
1079         to->timer.expires = start_jiffies + timespec_to_jiffies(ts);
1080         if (time_after(to->timer.expires, jiffies))
1081                 add_timer(&to->timer);
1082         else
1083                 to->timed_out = 1;
1084 }
1085
1086 static inline void clear_timeout(struct aio_timeout *to)
1087 {
1088         del_singleshot_timer_sync(&to->timer);
1089 }
1090
1091 static int read_events(struct kioctx *ctx,
1092                         long min_nr, long nr,
1093                         struct io_event __user *event,
1094                         struct timespec __user *timeout)
1095 {
1096         long                    start_jiffies = jiffies;
1097         struct task_struct      *tsk = current;
1098         DECLARE_WAITQUEUE(wait, tsk);
1099         int                     ret;
1100         int                     i = 0;
1101         struct io_event         ent;
1102         struct aio_timeout      to;
1103         int                     retry = 0;
1104
1105         /* needed to zero any padding within an entry (there shouldn't be 
1106          * any, but C is fun!
1107          */
1108         memset(&ent, 0, sizeof(ent));
1109 retry:
1110         ret = 0;
1111         while (likely(i < nr)) {
1112                 ret = aio_read_evt(ctx, &ent);
1113                 if (unlikely(ret <= 0))
1114                         break;
1115
1116                 dprintk("read event: %Lx %Lx %Lx %Lx\n",
1117                         ent.data, ent.obj, ent.res, ent.res2);
1118
1119                 /* Could we split the check in two? */
1120                 ret = -EFAULT;
1121                 if (unlikely(copy_to_user(event, &ent, sizeof(ent)))) {
1122                         dprintk("aio: lost an event due to EFAULT.\n");
1123                         break;
1124                 }
1125                 ret = 0;
1126
1127                 /* Good, event copied to userland, update counts. */
1128                 event ++;
1129                 i ++;
1130         }
1131
1132         if (min_nr <= i)
1133                 return i;
1134         if (ret)
1135                 return ret;
1136
1137         /* End fast path */
1138
1139         /* racey check, but it gets redone */
1140         if (!retry && unlikely(!list_empty(&ctx->run_list))) {
1141                 retry = 1;
1142                 aio_run_all_iocbs(ctx);
1143                 goto retry;
1144         }
1145
1146         init_timeout(&to);
1147         if (timeout) {
1148                 struct timespec ts;
1149                 ret = -EFAULT;
1150                 if (unlikely(copy_from_user(&ts, timeout, sizeof(ts))))
1151                         goto out;
1152
1153                 set_timeout(start_jiffies, &to, &ts);
1154         }
1155
1156         while (likely(i < nr)) {
1157                 add_wait_queue_exclusive(&ctx->wait, &wait);
1158                 do {
1159                         set_task_state(tsk, TASK_INTERRUPTIBLE);
1160                         ret = aio_read_evt(ctx, &ent);
1161                         if (ret)
1162                                 break;
1163                         if (min_nr <= i)
1164                                 break;
1165                         if (unlikely(ctx->dead)) {
1166                                 ret = -EINVAL;
1167                                 break;
1168                         }
1169                         if (to.timed_out)       /* Only check after read evt */
1170                                 break;
1171                         /* Try to only show up in io wait if there are ops
1172                          *  in flight */
1173                         if (ctx->reqs_active)
1174                                 io_schedule();
1175                         else
1176                                 schedule();
1177                         if (signal_pending(tsk)) {
1178                                 ret = -EINTR;
1179                                 break;
1180                         }
1181                         /*ret = aio_read_evt(ctx, &ent);*/
1182                 } while (1) ;
1183
1184                 set_task_state(tsk, TASK_RUNNING);
1185                 remove_wait_queue(&ctx->wait, &wait);
1186
1187                 if (unlikely(ret <= 0))
1188                         break;
1189
1190                 ret = -EFAULT;
1191                 if (unlikely(copy_to_user(event, &ent, sizeof(ent)))) {
1192                         dprintk("aio: lost an event due to EFAULT.\n");
1193                         break;
1194                 }
1195
1196                 /* Good, event copied to userland, update counts. */
1197                 event ++;
1198                 i ++;
1199         }
1200
1201         if (timeout)
1202                 clear_timeout(&to);
1203 out:
1204         destroy_timer_on_stack(&to.timer);
1205         return i ? i : ret;
1206 }
1207
1208 /* Take an ioctx and remove it from the list of ioctx's.  Protects 
1209  * against races with itself via ->dead.
1210  */
1211 static void io_destroy(struct kioctx *ioctx)
1212 {
1213         struct mm_struct *mm = current->mm;
1214         int was_dead;
1215
1216         /* delete the entry from the list is someone else hasn't already */
1217         spin_lock(&mm->ioctx_lock);
1218         was_dead = ioctx->dead;
1219         ioctx->dead = 1;
1220         hlist_del_rcu(&ioctx->list);
1221         spin_unlock(&mm->ioctx_lock);
1222
1223         dprintk("aio_release(%p)\n", ioctx);
1224         if (likely(!was_dead))
1225                 put_ioctx(ioctx);       /* twice for the list */
1226
1227         aio_cancel_all(ioctx);
1228         wait_for_all_aios(ioctx);
1229
1230         /*
1231          * Wake up any waiters.  The setting of ctx->dead must be seen
1232          * by other CPUs at this point.  Right now, we rely on the
1233          * locking done by the above calls to ensure this consistency.
1234          */
1235         wake_up(&ioctx->wait);
1236         put_ioctx(ioctx);       /* once for the lookup */
1237 }
1238
1239 /* sys_io_setup:
1240  *      Create an aio_context capable of receiving at least nr_events.
1241  *      ctxp must not point to an aio_context that already exists, and
1242  *      must be initialized to 0 prior to the call.  On successful
1243  *      creation of the aio_context, *ctxp is filled in with the resulting 
1244  *      handle.  May fail with -EINVAL if *ctxp is not initialized,
1245  *      if the specified nr_events exceeds internal limits.  May fail 
1246  *      with -EAGAIN if the specified nr_events exceeds the user's limit 
1247  *      of available events.  May fail with -ENOMEM if insufficient kernel
1248  *      resources are available.  May fail with -EFAULT if an invalid
1249  *      pointer is passed for ctxp.  Will fail with -ENOSYS if not
1250  *      implemented.
1251  */
1252 SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
1253 {
1254         struct kioctx *ioctx = NULL;
1255         unsigned long ctx;
1256         long ret;
1257
1258         ret = get_user(ctx, ctxp);
1259         if (unlikely(ret))
1260                 goto out;
1261
1262         ret = -EINVAL;
1263         if (unlikely(ctx || nr_events == 0)) {
1264                 pr_debug("EINVAL: io_setup: ctx %lu nr_events %u\n",
1265                          ctx, nr_events);
1266                 goto out;
1267         }
1268
1269         ioctx = ioctx_alloc(nr_events);
1270         ret = PTR_ERR(ioctx);
1271         if (!IS_ERR(ioctx)) {
1272                 ret = put_user(ioctx->user_id, ctxp);
1273                 if (!ret)
1274                         return 0;
1275
1276                 get_ioctx(ioctx); /* io_destroy() expects us to hold a ref */
1277                 io_destroy(ioctx);
1278         }
1279
1280 out:
1281         return ret;
1282 }
1283
1284 /* sys_io_destroy:
1285  *      Destroy the aio_context specified.  May cancel any outstanding 
1286  *      AIOs and block on completion.  Will fail with -ENOSYS if not
1287  *      implemented.  May fail with -EFAULT if the context pointed to
1288  *      is invalid.
1289  */
1290 SYSCALL_DEFINE1(io_destroy, aio_context_t, ctx)
1291 {
1292         struct kioctx *ioctx = lookup_ioctx(ctx);
1293         if (likely(NULL != ioctx)) {
1294                 io_destroy(ioctx);
1295                 return 0;
1296         }
1297         pr_debug("EINVAL: io_destroy: invalid context id\n");
1298         return -EINVAL;
1299 }
1300
1301 static void aio_advance_iovec(struct kiocb *iocb, ssize_t ret)
1302 {
1303         struct iovec *iov = &iocb->ki_iovec[iocb->ki_cur_seg];
1304
1305         BUG_ON(ret <= 0);
1306
1307         while (iocb->ki_cur_seg < iocb->ki_nr_segs && ret > 0) {
1308                 ssize_t this = min((ssize_t)iov->iov_len, ret);
1309                 iov->iov_base += this;
1310                 iov->iov_len -= this;
1311                 iocb->ki_left -= this;
1312                 ret -= this;
1313                 if (iov->iov_len == 0) {
1314                         iocb->ki_cur_seg++;
1315                         iov++;
1316                 }
1317         }
1318
1319         /* the caller should not have done more io than what fit in
1320          * the remaining iovecs */
1321         BUG_ON(ret > 0 && iocb->ki_left == 0);
1322 }
1323
1324 static ssize_t aio_rw_vect_retry(struct kiocb *iocb)
1325 {
1326         struct file *file = iocb->ki_filp;
1327         struct address_space *mapping = file->f_mapping;
1328         struct inode *inode = mapping->host;
1329         ssize_t (*rw_op)(struct kiocb *, const struct iovec *,
1330                          unsigned long, loff_t);
1331         ssize_t ret = 0;
1332         unsigned short opcode;
1333
1334         if ((iocb->ki_opcode == IOCB_CMD_PREADV) ||
1335                 (iocb->ki_opcode == IOCB_CMD_PREAD)) {
1336                 rw_op = file->f_op->aio_read;
1337                 opcode = IOCB_CMD_PREADV;
1338         } else {
1339                 rw_op = file->f_op->aio_write;
1340                 opcode = IOCB_CMD_PWRITEV;
1341         }
1342
1343         /* This matches the pread()/pwrite() logic */
1344         if (iocb->ki_pos < 0)
1345                 return -EINVAL;
1346
1347         do {
1348                 ret = rw_op(iocb, &iocb->ki_iovec[iocb->ki_cur_seg],
1349                             iocb->ki_nr_segs - iocb->ki_cur_seg,
1350                             iocb->ki_pos);
1351                 if (ret > 0)
1352                         aio_advance_iovec(iocb, ret);
1353
1354         /* retry all partial writes.  retry partial reads as long as its a
1355          * regular file. */
1356         } while (ret > 0 && iocb->ki_left > 0 &&
1357                  (opcode == IOCB_CMD_PWRITEV ||
1358                   (!S_ISFIFO(inode->i_mode) && !S_ISSOCK(inode->i_mode))));
1359
1360         /* This means we must have transferred all that we could */
1361         /* No need to retry anymore */
1362         if ((ret == 0) || (iocb->ki_left == 0))
1363                 ret = iocb->ki_nbytes - iocb->ki_left;
1364
1365         /* If we managed to write some out we return that, rather than
1366          * the eventual error. */
1367         if (opcode == IOCB_CMD_PWRITEV
1368             && ret < 0 && ret != -EIOCBQUEUED && ret != -EIOCBRETRY
1369             && iocb->ki_nbytes - iocb->ki_left)
1370                 ret = iocb->ki_nbytes - iocb->ki_left;
1371
1372         return ret;
1373 }
1374
1375 static ssize_t aio_fdsync(struct kiocb *iocb)
1376 {
1377         struct file *file = iocb->ki_filp;
1378         ssize_t ret = -EINVAL;
1379
1380         if (file->f_op->aio_fsync)
1381                 ret = file->f_op->aio_fsync(iocb, 1);
1382         return ret;
1383 }
1384
1385 static ssize_t aio_fsync(struct kiocb *iocb)
1386 {
1387         struct file *file = iocb->ki_filp;
1388         ssize_t ret = -EINVAL;
1389
1390         if (file->f_op->aio_fsync)
1391                 ret = file->f_op->aio_fsync(iocb, 0);
1392         return ret;
1393 }
1394
1395 static ssize_t aio_setup_vectored_rw(int type, struct kiocb *kiocb)
1396 {
1397         ssize_t ret;
1398
1399         ret = rw_copy_check_uvector(type, (struct iovec __user *)kiocb->ki_buf,
1400                                     kiocb->ki_nbytes, 1,
1401                                     &kiocb->ki_inline_vec, &kiocb->ki_iovec);
1402         if (ret < 0)
1403                 goto out;
1404
1405         kiocb->ki_nr_segs = kiocb->ki_nbytes;
1406         kiocb->ki_cur_seg = 0;
1407         /* ki_nbytes/left now reflect bytes instead of segs */
1408         kiocb->ki_nbytes = ret;
1409         kiocb->ki_left = ret;
1410
1411         ret = 0;
1412 out:
1413         return ret;
1414 }
1415
1416 static ssize_t aio_setup_single_vector(struct kiocb *kiocb)
1417 {
1418         kiocb->ki_iovec = &kiocb->ki_inline_vec;
1419         kiocb->ki_iovec->iov_base = kiocb->ki_buf;
1420         kiocb->ki_iovec->iov_len = kiocb->ki_left;
1421         kiocb->ki_nr_segs = 1;
1422         kiocb->ki_cur_seg = 0;
1423         return 0;
1424 }
1425
1426 /*
1427  * aio_setup_iocb:
1428  *      Performs the initial checks and aio retry method
1429  *      setup for the kiocb at the time of io submission.
1430  */
1431 static ssize_t aio_setup_iocb(struct kiocb *kiocb)
1432 {
1433         struct file *file = kiocb->ki_filp;
1434         ssize_t ret = 0;
1435
1436         switch (kiocb->ki_opcode) {
1437         case IOCB_CMD_PREAD:
1438                 ret = -EBADF;
1439                 if (unlikely(!(file->f_mode & FMODE_READ)))
1440                         break;
1441                 ret = -EFAULT;
1442                 if (unlikely(!access_ok(VERIFY_WRITE, kiocb->ki_buf,
1443                         kiocb->ki_left)))
1444                         break;
1445                 ret = security_file_permission(file, MAY_READ);
1446                 if (unlikely(ret))
1447                         break;
1448                 ret = aio_setup_single_vector(kiocb);
1449                 if (ret)
1450                         break;
1451                 ret = -EINVAL;
1452                 if (file->f_op->aio_read)
1453                         kiocb->ki_retry = aio_rw_vect_retry;
1454                 break;
1455         case IOCB_CMD_PWRITE:
1456                 ret = -EBADF;
1457                 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1458                         break;
1459                 ret = -EFAULT;
1460                 if (unlikely(!access_ok(VERIFY_READ, kiocb->ki_buf,
1461                         kiocb->ki_left)))
1462                         break;
1463                 ret = security_file_permission(file, MAY_WRITE);
1464                 if (unlikely(ret))
1465                         break;
1466                 ret = aio_setup_single_vector(kiocb);
1467                 if (ret)
1468                         break;
1469                 ret = -EINVAL;
1470                 if (file->f_op->aio_write)
1471                         kiocb->ki_retry = aio_rw_vect_retry;
1472                 break;
1473         case IOCB_CMD_PREADV:
1474                 ret = -EBADF;
1475                 if (unlikely(!(file->f_mode & FMODE_READ)))
1476                         break;
1477                 ret = security_file_permission(file, MAY_READ);
1478                 if (unlikely(ret))
1479                         break;
1480                 ret = aio_setup_vectored_rw(READ, kiocb);
1481                 if (ret)
1482                         break;
1483                 ret = -EINVAL;
1484                 if (file->f_op->aio_read)
1485                         kiocb->ki_retry = aio_rw_vect_retry;
1486                 break;
1487         case IOCB_CMD_PWRITEV:
1488                 ret = -EBADF;
1489                 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1490                         break;
1491                 ret = security_file_permission(file, MAY_WRITE);
1492                 if (unlikely(ret))
1493                         break;
1494                 ret = aio_setup_vectored_rw(WRITE, kiocb);
1495                 if (ret)
1496                         break;
1497                 ret = -EINVAL;
1498                 if (file->f_op->aio_write)
1499                         kiocb->ki_retry = aio_rw_vect_retry;
1500                 break;
1501         case IOCB_CMD_FDSYNC:
1502                 ret = -EINVAL;
1503                 if (file->f_op->aio_fsync)
1504                         kiocb->ki_retry = aio_fdsync;
1505                 break;
1506         case IOCB_CMD_FSYNC:
1507                 ret = -EINVAL;
1508                 if (file->f_op->aio_fsync)
1509                         kiocb->ki_retry = aio_fsync;
1510                 break;
1511         default:
1512                 dprintk("EINVAL: io_submit: no operation provided\n");
1513                 ret = -EINVAL;
1514         }
1515
1516         if (!kiocb->ki_retry)
1517                 return ret;
1518
1519         return 0;
1520 }
1521
1522 /*
1523  * aio_wake_function:
1524  *      wait queue callback function for aio notification,
1525  *      Simply triggers a retry of the operation via kick_iocb.
1526  *
1527  *      This callback is specified in the wait queue entry in
1528  *      a kiocb.
1529  *
1530  * Note:
1531  * This routine is executed with the wait queue lock held.
1532  * Since kick_iocb acquires iocb->ctx->ctx_lock, it nests
1533  * the ioctx lock inside the wait queue lock. This is safe
1534  * because this callback isn't used for wait queues which
1535  * are nested inside ioctx lock (i.e. ctx->wait)
1536  */
1537 static int aio_wake_function(wait_queue_t *wait, unsigned mode,
1538                              int sync, void *key)
1539 {
1540         struct kiocb *iocb = container_of(wait, struct kiocb, ki_wait);
1541
1542         list_del_init(&wait->task_list);
1543         kick_iocb(iocb);
1544         return 1;
1545 }
1546
1547 static void aio_batch_add(struct address_space *mapping,
1548                           struct hlist_head *batch_hash)
1549 {
1550         struct aio_batch_entry *abe;
1551         struct hlist_node *pos;
1552         unsigned bucket;
1553
1554         bucket = hash_ptr(mapping, AIO_BATCH_HASH_BITS);
1555         hlist_for_each_entry(abe, pos, &batch_hash[bucket], list) {
1556                 if (abe->mapping == mapping)
1557                         return;
1558         }
1559
1560         abe = mempool_alloc(abe_pool, GFP_KERNEL);
1561         BUG_ON(!igrab(mapping->host));
1562         abe->mapping = mapping;
1563         hlist_add_head(&abe->list, &batch_hash[bucket]);
1564         return;
1565 }
1566
1567 static void aio_batch_free(struct hlist_head *batch_hash)
1568 {
1569         struct aio_batch_entry *abe;
1570         struct hlist_node *pos, *n;
1571         int i;
1572
1573         for (i = 0; i < AIO_BATCH_HASH_SIZE; i++) {
1574                 hlist_for_each_entry_safe(abe, pos, n, &batch_hash[i], list) {
1575                         blk_run_address_space(abe->mapping);
1576                         iput(abe->mapping->host);
1577                         hlist_del(&abe->list);
1578                         mempool_free(abe, abe_pool);
1579                 }
1580         }
1581 }
1582
1583 static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
1584                          struct iocb *iocb, struct hlist_head *batch_hash)
1585 {
1586         struct kiocb *req;
1587         struct file *file;
1588         ssize_t ret;
1589
1590         /* enforce forwards compatibility on users */
1591         if (unlikely(iocb->aio_reserved1 || iocb->aio_reserved2)) {
1592                 pr_debug("EINVAL: io_submit: reserve field set\n");
1593                 return -EINVAL;
1594         }
1595
1596         /* prevent overflows */
1597         if (unlikely(
1598             (iocb->aio_buf != (unsigned long)iocb->aio_buf) ||
1599             (iocb->aio_nbytes != (size_t)iocb->aio_nbytes) ||
1600             ((ssize_t)iocb->aio_nbytes < 0)
1601            )) {
1602                 pr_debug("EINVAL: io_submit: overflow check\n");
1603                 return -EINVAL;
1604         }
1605
1606         file = fget(iocb->aio_fildes);
1607         if (unlikely(!file))
1608                 return -EBADF;
1609
1610         req = aio_get_req(ctx);         /* returns with 2 references to req */
1611         if (unlikely(!req)) {
1612                 fput(file);
1613                 return -EAGAIN;
1614         }
1615         req->ki_filp = file;
1616         if (iocb->aio_flags & IOCB_FLAG_RESFD) {
1617                 /*
1618                  * If the IOCB_FLAG_RESFD flag of aio_flags is set, get an
1619                  * instance of the file* now. The file descriptor must be
1620                  * an eventfd() fd, and will be signaled for each completed
1621                  * event using the eventfd_signal() function.
1622                  */
1623                 req->ki_eventfd = eventfd_ctx_fdget((int) iocb->aio_resfd);
1624                 if (IS_ERR(req->ki_eventfd)) {
1625                         ret = PTR_ERR(req->ki_eventfd);
1626                         req->ki_eventfd = NULL;
1627                         goto out_put_req;
1628                 }
1629         }
1630
1631         ret = put_user(req->ki_key, &user_iocb->aio_key);
1632         if (unlikely(ret)) {
1633                 dprintk("EFAULT: aio_key\n");
1634                 goto out_put_req;
1635         }
1636
1637         req->ki_obj.user = user_iocb;
1638         req->ki_user_data = iocb->aio_data;
1639         req->ki_pos = iocb->aio_offset;
1640
1641         req->ki_buf = (char __user *)(unsigned long)iocb->aio_buf;
1642         req->ki_left = req->ki_nbytes = iocb->aio_nbytes;
1643         req->ki_opcode = iocb->aio_lio_opcode;
1644         init_waitqueue_func_entry(&req->ki_wait, aio_wake_function);
1645         INIT_LIST_HEAD(&req->ki_wait.task_list);
1646
1647         ret = aio_setup_iocb(req);
1648
1649         if (ret)
1650                 goto out_put_req;
1651
1652         spin_lock_irq(&ctx->ctx_lock);
1653         aio_run_iocb(req);
1654         if (!list_empty(&ctx->run_list)) {
1655                 /* drain the run list */
1656                 while (__aio_run_iocbs(ctx))
1657                         ;
1658         }
1659         spin_unlock_irq(&ctx->ctx_lock);
1660         if (req->ki_opcode == IOCB_CMD_PREAD ||
1661             req->ki_opcode == IOCB_CMD_PREADV ||
1662             req->ki_opcode == IOCB_CMD_PWRITE ||
1663             req->ki_opcode == IOCB_CMD_PWRITEV)
1664                 aio_batch_add(file->f_mapping, batch_hash);
1665
1666         aio_put_req(req);       /* drop extra ref to req */
1667         return 0;
1668
1669 out_put_req:
1670         aio_put_req(req);       /* drop extra ref to req */
1671         aio_put_req(req);       /* drop i/o ref to req */
1672         return ret;
1673 }
1674
1675 /* sys_io_submit:
1676  *      Queue the nr iocbs pointed to by iocbpp for processing.  Returns
1677  *      the number of iocbs queued.  May return -EINVAL if the aio_context
1678  *      specified by ctx_id is invalid, if nr is < 0, if the iocb at
1679  *      *iocbpp[0] is not properly initialized, if the operation specified
1680  *      is invalid for the file descriptor in the iocb.  May fail with
1681  *      -EFAULT if any of the data structures point to invalid data.  May
1682  *      fail with -EBADF if the file descriptor specified in the first
1683  *      iocb is invalid.  May fail with -EAGAIN if insufficient resources
1684  *      are available to queue any iocbs.  Will return 0 if nr is 0.  Will
1685  *      fail with -ENOSYS if not implemented.
1686  */
1687 SYSCALL_DEFINE3(io_submit, aio_context_t, ctx_id, long, nr,
1688                 struct iocb __user * __user *, iocbpp)
1689 {
1690         struct kioctx *ctx;
1691         long ret = 0;
1692         int i;
1693         struct hlist_head batch_hash[AIO_BATCH_HASH_SIZE] = { { 0, }, };
1694
1695         if (unlikely(nr < 0))
1696                 return -EINVAL;
1697
1698         if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
1699                 return -EFAULT;
1700
1701         ctx = lookup_ioctx(ctx_id);
1702         if (unlikely(!ctx)) {
1703                 pr_debug("EINVAL: io_submit: invalid context id\n");
1704                 return -EINVAL;
1705         }
1706
1707         /*
1708          * AKPM: should this return a partial result if some of the IOs were
1709          * successfully submitted?
1710          */
1711         for (i=0; i<nr; i++) {
1712                 struct iocb __user *user_iocb;
1713                 struct iocb tmp;
1714
1715                 if (unlikely(__get_user(user_iocb, iocbpp + i))) {
1716                         ret = -EFAULT;
1717                         break;
1718                 }
1719
1720                 if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
1721                         ret = -EFAULT;
1722                         break;
1723                 }
1724
1725                 ret = io_submit_one(ctx, user_iocb, &tmp, batch_hash);
1726                 if (ret)
1727                         break;
1728         }
1729         aio_batch_free(batch_hash);
1730
1731         put_ioctx(ctx);
1732         return i ? i : ret;
1733 }
1734
1735 /* lookup_kiocb
1736  *      Finds a given iocb for cancellation.
1737  */
1738 static struct kiocb *lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb,
1739                                   u32 key)
1740 {
1741         struct list_head *pos;
1742
1743         assert_spin_locked(&ctx->ctx_lock);
1744
1745         /* TODO: use a hash or array, this sucks. */
1746         list_for_each(pos, &ctx->active_reqs) {
1747                 struct kiocb *kiocb = list_kiocb(pos);
1748                 if (kiocb->ki_obj.user == iocb && kiocb->ki_key == key)
1749                         return kiocb;
1750         }
1751         return NULL;
1752 }
1753
1754 /* sys_io_cancel:
1755  *      Attempts to cancel an iocb previously passed to io_submit.  If
1756  *      the operation is successfully cancelled, the resulting event is
1757  *      copied into the memory pointed to by result without being placed
1758  *      into the completion queue and 0 is returned.  May fail with
1759  *      -EFAULT if any of the data structures pointed to are invalid.
1760  *      May fail with -EINVAL if aio_context specified by ctx_id is
1761  *      invalid.  May fail with -EAGAIN if the iocb specified was not
1762  *      cancelled.  Will fail with -ENOSYS if not implemented.
1763  */
1764 SYSCALL_DEFINE3(io_cancel, aio_context_t, ctx_id, struct iocb __user *, iocb,
1765                 struct io_event __user *, result)
1766 {
1767         int (*cancel)(struct kiocb *iocb, struct io_event *res);
1768         struct kioctx *ctx;
1769         struct kiocb *kiocb;
1770         u32 key;
1771         int ret;
1772
1773         ret = get_user(key, &iocb->aio_key);
1774         if (unlikely(ret))
1775                 return -EFAULT;
1776
1777         ctx = lookup_ioctx(ctx_id);
1778         if (unlikely(!ctx))
1779                 return -EINVAL;
1780
1781         spin_lock_irq(&ctx->ctx_lock);
1782         ret = -EAGAIN;
1783         kiocb = lookup_kiocb(ctx, iocb, key);
1784         if (kiocb && kiocb->ki_cancel) {
1785                 cancel = kiocb->ki_cancel;
1786                 kiocb->ki_users ++;
1787                 kiocbSetCancelled(kiocb);
1788         } else
1789                 cancel = NULL;
1790         spin_unlock_irq(&ctx->ctx_lock);
1791
1792         if (NULL != cancel) {
1793                 struct io_event tmp;
1794                 pr_debug("calling cancel\n");
1795                 memset(&tmp, 0, sizeof(tmp));
1796                 tmp.obj = (u64)(unsigned long)kiocb->ki_obj.user;
1797                 tmp.data = kiocb->ki_user_data;
1798                 ret = cancel(kiocb, &tmp);
1799                 if (!ret) {
1800                         /* Cancellation succeeded -- copy the result
1801                          * into the user's buffer.
1802                          */
1803                         if (copy_to_user(result, &tmp, sizeof(tmp)))
1804                                 ret = -EFAULT;
1805                 }
1806         } else
1807                 ret = -EINVAL;
1808
1809         put_ioctx(ctx);
1810
1811         return ret;
1812 }
1813
1814 /* io_getevents:
1815  *      Attempts to read at least min_nr events and up to nr events from
1816  *      the completion queue for the aio_context specified by ctx_id.  May
1817  *      fail with -EINVAL if ctx_id is invalid, if min_nr is out of range,
1818  *      if nr is out of range, if when is out of range.  May fail with
1819  *      -EFAULT if any of the memory specified to is invalid.  May return
1820  *      0 or < min_nr if no events are available and the timeout specified
1821  *      by when has elapsed, where when == NULL specifies an infinite
1822  *      timeout.  Note that the timeout pointed to by when is relative and
1823  *      will be updated if not NULL and the operation blocks.  Will fail
1824  *      with -ENOSYS if not implemented.
1825  */
1826 SYSCALL_DEFINE5(io_getevents, aio_context_t, ctx_id,
1827                 long, min_nr,
1828                 long, nr,
1829                 struct io_event __user *, events,
1830                 struct timespec __user *, timeout)
1831 {
1832         struct kioctx *ioctx = lookup_ioctx(ctx_id);
1833         long ret = -EINVAL;
1834
1835         if (likely(ioctx)) {
1836                 if (likely(min_nr <= nr && min_nr >= 0 && nr >= 0))
1837                         ret = read_events(ioctx, min_nr, nr, events, timeout);
1838                 put_ioctx(ioctx);
1839         }
1840
1841         asmlinkage_protect(5, ret, ctx_id, min_nr, nr, events, timeout);
1842         return ret;
1843 }