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