VServer 1.9.2 (patch-2.6.8.1-vs1.9.2.diff)
[linux-2.6.git] / fs / aio.c
1 /*
2  *      An async IO implementation for Linux
3  *      Written by Benjamin LaHaise <bcrl@redhat.com>
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
18 #define DEBUG 0
19
20 #include <linux/sched.h>
21 #include <linux/fs.h>
22 #include <linux/file.h>
23 #include <linux/mm.h>
24 #include <linux/mman.h>
25 #include <linux/slab.h>
26 #include <linux/timer.h>
27 #include <linux/aio.h>
28 #include <linux/highmem.h>
29 #include <linux/workqueue.h>
30 #include <linux/security.h>
31
32 #include <asm/kmap_types.h>
33 #include <asm/uaccess.h>
34 #include <asm/mmu_context.h>
35
36 #if DEBUG > 1
37 #define dprintk         printk
38 #else
39 #define dprintk(x...)   do { ; } while (0)
40 #endif
41
42 /*------ sysctl variables----*/
43 atomic_t aio_nr = ATOMIC_INIT(0);       /* current system wide number of aio requests */
44 unsigned aio_max_nr = 0x10000;  /* system wide maximum number of aio requests */
45 /*----end sysctl variables---*/
46
47 static kmem_cache_t     *kiocb_cachep;
48 static kmem_cache_t     *kioctx_cachep;
49
50 static struct workqueue_struct *aio_wq;
51
52 /* Used for rare fput completion. */
53 static void aio_fput_routine(void *);
54 static DECLARE_WORK(fput_work, aio_fput_routine, NULL);
55
56 static spinlock_t       fput_lock = SPIN_LOCK_UNLOCKED;
57 LIST_HEAD(fput_head);
58
59 static void aio_kick_handler(void *);
60
61 /* aio_setup
62  *      Creates the slab caches used by the aio routines, panic on
63  *      failure as this is done early during the boot sequence.
64  */
65 static int __init aio_setup(void)
66 {
67         kiocb_cachep = kmem_cache_create("kiocb", sizeof(struct kiocb),
68                                 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
69         kioctx_cachep = kmem_cache_create("kioctx", sizeof(struct kioctx),
70                                 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
71
72         aio_wq = create_workqueue("aio");
73
74         pr_debug("aio_setup: sizeof(struct page) = %d\n", (int)sizeof(struct page));
75
76         return 0;
77 }
78
79 static void aio_free_ring(struct kioctx *ctx)
80 {
81         struct aio_ring_info *info = &ctx->ring_info;
82         long i;
83
84         for (i=0; i<info->nr_pages; i++)
85                 put_page(info->ring_pages[i]);
86
87         if (info->mmap_size) {
88                 down_write(&ctx->mm->mmap_sem);
89                 do_munmap(ctx->mm, info->mmap_base, info->mmap_size);
90                 up_write(&ctx->mm->mmap_sem);
91         }
92
93         if (info->ring_pages && info->ring_pages != info->internal_pages)
94                 kfree(info->ring_pages);
95         info->ring_pages = NULL;
96         info->nr = 0;
97 }
98
99 static int aio_setup_ring(struct kioctx *ctx)
100 {
101         struct aio_ring *ring;
102         struct aio_ring_info *info = &ctx->ring_info;
103         unsigned nr_events = ctx->max_reqs;
104         unsigned long size;
105         int nr_pages;
106
107         /* Compensate for the ring buffer's head/tail overlap entry */
108         nr_events += 2; /* 1 is required, 2 for good luck */
109
110         size = sizeof(struct aio_ring);
111         size += sizeof(struct io_event) * nr_events;
112         nr_pages = (size + PAGE_SIZE-1) >> PAGE_SHIFT;
113
114         if (nr_pages < 0)
115                 return -EINVAL;
116
117         info->nr_pages = nr_pages;
118
119         nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring)) / sizeof(struct io_event);
120
121         info->nr = 0;
122         info->ring_pages = info->internal_pages;
123         if (nr_pages > AIO_RING_PAGES) {
124                 info->ring_pages = kmalloc(sizeof(struct page *) * nr_pages, GFP_KERNEL);
125                 if (!info->ring_pages)
126                         return -ENOMEM;
127                 memset(info->ring_pages, 0, sizeof(struct page *) * nr_pages);
128         }
129
130         info->mmap_size = nr_pages * PAGE_SIZE;
131         dprintk("attempting mmap of %lu bytes\n", info->mmap_size);
132         down_write(&ctx->mm->mmap_sem);
133         info->mmap_base = do_mmap(NULL, 0, info->mmap_size, 
134                                   PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE,
135                                   0);
136         if (IS_ERR((void *)info->mmap_base)) {
137                 up_write(&ctx->mm->mmap_sem);
138                 printk("mmap err: %ld\n", -info->mmap_base);
139                 info->mmap_size = 0;
140                 aio_free_ring(ctx);
141                 return -EAGAIN;
142         }
143
144         dprintk("mmap address: 0x%08lx\n", info->mmap_base);
145         info->nr_pages = get_user_pages(current, ctx->mm,
146                                         info->mmap_base, nr_pages, 
147                                         1, 0, info->ring_pages, NULL);
148         up_write(&ctx->mm->mmap_sem);
149
150         if (unlikely(info->nr_pages != nr_pages)) {
151                 aio_free_ring(ctx);
152                 return -EAGAIN;
153         }
154
155         ctx->user_id = info->mmap_base;
156
157         info->nr = nr_events;           /* trusted copy */
158
159         ring = kmap_atomic(info->ring_pages[0], KM_USER0);
160         ring->nr = nr_events;   /* user copy */
161         ring->id = ctx->user_id;
162         ring->head = ring->tail = 0;
163         ring->magic = AIO_RING_MAGIC;
164         ring->compat_features = AIO_RING_COMPAT_FEATURES;
165         ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
166         ring->header_length = sizeof(struct aio_ring);
167         kunmap_atomic(ring, KM_USER0);
168
169         return 0;
170 }
171
172
173 /* aio_ring_event: returns a pointer to the event at the given index from
174  * kmap_atomic(, km).  Release the pointer with put_aio_ring_event();
175  */
176 #define AIO_EVENTS_PER_PAGE     (PAGE_SIZE / sizeof(struct io_event))
177 #define AIO_EVENTS_FIRST_PAGE   ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
178 #define AIO_EVENTS_OFFSET       (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
179
180 #define aio_ring_event(info, nr, km) ({                                 \
181         unsigned pos = (nr) + AIO_EVENTS_OFFSET;                        \
182         struct io_event *__event;                                       \
183         __event = kmap_atomic(                                          \
184                         (info)->ring_pages[pos / AIO_EVENTS_PER_PAGE], km); \
185         __event += pos % AIO_EVENTS_PER_PAGE;                           \
186         __event;                                                        \
187 })
188
189 #define put_aio_ring_event(event, km) do {      \
190         struct io_event *__event = (event);     \
191         (void)__event;                          \
192         kunmap_atomic((void *)((unsigned long)__event & PAGE_MASK), km); \
193 } while(0)
194
195 /* ioctx_alloc
196  *      Allocates and initializes an ioctx.  Returns an ERR_PTR if it failed.
197  */
198 static struct kioctx *ioctx_alloc(unsigned nr_events)
199 {
200         struct mm_struct *mm;
201         struct kioctx *ctx;
202
203         /* Prevent overflows */
204         if ((nr_events > (0x10000000U / sizeof(struct io_event))) ||
205             (nr_events > (0x10000000U / sizeof(struct kiocb)))) {
206                 pr_debug("ENOMEM: nr_events too high\n");
207                 return ERR_PTR(-EINVAL);
208         }
209
210         if (nr_events > aio_max_nr)
211                 return ERR_PTR(-EAGAIN);
212
213         ctx = kmem_cache_alloc(kioctx_cachep, GFP_KERNEL);
214         if (!ctx)
215                 return ERR_PTR(-ENOMEM);
216
217         memset(ctx, 0, sizeof(*ctx));
218         ctx->max_reqs = nr_events;
219         mm = ctx->mm = current->mm;
220         atomic_inc(&mm->mm_count);
221
222         atomic_set(&ctx->users, 1);
223         spin_lock_init(&ctx->ctx_lock);
224         spin_lock_init(&ctx->ring_info.ring_lock);
225         init_waitqueue_head(&ctx->wait);
226
227         INIT_LIST_HEAD(&ctx->active_reqs);
228         INIT_LIST_HEAD(&ctx->run_list);
229         INIT_WORK(&ctx->wq, aio_kick_handler, ctx);
230
231         if (aio_setup_ring(ctx) < 0)
232                 goto out_freectx;
233
234         /* limit the number of system wide aios */
235         atomic_add(ctx->max_reqs, &aio_nr);     /* undone by __put_ioctx */
236         if (unlikely(atomic_read(&aio_nr) > aio_max_nr))
237                 goto out_cleanup;
238
239         /* now link into global list.  kludge.  FIXME */
240         write_lock(&mm->ioctx_list_lock);
241         ctx->next = mm->ioctx_list;
242         mm->ioctx_list = ctx;
243         write_unlock(&mm->ioctx_list_lock);
244
245         dprintk("aio: allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
246                 ctx, ctx->user_id, current->mm, ctx->ring_info.nr);
247         return ctx;
248
249 out_cleanup:
250         atomic_sub(ctx->max_reqs, &aio_nr);
251         ctx->max_reqs = 0;      /* prevent __put_ioctx from sub'ing aio_nr */
252         __put_ioctx(ctx);
253         return ERR_PTR(-EAGAIN);
254
255 out_freectx:
256         mmdrop(mm);
257         kmem_cache_free(kioctx_cachep, ctx);
258         ctx = ERR_PTR(-ENOMEM);
259
260         dprintk("aio: error allocating ioctx %p\n", ctx);
261         return ctx;
262 }
263
264 /* aio_cancel_all
265  *      Cancels all outstanding aio requests on an aio context.  Used 
266  *      when the processes owning a context have all exited to encourage 
267  *      the rapid destruction of the kioctx.
268  */
269 static void aio_cancel_all(struct kioctx *ctx)
270 {
271         int (*cancel)(struct kiocb *, struct io_event *);
272         struct io_event res;
273         spin_lock_irq(&ctx->ctx_lock);
274         ctx->dead = 1;
275         while (!list_empty(&ctx->active_reqs)) {
276                 struct list_head *pos = ctx->active_reqs.next;
277                 struct kiocb *iocb = list_kiocb(pos);
278                 list_del_init(&iocb->ki_list);
279                 cancel = iocb->ki_cancel;
280                 if (cancel) {
281                         iocb->ki_users++;
282                         spin_unlock_irq(&ctx->ctx_lock);
283                         cancel(iocb, &res);
284                         spin_lock_irq(&ctx->ctx_lock);
285                 }
286         }
287         spin_unlock_irq(&ctx->ctx_lock);
288 }
289
290 void wait_for_all_aios(struct kioctx *ctx)
291 {
292         struct task_struct *tsk = current;
293         DECLARE_WAITQUEUE(wait, tsk);
294
295         if (!ctx->reqs_active)
296                 return;
297
298         add_wait_queue(&ctx->wait, &wait);
299         set_task_state(tsk, TASK_UNINTERRUPTIBLE);
300         while (ctx->reqs_active) {
301                 schedule();
302                 set_task_state(tsk, TASK_UNINTERRUPTIBLE);
303         }
304         __set_task_state(tsk, TASK_RUNNING);
305         remove_wait_queue(&ctx->wait, &wait);
306 }
307
308 /* wait_on_sync_kiocb:
309  *      Waits on the given sync kiocb to complete.
310  */
311 ssize_t fastcall wait_on_sync_kiocb(struct kiocb *iocb)
312 {
313         while (iocb->ki_users) {
314                 set_current_state(TASK_UNINTERRUPTIBLE);
315                 if (!iocb->ki_users)
316                         break;
317                 schedule();
318         }
319         __set_current_state(TASK_RUNNING);
320         return iocb->ki_user_data;
321 }
322
323 /* exit_aio: called when the last user of mm goes away.  At this point, 
324  * there is no way for any new requests to be submited or any of the 
325  * io_* syscalls to be called on the context.  However, there may be 
326  * outstanding requests which hold references to the context; as they 
327  * go away, they will call put_ioctx and release any pinned memory
328  * associated with the request (held via struct page * references).
329  */
330 void fastcall exit_aio(struct mm_struct *mm)
331 {
332         struct kioctx *ctx = mm->ioctx_list;
333         mm->ioctx_list = NULL;
334         while (ctx) {
335                 struct kioctx *next = ctx->next;
336                 ctx->next = NULL;
337                 aio_cancel_all(ctx);
338
339                 wait_for_all_aios(ctx);
340
341                 if (1 != atomic_read(&ctx->users))
342                         printk(KERN_DEBUG
343                                 "exit_aio:ioctx still alive: %d %d %d\n",
344                                 atomic_read(&ctx->users), ctx->dead,
345                                 ctx->reqs_active);
346                 put_ioctx(ctx);
347                 ctx = next;
348         }
349 }
350
351 /* __put_ioctx
352  *      Called when the last user of an aio context has gone away,
353  *      and the struct needs to be freed.
354  */
355 void fastcall __put_ioctx(struct kioctx *ctx)
356 {
357         unsigned nr_events = ctx->max_reqs;
358
359         if (unlikely(ctx->reqs_active))
360                 BUG();
361
362         aio_free_ring(ctx);
363         mmdrop(ctx->mm);
364         ctx->mm = NULL;
365         pr_debug("__put_ioctx: freeing %p\n", ctx);
366         kmem_cache_free(kioctx_cachep, ctx);
367
368         atomic_sub(nr_events, &aio_nr);
369 }
370
371 /* aio_get_req
372  *      Allocate a slot for an aio request.  Increments the users count
373  * of the kioctx so that the kioctx stays around until all requests are
374  * complete.  Returns NULL if no requests are free.
375  *
376  * Returns with kiocb->users set to 2.  The io submit code path holds
377  * an extra reference while submitting the i/o.
378  * This prevents races between the aio code path referencing the
379  * req (after submitting it) and aio_complete() freeing the req.
380  */
381 static struct kiocb *FASTCALL(__aio_get_req(struct kioctx *ctx));
382 static struct kiocb fastcall *__aio_get_req(struct kioctx *ctx)
383 {
384         struct kiocb *req = NULL;
385         struct aio_ring *ring;
386         int okay = 0;
387
388         req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL);
389         if (unlikely(!req))
390                 return NULL;
391
392         req->ki_flags = 1 << KIF_LOCKED;
393         req->ki_users = 2;
394         req->ki_key = 0;
395         req->ki_ctx = ctx;
396         req->ki_cancel = NULL;
397         req->ki_retry = NULL;
398         req->ki_obj.user = NULL;
399         req->ki_dtor = NULL;
400         req->private = NULL;
401
402         /* Check if the completion queue has enough free space to
403          * accept an event from this io.
404          */
405         spin_lock_irq(&ctx->ctx_lock);
406         ring = kmap_atomic(ctx->ring_info.ring_pages[0], KM_USER0);
407         if (ctx->reqs_active < aio_ring_avail(&ctx->ring_info, ring)) {
408                 list_add(&req->ki_list, &ctx->active_reqs);
409                 get_ioctx(ctx);
410                 ctx->reqs_active++;
411                 okay = 1;
412         }
413         kunmap_atomic(ring, KM_USER0);
414         spin_unlock_irq(&ctx->ctx_lock);
415
416         if (!okay) {
417                 kmem_cache_free(kiocb_cachep, req);
418                 req = NULL;
419         }
420
421         return req;
422 }
423
424 static inline struct kiocb *aio_get_req(struct kioctx *ctx)
425 {
426         struct kiocb *req;
427         /* Handle a potential starvation case -- should be exceedingly rare as 
428          * requests will be stuck on fput_head only if the aio_fput_routine is 
429          * delayed and the requests were the last user of the struct file.
430          */
431         req = __aio_get_req(ctx);
432         if (unlikely(NULL == req)) {
433                 aio_fput_routine(NULL);
434                 req = __aio_get_req(ctx);
435         }
436         return req;
437 }
438
439 static inline void really_put_req(struct kioctx *ctx, struct kiocb *req)
440 {
441         if (req->ki_dtor)
442                 req->ki_dtor(req);
443         req->ki_ctx = NULL;
444         req->ki_filp = NULL;
445         req->ki_obj.user = NULL;
446         req->ki_dtor = NULL;
447         req->private = NULL;
448         kmem_cache_free(kiocb_cachep, req);
449         ctx->reqs_active--;
450
451         if (unlikely(!ctx->reqs_active && ctx->dead))
452                 wake_up(&ctx->wait);
453 }
454
455 static void aio_fput_routine(void *data)
456 {
457         spin_lock_irq(&fput_lock);
458         while (likely(!list_empty(&fput_head))) {
459                 struct kiocb *req = list_kiocb(fput_head.next);
460                 struct kioctx *ctx = req->ki_ctx;
461
462                 list_del(&req->ki_list);
463                 spin_unlock_irq(&fput_lock);
464
465                 /* Complete the fput */
466                 __fput(req->ki_filp);
467
468                 /* Link the iocb into the context's free list */
469                 spin_lock_irq(&ctx->ctx_lock);
470                 really_put_req(ctx, req);
471                 spin_unlock_irq(&ctx->ctx_lock);
472
473                 put_ioctx(ctx);
474                 spin_lock_irq(&fput_lock);
475         }
476         spin_unlock_irq(&fput_lock);
477 }
478
479 /* __aio_put_req
480  *      Returns true if this put was the last user of the request.
481  */
482 static int __aio_put_req(struct kioctx *ctx, struct kiocb *req)
483 {
484         dprintk(KERN_DEBUG "aio_put(%p): f_count=%d\n",
485                 req, atomic_read(&req->ki_filp->f_count));
486
487         req->ki_users --;
488         if (unlikely(req->ki_users < 0))
489                 BUG();
490         if (likely(req->ki_users))
491                 return 0;
492         list_del(&req->ki_list);                /* remove from active_reqs */
493         req->ki_cancel = NULL;
494         req->ki_retry = NULL;
495
496         /* Must be done under the lock to serialise against cancellation.
497          * Call this aio_fput as it duplicates fput via the fput_work.
498          */
499         if (unlikely(atomic_dec_and_test(&req->ki_filp->f_count))) {
500                 get_ioctx(ctx);
501                 spin_lock(&fput_lock);
502                 list_add(&req->ki_list, &fput_head);
503                 spin_unlock(&fput_lock);
504                 queue_work(aio_wq, &fput_work);
505         } else
506                 really_put_req(ctx, req);
507         return 1;
508 }
509
510 /* aio_put_req
511  *      Returns true if this put was the last user of the kiocb,
512  *      false if the request is still in use.
513  */
514 int fastcall aio_put_req(struct kiocb *req)
515 {
516         struct kioctx *ctx = req->ki_ctx;
517         int ret;
518         spin_lock_irq(&ctx->ctx_lock);
519         ret = __aio_put_req(ctx, req);
520         spin_unlock_irq(&ctx->ctx_lock);
521         if (ret)
522                 put_ioctx(ctx);
523         return ret;
524 }
525
526 /*      Lookup an ioctx id.  ioctx_list is lockless for reads.
527  *      FIXME: this is O(n) and is only suitable for development.
528  */
529 struct kioctx *lookup_ioctx(unsigned long ctx_id)
530 {
531         struct kioctx *ioctx;
532         struct mm_struct *mm;
533
534         mm = current->mm;
535         read_lock(&mm->ioctx_list_lock);
536         for (ioctx = mm->ioctx_list; ioctx; ioctx = ioctx->next)
537                 if (likely(ioctx->user_id == ctx_id && !ioctx->dead)) {
538                         get_ioctx(ioctx);
539                         break;
540                 }
541         read_unlock(&mm->ioctx_list_lock);
542
543         return ioctx;
544 }
545
546 static void use_mm(struct mm_struct *mm)
547 {
548         struct mm_struct *active_mm;
549
550         atomic_inc(&mm->mm_count);
551         task_lock(current);
552         active_mm = current->active_mm;
553         current->mm = mm;
554         if (mm != active_mm) {
555                 current->active_mm = mm;
556                 activate_mm(active_mm, mm);
557         }
558         task_unlock(current);
559         mmdrop(active_mm);
560 }
561
562 static void unuse_mm(struct mm_struct *mm)
563 {
564         task_lock(current);
565         current->mm = NULL;
566         task_unlock(current);
567         /* active_mm is still 'mm' */
568         enter_lazy_tlb(mm, current);
569 }
570
571 /* Run on kevent's context.  FIXME: needs to be per-cpu and warn if an
572  * operation blocks.
573  */
574 static void aio_kick_handler(void *data)
575 {
576         struct kioctx *ctx = data;
577
578         use_mm(ctx->mm);
579
580         spin_lock_irq(&ctx->ctx_lock);
581         while (!list_empty(&ctx->run_list)) {
582                 struct kiocb *iocb;
583                 long ret;
584
585                 iocb = list_entry(ctx->run_list.next, struct kiocb,
586                                   ki_run_list);
587                 list_del(&iocb->ki_run_list);
588                 iocb->ki_users ++;
589                 spin_unlock_irq(&ctx->ctx_lock);
590
591                 kiocbClearKicked(iocb);
592                 ret = iocb->ki_retry(iocb);
593                 if (-EIOCBQUEUED != ret) {
594                         aio_complete(iocb, ret, 0);
595                         iocb = NULL;
596                 }
597
598                 spin_lock_irq(&ctx->ctx_lock);
599                 if (NULL != iocb)
600                         __aio_put_req(ctx, iocb);
601         }
602         spin_unlock_irq(&ctx->ctx_lock);
603
604         unuse_mm(ctx->mm);
605 }
606
607 void fastcall kick_iocb(struct kiocb *iocb)
608 {
609         struct kioctx   *ctx = iocb->ki_ctx;
610
611         /* sync iocbs are easy: they can only ever be executing from a 
612          * single context. */
613         if (is_sync_kiocb(iocb)) {
614                 kiocbSetKicked(iocb);
615                 wake_up_process(iocb->ki_obj.tsk);
616                 return;
617         }
618
619         if (!kiocbTryKick(iocb)) {
620                 unsigned long flags;
621                 spin_lock_irqsave(&ctx->ctx_lock, flags);
622                 list_add_tail(&iocb->ki_run_list, &ctx->run_list);
623                 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
624                 queue_work(aio_wq, &ctx->wq);
625         }
626 }
627 EXPORT_SYMBOL(kick_iocb);
628
629 /* aio_complete
630  *      Called when the io request on the given iocb is complete.
631  *      Returns true if this is the last user of the request.  The 
632  *      only other user of the request can be the cancellation code.
633  */
634 int fastcall aio_complete(struct kiocb *iocb, long res, long res2)
635 {
636         struct kioctx   *ctx = iocb->ki_ctx;
637         struct aio_ring_info    *info;
638         struct aio_ring *ring;
639         struct io_event *event;
640         unsigned long   flags;
641         unsigned long   tail;
642         int             ret;
643
644         /* Special case handling for sync iocbs: events go directly
645          * into the iocb for fast handling.  Note that this will not 
646          * work if we allow sync kiocbs to be cancelled. in which
647          * case the usage count checks will have to move under ctx_lock
648          * for all cases.
649          */
650         if (is_sync_kiocb(iocb)) {
651                 int ret;
652
653                 iocb->ki_user_data = res;
654                 if (iocb->ki_users == 1) {
655                         iocb->ki_users = 0;
656                         ret = 1;
657                 } else {
658                         spin_lock_irq(&ctx->ctx_lock);
659                         iocb->ki_users--;
660                         ret = (0 == iocb->ki_users);
661                         spin_unlock_irq(&ctx->ctx_lock);
662                 }
663                 /* sync iocbs put the task here for us */
664                 wake_up_process(iocb->ki_obj.tsk);
665                 return ret;
666         }
667
668         info = &ctx->ring_info;
669
670         /* add a completion event to the ring buffer.
671          * must be done holding ctx->ctx_lock to prevent
672          * other code from messing with the tail
673          * pointer since we might be called from irq
674          * context.
675          */
676         spin_lock_irqsave(&ctx->ctx_lock, flags);
677
678         ring = kmap_atomic(info->ring_pages[0], KM_IRQ1);
679
680         tail = info->tail;
681         event = aio_ring_event(info, tail, KM_IRQ0);
682         tail = (tail + 1) % info->nr;
683
684         event->obj = (u64)(unsigned long)iocb->ki_obj.user;
685         event->data = iocb->ki_user_data;
686         event->res = res;
687         event->res2 = res2;
688
689         dprintk("aio_complete: %p[%lu]: %p: %p %Lx %lx %lx\n",
690                 ctx, tail, iocb, iocb->ki_obj.user, iocb->ki_user_data,
691                 res, res2);
692
693         /* after flagging the request as done, we
694          * must never even look at it again
695          */
696         smp_wmb();      /* make event visible before updating tail */
697
698         info->tail = tail;
699         ring->tail = tail;
700
701         put_aio_ring_event(event, KM_IRQ0);
702         kunmap_atomic(ring, KM_IRQ1);
703
704         pr_debug("added to ring %p at [%lu]\n", iocb, tail);
705
706         /* everything turned out well, dispose of the aiocb. */
707         ret = __aio_put_req(ctx, iocb);
708
709         spin_unlock_irqrestore(&ctx->ctx_lock, flags);
710
711         if (waitqueue_active(&ctx->wait))
712                 wake_up(&ctx->wait);
713
714         if (ret)
715                 put_ioctx(ctx);
716
717         return ret;
718 }
719
720 /* aio_read_evt
721  *      Pull an event off of the ioctx's event ring.  Returns the number of 
722  *      events fetched (0 or 1 ;-)
723  *      FIXME: make this use cmpxchg.
724  *      TODO: make the ringbuffer user mmap()able (requires FIXME).
725  */
726 static int aio_read_evt(struct kioctx *ioctx, struct io_event *ent)
727 {
728         struct aio_ring_info *info = &ioctx->ring_info;
729         struct aio_ring *ring;
730         unsigned long head;
731         int ret = 0;
732
733         ring = kmap_atomic(info->ring_pages[0], KM_USER0);
734         dprintk("in aio_read_evt h%lu t%lu m%lu\n",
735                  (unsigned long)ring->head, (unsigned long)ring->tail,
736                  (unsigned long)ring->nr);
737
738         if (ring->head == ring->tail)
739                 goto out;
740
741         spin_lock(&info->ring_lock);
742
743         head = ring->head % info->nr;
744         if (head != ring->tail) {
745                 struct io_event *evp = aio_ring_event(info, head, KM_USER1);
746                 *ent = *evp;
747                 head = (head + 1) % info->nr;
748                 smp_mb(); /* finish reading the event before updatng the head */
749                 ring->head = head;
750                 ret = 1;
751                 put_aio_ring_event(evp, KM_USER1);
752         }
753         spin_unlock(&info->ring_lock);
754
755 out:
756         kunmap_atomic(ring, KM_USER0);
757         dprintk("leaving aio_read_evt: %d  h%lu t%lu\n", ret,
758                  (unsigned long)ring->head, (unsigned long)ring->tail);
759         return ret;
760 }
761
762 struct timeout {
763         struct timer_list       timer;
764         int                     timed_out;
765         struct task_struct      *p;
766 };
767
768 static void timeout_func(unsigned long data)
769 {
770         struct timeout *to = (struct timeout *)data;
771
772         to->timed_out = 1;
773         wake_up_process(to->p);
774 }
775
776 static inline void init_timeout(struct timeout *to)
777 {
778         init_timer(&to->timer);
779         to->timer.data = (unsigned long)to;
780         to->timer.function = timeout_func;
781         to->timed_out = 0;
782         to->p = current;
783 }
784
785 static inline void set_timeout(long start_jiffies, struct timeout *to,
786                                const struct timespec *ts)
787 {
788         to->timer.expires = start_jiffies + timespec_to_jiffies(ts);
789         if (time_after(to->timer.expires, jiffies))
790                 add_timer(&to->timer);
791         else
792                 to->timed_out = 1;
793 }
794
795 static inline void clear_timeout(struct timeout *to)
796 {
797         del_singleshot_timer_sync(&to->timer);
798 }
799
800 static int read_events(struct kioctx *ctx,
801                         long min_nr, long nr,
802                         struct io_event __user *event,
803                         struct timespec __user *timeout)
804 {
805         long                    start_jiffies = jiffies;
806         struct task_struct      *tsk = current;
807         DECLARE_WAITQUEUE(wait, tsk);
808         int                     ret;
809         int                     i = 0;
810         struct io_event         ent;
811         struct timeout          to;
812
813         /* needed to zero any padding within an entry (there shouldn't be 
814          * any, but C is fun!
815          */
816         memset(&ent, 0, sizeof(ent));
817         ret = 0;
818
819         while (likely(i < nr)) {
820                 ret = aio_read_evt(ctx, &ent);
821                 if (unlikely(ret <= 0))
822                         break;
823
824                 dprintk("read event: %Lx %Lx %Lx %Lx\n",
825                         ent.data, ent.obj, ent.res, ent.res2);
826
827                 /* Could we split the check in two? */
828                 ret = -EFAULT;
829                 if (unlikely(copy_to_user(event, &ent, sizeof(ent)))) {
830                         dprintk("aio: lost an event due to EFAULT.\n");
831                         break;
832                 }
833                 ret = 0;
834
835                 /* Good, event copied to userland, update counts. */
836                 event ++;
837                 i ++;
838         }
839
840         if (min_nr <= i)
841                 return i;
842         if (ret)
843                 return ret;
844
845         /* End fast path */
846
847         init_timeout(&to);
848         if (timeout) {
849                 struct timespec ts;
850                 ret = -EFAULT;
851                 if (unlikely(copy_from_user(&ts, timeout, sizeof(ts))))
852                         goto out;
853
854                 set_timeout(start_jiffies, &to, &ts);
855         }
856
857         while (likely(i < nr)) {
858                 add_wait_queue_exclusive(&ctx->wait, &wait);
859                 do {
860                         set_task_state(tsk, TASK_INTERRUPTIBLE);
861
862                         ret = aio_read_evt(ctx, &ent);
863                         if (ret)
864                                 break;
865                         if (min_nr <= i)
866                                 break;
867                         ret = 0;
868                         if (to.timed_out)       /* Only check after read evt */
869                                 break;
870                         schedule();
871                         if (signal_pending(tsk)) {
872                                 ret = -EINTR;
873                                 break;
874                         }
875                         /*ret = aio_read_evt(ctx, &ent);*/
876                 } while (1) ;
877
878                 set_task_state(tsk, TASK_RUNNING);
879                 remove_wait_queue(&ctx->wait, &wait);
880
881                 if (unlikely(ret <= 0))
882                         break;
883
884                 ret = -EFAULT;
885                 if (unlikely(copy_to_user(event, &ent, sizeof(ent)))) {
886                         dprintk("aio: lost an event due to EFAULT.\n");
887                         break;
888                 }
889
890                 /* Good, event copied to userland, update counts. */
891                 event ++;
892                 i ++;
893         }
894
895         if (timeout)
896                 clear_timeout(&to);
897 out:
898         return i ? i : ret;
899 }
900
901 /* Take an ioctx and remove it from the list of ioctx's.  Protects 
902  * against races with itself via ->dead.
903  */
904 static void io_destroy(struct kioctx *ioctx)
905 {
906         struct mm_struct *mm = current->mm;
907         struct kioctx **tmp;
908         int was_dead;
909
910         /* delete the entry from the list is someone else hasn't already */
911         write_lock(&mm->ioctx_list_lock);
912         was_dead = ioctx->dead;
913         ioctx->dead = 1;
914         for (tmp = &mm->ioctx_list; *tmp && *tmp != ioctx;
915              tmp = &(*tmp)->next)
916                 ;
917         if (*tmp)
918                 *tmp = ioctx->next;
919         write_unlock(&mm->ioctx_list_lock);
920
921         dprintk("aio_release(%p)\n", ioctx);
922         if (likely(!was_dead))
923                 put_ioctx(ioctx);       /* twice for the list */
924
925         aio_cancel_all(ioctx);
926         wait_for_all_aios(ioctx);
927         put_ioctx(ioctx);       /* once for the lookup */
928 }
929
930 /* sys_io_setup:
931  *      Create an aio_context capable of receiving at least nr_events.
932  *      ctxp must not point to an aio_context that already exists, and
933  *      must be initialized to 0 prior to the call.  On successful
934  *      creation of the aio_context, *ctxp is filled in with the resulting 
935  *      handle.  May fail with -EINVAL if *ctxp is not initialized,
936  *      if the specified nr_events exceeds internal limits.  May fail 
937  *      with -EAGAIN if the specified nr_events exceeds the user's limit 
938  *      of available events.  May fail with -ENOMEM if insufficient kernel
939  *      resources are available.  May fail with -EFAULT if an invalid
940  *      pointer is passed for ctxp.  Will fail with -ENOSYS if not
941  *      implemented.
942  */
943 asmlinkage long sys_io_setup(unsigned nr_events, aio_context_t __user *ctxp)
944 {
945         struct kioctx *ioctx = NULL;
946         unsigned long ctx;
947         long ret;
948
949         ret = get_user(ctx, ctxp);
950         if (unlikely(ret))
951                 goto out;
952
953         ret = -EINVAL;
954         if (unlikely(ctx || (int)nr_events <= 0)) {
955                 pr_debug("EINVAL: io_setup: ctx or nr_events > max\n");
956                 goto out;
957         }
958
959         ioctx = ioctx_alloc(nr_events);
960         ret = PTR_ERR(ioctx);
961         if (!IS_ERR(ioctx)) {
962                 ret = put_user(ioctx->user_id, ctxp);
963                 if (!ret)
964                         return 0;
965                 get_ioctx(ioctx);
966                 io_destroy(ioctx);
967         }
968
969 out:
970         return ret;
971 }
972
973 /* sys_io_destroy:
974  *      Destroy the aio_context specified.  May cancel any outstanding 
975  *      AIOs and block on completion.  Will fail with -ENOSYS if not
976  *      implemented.  May fail with -EFAULT if the context pointed to
977  *      is invalid.
978  */
979 asmlinkage long sys_io_destroy(aio_context_t ctx)
980 {
981         struct kioctx *ioctx = lookup_ioctx(ctx);
982         if (likely(NULL != ioctx)) {
983                 io_destroy(ioctx);
984                 return 0;
985         }
986         pr_debug("EINVAL: io_destroy: invalid context id\n");
987         return -EINVAL;
988 }
989
990 int fastcall io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
991                          struct iocb *iocb)
992 {
993         struct kiocb *req;
994         struct file *file;
995         ssize_t ret;
996         char __user *buf;
997
998         /* enforce forwards compatibility on users */
999         if (unlikely(iocb->aio_reserved1 || iocb->aio_reserved2 ||
1000                      iocb->aio_reserved3)) {
1001                 pr_debug("EINVAL: io_submit: reserve field set\n");
1002                 return -EINVAL;
1003         }
1004
1005         /* prevent overflows */
1006         if (unlikely(
1007             (iocb->aio_buf != (unsigned long)iocb->aio_buf) ||
1008             (iocb->aio_nbytes != (size_t)iocb->aio_nbytes) ||
1009             ((ssize_t)iocb->aio_nbytes < 0)
1010            )) {
1011                 pr_debug("EINVAL: io_submit: overflow check\n");
1012                 return -EINVAL;
1013         }
1014
1015         file = fget(iocb->aio_fildes);
1016         if (unlikely(!file))
1017                 return -EBADF;
1018
1019         req = aio_get_req(ctx);         /* returns with 2 references to req */
1020         if (unlikely(!req)) {
1021                 fput(file);
1022                 return -EAGAIN;
1023         }
1024
1025         req->ki_filp = file;
1026         iocb->aio_key = req->ki_key;
1027         ret = put_user(iocb->aio_key, &user_iocb->aio_key);
1028         if (unlikely(ret)) {
1029                 dprintk("EFAULT: aio_key\n");
1030                 goto out_put_req;
1031         }
1032
1033         req->ki_obj.user = user_iocb;
1034         req->ki_user_data = iocb->aio_data;
1035         req->ki_pos = iocb->aio_offset;
1036
1037         buf = (char __user *)(unsigned long)iocb->aio_buf;
1038
1039         switch (iocb->aio_lio_opcode) {
1040         case IOCB_CMD_PREAD:
1041                 ret = -EBADF;
1042                 if (unlikely(!(file->f_mode & FMODE_READ)))
1043                         goto out_put_req;
1044                 ret = -EFAULT;
1045                 if (unlikely(!access_ok(VERIFY_WRITE, buf, iocb->aio_nbytes)))
1046                         goto out_put_req;
1047                 ret = security_file_permission (file, MAY_READ);
1048                 if (ret)
1049                         goto out_put_req;
1050                 ret = -EINVAL;
1051                 if (file->f_op->aio_read)
1052                         ret = file->f_op->aio_read(req, buf,
1053                                         iocb->aio_nbytes, req->ki_pos);
1054                 break;
1055         case IOCB_CMD_PWRITE:
1056                 ret = -EBADF;
1057                 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1058                         goto out_put_req;
1059                 ret = -EFAULT;
1060                 if (unlikely(!access_ok(VERIFY_READ, buf, iocb->aio_nbytes)))
1061                         goto out_put_req;
1062                 ret = security_file_permission (file, MAY_WRITE);
1063                 if (ret)
1064                         goto out_put_req;
1065                 ret = -EINVAL;
1066                 if (file->f_op->aio_write)
1067                         ret = file->f_op->aio_write(req, buf,
1068                                         iocb->aio_nbytes, req->ki_pos);
1069                 break;
1070         case IOCB_CMD_FDSYNC:
1071                 ret = -EINVAL;
1072                 if (file->f_op->aio_fsync)
1073                         ret = file->f_op->aio_fsync(req, 1);
1074                 break;
1075         case IOCB_CMD_FSYNC:
1076                 ret = -EINVAL;
1077                 if (file->f_op->aio_fsync)
1078                         ret = file->f_op->aio_fsync(req, 0);
1079                 break;
1080         default:
1081                 dprintk("EINVAL: io_submit: no operation provided\n");
1082                 ret = -EINVAL;
1083         }
1084
1085         aio_put_req(req);       /* drop extra ref to req */
1086         if (likely(-EIOCBQUEUED == ret))
1087                 return 0;
1088         aio_complete(req, ret, 0);      /* will drop i/o ref to req */
1089         return 0;
1090
1091 out_put_req:
1092         aio_put_req(req);       /* drop extra ref to req */
1093         aio_put_req(req);       /* drop i/o ref to req */
1094         return ret;
1095 }
1096
1097 /* sys_io_submit:
1098  *      Queue the nr iocbs pointed to by iocbpp for processing.  Returns
1099  *      the number of iocbs queued.  May return -EINVAL if the aio_context
1100  *      specified by ctx_id is invalid, if nr is < 0, if the iocb at
1101  *      *iocbpp[0] is not properly initialized, if the operation specified
1102  *      is invalid for the file descriptor in the iocb.  May fail with
1103  *      -EFAULT if any of the data structures point to invalid data.  May
1104  *      fail with -EBADF if the file descriptor specified in the first
1105  *      iocb is invalid.  May fail with -EAGAIN if insufficient resources
1106  *      are available to queue any iocbs.  Will return 0 if nr is 0.  Will
1107  *      fail with -ENOSYS if not implemented.
1108  */
1109 asmlinkage long sys_io_submit(aio_context_t ctx_id, long nr,
1110                               struct iocb __user * __user *iocbpp)
1111 {
1112         struct kioctx *ctx;
1113         long ret = 0;
1114         int i;
1115
1116         if (unlikely(nr < 0))
1117                 return -EINVAL;
1118
1119         if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
1120                 return -EFAULT;
1121
1122         ctx = lookup_ioctx(ctx_id);
1123         if (unlikely(!ctx)) {
1124                 pr_debug("EINVAL: io_submit: invalid context id\n");
1125                 return -EINVAL;
1126         }
1127
1128         /*
1129          * AKPM: should this return a partial result if some of the IOs were
1130          * successfully submitted?
1131          */
1132         for (i=0; i<nr; i++) {
1133                 struct iocb __user *user_iocb;
1134                 struct iocb tmp;
1135
1136                 if (unlikely(__get_user(user_iocb, iocbpp + i))) {
1137                         ret = -EFAULT;
1138                         break;
1139                 }
1140
1141                 if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
1142                         ret = -EFAULT;
1143                         break;
1144                 }
1145
1146                 ret = io_submit_one(ctx, user_iocb, &tmp);
1147                 if (ret)
1148                         break;
1149         }
1150
1151         put_ioctx(ctx);
1152         return i ? i : ret;
1153 }
1154
1155 /* lookup_kiocb
1156  *      Finds a given iocb for cancellation.
1157  *      MUST be called with ctx->ctx_lock held.
1158  */
1159 struct kiocb *lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb, u32 key)
1160 {
1161         struct list_head *pos;
1162         /* TODO: use a hash or array, this sucks. */
1163         list_for_each(pos, &ctx->active_reqs) {
1164                 struct kiocb *kiocb = list_kiocb(pos);
1165                 if (kiocb->ki_obj.user == iocb && kiocb->ki_key == key)
1166                         return kiocb;
1167         }
1168         return NULL;
1169 }
1170
1171 /* sys_io_cancel:
1172  *      Attempts to cancel an iocb previously passed to io_submit.  If
1173  *      the operation is successfully cancelled, the resulting event is
1174  *      copied into the memory pointed to by result without being placed
1175  *      into the completion queue and 0 is returned.  May fail with
1176  *      -EFAULT if any of the data structures pointed to are invalid.
1177  *      May fail with -EINVAL if aio_context specified by ctx_id is
1178  *      invalid.  May fail with -EAGAIN if the iocb specified was not
1179  *      cancelled.  Will fail with -ENOSYS if not implemented.
1180  */
1181 asmlinkage long sys_io_cancel(aio_context_t ctx_id, struct iocb __user *iocb,
1182                               struct io_event __user *result)
1183 {
1184         int (*cancel)(struct kiocb *iocb, struct io_event *res);
1185         struct kioctx *ctx;
1186         struct kiocb *kiocb;
1187         u32 key;
1188         int ret;
1189
1190         ret = get_user(key, &iocb->aio_key);
1191         if (unlikely(ret))
1192                 return -EFAULT;
1193
1194         ctx = lookup_ioctx(ctx_id);
1195         if (unlikely(!ctx))
1196                 return -EINVAL;
1197
1198         spin_lock_irq(&ctx->ctx_lock);
1199         ret = -EAGAIN;
1200         kiocb = lookup_kiocb(ctx, iocb, key);
1201         if (kiocb && kiocb->ki_cancel) {
1202                 cancel = kiocb->ki_cancel;
1203                 kiocb->ki_users ++;
1204         } else
1205                 cancel = NULL;
1206         spin_unlock_irq(&ctx->ctx_lock);
1207
1208         if (NULL != cancel) {
1209                 struct io_event tmp;
1210                 pr_debug("calling cancel\n");
1211                 memset(&tmp, 0, sizeof(tmp));
1212                 tmp.obj = (u64)(unsigned long)kiocb->ki_obj.user;
1213                 tmp.data = kiocb->ki_user_data;
1214                 ret = cancel(kiocb, &tmp);
1215                 if (!ret) {
1216                         /* Cancellation succeeded -- copy the result
1217                          * into the user's buffer.
1218                          */
1219                         if (copy_to_user(result, &tmp, sizeof(tmp)))
1220                                 ret = -EFAULT;
1221                 }
1222         } else
1223                 printk(KERN_DEBUG "iocb has no cancel operation\n");
1224
1225         put_ioctx(ctx);
1226
1227         return ret;
1228 }
1229
1230 /* io_getevents:
1231  *      Attempts to read at least min_nr events and up to nr events from
1232  *      the completion queue for the aio_context specified by ctx_id.  May
1233  *      fail with -EINVAL if ctx_id is invalid, if min_nr is out of range,
1234  *      if nr is out of range, if when is out of range.  May fail with
1235  *      -EFAULT if any of the memory specified to is invalid.  May return
1236  *      0 or < min_nr if no events are available and the timeout specified
1237  *      by when has elapsed, where when == NULL specifies an infinite
1238  *      timeout.  Note that the timeout pointed to by when is relative and
1239  *      will be updated if not NULL and the operation blocks.  Will fail
1240  *      with -ENOSYS if not implemented.
1241  */
1242 asmlinkage long sys_io_getevents(aio_context_t ctx_id,
1243                                  long min_nr,
1244                                  long nr,
1245                                  struct io_event __user *events,
1246                                  struct timespec __user *timeout)
1247 {
1248         struct kioctx *ioctx = lookup_ioctx(ctx_id);
1249         long ret = -EINVAL;
1250
1251         if (likely(ioctx)) {
1252                 if (likely(min_nr <= nr && min_nr >= 0 && nr >= 0))
1253                         ret = read_events(ioctx, min_nr, nr, events, timeout);
1254                 put_ioctx(ioctx);
1255         }
1256
1257         return ret;
1258 }
1259
1260 __initcall(aio_setup);
1261
1262 EXPORT_SYMBOL(aio_complete);
1263 EXPORT_SYMBOL(aio_put_req);
1264 EXPORT_SYMBOL(wait_on_sync_kiocb);