~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/fs/aio.c

Version: ~ [ linux-5.17-rc1 ] ~ [ linux-5.16.2 ] ~ [ linux-5.15.16 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.93 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.173 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.225 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.262 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.297 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.299 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.18.140 ] ~ [ linux-3.16.85 ] ~ [ linux-3.14.79 ] ~ [ linux-3.12.74 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  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 #define pr_fmt(fmt) "%s: " fmt, __func__
 12 
 13 #include <linux/kernel.h>
 14 #include <linux/init.h>
 15 #include <linux/errno.h>
 16 #include <linux/time.h>
 17 #include <linux/aio_abi.h>
 18 #include <linux/export.h>
 19 #include <linux/syscalls.h>
 20 #include <linux/backing-dev.h>
 21 #include <linux/uio.h>
 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/percpu.h>
 30 #include <linux/slab.h>
 31 #include <linux/timer.h>
 32 #include <linux/aio.h>
 33 #include <linux/highmem.h>
 34 #include <linux/workqueue.h>
 35 #include <linux/security.h>
 36 #include <linux/eventfd.h>
 37 #include <linux/blkdev.h>
 38 #include <linux/compat.h>
 39 #include <linux/migrate.h>
 40 #include <linux/ramfs.h>
 41 #include <linux/percpu-refcount.h>
 42 #include <linux/mount.h>
 43 
 44 #include <asm/kmap_types.h>
 45 #include <asm/uaccess.h>
 46 
 47 #include "internal.h"
 48 
 49 #define AIO_RING_MAGIC                  0xa10a10a1
 50 #define AIO_RING_COMPAT_FEATURES        1
 51 #define AIO_RING_INCOMPAT_FEATURES      0
 52 struct aio_ring {
 53         unsigned        id;     /* kernel internal index number */
 54         unsigned        nr;     /* number of io_events */
 55         unsigned        head;   /* Written to by userland or under ring_lock
 56                                  * mutex by aio_read_events_ring(). */
 57         unsigned        tail;
 58 
 59         unsigned        magic;
 60         unsigned        compat_features;
 61         unsigned        incompat_features;
 62         unsigned        header_length;  /* size of aio_ring */
 63 
 64 
 65         struct io_event         io_events[0];
 66 }; /* 128 bytes + ring size */
 67 
 68 #define AIO_RING_PAGES  8
 69 
 70 struct kioctx_table {
 71         struct rcu_head rcu;
 72         unsigned        nr;
 73         struct kioctx   *table[];
 74 };
 75 
 76 struct kioctx_cpu {
 77         unsigned                reqs_available;
 78 };
 79 
 80 struct ctx_rq_wait {
 81         struct completion comp;
 82         atomic_t count;
 83 };
 84 
 85 struct kioctx {
 86         struct percpu_ref       users;
 87         atomic_t                dead;
 88 
 89         struct percpu_ref       reqs;
 90 
 91         unsigned long           user_id;
 92 
 93         struct __percpu kioctx_cpu *cpu;
 94 
 95         /*
 96          * For percpu reqs_available, number of slots we move to/from global
 97          * counter at a time:
 98          */
 99         unsigned                req_batch;
100         /*
101          * This is what userspace passed to io_setup(), it's not used for
102          * anything but counting against the global max_reqs quota.
103          *
104          * The real limit is nr_events - 1, which will be larger (see
105          * aio_setup_ring())
106          */
107         unsigned                max_reqs;
108 
109         /* Size of ringbuffer, in units of struct io_event */
110         unsigned                nr_events;
111 
112         unsigned long           mmap_base;
113         unsigned long           mmap_size;
114 
115         struct page             **ring_pages;
116         long                    nr_pages;
117 
118         struct work_struct      free_work;
119 
120         /*
121          * signals when all in-flight requests are done
122          */
123         struct ctx_rq_wait      *rq_wait;
124 
125         struct {
126                 /*
127                  * This counts the number of available slots in the ringbuffer,
128                  * so we avoid overflowing it: it's decremented (if positive)
129                  * when allocating a kiocb and incremented when the resulting
130                  * io_event is pulled off the ringbuffer.
131                  *
132                  * We batch accesses to it with a percpu version.
133                  */
134                 atomic_t        reqs_available;
135         } ____cacheline_aligned_in_smp;
136 
137         struct {
138                 spinlock_t      ctx_lock;
139                 struct list_head active_reqs;   /* used for cancellation */
140         } ____cacheline_aligned_in_smp;
141 
142         struct {
143                 struct mutex    ring_lock;
144                 wait_queue_head_t wait;
145         } ____cacheline_aligned_in_smp;
146 
147         struct {
148                 unsigned        tail;
149                 unsigned        completed_events;
150                 spinlock_t      completion_lock;
151         } ____cacheline_aligned_in_smp;
152 
153         struct page             *internal_pages[AIO_RING_PAGES];
154         struct file             *aio_ring_file;
155 
156         unsigned                id;
157 };
158 
159 /*------ sysctl variables----*/
160 static DEFINE_SPINLOCK(aio_nr_lock);
161 unsigned long aio_nr;           /* current system wide number of aio requests */
162 unsigned long aio_max_nr = 0x10000; /* system wide maximum number of aio requests */
163 /*----end sysctl variables---*/
164 
165 static struct kmem_cache        *kiocb_cachep;
166 static struct kmem_cache        *kioctx_cachep;
167 
168 static struct vfsmount *aio_mnt;
169 
170 static const struct file_operations aio_ring_fops;
171 static const struct address_space_operations aio_ctx_aops;
172 
173 /* Backing dev info for aio fs.
174  * -no dirty page accounting or writeback happens
175  */
176 static struct backing_dev_info aio_fs_backing_dev_info = {
177         .name           = "aiofs",
178         .state          = 0,
179         .capabilities   = BDI_CAP_NO_ACCT_AND_WRITEBACK | BDI_CAP_MAP_COPY,
180 };
181 
182 static struct file *aio_private_file(struct kioctx *ctx, loff_t nr_pages)
183 {
184         struct qstr this = QSTR_INIT("[aio]", 5);
185         struct file *file;
186         struct path path;
187         struct inode *inode = alloc_anon_inode(aio_mnt->mnt_sb);
188         if (IS_ERR(inode))
189                 return ERR_CAST(inode);
190 
191         inode->i_mapping->a_ops = &aio_ctx_aops;
192         inode->i_mapping->private_data = ctx;
193         inode->i_mapping->backing_dev_info = &aio_fs_backing_dev_info;
194         inode->i_size = PAGE_SIZE * nr_pages;
195 
196         path.dentry = d_alloc_pseudo(aio_mnt->mnt_sb, &this);
197         if (!path.dentry) {
198                 iput(inode);
199                 return ERR_PTR(-ENOMEM);
200         }
201         path.mnt = mntget(aio_mnt);
202 
203         d_instantiate(path.dentry, inode);
204         file = alloc_file(&path, FMODE_READ | FMODE_WRITE, &aio_ring_fops);
205         if (IS_ERR(file)) {
206                 path_put(&path);
207                 return file;
208         }
209 
210         file->f_flags = O_RDWR;
211         file->private_data = ctx;
212         return file;
213 }
214 
215 static struct dentry *aio_mount(struct file_system_type *fs_type,
216                                 int flags, const char *dev_name, void *data)
217 {
218         static const struct dentry_operations ops = {
219                 .d_dname        = simple_dname,
220         };
221         return mount_pseudo(fs_type, "aio:", NULL, &ops, 0xa10a10a1);
222 }
223 
224 /* aio_setup
225  *      Creates the slab caches used by the aio routines, panic on
226  *      failure as this is done early during the boot sequence.
227  */
228 static int __init aio_setup(void)
229 {
230         static struct file_system_type aio_fs = {
231                 .name           = "aio",
232                 .mount          = aio_mount,
233                 .kill_sb        = kill_anon_super,
234         };
235         aio_mnt = kern_mount(&aio_fs);
236         if (IS_ERR(aio_mnt))
237                 panic("Failed to create aio fs mount.");
238 
239         if (bdi_init(&aio_fs_backing_dev_info))
240                 panic("Failed to init aio fs backing dev info.");
241 
242         kiocb_cachep = KMEM_CACHE(kiocb, SLAB_HWCACHE_ALIGN|SLAB_PANIC);
243         kioctx_cachep = KMEM_CACHE(kioctx,SLAB_HWCACHE_ALIGN|SLAB_PANIC);
244 
245         pr_debug("sizeof(struct page) = %zu\n", sizeof(struct page));
246 
247         return 0;
248 }
249 __initcall(aio_setup);
250 
251 static void put_aio_ring_file(struct kioctx *ctx)
252 {
253         struct file *aio_ring_file = ctx->aio_ring_file;
254         if (aio_ring_file) {
255                 truncate_setsize(aio_ring_file->f_inode, 0);
256 
257                 /* Prevent further access to the kioctx from migratepages */
258                 spin_lock(&aio_ring_file->f_inode->i_mapping->private_lock);
259                 aio_ring_file->f_inode->i_mapping->private_data = NULL;
260                 ctx->aio_ring_file = NULL;
261                 spin_unlock(&aio_ring_file->f_inode->i_mapping->private_lock);
262 
263                 fput(aio_ring_file);
264         }
265 }
266 
267 static void aio_free_ring(struct kioctx *ctx)
268 {
269         int i;
270 
271         /* Disconnect the kiotx from the ring file.  This prevents future
272          * accesses to the kioctx from page migration.
273          */
274         put_aio_ring_file(ctx);
275 
276         for (i = 0; i < ctx->nr_pages; i++) {
277                 struct page *page;
278                 pr_debug("pid(%d) [%d] page->count=%d\n", current->pid, i,
279                                 page_count(ctx->ring_pages[i]));
280                 page = ctx->ring_pages[i];
281                 if (!page)
282                         continue;
283                 ctx->ring_pages[i] = NULL;
284                 put_page(page);
285         }
286 
287         if (ctx->ring_pages && ctx->ring_pages != ctx->internal_pages) {
288                 kfree(ctx->ring_pages);
289                 ctx->ring_pages = NULL;
290         }
291 }
292 
293 static int aio_ring_mmap(struct file *file, struct vm_area_struct *vma)
294 {
295         vma->vm_ops = &generic_file_vm_ops;
296         return 0;
297 }
298 
299 static const struct file_operations aio_ring_fops = {
300         .mmap = aio_ring_mmap,
301 };
302 
303 #if IS_ENABLED(CONFIG_MIGRATION)
304 static int aio_migratepage(struct address_space *mapping, struct page *new,
305                         struct page *old, enum migrate_mode mode)
306 {
307         struct kioctx *ctx;
308         unsigned long flags;
309         pgoff_t idx;
310         int rc;
311 
312         rc = 0;
313 
314         /* mapping->private_lock here protects against the kioctx teardown.  */
315         spin_lock(&mapping->private_lock);
316         ctx = mapping->private_data;
317         if (!ctx) {
318                 rc = -EINVAL;
319                 goto out;
320         }
321 
322         /* The ring_lock mutex.  The prevents aio_read_events() from writing
323          * to the ring's head, and prevents page migration from mucking in
324          * a partially initialized kiotx.
325          */
326         if (!mutex_trylock(&ctx->ring_lock)) {
327                 rc = -EAGAIN;
328                 goto out;
329         }
330 
331         idx = old->index;
332         if (idx < (pgoff_t)ctx->nr_pages) {
333                 /* Make sure the old page hasn't already been changed */
334                 if (ctx->ring_pages[idx] != old)
335                         rc = -EAGAIN;
336         } else
337                 rc = -EINVAL;
338 
339         if (rc != 0)
340                 goto out_unlock;
341 
342         /* Writeback must be complete */
343         BUG_ON(PageWriteback(old));
344         get_page(new);
345 
346         rc = migrate_page_move_mapping(mapping, new, old, NULL, mode, 1);
347         if (rc != MIGRATEPAGE_SUCCESS) {
348                 put_page(new);
349                 goto out_unlock;
350         }
351 
352         /* Take completion_lock to prevent other writes to the ring buffer
353          * while the old page is copied to the new.  This prevents new
354          * events from being lost.
355          */
356         spin_lock_irqsave(&ctx->completion_lock, flags);
357         migrate_page_copy(new, old);
358         BUG_ON(ctx->ring_pages[idx] != old);
359         ctx->ring_pages[idx] = new;
360         spin_unlock_irqrestore(&ctx->completion_lock, flags);
361 
362         /* The old page is no longer accessible. */
363         put_page(old);
364 
365 out_unlock:
366         mutex_unlock(&ctx->ring_lock);
367 out:
368         spin_unlock(&mapping->private_lock);
369         return rc;
370 }
371 #endif
372 
373 static const struct address_space_operations aio_ctx_aops = {
374         .set_page_dirty = __set_page_dirty_no_writeback,
375 #if IS_ENABLED(CONFIG_MIGRATION)
376         .migratepage    = aio_migratepage,
377 #endif
378 };
379 
380 static int aio_setup_ring(struct kioctx *ctx)
381 {
382         struct aio_ring *ring;
383         unsigned nr_events = ctx->max_reqs;
384         struct mm_struct *mm = current->mm;
385         unsigned long size, unused;
386         int nr_pages;
387         int i;
388         struct file *file;
389 
390         /* Compensate for the ring buffer's head/tail overlap entry */
391         nr_events += 2; /* 1 is required, 2 for good luck */
392 
393         size = sizeof(struct aio_ring);
394         size += sizeof(struct io_event) * nr_events;
395 
396         nr_pages = PFN_UP(size);
397         if (nr_pages < 0)
398                 return -EINVAL;
399 
400         file = aio_private_file(ctx, nr_pages);
401         if (IS_ERR(file)) {
402                 ctx->aio_ring_file = NULL;
403                 return -ENOMEM;
404         }
405 
406         ctx->aio_ring_file = file;
407         nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring))
408                         / sizeof(struct io_event);
409 
410         ctx->ring_pages = ctx->internal_pages;
411         if (nr_pages > AIO_RING_PAGES) {
412                 ctx->ring_pages = kcalloc(nr_pages, sizeof(struct page *),
413                                           GFP_KERNEL);
414                 if (!ctx->ring_pages) {
415                         put_aio_ring_file(ctx);
416                         return -ENOMEM;
417                 }
418         }
419 
420         for (i = 0; i < nr_pages; i++) {
421                 struct page *page;
422                 page = find_or_create_page(file->f_inode->i_mapping,
423                                            i, GFP_HIGHUSER | __GFP_ZERO);
424                 if (!page)
425                         break;
426                 pr_debug("pid(%d) page[%d]->count=%d\n",
427                          current->pid, i, page_count(page));
428                 SetPageUptodate(page);
429                 unlock_page(page);
430 
431                 ctx->ring_pages[i] = page;
432         }
433         ctx->nr_pages = i;
434 
435         if (unlikely(i != nr_pages)) {
436                 aio_free_ring(ctx);
437                 return -ENOMEM;
438         }
439 
440         ctx->mmap_size = nr_pages * PAGE_SIZE;
441         pr_debug("attempting mmap of %lu bytes\n", ctx->mmap_size);
442 
443         down_write(&mm->mmap_sem);
444         ctx->mmap_base = do_mmap_pgoff(ctx->aio_ring_file, 0, ctx->mmap_size,
445                                        PROT_READ | PROT_WRITE,
446                                        MAP_SHARED, 0, &unused);
447         up_write(&mm->mmap_sem);
448         if (IS_ERR((void *)ctx->mmap_base)) {
449                 ctx->mmap_size = 0;
450                 aio_free_ring(ctx);
451                 return -ENOMEM;
452         }
453 
454         pr_debug("mmap address: 0x%08lx\n", ctx->mmap_base);
455 
456         ctx->user_id = ctx->mmap_base;
457         ctx->nr_events = nr_events; /* trusted copy */
458 
459         ring = kmap_atomic(ctx->ring_pages[0]);
460         ring->nr = nr_events;   /* user copy */
461         ring->id = ~0U;
462         ring->head = ring->tail = 0;
463         ring->magic = AIO_RING_MAGIC;
464         ring->compat_features = AIO_RING_COMPAT_FEATURES;
465         ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
466         ring->header_length = sizeof(struct aio_ring);
467         kunmap_atomic(ring);
468         flush_dcache_page(ctx->ring_pages[0]);
469 
470         return 0;
471 }
472 
473 #define AIO_EVENTS_PER_PAGE     (PAGE_SIZE / sizeof(struct io_event))
474 #define AIO_EVENTS_FIRST_PAGE   ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
475 #define AIO_EVENTS_OFFSET       (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
476 
477 void kiocb_set_cancel_fn(struct kiocb *req, kiocb_cancel_fn *cancel)
478 {
479         struct kioctx *ctx = req->ki_ctx;
480         unsigned long flags;
481 
482         spin_lock_irqsave(&ctx->ctx_lock, flags);
483 
484         if (!req->ki_list.next)
485                 list_add(&req->ki_list, &ctx->active_reqs);
486 
487         req->ki_cancel = cancel;
488 
489         spin_unlock_irqrestore(&ctx->ctx_lock, flags);
490 }
491 EXPORT_SYMBOL(kiocb_set_cancel_fn);
492 
493 static int kiocb_cancel(struct kioctx *ctx, struct kiocb *kiocb)
494 {
495         kiocb_cancel_fn *old, *cancel;
496 
497         /*
498          * Don't want to set kiocb->ki_cancel = KIOCB_CANCELLED unless it
499          * actually has a cancel function, hence the cmpxchg()
500          */
501 
502         cancel = ACCESS_ONCE(kiocb->ki_cancel);
503         do {
504                 if (!cancel || cancel == KIOCB_CANCELLED)
505                         return -EINVAL;
506 
507                 old = cancel;
508                 cancel = cmpxchg(&kiocb->ki_cancel, old, KIOCB_CANCELLED);
509         } while (cancel != old);
510 
511         return cancel(kiocb);
512 }
513 
514 static void free_ioctx(struct work_struct *work)
515 {
516         struct kioctx *ctx = container_of(work, struct kioctx, free_work);
517 
518         pr_debug("freeing %p\n", ctx);
519 
520         aio_free_ring(ctx);
521         free_percpu(ctx->cpu);
522         kmem_cache_free(kioctx_cachep, ctx);
523 }
524 
525 static void free_ioctx_reqs(struct percpu_ref *ref)
526 {
527         struct kioctx *ctx = container_of(ref, struct kioctx, reqs);
528 
529         /* At this point we know that there are no any in-flight requests */
530         if (ctx->rq_wait && atomic_dec_and_test(&ctx->rq_wait->count))
531                 complete(&ctx->rq_wait->comp);
532 
533         INIT_WORK(&ctx->free_work, free_ioctx);
534         schedule_work(&ctx->free_work);
535 }
536 
537 /*
538  * When this function runs, the kioctx has been removed from the "hash table"
539  * and ctx->users has dropped to 0, so we know no more kiocbs can be submitted -
540  * now it's safe to cancel any that need to be.
541  */
542 static void free_ioctx_users(struct percpu_ref *ref)
543 {
544         struct kioctx *ctx = container_of(ref, struct kioctx, users);
545         struct kiocb *req;
546 
547         spin_lock_irq(&ctx->ctx_lock);
548 
549         while (!list_empty(&ctx->active_reqs)) {
550                 req = list_first_entry(&ctx->active_reqs,
551                                        struct kiocb, ki_list);
552 
553                 list_del_init(&req->ki_list);
554                 kiocb_cancel(ctx, req);
555         }
556 
557         spin_unlock_irq(&ctx->ctx_lock);
558 
559         percpu_ref_kill(&ctx->reqs);
560         percpu_ref_put(&ctx->reqs);
561 }
562 
563 static int ioctx_add_table(struct kioctx *ctx, struct mm_struct *mm)
564 {
565         unsigned i, new_nr;
566         struct kioctx_table *table, *old;
567         struct aio_ring *ring;
568 
569         spin_lock(&mm->ioctx_lock);
570         rcu_read_lock();
571         table = rcu_dereference(mm->ioctx_table);
572 
573         while (1) {
574                 if (table)
575                         for (i = 0; i < table->nr; i++)
576                                 if (!table->table[i]) {
577                                         ctx->id = i;
578                                         table->table[i] = ctx;
579                                         rcu_read_unlock();
580                                         spin_unlock(&mm->ioctx_lock);
581 
582                                         /* While kioctx setup is in progress,
583                                          * we are protected from page migration
584                                          * changes ring_pages by ->ring_lock.
585                                          */
586                                         ring = kmap_atomic(ctx->ring_pages[0]);
587                                         ring->id = ctx->id;
588                                         kunmap_atomic(ring);
589                                         return 0;
590                                 }
591 
592                 new_nr = (table ? table->nr : 1) * 4;
593 
594                 rcu_read_unlock();
595                 spin_unlock(&mm->ioctx_lock);
596 
597                 table = kzalloc(sizeof(*table) + sizeof(struct kioctx *) *
598                                 new_nr, GFP_KERNEL);
599                 if (!table)
600                         return -ENOMEM;
601 
602                 table->nr = new_nr;
603 
604                 spin_lock(&mm->ioctx_lock);
605                 rcu_read_lock();
606                 old = rcu_dereference(mm->ioctx_table);
607 
608                 if (!old) {
609                         rcu_assign_pointer(mm->ioctx_table, table);
610                 } else if (table->nr > old->nr) {
611                         memcpy(table->table, old->table,
612                                old->nr * sizeof(struct kioctx *));
613 
614                         rcu_assign_pointer(mm->ioctx_table, table);
615                         kfree_rcu(old, rcu);
616                 } else {
617                         kfree(table);
618                         table = old;
619                 }
620         }
621 }
622 
623 static void aio_nr_sub(unsigned nr)
624 {
625         spin_lock(&aio_nr_lock);
626         if (WARN_ON(aio_nr - nr > aio_nr))
627                 aio_nr = 0;
628         else
629                 aio_nr -= nr;
630         spin_unlock(&aio_nr_lock);
631 }
632 
633 /* ioctx_alloc
634  *      Allocates and initializes an ioctx.  Returns an ERR_PTR if it failed.
635  */
636 static struct kioctx *ioctx_alloc(unsigned nr_events)
637 {
638         struct mm_struct *mm = current->mm;
639         struct kioctx *ctx;
640         int err = -ENOMEM;
641 
642         /*
643          * We keep track of the number of available ringbuffer slots, to prevent
644          * overflow (reqs_available), and we also use percpu counters for this.
645          *
646          * So since up to half the slots might be on other cpu's percpu counters
647          * and unavailable, double nr_events so userspace sees what they
648          * expected: additionally, we move req_batch slots to/from percpu
649          * counters at a time, so make sure that isn't 0:
650          */
651         nr_events = max(nr_events, num_possible_cpus() * 4);
652         nr_events *= 2;
653 
654         /* Prevent overflows */
655         if ((nr_events > (0x10000000U / sizeof(struct io_event))) ||
656             (nr_events > (0x10000000U / sizeof(struct kiocb)))) {
657                 pr_debug("ENOMEM: nr_events too high\n");
658                 return ERR_PTR(-EINVAL);
659         }
660 
661         if (!nr_events || (unsigned long)nr_events > (aio_max_nr * 2UL))
662                 return ERR_PTR(-EAGAIN);
663 
664         ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
665         if (!ctx)
666                 return ERR_PTR(-ENOMEM);
667 
668         ctx->max_reqs = nr_events;
669 
670         spin_lock_init(&ctx->ctx_lock);
671         spin_lock_init(&ctx->completion_lock);
672         mutex_init(&ctx->ring_lock);
673         /* Protect against page migration throughout kiotx setup by keeping
674          * the ring_lock mutex held until setup is complete. */
675         mutex_lock(&ctx->ring_lock);
676         init_waitqueue_head(&ctx->wait);
677 
678         INIT_LIST_HEAD(&ctx->active_reqs);
679 
680         if (percpu_ref_init(&ctx->users, free_ioctx_users))
681                 goto err;
682 
683         if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs))
684                 goto err;
685 
686         ctx->cpu = alloc_percpu(struct kioctx_cpu);
687         if (!ctx->cpu)
688                 goto err;
689 
690         err = aio_setup_ring(ctx);
691         if (err < 0)
692                 goto err;
693 
694         atomic_set(&ctx->reqs_available, ctx->nr_events - 1);
695         ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4);
696         if (ctx->req_batch < 1)
697                 ctx->req_batch = 1;
698 
699         /* limit the number of system wide aios */
700         spin_lock(&aio_nr_lock);
701         if (aio_nr + nr_events > (aio_max_nr * 2UL) ||
702             aio_nr + nr_events < aio_nr) {
703                 spin_unlock(&aio_nr_lock);
704                 err = -EAGAIN;
705                 goto err_ctx;
706         }
707         aio_nr += ctx->max_reqs;
708         spin_unlock(&aio_nr_lock);
709 
710         percpu_ref_get(&ctx->users);    /* io_setup() will drop this ref */
711         percpu_ref_get(&ctx->reqs);     /* free_ioctx_users() will drop this */
712 
713         err = ioctx_add_table(ctx, mm);
714         if (err)
715                 goto err_cleanup;
716 
717         /* Release the ring_lock mutex now that all setup is complete. */
718         mutex_unlock(&ctx->ring_lock);
719 
720         pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
721                  ctx, ctx->user_id, mm, ctx->nr_events);
722         return ctx;
723 
724 err_cleanup:
725         aio_nr_sub(ctx->max_reqs);
726 err_ctx:
727         atomic_set(&ctx->dead, 1);
728         if (ctx->mmap_size)
729                 vm_munmap(ctx->mmap_base, ctx->mmap_size);
730         aio_free_ring(ctx);
731 err:
732         mutex_unlock(&ctx->ring_lock);
733         free_percpu(ctx->cpu);
734         free_percpu(ctx->reqs.pcpu_count);
735         free_percpu(ctx->users.pcpu_count);
736         kmem_cache_free(kioctx_cachep, ctx);
737         pr_debug("error allocating ioctx %d\n", err);
738         return ERR_PTR(err);
739 }
740 
741 /* kill_ioctx
742  *      Cancels all outstanding aio requests on an aio context.  Used
743  *      when the processes owning a context have all exited to encourage
744  *      the rapid destruction of the kioctx.
745  */
746 static void kill_ioctx(struct mm_struct *mm, struct kioctx *ctx,
747                       struct ctx_rq_wait *wait)
748 {
749         if (!atomic_xchg(&ctx->dead, 1)) {
750                 struct kioctx_table *table;
751 
752                 spin_lock(&mm->ioctx_lock);
753                 rcu_read_lock();
754                 table = rcu_dereference(mm->ioctx_table);
755 
756                 WARN_ON(ctx != table->table[ctx->id]);
757                 table->table[ctx->id] = NULL;
758                 rcu_read_unlock();
759                 spin_unlock(&mm->ioctx_lock);
760 
761                 /* percpu_ref_kill() will do the necessary call_rcu() */
762                 wake_up_all(&ctx->wait);
763 
764                 /*
765                  * It'd be more correct to do this in free_ioctx(), after all
766                  * the outstanding kiocbs have finished - but by then io_destroy
767                  * has already returned, so io_setup() could potentially return
768                  * -EAGAIN with no ioctxs actually in use (as far as userspace
769                  *  could tell).
770                  */
771                 aio_nr_sub(ctx->max_reqs);
772 
773                 if (ctx->mmap_size)
774                         vm_munmap(ctx->mmap_base, ctx->mmap_size);
775 
776                 ctx->rq_wait = wait;
777                 percpu_ref_kill(&ctx->users);
778         } else {
779                 if (wait && atomic_dec_and_test(&wait->count))
780                         complete(&wait->comp);
781         }
782 }
783 
784 /* wait_on_sync_kiocb:
785  *      Waits on the given sync kiocb to complete.
786  */
787 ssize_t wait_on_sync_kiocb(struct kiocb *req)
788 {
789         while (!req->ki_ctx) {
790                 set_current_state(TASK_UNINTERRUPTIBLE);
791                 if (req->ki_ctx)
792                         break;
793                 io_schedule();
794         }
795         __set_current_state(TASK_RUNNING);
796         return req->ki_user_data;
797 }
798 EXPORT_SYMBOL(wait_on_sync_kiocb);
799 
800 /*
801  * exit_aio: called when the last user of mm goes away.  At this point, there is
802  * no way for any new requests to be submited or any of the io_* syscalls to be
803  * called on the context.
804  *
805  * There may be outstanding kiocbs, but free_ioctx() will explicitly wait on
806  * them.
807  */
808 void exit_aio(struct mm_struct *mm)
809 {
810         struct kioctx_table *table = rcu_dereference_raw(mm->ioctx_table);
811         struct ctx_rq_wait wait;
812         int i, skipped;
813 
814         if (!table)
815                 return;
816 
817         atomic_set(&wait.count, table->nr);
818         init_completion(&wait.comp);
819 
820         skipped = 0;
821         for (i = 0; i < table->nr; ++i) {
822                 struct kioctx *ctx = table->table[i];
823 
824                 if (!ctx) {
825                         skipped++;
826                         continue;
827                 }
828 
829                 /*
830                  * We don't need to bother with munmap() here - exit_mmap(mm)
831                  * is coming and it'll unmap everything. And we simply can't,
832                  * this is not necessarily our ->mm.
833                  * Since kill_ioctx() uses non-zero ->mmap_size as indicator
834                  * that it needs to unmap the area, just set it to 0.
835                  */
836                 ctx->mmap_size = 0;
837 
838                 kill_ioctx(mm, ctx, &wait);
839         }
840 
841         if (!atomic_sub_and_test(skipped, &wait.count)) {
842                 /* Wait until all IO for the context are done. */
843                 wait_for_completion(&wait.comp);
844         }
845 
846         RCU_INIT_POINTER(mm->ioctx_table, NULL);
847         kfree(table);
848 }
849 
850 static void put_reqs_available(struct kioctx *ctx, unsigned nr)
851 {
852         struct kioctx_cpu *kcpu;
853         unsigned long flags;
854 
855         preempt_disable();
856         kcpu = this_cpu_ptr(ctx->cpu);
857 
858         local_irq_save(flags);
859         kcpu->reqs_available += nr;
860 
861         while (kcpu->reqs_available >= ctx->req_batch * 2) {
862                 kcpu->reqs_available -= ctx->req_batch;
863                 atomic_add(ctx->req_batch, &ctx->reqs_available);
864         }
865 
866         local_irq_restore(flags);
867         preempt_enable();
868 }
869 
870 static bool get_reqs_available(struct kioctx *ctx)
871 {
872         struct kioctx_cpu *kcpu;
873         bool ret = false;
874         unsigned long flags;
875 
876         preempt_disable();
877         kcpu = this_cpu_ptr(ctx->cpu);
878 
879         local_irq_save(flags);
880         if (!kcpu->reqs_available) {
881                 int old, avail = atomic_read(&ctx->reqs_available);
882 
883                 do {
884                         if (avail < ctx->req_batch)
885                                 goto out;
886 
887                         old = avail;
888                         avail = atomic_cmpxchg(&ctx->reqs_available,
889                                                avail, avail - ctx->req_batch);
890                 } while (avail != old);
891 
892                 kcpu->reqs_available += ctx->req_batch;
893         }
894 
895         ret = true;
896         kcpu->reqs_available--;
897 out:
898         local_irq_restore(flags);
899         preempt_enable();
900         return ret;
901 }
902 
903 /* refill_reqs_available
904  *      Updates the reqs_available reference counts used for tracking the
905  *      number of free slots in the completion ring.  This can be called
906  *      from aio_complete() (to optimistically update reqs_available) or
907  *      from aio_get_req() (the we're out of events case).  It must be
908  *      called holding ctx->completion_lock.
909  */
910 static void refill_reqs_available(struct kioctx *ctx, unsigned head,
911                                   unsigned tail)
912 {
913         unsigned events_in_ring, completed;
914 
915         /* Clamp head since userland can write to it. */
916         head %= ctx->nr_events;
917         if (head <= tail)
918                 events_in_ring = tail - head;
919         else
920                 events_in_ring = ctx->nr_events - (head - tail);
921 
922         completed = ctx->completed_events;
923         if (events_in_ring < completed)
924                 completed -= events_in_ring;
925         else
926                 completed = 0;
927 
928         if (!completed)
929                 return;
930 
931         ctx->completed_events -= completed;
932         put_reqs_available(ctx, completed);
933 }
934 
935 /* user_refill_reqs_available
936  *      Called to refill reqs_available when aio_get_req() encounters an
937  *      out of space in the completion ring.
938  */
939 static void user_refill_reqs_available(struct kioctx *ctx)
940 {
941         spin_lock_irq(&ctx->completion_lock);
942         if (ctx->completed_events) {
943                 struct aio_ring *ring;
944                 unsigned head;
945 
946                 /* Access of ring->head may race with aio_read_events_ring()
947                  * here, but that's okay since whether we read the old version
948                  * or the new version, and either will be valid.  The important
949                  * part is that head cannot pass tail since we prevent
950                  * aio_complete() from updating tail by holding
951                  * ctx->completion_lock.  Even if head is invalid, the check
952                  * against ctx->completed_events below will make sure we do the
953                  * safe/right thing.
954                  */
955                 ring = kmap_atomic(ctx->ring_pages[0]);
956                 head = ring->head;
957                 kunmap_atomic(ring);
958 
959                 refill_reqs_available(ctx, head, ctx->tail);
960         }
961 
962         spin_unlock_irq(&ctx->completion_lock);
963 }
964 
965 /* aio_get_req
966  *      Allocate a slot for an aio request.
967  * Returns NULL if no requests are free.
968  */
969 static inline struct kiocb *aio_get_req(struct kioctx *ctx)
970 {
971         struct kiocb *req;
972 
973         if (!get_reqs_available(ctx)) {
974                 user_refill_reqs_available(ctx);
975                 if (!get_reqs_available(ctx))
976                         return NULL;
977         }
978 
979         req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL|__GFP_ZERO);
980         if (unlikely(!req))
981                 goto out_put;
982 
983         percpu_ref_get(&ctx->reqs);
984 
985         req->ki_ctx = ctx;
986         return req;
987 out_put:
988         put_reqs_available(ctx, 1);
989         return NULL;
990 }
991 
992 static void kiocb_free(struct kiocb *req)
993 {
994         if (req->ki_filp)
995                 fput(req->ki_filp);
996         if (req->ki_eventfd != NULL)
997                 eventfd_ctx_put(req->ki_eventfd);
998         kmem_cache_free(kiocb_cachep, req);
999 }
1000 
1001 static struct kioctx *lookup_ioctx(unsigned long ctx_id)
1002 {
1003         struct aio_ring __user *ring  = (void __user *)ctx_id;
1004         struct mm_struct *mm = current->mm;
1005         struct kioctx *ctx, *ret = NULL;
1006         struct kioctx_table *table;
1007         unsigned id;
1008 
1009         if (get_user(id, &ring->id))
1010                 return NULL;
1011 
1012         rcu_read_lock();
1013         table = rcu_dereference(mm->ioctx_table);
1014 
1015         if (!table || id >= table->nr)
1016                 goto out;
1017 
1018         ctx = table->table[id];
1019         if (ctx && ctx->user_id == ctx_id) {
1020                 percpu_ref_get(&ctx->users);
1021                 ret = ctx;
1022         }
1023 out:
1024         rcu_read_unlock();
1025         return ret;
1026 }
1027 
1028 /* aio_complete
1029  *      Called when the io request on the given iocb is complete.
1030  */
1031 void aio_complete(struct kiocb *iocb, long res, long res2)
1032 {
1033         struct kioctx   *ctx = iocb->ki_ctx;
1034         struct aio_ring *ring;
1035         struct io_event *ev_page, *event;
1036         unsigned tail, pos, head;
1037         unsigned long   flags;
1038 
1039         /*
1040          * Special case handling for sync iocbs:
1041          *  - events go directly into the iocb for fast handling
1042          *  - the sync task with the iocb in its stack holds the single iocb
1043          *    ref, no other paths have a way to get another ref
1044          *  - the sync task helpfully left a reference to itself in the iocb
1045          */
1046         if (is_sync_kiocb(iocb)) {
1047                 iocb->ki_user_data = res;
1048                 smp_wmb();
1049                 iocb->ki_ctx = ERR_PTR(-EXDEV);
1050                 wake_up_process(iocb->ki_obj.tsk);
1051                 return;
1052         }
1053 
1054         if (iocb->ki_list.next) {
1055                 unsigned long flags;
1056 
1057                 spin_lock_irqsave(&ctx->ctx_lock, flags);
1058                 list_del(&iocb->ki_list);
1059                 spin_unlock_irqrestore(&ctx->ctx_lock, flags);
1060         }
1061 
1062         /*
1063          * Add a completion event to the ring buffer. Must be done holding
1064          * ctx->completion_lock to prevent other code from messing with the tail
1065          * pointer since we might be called from irq context.
1066          */
1067         spin_lock_irqsave(&ctx->completion_lock, flags);
1068 
1069         tail = ctx->tail;
1070         pos = tail + AIO_EVENTS_OFFSET;
1071 
1072         if (++tail >= ctx->nr_events)
1073                 tail = 0;
1074 
1075         ev_page = kmap_atomic(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
1076         event = ev_page + pos % AIO_EVENTS_PER_PAGE;
1077 
1078         event->obj = (u64)(unsigned long)iocb->ki_obj.user;
1079         event->data = iocb->ki_user_data;
1080         event->res = res;
1081         event->res2 = res2;
1082 
1083         kunmap_atomic(ev_page);
1084         flush_dcache_page(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
1085 
1086         pr_debug("%p[%u]: %p: %p %Lx %lx %lx\n",
1087                  ctx, tail, iocb, iocb->ki_obj.user, iocb->ki_user_data,
1088                  res, res2);
1089 
1090         /* after flagging the request as done, we
1091          * must never even look at it again
1092          */
1093         smp_wmb();      /* make event visible before updating tail */
1094 
1095         ctx->tail = tail;
1096 
1097         ring = kmap_atomic(ctx->ring_pages[0]);
1098         head = ring->head;
1099         ring->tail = tail;
1100         kunmap_atomic(ring);
1101         flush_dcache_page(ctx->ring_pages[0]);
1102 
1103         ctx->completed_events++;
1104         if (ctx->completed_events > 1)
1105                 refill_reqs_available(ctx, head, tail);
1106         spin_unlock_irqrestore(&ctx->completion_lock, flags);
1107 
1108         pr_debug("added to ring %p at [%u]\n", iocb, tail);
1109 
1110         /*
1111          * Check if the user asked us to deliver the result through an
1112          * eventfd. The eventfd_signal() function is safe to be called
1113          * from IRQ context.
1114          */
1115         if (iocb->ki_eventfd != NULL)
1116                 eventfd_signal(iocb->ki_eventfd, 1);
1117 
1118         /* everything turned out well, dispose of the aiocb. */
1119         kiocb_free(iocb);
1120 
1121         /*
1122          * We have to order our ring_info tail store above and test
1123          * of the wait list below outside the wait lock.  This is
1124          * like in wake_up_bit() where clearing a bit has to be
1125          * ordered with the unlocked test.
1126          */
1127         smp_mb();
1128 
1129         if (waitqueue_active(&ctx->wait))
1130                 wake_up(&ctx->wait);
1131 
1132         percpu_ref_put(&ctx->reqs);
1133 }
1134 EXPORT_SYMBOL(aio_complete);
1135 
1136 /* aio_read_events
1137  *      Pull an event off of the ioctx's event ring.  Returns the number of
1138  *      events fetched
1139  */
1140 static long aio_read_events_ring(struct kioctx *ctx,
1141                                  struct io_event __user *event, long nr)
1142 {
1143         struct aio_ring *ring;
1144         unsigned head, tail, pos;
1145         long ret = 0;
1146         int copy_ret;
1147 
1148         mutex_lock(&ctx->ring_lock);
1149 
1150         /* Access to ->ring_pages here is protected by ctx->ring_lock. */
1151         ring = kmap_atomic(ctx->ring_pages[0]);
1152         head = ring->head;
1153         tail = ring->tail;
1154         kunmap_atomic(ring);
1155 
1156         /*
1157          * Ensure that once we've read the current tail pointer, that
1158          * we also see the events that were stored up to the tail.
1159          */
1160         smp_rmb();
1161 
1162         pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
1163 
1164         if (head == tail)
1165                 goto out;
1166 
1167         head %= ctx->nr_events;
1168         tail %= ctx->nr_events;
1169 
1170         while (ret < nr) {
1171                 long avail;
1172                 struct io_event *ev;
1173                 struct page *page;
1174 
1175                 avail = (head <= tail ?  tail : ctx->nr_events) - head;
1176                 if (head == tail)
1177                         break;
1178 
1179                 avail = min(avail, nr - ret);
1180                 avail = min_t(long, avail, AIO_EVENTS_PER_PAGE -
1181                             ((head + AIO_EVENTS_OFFSET) % AIO_EVENTS_PER_PAGE));
1182 
1183                 pos = head + AIO_EVENTS_OFFSET;
1184                 page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
1185                 pos %= AIO_EVENTS_PER_PAGE;
1186 
1187                 ev = kmap(page);
1188                 copy_ret = copy_to_user(event + ret, ev + pos,
1189                                         sizeof(*ev) * avail);
1190                 kunmap(page);
1191 
1192                 if (unlikely(copy_ret)) {
1193                         ret = -EFAULT;
1194                         goto out;
1195                 }
1196 
1197                 ret += avail;
1198                 head += avail;
1199                 head %= ctx->nr_events;
1200         }
1201 
1202         ring = kmap_atomic(ctx->ring_pages[0]);
1203         ring->head = head;
1204         kunmap_atomic(ring);
1205         flush_dcache_page(ctx->ring_pages[0]);
1206 
1207         pr_debug("%li  h%u t%u\n", ret, head, tail);
1208 out:
1209         mutex_unlock(&ctx->ring_lock);
1210 
1211         return ret;
1212 }
1213 
1214 static bool aio_read_events(struct kioctx *ctx, long min_nr, long nr,
1215                             struct io_event __user *event, long *i)
1216 {
1217         long ret = aio_read_events_ring(ctx, event + *i, nr - *i);
1218 
1219         if (ret > 0)
1220                 *i += ret;
1221 
1222         if (unlikely(atomic_read(&ctx->dead)))
1223                 ret = -EINVAL;
1224 
1225         if (!*i)
1226                 *i = ret;
1227 
1228         return ret < 0 || *i >= min_nr;
1229 }
1230 
1231 static long read_events(struct kioctx *ctx, long min_nr, long nr,
1232                         struct io_event __user *event,
1233                         struct timespec __user *timeout)
1234 {
1235         ktime_t until = { .tv64 = KTIME_MAX };
1236         long ret = 0;
1237 
1238         if (timeout) {
1239                 struct timespec ts;
1240 
1241                 if (unlikely(copy_from_user(&ts, timeout, sizeof(ts))))
1242                         return -EFAULT;
1243 
1244                 until = timespec_to_ktime(ts);
1245         }
1246 
1247         /*
1248          * Note that aio_read_events() is being called as the conditional - i.e.
1249          * we're calling it after prepare_to_wait() has set task state to
1250          * TASK_INTERRUPTIBLE.
1251          *
1252          * But aio_read_events() can block, and if it blocks it's going to flip
1253          * the task state back to TASK_RUNNING.
1254          *
1255          * This should be ok, provided it doesn't flip the state back to
1256          * TASK_RUNNING and return 0 too much - that causes us to spin. That
1257          * will only happen if the mutex_lock() call blocks, and we then find
1258          * the ringbuffer empty. So in practice we should be ok, but it's
1259          * something to be aware of when touching this code.
1260          */
1261         wait_event_interruptible_hrtimeout(ctx->wait,
1262                         aio_read_events(ctx, min_nr, nr, event, &ret), until);
1263 
1264         if (!ret && signal_pending(current))
1265                 ret = -EINTR;
1266 
1267         return ret;
1268 }
1269 
1270 /* sys_io_setup:
1271  *      Create an aio_context capable of receiving at least nr_events.
1272  *      ctxp must not point to an aio_context that already exists, and
1273  *      must be initialized to 0 prior to the call.  On successful
1274  *      creation of the aio_context, *ctxp is filled in with the resulting 
1275  *      handle.  May fail with -EINVAL if *ctxp is not initialized,
1276  *      if the specified nr_events exceeds internal limits.  May fail 
1277  *      with -EAGAIN if the specified nr_events exceeds the user's limit 
1278  *      of available events.  May fail with -ENOMEM if insufficient kernel
1279  *      resources are available.  May fail with -EFAULT if an invalid
1280  *      pointer is passed for ctxp.  Will fail with -ENOSYS if not
1281  *      implemented.
1282  */
1283 SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
1284 {
1285         struct kioctx *ioctx = NULL;
1286         unsigned long ctx;
1287         long ret;
1288 
1289         ret = get_user(ctx, ctxp);
1290         if (unlikely(ret))
1291                 goto out;
1292 
1293         ret = -EINVAL;
1294         if (unlikely(ctx || nr_events == 0)) {
1295                 pr_debug("EINVAL: io_setup: ctx %lu nr_events %u\n",
1296                          ctx, nr_events);
1297                 goto out;
1298         }
1299 
1300         ioctx = ioctx_alloc(nr_events);
1301         ret = PTR_ERR(ioctx);
1302         if (!IS_ERR(ioctx)) {
1303                 ret = put_user(ioctx->user_id, ctxp);
1304                 if (ret)
1305                         kill_ioctx(current->mm, ioctx, NULL);
1306                 percpu_ref_put(&ioctx->users);
1307         }
1308 
1309 out:
1310         return ret;
1311 }
1312 
1313 /* sys_io_destroy:
1314  *      Destroy the aio_context specified.  May cancel any outstanding 
1315  *      AIOs and block on completion.  Will fail with -ENOSYS if not
1316  *      implemented.  May fail with -EINVAL if the context pointed to
1317  *      is invalid.
1318  */
1319 SYSCALL_DEFINE1(io_destroy, aio_context_t, ctx)
1320 {
1321         struct kioctx *ioctx = lookup_ioctx(ctx);
1322         if (likely(NULL != ioctx)) {
1323                 struct ctx_rq_wait wait;
1324 
1325                 init_completion(&wait.comp);
1326                 atomic_set(&wait.count, 1);
1327 
1328                 /* Pass requests_done to kill_ioctx() where it can be set
1329                  * in a thread-safe way. If we try to set it here then we have
1330                  * a race condition if two io_destroy() called simultaneously.
1331                  */
1332                 kill_ioctx(current->mm, ioctx, &wait);
1333                 percpu_ref_put(&ioctx->users);
1334 
1335                 /* Wait until all IO for the context are done. Otherwise kernel
1336                  * keep using user-space buffers even if user thinks the context
1337                  * is destroyed.
1338                  */
1339                 wait_for_completion(&wait.comp);
1340 
1341                 return 0;
1342         }
1343         pr_debug("EINVAL: io_destroy: invalid context id\n");
1344         return -EINVAL;
1345 }
1346 
1347 typedef ssize_t (aio_rw_op)(struct kiocb *, const struct iovec *,
1348                             unsigned long, loff_t);
1349 
1350 static ssize_t aio_setup_vectored_rw(struct kiocb *kiocb,
1351                                      int rw, char __user *buf,
1352                                      unsigned long *nr_segs,
1353                                      struct iovec **iovec,
1354                                      bool compat)
1355 {
1356         ssize_t ret;
1357 
1358         *nr_segs = kiocb->ki_nbytes;
1359 
1360 #ifdef CONFIG_COMPAT
1361         if (compat)
1362                 ret = compat_rw_copy_check_uvector(rw,
1363                                 (struct compat_iovec __user *)buf,
1364                                 *nr_segs, 1, *iovec, iovec);
1365         else
1366 #endif
1367                 ret = rw_copy_check_uvector(rw,
1368                                 (struct iovec __user *)buf,
1369                                 *nr_segs, 1, *iovec, iovec);
1370         if (ret < 0)
1371                 return ret;
1372 
1373         /* ki_nbytes now reflect bytes instead of segs */
1374         kiocb->ki_nbytes = ret;
1375         return 0;
1376 }
1377 
1378 static ssize_t aio_setup_single_vector(struct kiocb *kiocb,
1379                                        int rw, char __user *buf,
1380                                        unsigned long *nr_segs,
1381                                        struct iovec *iovec)
1382 {
1383         size_t len = kiocb->ki_nbytes;
1384 
1385         if (len > MAX_RW_COUNT)
1386                 len = MAX_RW_COUNT;
1387 
1388         if (unlikely(!access_ok(!rw, buf, len)))
1389                 return -EFAULT;
1390 
1391         iovec->iov_base = buf;
1392         iovec->iov_len = len;
1393         *nr_segs = 1;
1394         return 0;
1395 }
1396 
1397 /*
1398  * aio_setup_iocb:
1399  *      Performs the initial checks and aio retry method
1400  *      setup for the kiocb at the time of io submission.
1401  */
1402 static ssize_t aio_run_iocb(struct kiocb *req, unsigned opcode,
1403                             char __user *buf, bool compat)
1404 {
1405         struct file *file = req->ki_filp;
1406         ssize_t ret;
1407         unsigned long nr_segs;
1408         int rw;
1409         fmode_t mode;
1410         aio_rw_op *rw_op;
1411         struct iovec inline_vec, *iovec = &inline_vec;
1412 
1413         switch (opcode) {
1414         case IOCB_CMD_PREAD:
1415         case IOCB_CMD_PREADV:
1416                 mode    = FMODE_READ;
1417                 rw      = READ;
1418                 rw_op   = file->f_op->aio_read;
1419                 goto rw_common;
1420 
1421         case IOCB_CMD_PWRITE:
1422         case IOCB_CMD_PWRITEV:
1423                 mode    = FMODE_WRITE;
1424                 rw      = WRITE;
1425                 rw_op   = file->f_op->aio_write;
1426                 goto rw_common;
1427 rw_common:
1428                 if (unlikely(!(file->f_mode & mode)))
1429                         return -EBADF;
1430 
1431                 if (!rw_op)
1432                         return -EINVAL;
1433 
1434                 ret = (opcode == IOCB_CMD_PREADV ||
1435                        opcode == IOCB_CMD_PWRITEV)
1436                         ? aio_setup_vectored_rw(req, rw, buf, &nr_segs,
1437                                                 &iovec, compat)
1438                         : aio_setup_single_vector(req, rw, buf, &nr_segs,
1439                                                   iovec);
1440                 if (!ret)
1441                         ret = rw_verify_area(rw, file, &req->ki_pos, req->ki_nbytes);
1442                 if (ret < 0) {
1443                         if (iovec != &inline_vec)
1444                                 kfree(iovec);
1445                         return ret;
1446                 }
1447 
1448                 req->ki_nbytes = ret;
1449 
1450                 /* XXX: move/kill - rw_verify_area()? */
1451                 /* This matches the pread()/pwrite() logic */
1452                 if (req->ki_pos < 0) {
1453                         ret = -EINVAL;
1454                         break;
1455                 }
1456 
1457                 if (rw == WRITE)
1458                         file_start_write(file);
1459 
1460                 ret = rw_op(req, iovec, nr_segs, req->ki_pos);
1461 
1462                 if (rw == WRITE)
1463                         file_end_write(file);
1464                 break;
1465 
1466         case IOCB_CMD_FDSYNC:
1467                 if (!file->f_op->aio_fsync)
1468                         return -EINVAL;
1469 
1470                 ret = file->f_op->aio_fsync(req, 1);
1471                 break;
1472 
1473         case IOCB_CMD_FSYNC:
1474                 if (!file->f_op->aio_fsync)
1475                         return -EINVAL;
1476 
1477                 ret = file->f_op->aio_fsync(req, 0);
1478                 break;
1479 
1480         default:
1481                 pr_debug("EINVAL: no operation provided\n");
1482                 return -EINVAL;
1483         }
1484 
1485         if (iovec != &inline_vec)
1486                 kfree(iovec);
1487 
1488         if (ret != -EIOCBQUEUED) {
1489                 /*
1490                  * There's no easy way to restart the syscall since other AIO's
1491                  * may be already running. Just fail this IO with EINTR.
1492                  */
1493                 if (unlikely(ret == -ERESTARTSYS || ret == -ERESTARTNOINTR ||
1494                              ret == -ERESTARTNOHAND ||
1495                              ret == -ERESTART_RESTARTBLOCK))
1496                         ret = -EINTR;
1497                 aio_complete(req, ret, 0);
1498         }
1499 
1500         return 0;
1501 }
1502 
1503 static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
1504                          struct iocb *iocb, bool compat)
1505 {
1506         struct kiocb *req;
1507         ssize_t ret;
1508 
1509         /* enforce forwards compatibility on users */
1510         if (unlikely(iocb->aio_reserved1 || iocb->aio_reserved2)) {
1511                 pr_debug("EINVAL: reserve field set\n");
1512                 return -EINVAL;
1513         }
1514 
1515         /* prevent overflows */
1516         if (unlikely(
1517             (iocb->aio_buf != (unsigned long)iocb->aio_buf) ||
1518             (iocb->aio_nbytes != (size_t)iocb->aio_nbytes) ||
1519             ((ssize_t)iocb->aio_nbytes < 0)
1520            )) {
1521                 pr_debug("EINVAL: io_submit: overflow check\n");
1522                 return -EINVAL;
1523         }
1524 
1525         req = aio_get_req(ctx);
1526         if (unlikely(!req))
1527                 return -EAGAIN;
1528 
1529         req->ki_filp = fget(iocb->aio_fildes);
1530         if (unlikely(!req->ki_filp)) {
1531                 ret = -EBADF;
1532                 goto out_put_req;
1533         }
1534 
1535         if (iocb->aio_flags & IOCB_FLAG_RESFD) {
1536                 /*
1537                  * If the IOCB_FLAG_RESFD flag of aio_flags is set, get an
1538                  * instance of the file* now. The file descriptor must be
1539                  * an eventfd() fd, and will be signaled for each completed
1540                  * event using the eventfd_signal() function.
1541                  */
1542                 req->ki_eventfd = eventfd_ctx_fdget((int) iocb->aio_resfd);
1543                 if (IS_ERR(req->ki_eventfd)) {
1544                         ret = PTR_ERR(req->ki_eventfd);
1545                         req->ki_eventfd = NULL;
1546                         goto out_put_req;
1547                 }
1548         }
1549 
1550         ret = put_user(KIOCB_KEY, &user_iocb->aio_key);
1551         if (unlikely(ret)) {
1552                 pr_debug("EFAULT: aio_key\n");
1553                 goto out_put_req;
1554         }
1555 
1556         req->ki_obj.user = user_iocb;
1557         req->ki_user_data = iocb->aio_data;
1558         req->ki_pos = iocb->aio_offset;
1559         req->ki_nbytes = iocb->aio_nbytes;
1560 
1561         ret = aio_run_iocb(req, iocb->aio_lio_opcode,
1562                            (char __user *)(unsigned long)iocb->aio_buf,
1563                            compat);
1564         if (ret)
1565                 goto out_put_req;
1566 
1567         return 0;
1568 out_put_req:
1569         put_reqs_available(ctx, 1);
1570         percpu_ref_put(&ctx->reqs);
1571         kiocb_free(req);
1572         return ret;
1573 }
1574 
1575 long do_io_submit(aio_context_t ctx_id, long nr,
1576                   struct iocb __user *__user *iocbpp, bool compat)
1577 {
1578         struct kioctx *ctx;
1579         long ret = 0;
1580         int i = 0;
1581         struct blk_plug plug;
1582 
1583         if (unlikely(nr < 0))
1584                 return -EINVAL;
1585 
1586         if (unlikely(nr > LONG_MAX/sizeof(*iocbpp)))
1587                 nr = LONG_MAX/sizeof(*iocbpp);
1588 
1589         if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
1590                 return -EFAULT;
1591 
1592         ctx = lookup_ioctx(ctx_id);
1593         if (unlikely(!ctx)) {
1594                 pr_debug("EINVAL: invalid context id\n");
1595                 return -EINVAL;
1596         }
1597 
1598         blk_start_plug(&plug);
1599 
1600         /*
1601          * AKPM: should this return a partial result if some of the IOs were
1602          * successfully submitted?
1603          */
1604         for (i=0; i<nr; i++) {
1605                 struct iocb __user *user_iocb;
1606                 struct iocb tmp;
1607 
1608                 if (unlikely(__get_user(user_iocb, iocbpp + i))) {
1609                         ret = -EFAULT;
1610                         break;
1611                 }
1612 
1613                 if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
1614                         ret = -EFAULT;
1615                         break;
1616                 }
1617 
1618                 ret = io_submit_one(ctx, user_iocb, &tmp, compat);
1619                 if (ret)
1620                         break;
1621         }
1622         blk_finish_plug(&plug);
1623 
1624         percpu_ref_put(&ctx->users);
1625         return i ? i : ret;
1626 }
1627 
1628 /* sys_io_submit:
1629  *      Queue the nr iocbs pointed to by iocbpp for processing.  Returns
1630  *      the number of iocbs queued.  May return -EINVAL if the aio_context
1631  *      specified by ctx_id is invalid, if nr is < 0, if the iocb at
1632  *      *iocbpp[0] is not properly initialized, if the operation specified
1633  *      is invalid for the file descriptor in the iocb.  May fail with
1634  *      -EFAULT if any of the data structures point to invalid data.  May
1635  *      fail with -EBADF if the file descriptor specified in the first
1636  *      iocb is invalid.  May fail with -EAGAIN if insufficient resources
1637  *      are available to queue any iocbs.  Will return 0 if nr is 0.  Will
1638  *      fail with -ENOSYS if not implemented.
1639  */
1640 SYSCALL_DEFINE3(io_submit, aio_context_t, ctx_id, long, nr,
1641                 struct iocb __user * __user *, iocbpp)
1642 {
1643         return do_io_submit(ctx_id, nr, iocbpp, 0);
1644 }
1645 
1646 /* lookup_kiocb
1647  *      Finds a given iocb for cancellation.
1648  */
1649 static struct kiocb *lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb,
1650                                   u32 key)
1651 {
1652         struct list_head *pos;
1653 
1654         assert_spin_locked(&ctx->ctx_lock);
1655 
1656         if (key != KIOCB_KEY)
1657                 return NULL;
1658 
1659         /* TODO: use a hash or array, this sucks. */
1660         list_for_each(pos, &ctx->active_reqs) {
1661                 struct kiocb *kiocb = list_kiocb(pos);
1662                 if (kiocb->ki_obj.user == iocb)
1663                         return kiocb;
1664         }
1665         return NULL;
1666 }
1667 
1668 /* sys_io_cancel:
1669  *      Attempts to cancel an iocb previously passed to io_submit.  If
1670  *      the operation is successfully cancelled, the resulting event is
1671  *      copied into the memory pointed to by result without being placed
1672  *      into the completion queue and 0 is returned.  May fail with
1673  *      -EFAULT if any of the data structures pointed to are invalid.
1674  *      May fail with -EINVAL if aio_context specified by ctx_id is
1675  *      invalid.  May fail with -EAGAIN if the iocb specified was not
1676  *      cancelled.  Will fail with -ENOSYS if not implemented.
1677  */
1678 SYSCALL_DEFINE3(io_cancel, aio_context_t, ctx_id, struct iocb __user *, iocb,
1679                 struct io_event __user *, result)
1680 {
1681         struct kioctx *ctx;
1682         struct kiocb *kiocb;
1683         u32 key;
1684         int ret;
1685 
1686         ret = get_user(key, &iocb->aio_key);
1687         if (unlikely(ret))
1688                 return -EFAULT;
1689 
1690         ctx = lookup_ioctx(ctx_id);
1691         if (unlikely(!ctx))
1692                 return -EINVAL;
1693 
1694         spin_lock_irq(&ctx->ctx_lock);
1695 
1696         kiocb = lookup_kiocb(ctx, iocb, key);
1697         if (kiocb)
1698                 ret = kiocb_cancel(ctx, kiocb);
1699         else
1700                 ret = -EINVAL;
1701 
1702         spin_unlock_irq(&ctx->ctx_lock);
1703 
1704         if (!ret) {
1705                 /*
1706                  * The result argument is no longer used - the io_event is
1707                  * always delivered via the ring buffer. -EINPROGRESS indicates
1708                  * cancellation is progress:
1709                  */
1710                 ret = -EINPROGRESS;
1711         }
1712 
1713         percpu_ref_put(&ctx->users);
1714 
1715         return ret;
1716 }
1717 
1718 /* io_getevents:
1719  *      Attempts to read at least min_nr events and up to nr events from
1720  *      the completion queue for the aio_context specified by ctx_id. If
1721  *      it succeeds, the number of read events is returned. May fail with
1722  *      -EINVAL if ctx_id is invalid, if min_nr is out of range, if nr is
1723  *      out of range, if timeout is out of range.  May fail with -EFAULT
1724  *      if any of the memory specified is invalid.  May return 0 or
1725  *      < min_nr if the timeout specified by timeout has elapsed
1726  *      before sufficient events are available, where timeout == NULL
1727  *      specifies an infinite timeout. Note that the timeout pointed to by
1728  *      timeout is relative.  Will fail with -ENOSYS if not implemented.
1729  */
1730 SYSCALL_DEFINE5(io_getevents, aio_context_t, ctx_id,
1731                 long, min_nr,
1732                 long, nr,
1733                 struct io_event __user *, events,
1734                 struct timespec __user *, timeout)
1735 {
1736         struct kioctx *ioctx = lookup_ioctx(ctx_id);
1737         long ret = -EINVAL;
1738 
1739         if (likely(ioctx)) {
1740                 if (likely(min_nr <= nr && min_nr >= 0))
1741                         ret = read_events(ioctx, min_nr, nr, events, timeout);
1742                 percpu_ref_put(&ioctx->users);
1743         }
1744         return ret;
1745 }
1746 

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp