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