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