Merge to Fedora kernel-2.6.7-1.441
[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
400         /* Check if the completion queue has enough free space to
401          * accept an event from this io.
402          */
403         spin_lock_irq(&ctx->ctx_lock);
404         ring = kmap_atomic(ctx->ring_info.ring_pages[0], KM_USER0);
405         if (ctx->reqs_active < aio_ring_avail(&ctx->ring_info, ring)) {
406                 list_add(&req->ki_list, &ctx->active_reqs);
407                 get_ioctx(ctx);
408                 ctx->reqs_active++;
409                 okay = 1;
410         }
411         kunmap_atomic(ring, KM_USER0);
412         spin_unlock_irq(&ctx->ctx_lock);
413
414         if (!okay) {
415                 kmem_cache_free(kiocb_cachep, req);
416                 req = NULL;
417         }
418
419         return req;
420 }
421
422 static inline struct kiocb *aio_get_req(struct kioctx *ctx)
423 {
424         struct kiocb *req;
425         /* Handle a potential starvation case -- should be exceedingly rare as 
426          * requests will be stuck on fput_head only if the aio_fput_routine is 
427          * delayed and the requests were the last user of the struct file.
428          */
429         req = __aio_get_req(ctx);
430         if (unlikely(NULL == req)) {
431                 aio_fput_routine(NULL);
432                 req = __aio_get_req(ctx);
433         }
434         return req;
435 }
436
437 static inline void really_put_req(struct kioctx *ctx, struct kiocb *req)
438 {
439         req->ki_ctx = NULL;
440         req->ki_filp = NULL;
441         req->ki_obj.user = NULL;
442         kmem_cache_free(kiocb_cachep, req);
443         ctx->reqs_active--;
444
445         if (unlikely(!ctx->reqs_active && ctx->dead))
446                 wake_up(&ctx->wait);
447 }
448
449 static void aio_fput_routine(void *data)
450 {
451         spin_lock_irq(&fput_lock);
452         while (likely(!list_empty(&fput_head))) {
453                 struct kiocb *req = list_kiocb(fput_head.next);
454                 struct kioctx *ctx = req->ki_ctx;
455
456                 list_del(&req->ki_list);
457                 spin_unlock_irq(&fput_lock);
458
459                 /* Complete the fput */
460                 __fput(req->ki_filp);
461
462                 /* Link the iocb into the context's free list */
463                 spin_lock_irq(&ctx->ctx_lock);
464                 really_put_req(ctx, req);
465                 spin_unlock_irq(&ctx->ctx_lock);
466
467                 put_ioctx(ctx);
468                 spin_lock_irq(&fput_lock);
469         }
470         spin_unlock_irq(&fput_lock);
471 }
472
473 /* __aio_put_req
474  *      Returns true if this put was the last user of the request.
475  */
476 static int __aio_put_req(struct kioctx *ctx, struct kiocb *req)
477 {
478         dprintk(KERN_DEBUG "aio_put(%p): f_count=%d\n",
479                 req, atomic_read(&req->ki_filp->f_count));
480
481         req->ki_users --;
482         if (unlikely(req->ki_users < 0))
483                 BUG();
484         if (likely(req->ki_users))
485                 return 0;
486         list_del(&req->ki_list);                /* remove from active_reqs */
487         req->ki_cancel = NULL;
488         req->ki_retry = NULL;
489
490         /* Must be done under the lock to serialise against cancellation.
491          * Call this aio_fput as it duplicates fput via the fput_work.
492          */
493         if (unlikely(atomic_dec_and_test(&req->ki_filp->f_count))) {
494                 get_ioctx(ctx);
495                 spin_lock(&fput_lock);
496                 list_add(&req->ki_list, &fput_head);
497                 spin_unlock(&fput_lock);
498                 queue_work(aio_wq, &fput_work);
499         } else
500                 really_put_req(ctx, req);
501         return 1;
502 }
503
504 /* aio_put_req
505  *      Returns true if this put was the last user of the kiocb,
506  *      false if the request is still in use.
507  */
508 int fastcall aio_put_req(struct kiocb *req)
509 {
510         struct kioctx *ctx = req->ki_ctx;
511         int ret;
512         spin_lock_irq(&ctx->ctx_lock);
513         ret = __aio_put_req(ctx, req);
514         spin_unlock_irq(&ctx->ctx_lock);
515         if (ret)
516                 put_ioctx(ctx);
517         return ret;
518 }
519
520 /*      Lookup an ioctx id.  ioctx_list is lockless for reads.
521  *      FIXME: this is O(n) and is only suitable for development.
522  */
523 struct kioctx *lookup_ioctx(unsigned long ctx_id)
524 {
525         struct kioctx *ioctx;
526         struct mm_struct *mm;
527
528         mm = current->mm;
529         read_lock(&mm->ioctx_list_lock);
530         for (ioctx = mm->ioctx_list; ioctx; ioctx = ioctx->next)
531                 if (likely(ioctx->user_id == ctx_id && !ioctx->dead)) {
532                         get_ioctx(ioctx);
533                         break;
534                 }
535         read_unlock(&mm->ioctx_list_lock);
536
537         return ioctx;
538 }
539
540 static void use_mm(struct mm_struct *mm)
541 {
542         struct mm_struct *active_mm;
543
544         atomic_inc(&mm->mm_count);
545         task_lock(current);
546         active_mm = current->active_mm;
547         current->mm = mm;
548         if (mm != active_mm) {
549                 current->active_mm = mm;
550                 activate_mm(active_mm, mm);
551         }
552         task_unlock(current);
553         mmdrop(active_mm);
554 }
555
556 static void unuse_mm(struct mm_struct *mm)
557 {
558         task_lock(current);
559         current->mm = NULL;
560         task_unlock(current);
561         /* active_mm is still 'mm' */
562         enter_lazy_tlb(mm, current);
563 }
564
565 /* Run on kevent's context.  FIXME: needs to be per-cpu and warn if an
566  * operation blocks.
567  */
568 static void aio_kick_handler(void *data)
569 {
570         struct kioctx *ctx = data;
571
572         use_mm(ctx->mm);
573
574         spin_lock_irq(&ctx->ctx_lock);
575         while (!list_empty(&ctx->run_list)) {
576                 struct kiocb *iocb;
577                 long ret;
578
579                 iocb = list_entry(ctx->run_list.next, struct kiocb,
580                                   ki_run_list);
581                 list_del(&iocb->ki_run_list);
582                 iocb->ki_users ++;
583                 spin_unlock_irq(&ctx->ctx_lock);
584
585                 kiocbClearKicked(iocb);
586                 ret = iocb->ki_retry(iocb);
587                 if (-EIOCBQUEUED != ret) {
588                         aio_complete(iocb, ret, 0);
589                         iocb = NULL;
590                 }
591
592                 spin_lock_irq(&ctx->ctx_lock);
593                 if (NULL != iocb)
594                         __aio_put_req(ctx, iocb);
595         }
596         spin_unlock_irq(&ctx->ctx_lock);
597
598         unuse_mm(ctx->mm);
599 }
600
601 void fastcall kick_iocb(struct kiocb *iocb)
602 {
603         struct kioctx   *ctx = iocb->ki_ctx;
604
605         /* sync iocbs are easy: they can only ever be executing from a 
606          * single context. */
607         if (is_sync_kiocb(iocb)) {
608                 kiocbSetKicked(iocb);
609                 wake_up_process(iocb->ki_obj.tsk);
610                 return;
611         }
612
613         if (!kiocbTryKick(iocb)) {
614                 unsigned long flags;
615                 spin_lock_irqsave(&ctx->ctx_lock, flags);
616                 list_add_tail(&iocb->ki_run_list, &ctx->run_list);
617                 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
618                 queue_work(aio_wq, &ctx->wq);
619         }
620 }
621
622 /* aio_complete
623  *      Called when the io request on the given iocb is complete.
624  *      Returns true if this is the last user of the request.  The 
625  *      only other user of the request can be the cancellation code.
626  */
627 int fastcall aio_complete(struct kiocb *iocb, long res, long res2)
628 {
629         struct kioctx   *ctx = iocb->ki_ctx;
630         struct aio_ring_info    *info;
631         struct aio_ring *ring;
632         struct io_event *event;
633         unsigned long   flags;
634         unsigned long   tail;
635         int             ret;
636
637         /* Special case handling for sync iocbs: events go directly
638          * into the iocb for fast handling.  Note that this will not 
639          * work if we allow sync kiocbs to be cancelled. in which
640          * case the usage count checks will have to move under ctx_lock
641          * for all cases.
642          */
643         if (is_sync_kiocb(iocb)) {
644                 int ret;
645
646                 iocb->ki_user_data = res;
647                 if (iocb->ki_users == 1) {
648                         iocb->ki_users = 0;
649                         ret = 1;
650                 } else {
651                         spin_lock_irq(&ctx->ctx_lock);
652                         iocb->ki_users--;
653                         ret = (0 == iocb->ki_users);
654                         spin_unlock_irq(&ctx->ctx_lock);
655                 }
656                 /* sync iocbs put the task here for us */
657                 wake_up_process(iocb->ki_obj.tsk);
658                 return ret;
659         }
660
661         info = &ctx->ring_info;
662
663         /* add a completion event to the ring buffer.
664          * must be done holding ctx->ctx_lock to prevent
665          * other code from messing with the tail
666          * pointer since we might be called from irq
667          * context.
668          */
669         spin_lock_irqsave(&ctx->ctx_lock, flags);
670
671         ring = kmap_atomic(info->ring_pages[0], KM_IRQ1);
672
673         tail = info->tail;
674         event = aio_ring_event(info, tail, KM_IRQ0);
675         tail = (tail + 1) % info->nr;
676
677         event->obj = (u64)(unsigned long)iocb->ki_obj.user;
678         event->data = iocb->ki_user_data;
679         event->res = res;
680         event->res2 = res2;
681
682         dprintk("aio_complete: %p[%lu]: %p: %p %Lx %lx %lx\n",
683                 ctx, tail, iocb, iocb->ki_obj.user, iocb->ki_user_data,
684                 res, res2);
685
686         /* after flagging the request as done, we
687          * must never even look at it again
688          */
689         smp_wmb();      /* make event visible before updating tail */
690
691         info->tail = tail;
692         ring->tail = tail;
693
694         put_aio_ring_event(event, KM_IRQ0);
695         kunmap_atomic(ring, KM_IRQ1);
696
697         pr_debug("added to ring %p at [%lu]\n", iocb, tail);
698
699         /* everything turned out well, dispose of the aiocb. */
700         ret = __aio_put_req(ctx, iocb);
701
702         spin_unlock_irqrestore(&ctx->ctx_lock, flags);
703
704         if (waitqueue_active(&ctx->wait))
705                 wake_up(&ctx->wait);
706
707         if (ret)
708                 put_ioctx(ctx);
709
710         return ret;
711 }
712
713 /* aio_read_evt
714  *      Pull an event off of the ioctx's event ring.  Returns the number of 
715  *      events fetched (0 or 1 ;-)
716  *      FIXME: make this use cmpxchg.
717  *      TODO: make the ringbuffer user mmap()able (requires FIXME).
718  */
719 static int aio_read_evt(struct kioctx *ioctx, struct io_event *ent)
720 {
721         struct aio_ring_info *info = &ioctx->ring_info;
722         struct aio_ring *ring;
723         unsigned long head;
724         int ret = 0;
725
726         ring = kmap_atomic(info->ring_pages[0], KM_USER0);
727         dprintk("in aio_read_evt h%lu t%lu m%lu\n",
728                  (unsigned long)ring->head, (unsigned long)ring->tail,
729                  (unsigned long)ring->nr);
730
731         if (ring->head == ring->tail)
732                 goto out;
733
734         spin_lock(&info->ring_lock);
735
736         head = ring->head % info->nr;
737         if (head != ring->tail) {
738                 struct io_event *evp = aio_ring_event(info, head, KM_USER1);
739                 *ent = *evp;
740                 head = (head + 1) % info->nr;
741                 smp_mb(); /* finish reading the event before updatng the head */
742                 ring->head = head;
743                 ret = 1;
744                 put_aio_ring_event(evp, KM_USER1);
745         }
746         spin_unlock(&info->ring_lock);
747
748 out:
749         kunmap_atomic(ring, KM_USER0);
750         dprintk("leaving aio_read_evt: %d  h%lu t%lu\n", ret,
751                  (unsigned long)ring->head, (unsigned long)ring->tail);
752         return ret;
753 }
754
755 struct timeout {
756         struct timer_list       timer;
757         int                     timed_out;
758         struct task_struct      *p;
759 };
760
761 static void timeout_func(unsigned long data)
762 {
763         struct timeout *to = (struct timeout *)data;
764
765         to->timed_out = 1;
766         wake_up_process(to->p);
767 }
768
769 static inline void init_timeout(struct timeout *to)
770 {
771         init_timer(&to->timer);
772         to->timer.data = (unsigned long)to;
773         to->timer.function = timeout_func;
774         to->timed_out = 0;
775         to->p = current;
776 }
777
778 static inline void set_timeout(long start_jiffies, struct timeout *to,
779                                const struct timespec *ts)
780 {
781         to->timer.expires = start_jiffies + timespec_to_jiffies(ts);
782         if (time_after(to->timer.expires, jiffies))
783                 add_timer(&to->timer);
784         else
785                 to->timed_out = 1;
786 }
787
788 static inline void clear_timeout(struct timeout *to)
789 {
790         del_singleshot_timer_sync(&to->timer);
791 }
792
793 static int read_events(struct kioctx *ctx,
794                         long min_nr, long nr,
795                         struct io_event __user *event,
796                         struct timespec __user *timeout)
797 {
798         long                    start_jiffies = jiffies;
799         struct task_struct      *tsk = current;
800         DECLARE_WAITQUEUE(wait, tsk);
801         int                     ret;
802         int                     i = 0;
803         struct io_event         ent;
804         struct timeout          to;
805
806         /* needed to zero any padding within an entry (there shouldn't be 
807          * any, but C is fun!
808          */
809         memset(&ent, 0, sizeof(ent));
810         ret = 0;
811
812         while (likely(i < nr)) {
813                 ret = aio_read_evt(ctx, &ent);
814                 if (unlikely(ret <= 0))
815                         break;
816
817                 dprintk("read event: %Lx %Lx %Lx %Lx\n",
818                         ent.data, ent.obj, ent.res, ent.res2);
819
820                 /* Could we split the check in two? */
821                 ret = -EFAULT;
822                 if (unlikely(copy_to_user(event, &ent, sizeof(ent)))) {
823                         dprintk("aio: lost an event due to EFAULT.\n");
824                         break;
825                 }
826                 ret = 0;
827
828                 /* Good, event copied to userland, update counts. */
829                 event ++;
830                 i ++;
831         }
832
833         if (min_nr <= i)
834                 return i;
835         if (ret)
836                 return ret;
837
838         /* End fast path */
839
840         init_timeout(&to);
841         if (timeout) {
842                 struct timespec ts;
843                 ret = -EFAULT;
844                 if (unlikely(copy_from_user(&ts, timeout, sizeof(ts))))
845                         goto out;
846
847                 set_timeout(start_jiffies, &to, &ts);
848         }
849
850         while (likely(i < nr)) {
851                 add_wait_queue_exclusive(&ctx->wait, &wait);
852                 do {
853                         set_task_state(tsk, TASK_INTERRUPTIBLE);
854
855                         ret = aio_read_evt(ctx, &ent);
856                         if (ret)
857                                 break;
858                         if (min_nr <= i)
859                                 break;
860                         ret = 0;
861                         if (to.timed_out)       /* Only check after read evt */
862                                 break;
863                         schedule();
864                         if (signal_pending(tsk)) {
865                                 ret = -EINTR;
866                                 break;
867                         }
868                         /*ret = aio_read_evt(ctx, &ent);*/
869                 } while (1) ;
870
871                 set_task_state(tsk, TASK_RUNNING);
872                 remove_wait_queue(&ctx->wait, &wait);
873
874                 if (unlikely(ret <= 0))
875                         break;
876
877                 ret = -EFAULT;
878                 if (unlikely(copy_to_user(event, &ent, sizeof(ent)))) {
879                         dprintk("aio: lost an event due to EFAULT.\n");
880                         break;
881                 }
882
883                 /* Good, event copied to userland, update counts. */
884                 event ++;
885                 i ++;
886         }
887
888         if (timeout)
889                 clear_timeout(&to);
890 out:
891         return i ? i : ret;
892 }
893
894 /* Take an ioctx and remove it from the list of ioctx's.  Protects 
895  * against races with itself via ->dead.
896  */
897 static void io_destroy(struct kioctx *ioctx)
898 {
899         struct mm_struct *mm = current->mm;
900         struct kioctx **tmp;
901         int was_dead;
902
903         /* delete the entry from the list is someone else hasn't already */
904         write_lock(&mm->ioctx_list_lock);
905         was_dead = ioctx->dead;
906         ioctx->dead = 1;
907         for (tmp = &mm->ioctx_list; *tmp && *tmp != ioctx;
908              tmp = &(*tmp)->next)
909                 ;
910         if (*tmp)
911                 *tmp = ioctx->next;
912         write_unlock(&mm->ioctx_list_lock);
913
914         dprintk("aio_release(%p)\n", ioctx);
915         if (likely(!was_dead))
916                 put_ioctx(ioctx);       /* twice for the list */
917
918         aio_cancel_all(ioctx);
919         wait_for_all_aios(ioctx);
920         put_ioctx(ioctx);       /* once for the lookup */
921 }
922
923 /* sys_io_setup:
924  *      Create an aio_context capable of receiving at least nr_events.
925  *      ctxp must not point to an aio_context that already exists, and
926  *      must be initialized to 0 prior to the call.  On successful
927  *      creation of the aio_context, *ctxp is filled in with the resulting 
928  *      handle.  May fail with -EINVAL if *ctxp is not initialized,
929  *      if the specified nr_events exceeds internal limits.  May fail 
930  *      with -EAGAIN if the specified nr_events exceeds the user's limit 
931  *      of available events.  May fail with -ENOMEM if insufficient kernel
932  *      resources are available.  May fail with -EFAULT if an invalid
933  *      pointer is passed for ctxp.  Will fail with -ENOSYS if not
934  *      implemented.
935  */
936 asmlinkage long sys_io_setup(unsigned nr_events, aio_context_t __user *ctxp)
937 {
938         struct kioctx *ioctx = NULL;
939         unsigned long ctx;
940         long ret;
941
942         ret = get_user(ctx, ctxp);
943         if (unlikely(ret))
944                 goto out;
945
946         ret = -EINVAL;
947         if (unlikely(ctx || (int)nr_events <= 0)) {
948                 pr_debug("EINVAL: io_setup: ctx or nr_events > max\n");
949                 goto out;
950         }
951
952         ioctx = ioctx_alloc(nr_events);
953         ret = PTR_ERR(ioctx);
954         if (!IS_ERR(ioctx)) {
955                 ret = put_user(ioctx->user_id, ctxp);
956                 if (!ret)
957                         return 0;
958                 get_ioctx(ioctx);
959                 io_destroy(ioctx);
960         }
961
962 out:
963         return ret;
964 }
965
966 /* sys_io_destroy:
967  *      Destroy the aio_context specified.  May cancel any outstanding 
968  *      AIOs and block on completion.  Will fail with -ENOSYS if not
969  *      implemented.  May fail with -EFAULT if the context pointed to
970  *      is invalid.
971  */
972 asmlinkage long sys_io_destroy(aio_context_t ctx)
973 {
974         struct kioctx *ioctx = lookup_ioctx(ctx);
975         if (likely(NULL != ioctx)) {
976                 io_destroy(ioctx);
977                 return 0;
978         }
979         pr_debug("EINVAL: io_destroy: invalid context id\n");
980         return -EINVAL;
981 }
982
983 int fastcall io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
984                          struct iocb *iocb)
985 {
986         struct kiocb *req;
987         struct file *file;
988         ssize_t ret;
989         char __user *buf;
990
991         /* enforce forwards compatibility on users */
992         if (unlikely(iocb->aio_reserved1 || iocb->aio_reserved2 ||
993                      iocb->aio_reserved3)) {
994                 pr_debug("EINVAL: io_submit: reserve field set\n");
995                 return -EINVAL;
996         }
997
998         /* prevent overflows */
999         if (unlikely(
1000             (iocb->aio_buf != (unsigned long)iocb->aio_buf) ||
1001             (iocb->aio_nbytes != (size_t)iocb->aio_nbytes) ||
1002             ((ssize_t)iocb->aio_nbytes < 0)
1003            )) {
1004                 pr_debug("EINVAL: io_submit: overflow check\n");
1005                 return -EINVAL;
1006         }
1007
1008         file = fget(iocb->aio_fildes);
1009         if (unlikely(!file))
1010                 return -EBADF;
1011
1012         req = aio_get_req(ctx);         /* returns with 2 references to req */
1013         if (unlikely(!req)) {
1014                 fput(file);
1015                 return -EAGAIN;
1016         }
1017
1018         req->ki_filp = file;
1019         iocb->aio_key = req->ki_key;
1020         ret = put_user(iocb->aio_key, &user_iocb->aio_key);
1021         if (unlikely(ret)) {
1022                 dprintk("EFAULT: aio_key\n");
1023                 goto out_put_req;
1024         }
1025
1026         req->ki_obj.user = user_iocb;
1027         req->ki_user_data = iocb->aio_data;
1028         req->ki_pos = iocb->aio_offset;
1029
1030         buf = (char __user *)(unsigned long)iocb->aio_buf;
1031
1032         switch (iocb->aio_lio_opcode) {
1033         case IOCB_CMD_PREAD:
1034                 ret = -EBADF;
1035                 if (unlikely(!(file->f_mode & FMODE_READ)))
1036                         goto out_put_req;
1037                 ret = -EFAULT;
1038                 if (unlikely(!access_ok(VERIFY_WRITE, buf, iocb->aio_nbytes)))
1039                         goto out_put_req;
1040                 ret = security_file_permission (file, MAY_READ);
1041                 if (ret)
1042                         goto out_put_req;
1043                 ret = -EINVAL;
1044                 if (file->f_op->aio_read)
1045                         ret = file->f_op->aio_read(req, buf,
1046                                         iocb->aio_nbytes, req->ki_pos);
1047                 break;
1048         case IOCB_CMD_PWRITE:
1049                 ret = -EBADF;
1050                 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1051                         goto out_put_req;
1052                 ret = -EFAULT;
1053                 if (unlikely(!access_ok(VERIFY_READ, buf, iocb->aio_nbytes)))
1054                         goto out_put_req;
1055                 ret = security_file_permission (file, MAY_WRITE);
1056                 if (ret)
1057                         goto out_put_req;
1058                 ret = -EINVAL;
1059                 if (file->f_op->aio_write)
1060                         ret = file->f_op->aio_write(req, buf,
1061                                         iocb->aio_nbytes, req->ki_pos);
1062                 break;
1063         case IOCB_CMD_FDSYNC:
1064                 ret = -EINVAL;
1065                 if (file->f_op->aio_fsync)
1066                         ret = file->f_op->aio_fsync(req, 1);
1067                 break;
1068         case IOCB_CMD_FSYNC:
1069                 ret = -EINVAL;
1070                 if (file->f_op->aio_fsync)
1071                         ret = file->f_op->aio_fsync(req, 0);
1072                 break;
1073         default:
1074                 dprintk("EINVAL: io_submit: no operation provided\n");
1075                 ret = -EINVAL;
1076         }
1077
1078         aio_put_req(req);       /* drop extra ref to req */
1079         if (likely(-EIOCBQUEUED == ret))
1080                 return 0;
1081         aio_complete(req, ret, 0);      /* will drop i/o ref to req */
1082         return 0;
1083
1084 out_put_req:
1085         aio_put_req(req);       /* drop extra ref to req */
1086         aio_put_req(req);       /* drop i/o ref to req */
1087         return ret;
1088 }
1089
1090 /* sys_io_submit:
1091  *      Queue the nr iocbs pointed to by iocbpp for processing.  Returns
1092  *      the number of iocbs queued.  May return -EINVAL if the aio_context
1093  *      specified by ctx_id is invalid, if nr is < 0, if the iocb at
1094  *      *iocbpp[0] is not properly initialized, if the operation specified
1095  *      is invalid for the file descriptor in the iocb.  May fail with
1096  *      -EFAULT if any of the data structures point to invalid data.  May
1097  *      fail with -EBADF if the file descriptor specified in the first
1098  *      iocb is invalid.  May fail with -EAGAIN if insufficient resources
1099  *      are available to queue any iocbs.  Will return 0 if nr is 0.  Will
1100  *      fail with -ENOSYS if not implemented.
1101  */
1102 asmlinkage long sys_io_submit(aio_context_t ctx_id, long nr,
1103                               struct iocb __user * __user *iocbpp)
1104 {
1105         struct kioctx *ctx;
1106         long ret = 0;
1107         int i;
1108
1109         if (unlikely(nr < 0))
1110                 return -EINVAL;
1111
1112         if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
1113                 return -EFAULT;
1114
1115         ctx = lookup_ioctx(ctx_id);
1116         if (unlikely(!ctx)) {
1117                 pr_debug("EINVAL: io_submit: invalid context id\n");
1118                 return -EINVAL;
1119         }
1120
1121         /*
1122          * AKPM: should this return a partial result if some of the IOs were
1123          * successfully submitted?
1124          */
1125         for (i=0; i<nr; i++) {
1126                 struct iocb __user *user_iocb;
1127                 struct iocb tmp;
1128
1129                 if (unlikely(__get_user(user_iocb, iocbpp + i))) {
1130                         ret = -EFAULT;
1131                         break;
1132                 }
1133
1134                 if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
1135                         ret = -EFAULT;
1136                         break;
1137                 }
1138
1139                 ret = io_submit_one(ctx, user_iocb, &tmp);
1140                 if (ret)
1141                         break;
1142         }
1143
1144         put_ioctx(ctx);
1145         return i ? i : ret;
1146 }
1147
1148 /* lookup_kiocb
1149  *      Finds a given iocb for cancellation.
1150  *      MUST be called with ctx->ctx_lock held.
1151  */
1152 struct kiocb *lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb, u32 key)
1153 {
1154         struct list_head *pos;
1155         /* TODO: use a hash or array, this sucks. */
1156         list_for_each(pos, &ctx->active_reqs) {
1157                 struct kiocb *kiocb = list_kiocb(pos);
1158                 if (kiocb->ki_obj.user == iocb && kiocb->ki_key == key)
1159                         return kiocb;
1160         }
1161         return NULL;
1162 }
1163
1164 /* sys_io_cancel:
1165  *      Attempts to cancel an iocb previously passed to io_submit.  If
1166  *      the operation is successfully cancelled, the resulting event is
1167  *      copied into the memory pointed to by result without being placed
1168  *      into the completion queue and 0 is returned.  May fail with
1169  *      -EFAULT if any of the data structures pointed to are invalid.
1170  *      May fail with -EINVAL if aio_context specified by ctx_id is
1171  *      invalid.  May fail with -EAGAIN if the iocb specified was not
1172  *      cancelled.  Will fail with -ENOSYS if not implemented.
1173  */
1174 asmlinkage long sys_io_cancel(aio_context_t ctx_id, struct iocb __user *iocb,
1175                               struct io_event __user *result)
1176 {
1177         int (*cancel)(struct kiocb *iocb, struct io_event *res);
1178         struct kioctx *ctx;
1179         struct kiocb *kiocb;
1180         u32 key;
1181         int ret;
1182
1183         ret = get_user(key, &iocb->aio_key);
1184         if (unlikely(ret))
1185                 return -EFAULT;
1186
1187         ctx = lookup_ioctx(ctx_id);
1188         if (unlikely(!ctx))
1189                 return -EINVAL;
1190
1191         spin_lock_irq(&ctx->ctx_lock);
1192         ret = -EAGAIN;
1193         kiocb = lookup_kiocb(ctx, iocb, key);
1194         if (kiocb && kiocb->ki_cancel) {
1195                 cancel = kiocb->ki_cancel;
1196                 kiocb->ki_users ++;
1197         } else
1198                 cancel = NULL;
1199         spin_unlock_irq(&ctx->ctx_lock);
1200
1201         if (NULL != cancel) {
1202                 struct io_event tmp;
1203                 pr_debug("calling cancel\n");
1204                 memset(&tmp, 0, sizeof(tmp));
1205                 tmp.obj = (u64)(unsigned long)kiocb->ki_obj.user;
1206                 tmp.data = kiocb->ki_user_data;
1207                 ret = cancel(kiocb, &tmp);
1208                 if (!ret) {
1209                         /* Cancellation succeeded -- copy the result
1210                          * into the user's buffer.
1211                          */
1212                         if (copy_to_user(result, &tmp, sizeof(tmp)))
1213                                 ret = -EFAULT;
1214                 }
1215         } else
1216                 printk(KERN_DEBUG "iocb has no cancel operation\n");
1217
1218         put_ioctx(ctx);
1219
1220         return ret;
1221 }
1222
1223 /* io_getevents:
1224  *      Attempts to read at least min_nr events and up to nr events from
1225  *      the completion queue for the aio_context specified by ctx_id.  May
1226  *      fail with -EINVAL if ctx_id is invalid, if min_nr is out of range,
1227  *      if nr is out of range, if when is out of range.  May fail with
1228  *      -EFAULT if any of the memory specified to is invalid.  May return
1229  *      0 or < min_nr if no events are available and the timeout specified
1230  *      by when has elapsed, where when == NULL specifies an infinite
1231  *      timeout.  Note that the timeout pointed to by when is relative and
1232  *      will be updated if not NULL and the operation blocks.  Will fail
1233  *      with -ENOSYS if not implemented.
1234  */
1235 asmlinkage long sys_io_getevents(aio_context_t ctx_id,
1236                                  long min_nr,
1237                                  long nr,
1238                                  struct io_event __user *events,
1239                                  struct timespec __user *timeout)
1240 {
1241         struct kioctx *ioctx = lookup_ioctx(ctx_id);
1242         long ret = -EINVAL;
1243
1244         if (likely(ioctx)) {
1245                 if (likely(min_nr <= nr && min_nr >= 0 && nr >= 0))
1246                         ret = read_events(ioctx, min_nr, nr, events, timeout);
1247                 put_ioctx(ioctx);
1248         }
1249
1250         return ret;
1251 }
1252
1253 __initcall(aio_setup);
1254
1255 EXPORT_SYMBOL(aio_complete);
1256 EXPORT_SYMBOL(aio_put_req);
1257 EXPORT_SYMBOL(wait_on_sync_kiocb);