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