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