linux/virt/kvm/kvm_main.c
<<
>>
Prefs
   1/*
   2 * Kernel-based Virtual Machine driver for Linux
   3 *
   4 * This module enables machines with Intel VT-x extensions to run virtual
   5 * machines without emulation or binary translation.
   6 *
   7 * Copyright (C) 2006 Qumranet, Inc.
   8 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
   9 *
  10 * Authors:
  11 *   Avi Kivity   <avi@qumranet.com>
  12 *   Yaniv Kamay  <yaniv@qumranet.com>
  13 *
  14 * This work is licensed under the terms of the GNU GPL, version 2.  See
  15 * the COPYING file in the top-level directory.
  16 *
  17 */
  18
  19#include "iodev.h"
  20
  21#include <linux/kvm_host.h>
  22#include <linux/kvm.h>
  23#include <linux/module.h>
  24#include <linux/errno.h>
  25#include <linux/percpu.h>
  26#include <linux/mm.h>
  27#include <linux/miscdevice.h>
  28#include <linux/vmalloc.h>
  29#include <linux/reboot.h>
  30#include <linux/debugfs.h>
  31#include <linux/highmem.h>
  32#include <linux/file.h>
  33#include <linux/syscore_ops.h>
  34#include <linux/cpu.h>
  35#include <linux/sched.h>
  36#include <linux/cpumask.h>
  37#include <linux/smp.h>
  38#include <linux/anon_inodes.h>
  39#include <linux/profile.h>
  40#include <linux/kvm_para.h>
  41#include <linux/pagemap.h>
  42#include <linux/mman.h>
  43#include <linux/swap.h>
  44#include <linux/bitops.h>
  45#include <linux/spinlock.h>
  46#include <linux/compat.h>
  47#include <linux/srcu.h>
  48#include <linux/hugetlb.h>
  49#include <linux/slab.h>
  50#include <linux/sort.h>
  51#include <linux/bsearch.h>
  52
  53#include <asm/processor.h>
  54#include <asm/io.h>
  55#include <asm/uaccess.h>
  56#include <asm/pgtable.h>
  57
  58#include "coalesced_mmio.h"
  59#include "async_pf.h"
  60
  61#define CREATE_TRACE_POINTS
  62#include <trace/events/kvm.h>
  63
  64MODULE_AUTHOR("Qumranet");
  65MODULE_LICENSE("GPL");
  66
  67/*
  68 * Ordering of locks:
  69 *
  70 *              kvm->lock --> kvm->slots_lock --> kvm->irq_lock
  71 */
  72
  73DEFINE_RAW_SPINLOCK(kvm_lock);
  74LIST_HEAD(vm_list);
  75
  76static cpumask_var_t cpus_hardware_enabled;
  77static int kvm_usage_count = 0;
  78static atomic_t hardware_enable_failed;
  79
  80struct kmem_cache *kvm_vcpu_cache;
  81EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
  82
  83static __read_mostly struct preempt_ops kvm_preempt_ops;
  84
  85struct dentry *kvm_debugfs_dir;
  86
  87static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
  88                           unsigned long arg);
  89#ifdef CONFIG_COMPAT
  90static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
  91                                  unsigned long arg);
  92#endif
  93static int hardware_enable_all(void);
  94static void hardware_disable_all(void);
  95
  96static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
  97
  98bool kvm_rebooting;
  99EXPORT_SYMBOL_GPL(kvm_rebooting);
 100
 101static bool largepages_enabled = true;
 102
 103bool kvm_is_mmio_pfn(pfn_t pfn)
 104{
 105        if (pfn_valid(pfn)) {
 106                int reserved;
 107                struct page *tail = pfn_to_page(pfn);
 108                struct page *head = compound_trans_head(tail);
 109                reserved = PageReserved(head);
 110                if (head != tail) {
 111                        /*
 112                         * "head" is not a dangling pointer
 113                         * (compound_trans_head takes care of that)
 114                         * but the hugepage may have been splitted
 115                         * from under us (and we may not hold a
 116                         * reference count on the head page so it can
 117                         * be reused before we run PageReferenced), so
 118                         * we've to check PageTail before returning
 119                         * what we just read.
 120                         */
 121                        smp_rmb();
 122                        if (PageTail(tail))
 123                                return reserved;
 124                }
 125                return PageReserved(tail);
 126        }
 127
 128        return true;
 129}
 130
 131/*
 132 * Switches to specified vcpu, until a matching vcpu_put()
 133 */
 134int vcpu_load(struct kvm_vcpu *vcpu)
 135{
 136        int cpu;
 137
 138        if (mutex_lock_killable(&vcpu->mutex))
 139                return -EINTR;
 140        if (unlikely(vcpu->pid != current->pids[PIDTYPE_PID].pid)) {
 141                /* The thread running this VCPU changed. */
 142                struct pid *oldpid = vcpu->pid;
 143                struct pid *newpid = get_task_pid(current, PIDTYPE_PID);
 144                rcu_assign_pointer(vcpu->pid, newpid);
 145                synchronize_rcu();
 146                put_pid(oldpid);
 147        }
 148        cpu = get_cpu();
 149        preempt_notifier_register(&vcpu->preempt_notifier);
 150        kvm_arch_vcpu_load(vcpu, cpu);
 151        put_cpu();
 152        return 0;
 153}
 154
 155void vcpu_put(struct kvm_vcpu *vcpu)
 156{
 157        preempt_disable();
 158        kvm_arch_vcpu_put(vcpu);
 159        preempt_notifier_unregister(&vcpu->preempt_notifier);
 160        preempt_enable();
 161        mutex_unlock(&vcpu->mutex);
 162}
 163
 164static void ack_flush(void *_completed)
 165{
 166}
 167
 168static bool make_all_cpus_request(struct kvm *kvm, unsigned int req)
 169{
 170        int i, cpu, me;
 171        cpumask_var_t cpus;
 172        bool called = true;
 173        struct kvm_vcpu *vcpu;
 174
 175        zalloc_cpumask_var(&cpus, GFP_ATOMIC);
 176
 177        me = get_cpu();
 178        kvm_for_each_vcpu(i, vcpu, kvm) {
 179                kvm_make_request(req, vcpu);
 180                cpu = vcpu->cpu;
 181
 182                /* Set ->requests bit before we read ->mode */
 183                smp_mb();
 184
 185                if (cpus != NULL && cpu != -1 && cpu != me &&
 186                      kvm_vcpu_exiting_guest_mode(vcpu) != OUTSIDE_GUEST_MODE)
 187                        cpumask_set_cpu(cpu, cpus);
 188        }
 189        if (unlikely(cpus == NULL))
 190                smp_call_function_many(cpu_online_mask, ack_flush, NULL, 1);
 191        else if (!cpumask_empty(cpus))
 192                smp_call_function_many(cpus, ack_flush, NULL, 1);
 193        else
 194                called = false;
 195        put_cpu();
 196        free_cpumask_var(cpus);
 197        return called;
 198}
 199
 200void kvm_flush_remote_tlbs(struct kvm *kvm)
 201{
 202        long dirty_count = kvm->tlbs_dirty;
 203
 204        smp_mb();
 205        if (make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
 206                ++kvm->stat.remote_tlb_flush;
 207        cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
 208}
 209
 210void kvm_reload_remote_mmus(struct kvm *kvm)
 211{
 212        make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
 213}
 214
 215int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
 216{
 217        struct page *page;
 218        int r;
 219
 220        mutex_init(&vcpu->mutex);
 221        vcpu->cpu = -1;
 222        vcpu->kvm = kvm;
 223        vcpu->vcpu_id = id;
 224        vcpu->pid = NULL;
 225        init_waitqueue_head(&vcpu->wq);
 226        kvm_async_pf_vcpu_init(vcpu);
 227
 228        page = alloc_page(GFP_KERNEL | __GFP_ZERO);
 229        if (!page) {
 230                r = -ENOMEM;
 231                goto fail;
 232        }
 233        vcpu->run = page_address(page);
 234
 235        kvm_vcpu_set_in_spin_loop(vcpu, false);
 236        kvm_vcpu_set_dy_eligible(vcpu, false);
 237
 238        r = kvm_arch_vcpu_init(vcpu);
 239        if (r < 0)
 240                goto fail_free_run;
 241        return 0;
 242
 243fail_free_run:
 244        free_page((unsigned long)vcpu->run);
 245fail:
 246        return r;
 247}
 248EXPORT_SYMBOL_GPL(kvm_vcpu_init);
 249
 250void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
 251{
 252        put_pid(vcpu->pid);
 253        kvm_arch_vcpu_uninit(vcpu);
 254        free_page((unsigned long)vcpu->run);
 255}
 256EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
 257
 258#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
 259static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
 260{
 261        return container_of(mn, struct kvm, mmu_notifier);
 262}
 263
 264static void kvm_mmu_notifier_invalidate_page(struct mmu_notifier *mn,
 265                                             struct mm_struct *mm,
 266                                             unsigned long address)
 267{
 268        struct kvm *kvm = mmu_notifier_to_kvm(mn);
 269        int need_tlb_flush, idx;
 270
 271        /*
 272         * When ->invalidate_page runs, the linux pte has been zapped
 273         * already but the page is still allocated until
 274         * ->invalidate_page returns. So if we increase the sequence
 275         * here the kvm page fault will notice if the spte can't be
 276         * established because the page is going to be freed. If
 277         * instead the kvm page fault establishes the spte before
 278         * ->invalidate_page runs, kvm_unmap_hva will release it
 279         * before returning.
 280         *
 281         * The sequence increase only need to be seen at spin_unlock
 282         * time, and not at spin_lock time.
 283         *
 284         * Increasing the sequence after the spin_unlock would be
 285         * unsafe because the kvm page fault could then establish the
 286         * pte after kvm_unmap_hva returned, without noticing the page
 287         * is going to be freed.
 288         */
 289        idx = srcu_read_lock(&kvm->srcu);
 290        spin_lock(&kvm->mmu_lock);
 291
 292        kvm->mmu_notifier_seq++;
 293        need_tlb_flush = kvm_unmap_hva(kvm, address) | kvm->tlbs_dirty;
 294        /* we've to flush the tlb before the pages can be freed */
 295        if (need_tlb_flush)
 296                kvm_flush_remote_tlbs(kvm);
 297
 298        spin_unlock(&kvm->mmu_lock);
 299        srcu_read_unlock(&kvm->srcu, idx);
 300}
 301
 302static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
 303                                        struct mm_struct *mm,
 304                                        unsigned long address,
 305                                        pte_t pte)
 306{
 307        struct kvm *kvm = mmu_notifier_to_kvm(mn);
 308        int idx;
 309
 310        idx = srcu_read_lock(&kvm->srcu);
 311        spin_lock(&kvm->mmu_lock);
 312        kvm->mmu_notifier_seq++;
 313        kvm_set_spte_hva(kvm, address, pte);
 314        spin_unlock(&kvm->mmu_lock);
 315        srcu_read_unlock(&kvm->srcu, idx);
 316}
 317
 318static void kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
 319                                                    struct mm_struct *mm,
 320                                                    unsigned long start,
 321                                                    unsigned long end)
 322{
 323        struct kvm *kvm = mmu_notifier_to_kvm(mn);
 324        int need_tlb_flush = 0, idx;
 325
 326        idx = srcu_read_lock(&kvm->srcu);
 327        spin_lock(&kvm->mmu_lock);
 328        /*
 329         * The count increase must become visible at unlock time as no
 330         * spte can be established without taking the mmu_lock and
 331         * count is also read inside the mmu_lock critical section.
 332         */
 333        kvm->mmu_notifier_count++;
 334        need_tlb_flush = kvm_unmap_hva_range(kvm, start, end);
 335        need_tlb_flush |= kvm->tlbs_dirty;
 336        /* we've to flush the tlb before the pages can be freed */
 337        if (need_tlb_flush)
 338                kvm_flush_remote_tlbs(kvm);
 339
 340        spin_unlock(&kvm->mmu_lock);
 341        srcu_read_unlock(&kvm->srcu, idx);
 342}
 343
 344static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
 345                                                  struct mm_struct *mm,
 346                                                  unsigned long start,
 347                                                  unsigned long end)
 348{
 349        struct kvm *kvm = mmu_notifier_to_kvm(mn);
 350
 351        spin_lock(&kvm->mmu_lock);
 352        /*
 353         * This sequence increase will notify the kvm page fault that
 354         * the page that is going to be mapped in the spte could have
 355         * been freed.
 356         */
 357        kvm->mmu_notifier_seq++;
 358        smp_wmb();
 359        /*
 360         * The above sequence increase must be visible before the
 361         * below count decrease, which is ensured by the smp_wmb above
 362         * in conjunction with the smp_rmb in mmu_notifier_retry().
 363         */
 364        kvm->mmu_notifier_count--;
 365        spin_unlock(&kvm->mmu_lock);
 366
 367        BUG_ON(kvm->mmu_notifier_count < 0);
 368}
 369
 370static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
 371                                              struct mm_struct *mm,
 372                                              unsigned long address)
 373{
 374        struct kvm *kvm = mmu_notifier_to_kvm(mn);
 375        int young, idx;
 376
 377        idx = srcu_read_lock(&kvm->srcu);
 378        spin_lock(&kvm->mmu_lock);
 379
 380        young = kvm_age_hva(kvm, address);
 381        if (young)
 382                kvm_flush_remote_tlbs(kvm);
 383
 384        spin_unlock(&kvm->mmu_lock);
 385        srcu_read_unlock(&kvm->srcu, idx);
 386
 387        return young;
 388}
 389
 390static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
 391                                       struct mm_struct *mm,
 392                                       unsigned long address)
 393{
 394        struct kvm *kvm = mmu_notifier_to_kvm(mn);
 395        int young, idx;
 396
 397        idx = srcu_read_lock(&kvm->srcu);
 398        spin_lock(&kvm->mmu_lock);
 399        young = kvm_test_age_hva(kvm, address);
 400        spin_unlock(&kvm->mmu_lock);
 401        srcu_read_unlock(&kvm->srcu, idx);
 402
 403        return young;
 404}
 405
 406static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
 407                                     struct mm_struct *mm)
 408{
 409        struct kvm *kvm = mmu_notifier_to_kvm(mn);
 410        int idx;
 411
 412        idx = srcu_read_lock(&kvm->srcu);
 413        kvm_arch_flush_shadow_all(kvm);
 414        srcu_read_unlock(&kvm->srcu, idx);
 415}
 416
 417static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
 418        .invalidate_page        = kvm_mmu_notifier_invalidate_page,
 419        .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
 420        .invalidate_range_end   = kvm_mmu_notifier_invalidate_range_end,
 421        .clear_flush_young      = kvm_mmu_notifier_clear_flush_young,
 422        .test_young             = kvm_mmu_notifier_test_young,
 423        .change_pte             = kvm_mmu_notifier_change_pte,
 424        .release                = kvm_mmu_notifier_release,
 425};
 426
 427static int kvm_init_mmu_notifier(struct kvm *kvm)
 428{
 429        kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
 430        return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
 431}
 432
 433#else  /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
 434
 435static int kvm_init_mmu_notifier(struct kvm *kvm)
 436{
 437        return 0;
 438}
 439
 440#endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
 441
 442static void kvm_init_memslots_id(struct kvm *kvm)
 443{
 444        int i;
 445        struct kvm_memslots *slots = kvm->memslots;
 446
 447        for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
 448                slots->id_to_index[i] = slots->memslots[i].id = i;
 449}
 450
 451static struct kvm *kvm_create_vm(unsigned long type)
 452{
 453        int r, i;
 454        struct kvm *kvm = kvm_arch_alloc_vm();
 455
 456        if (!kvm)
 457                return ERR_PTR(-ENOMEM);
 458
 459        r = kvm_arch_init_vm(kvm, type);
 460        if (r)
 461                goto out_err_nodisable;
 462
 463        r = hardware_enable_all();
 464        if (r)
 465                goto out_err_nodisable;
 466
 467#ifdef CONFIG_HAVE_KVM_IRQCHIP
 468        INIT_HLIST_HEAD(&kvm->mask_notifier_list);
 469        INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
 470#endif
 471
 472        r = -ENOMEM;
 473        kvm->memslots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
 474        if (!kvm->memslots)
 475                goto out_err_nosrcu;
 476        kvm_init_memslots_id(kvm);
 477        if (init_srcu_struct(&kvm->srcu))
 478                goto out_err_nosrcu;
 479        for (i = 0; i < KVM_NR_BUSES; i++) {
 480                kvm->buses[i] = kzalloc(sizeof(struct kvm_io_bus),
 481                                        GFP_KERNEL);
 482                if (!kvm->buses[i])
 483                        goto out_err;
 484        }
 485
 486        spin_lock_init(&kvm->mmu_lock);
 487        kvm->mm = current->mm;
 488        atomic_inc(&kvm->mm->mm_count);
 489        kvm_eventfd_init(kvm);
 490        mutex_init(&kvm->lock);
 491        mutex_init(&kvm->irq_lock);
 492        mutex_init(&kvm->slots_lock);
 493        atomic_set(&kvm->users_count, 1);
 494
 495        r = kvm_init_mmu_notifier(kvm);
 496        if (r)
 497                goto out_err;
 498
 499        raw_spin_lock(&kvm_lock);
 500        list_add(&kvm->vm_list, &vm_list);
 501        raw_spin_unlock(&kvm_lock);
 502
 503        return kvm;
 504
 505out_err:
 506        cleanup_srcu_struct(&kvm->srcu);
 507out_err_nosrcu:
 508        hardware_disable_all();
 509out_err_nodisable:
 510        for (i = 0; i < KVM_NR_BUSES; i++)
 511                kfree(kvm->buses[i]);
 512        kfree(kvm->memslots);
 513        kvm_arch_free_vm(kvm);
 514        return ERR_PTR(r);
 515}
 516
 517/*
 518 * Avoid using vmalloc for a small buffer.
 519 * Should not be used when the size is statically known.
 520 */
 521void *kvm_kvzalloc(unsigned long size)
 522{
 523        if (size > PAGE_SIZE)
 524                return vzalloc(size);
 525        else
 526                return kzalloc(size, GFP_KERNEL);
 527}
 528
 529void kvm_kvfree(const void *addr)
 530{
 531        if (is_vmalloc_addr(addr))
 532                vfree(addr);
 533        else
 534                kfree(addr);
 535}
 536
 537static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
 538{
 539        if (!memslot->dirty_bitmap)
 540                return;
 541
 542        kvm_kvfree(memslot->dirty_bitmap);
 543        memslot->dirty_bitmap = NULL;
 544}
 545
 546/*
 547 * Free any memory in @free but not in @dont.
 548 */
 549static void kvm_free_physmem_slot(struct kvm_memory_slot *free,
 550                                  struct kvm_memory_slot *dont)
 551{
 552        if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
 553                kvm_destroy_dirty_bitmap(free);
 554
 555        kvm_arch_free_memslot(free, dont);
 556
 557        free->npages = 0;
 558}
 559
 560void kvm_free_physmem(struct kvm *kvm)
 561{
 562        struct kvm_memslots *slots = kvm->memslots;
 563        struct kvm_memory_slot *memslot;
 564
 565        kvm_for_each_memslot(memslot, slots)
 566                kvm_free_physmem_slot(memslot, NULL);
 567
 568        kfree(kvm->memslots);
 569}
 570
 571static void kvm_destroy_vm(struct kvm *kvm)
 572{
 573        int i;
 574        struct mm_struct *mm = kvm->mm;
 575
 576        kvm_arch_sync_events(kvm);
 577        raw_spin_lock(&kvm_lock);
 578        list_del(&kvm->vm_list);
 579        raw_spin_unlock(&kvm_lock);
 580        kvm_free_irq_routing(kvm);
 581        for (i = 0; i < KVM_NR_BUSES; i++)
 582                kvm_io_bus_destroy(kvm->buses[i]);
 583        kvm_coalesced_mmio_free(kvm);
 584#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
 585        mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
 586#else
 587        kvm_arch_flush_shadow_all(kvm);
 588#endif
 589        kvm_arch_destroy_vm(kvm);
 590        kvm_free_physmem(kvm);
 591        cleanup_srcu_struct(&kvm->srcu);
 592        kvm_arch_free_vm(kvm);
 593        hardware_disable_all();
 594        mmdrop(mm);
 595}
 596
 597void kvm_get_kvm(struct kvm *kvm)
 598{
 599        atomic_inc(&kvm->users_count);
 600}
 601EXPORT_SYMBOL_GPL(kvm_get_kvm);
 602
 603void kvm_put_kvm(struct kvm *kvm)
 604{
 605        if (atomic_dec_and_test(&kvm->users_count))
 606                kvm_destroy_vm(kvm);
 607}
 608EXPORT_SYMBOL_GPL(kvm_put_kvm);
 609
 610
 611static int kvm_vm_release(struct inode *inode, struct file *filp)
 612{
 613        struct kvm *kvm = filp->private_data;
 614
 615        kvm_irqfd_release(kvm);
 616
 617        kvm_put_kvm(kvm);
 618        return 0;
 619}
 620
 621/*
 622 * Allocation size is twice as large as the actual dirty bitmap size.
 623 * See x86's kvm_vm_ioctl_get_dirty_log() why this is needed.
 624 */
 625static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
 626{
 627#ifndef CONFIG_S390
 628        unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
 629
 630        memslot->dirty_bitmap = kvm_kvzalloc(dirty_bytes);
 631        if (!memslot->dirty_bitmap)
 632                return -ENOMEM;
 633
 634#endif /* !CONFIG_S390 */
 635        return 0;
 636}
 637
 638static int cmp_memslot(const void *slot1, const void *slot2)
 639{
 640        struct kvm_memory_slot *s1, *s2;
 641
 642        s1 = (struct kvm_memory_slot *)slot1;
 643        s2 = (struct kvm_memory_slot *)slot2;
 644
 645        if (s1->npages < s2->npages)
 646                return 1;
 647        if (s1->npages > s2->npages)
 648                return -1;
 649
 650        return 0;
 651}
 652
 653/*
 654 * Sort the memslots base on its size, so the larger slots
 655 * will get better fit.
 656 */
 657static void sort_memslots(struct kvm_memslots *slots)
 658{
 659        int i;
 660
 661        sort(slots->memslots, KVM_MEM_SLOTS_NUM,
 662              sizeof(struct kvm_memory_slot), cmp_memslot, NULL);
 663
 664        for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
 665                slots->id_to_index[slots->memslots[i].id] = i;
 666}
 667
 668void update_memslots(struct kvm_memslots *slots, struct kvm_memory_slot *new)
 669{
 670        if (new) {
 671                int id = new->id;
 672                struct kvm_memory_slot *old = id_to_memslot(slots, id);
 673                unsigned long npages = old->npages;
 674
 675                *old = *new;
 676                if (new->npages != npages)
 677                        sort_memslots(slots);
 678        }
 679
 680        slots->generation++;
 681}
 682
 683static int check_memory_region_flags(struct kvm_userspace_memory_region *mem)
 684{
 685        u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
 686
 687#ifdef KVM_CAP_READONLY_MEM
 688        valid_flags |= KVM_MEM_READONLY;
 689#endif
 690
 691        if (mem->flags & ~valid_flags)
 692                return -EINVAL;
 693
 694        return 0;
 695}
 696
 697/*
 698 * Allocate some memory and give it an address in the guest physical address
 699 * space.
 700 *
 701 * Discontiguous memory is allowed, mostly for framebuffers.
 702 *
 703 * Must be called holding mmap_sem for write.
 704 */
 705int __kvm_set_memory_region(struct kvm *kvm,
 706                            struct kvm_userspace_memory_region *mem,
 707                            int user_alloc)
 708{
 709        int r;
 710        gfn_t base_gfn;
 711        unsigned long npages;
 712        struct kvm_memory_slot *memslot, *slot;
 713        struct kvm_memory_slot old, new;
 714        struct kvm_memslots *slots, *old_memslots;
 715
 716        r = check_memory_region_flags(mem);
 717        if (r)
 718                goto out;
 719
 720        r = -EINVAL;
 721        /* General sanity checks */
 722        if (mem->memory_size & (PAGE_SIZE - 1))
 723                goto out;
 724        if (mem->guest_phys_addr & (PAGE_SIZE - 1))
 725                goto out;
 726        /* We can read the guest memory with __xxx_user() later on. */
 727        if (user_alloc &&
 728            ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
 729             !access_ok(VERIFY_WRITE,
 730                        (void __user *)(unsigned long)mem->userspace_addr,
 731                        mem->memory_size)))
 732                goto out;
 733        if (mem->slot >= KVM_MEM_SLOTS_NUM)
 734                goto out;
 735        if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
 736                goto out;
 737
 738        memslot = id_to_memslot(kvm->memslots, mem->slot);
 739        base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
 740        npages = mem->memory_size >> PAGE_SHIFT;
 741
 742        r = -EINVAL;
 743        if (npages > KVM_MEM_MAX_NR_PAGES)
 744                goto out;
 745
 746        if (!npages)
 747                mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
 748
 749        new = old = *memslot;
 750
 751        new.id = mem->slot;
 752        new.base_gfn = base_gfn;
 753        new.npages = npages;
 754        new.flags = mem->flags;
 755
 756        /* Disallow changing a memory slot's size. */
 757        r = -EINVAL;
 758        if (npages && old.npages && npages != old.npages)
 759                goto out_free;
 760
 761        /* Check for overlaps */
 762        r = -EEXIST;
 763        kvm_for_each_memslot(slot, kvm->memslots) {
 764                if (slot->id >= KVM_MEMORY_SLOTS || slot == memslot)
 765                        continue;
 766                if (!((base_gfn + npages <= slot->base_gfn) ||
 767                      (base_gfn >= slot->base_gfn + slot->npages)))
 768                        goto out_free;
 769        }
 770
 771        /* Free page dirty bitmap if unneeded */
 772        if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
 773                new.dirty_bitmap = NULL;
 774
 775        r = -ENOMEM;
 776
 777        /* Allocate if a slot is being created */
 778        if (npages && !old.npages) {
 779                new.user_alloc = user_alloc;
 780                new.userspace_addr = mem->userspace_addr;
 781
 782                if (kvm_arch_create_memslot(&new, npages))
 783                        goto out_free;
 784        }
 785
 786        /* Allocate page dirty bitmap if needed */
 787        if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
 788                if (kvm_create_dirty_bitmap(&new) < 0)
 789                        goto out_free;
 790                /* destroy any largepage mappings for dirty tracking */
 791        }
 792
 793        if (!npages || base_gfn != old.base_gfn) {
 794                struct kvm_memory_slot *slot;
 795
 796                r = -ENOMEM;
 797                slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
 798                                GFP_KERNEL);
 799                if (!slots)
 800                        goto out_free;
 801                slot = id_to_memslot(slots, mem->slot);
 802                slot->flags |= KVM_MEMSLOT_INVALID;
 803
 804                update_memslots(slots, NULL);
 805
 806                old_memslots = kvm->memslots;
 807                rcu_assign_pointer(kvm->memslots, slots);
 808                synchronize_srcu_expedited(&kvm->srcu);
 809                /* From this point no new shadow pages pointing to a deleted,
 810                 * or moved, memslot will be created.
 811                 *
 812                 * validation of sp->gfn happens in:
 813                 *      - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
 814                 *      - kvm_is_visible_gfn (mmu_check_roots)
 815                 */
 816                kvm_arch_flush_shadow_memslot(kvm, slot);
 817                kfree(old_memslots);
 818        }
 819
 820        r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc);
 821        if (r)
 822                goto out_free;
 823
 824        /* map/unmap the pages in iommu page table */
 825        if (npages) {
 826                r = kvm_iommu_map_pages(kvm, &new);
 827                if (r)
 828                        goto out_free;
 829        } else
 830                kvm_iommu_unmap_pages(kvm, &old);
 831
 832        r = -ENOMEM;
 833        slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
 834                        GFP_KERNEL);
 835        if (!slots)
 836                goto out_free;
 837
 838        /* actual memory is freed via old in kvm_free_physmem_slot below */
 839        if (!npages) {
 840                new.dirty_bitmap = NULL;
 841                memset(&new.arch, 0, sizeof(new.arch));
 842        }
 843
 844        update_memslots(slots, &new);
 845        old_memslots = kvm->memslots;
 846        rcu_assign_pointer(kvm->memslots, slots);
 847        synchronize_srcu_expedited(&kvm->srcu);
 848
 849        kvm_arch_commit_memory_region(kvm, mem, old, user_alloc);
 850
 851        kvm_free_physmem_slot(&old, &new);
 852        kfree(old_memslots);
 853
 854        return 0;
 855
 856out_free:
 857        kvm_free_physmem_slot(&new, &old);
 858out:
 859        return r;
 860
 861}
 862EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
 863
 864int kvm_set_memory_region(struct kvm *kvm,
 865                          struct kvm_userspace_memory_region *mem,
 866                          int user_alloc)
 867{
 868        int r;
 869
 870        mutex_lock(&kvm->slots_lock);
 871        r = __kvm_set_memory_region(kvm, mem, user_alloc);
 872        mutex_unlock(&kvm->slots_lock);
 873        return r;
 874}
 875EXPORT_SYMBOL_GPL(kvm_set_memory_region);
 876
 877int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
 878                                   struct
 879                                   kvm_userspace_memory_region *mem,
 880                                   int user_alloc)
 881{
 882        if (mem->slot >= KVM_MEMORY_SLOTS)
 883                return -EINVAL;
 884        return kvm_set_memory_region(kvm, mem, user_alloc);
 885}
 886
 887int kvm_get_dirty_log(struct kvm *kvm,
 888                        struct kvm_dirty_log *log, int *is_dirty)
 889{
 890        struct kvm_memory_slot *memslot;
 891        int r, i;
 892        unsigned long n;
 893        unsigned long any = 0;
 894
 895        r = -EINVAL;
 896        if (log->slot >= KVM_MEMORY_SLOTS)
 897                goto out;
 898
 899        memslot = id_to_memslot(kvm->memslots, log->slot);
 900        r = -ENOENT;
 901        if (!memslot->dirty_bitmap)
 902                goto out;
 903
 904        n = kvm_dirty_bitmap_bytes(memslot);
 905
 906        for (i = 0; !any && i < n/sizeof(long); ++i)
 907                any = memslot->dirty_bitmap[i];
 908
 909        r = -EFAULT;
 910        if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
 911                goto out;
 912
 913        if (any)
 914                *is_dirty = 1;
 915
 916        r = 0;
 917out:
 918        return r;
 919}
 920
 921bool kvm_largepages_enabled(void)
 922{
 923        return largepages_enabled;
 924}
 925
 926void kvm_disable_largepages(void)
 927{
 928        largepages_enabled = false;
 929}
 930EXPORT_SYMBOL_GPL(kvm_disable_largepages);
 931
 932struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
 933{
 934        return __gfn_to_memslot(kvm_memslots(kvm), gfn);
 935}
 936EXPORT_SYMBOL_GPL(gfn_to_memslot);
 937
 938int kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
 939{
 940        struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
 941
 942        if (!memslot || memslot->id >= KVM_MEMORY_SLOTS ||
 943              memslot->flags & KVM_MEMSLOT_INVALID)
 944                return 0;
 945
 946        return 1;
 947}
 948EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
 949
 950unsigned long kvm_host_page_size(struct kvm *kvm, gfn_t gfn)
 951{
 952        struct vm_area_struct *vma;
 953        unsigned long addr, size;
 954
 955        size = PAGE_SIZE;
 956
 957        addr = gfn_to_hva(kvm, gfn);
 958        if (kvm_is_error_hva(addr))
 959                return PAGE_SIZE;
 960
 961        down_read(&current->mm->mmap_sem);
 962        vma = find_vma(current->mm, addr);
 963        if (!vma)
 964                goto out;
 965
 966        size = vma_kernel_pagesize(vma);
 967
 968out:
 969        up_read(&current->mm->mmap_sem);
 970
 971        return size;
 972}
 973
 974static bool memslot_is_readonly(struct kvm_memory_slot *slot)
 975{
 976        return slot->flags & KVM_MEM_READONLY;
 977}
 978
 979static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
 980                                       gfn_t *nr_pages, bool write)
 981{
 982        if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
 983                return KVM_HVA_ERR_BAD;
 984
 985        if (memslot_is_readonly(slot) && write)
 986                return KVM_HVA_ERR_RO_BAD;
 987
 988        if (nr_pages)
 989                *nr_pages = slot->npages - (gfn - slot->base_gfn);
 990
 991        return __gfn_to_hva_memslot(slot, gfn);
 992}
 993
 994static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
 995                                     gfn_t *nr_pages)
 996{
 997        return __gfn_to_hva_many(slot, gfn, nr_pages, true);
 998}
 999
1000unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
1001                                 gfn_t gfn)
1002{
1003        return gfn_to_hva_many(slot, gfn, NULL);
1004}
1005EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1006
1007unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1008{
1009        return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1010}
1011EXPORT_SYMBOL_GPL(gfn_to_hva);
1012
1013/*
1014 * The hva returned by this function is only allowed to be read.
1015 * It should pair with kvm_read_hva() or kvm_read_hva_atomic().
1016 */
1017static unsigned long gfn_to_hva_read(struct kvm *kvm, gfn_t gfn)
1018{
1019        return __gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL, false);
1020}
1021
1022static int kvm_read_hva(void *data, void __user *hva, int len)
1023{
1024        return __copy_from_user(data, hva, len);
1025}
1026
1027static int kvm_read_hva_atomic(void *data, void __user *hva, int len)
1028{
1029        return __copy_from_user_inatomic(data, hva, len);
1030}
1031
1032int get_user_page_nowait(struct task_struct *tsk, struct mm_struct *mm,
1033        unsigned long start, int write, struct page **page)
1034{
1035        int flags = FOLL_TOUCH | FOLL_NOWAIT | FOLL_HWPOISON | FOLL_GET;
1036
1037        if (write)
1038                flags |= FOLL_WRITE;
1039
1040        return __get_user_pages(tsk, mm, start, 1, flags, page, NULL, NULL);
1041}
1042
1043static inline int check_user_page_hwpoison(unsigned long addr)
1044{
1045        int rc, flags = FOLL_TOUCH | FOLL_HWPOISON | FOLL_WRITE;
1046
1047        rc = __get_user_pages(current, current->mm, addr, 1,
1048                              flags, NULL, NULL, NULL);
1049        return rc == -EHWPOISON;
1050}
1051
1052/*
1053 * The atomic path to get the writable pfn which will be stored in @pfn,
1054 * true indicates success, otherwise false is returned.
1055 */
1056static bool hva_to_pfn_fast(unsigned long addr, bool atomic, bool *async,
1057                            bool write_fault, bool *writable, pfn_t *pfn)
1058{
1059        struct page *page[1];
1060        int npages;
1061
1062        if (!(async || atomic))
1063                return false;
1064
1065        /*
1066         * Fast pin a writable pfn only if it is a write fault request
1067         * or the caller allows to map a writable pfn for a read fault
1068         * request.
1069         */
1070        if (!(write_fault || writable))
1071                return false;
1072
1073        npages = __get_user_pages_fast(addr, 1, 1, page);
1074        if (npages == 1) {
1075                *pfn = page_to_pfn(page[0]);
1076
1077                if (writable)
1078                        *writable = true;
1079                return true;
1080        }
1081
1082        return false;
1083}
1084
1085/*
1086 * The slow path to get the pfn of the specified host virtual address,
1087 * 1 indicates success, -errno is returned if error is detected.
1088 */
1089static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
1090                           bool *writable, pfn_t *pfn)
1091{
1092        struct page *page[1];
1093        int npages = 0;
1094
1095        might_sleep();
1096
1097        if (writable)
1098                *writable = write_fault;
1099
1100        if (async) {
1101                down_read(&current->mm->mmap_sem);
1102                npages = get_user_page_nowait(current, current->mm,
1103                                              addr, write_fault, page);
1104                up_read(&current->mm->mmap_sem);
1105        } else
1106                npages = get_user_pages_fast(addr, 1, write_fault,
1107                                             page);
1108        if (npages != 1)
1109                return npages;
1110
1111        /* map read fault as writable if possible */
1112        if (unlikely(!write_fault) && writable) {
1113                struct page *wpage[1];
1114
1115                npages = __get_user_pages_fast(addr, 1, 1, wpage);
1116                if (npages == 1) {
1117                        *writable = true;
1118                        put_page(page[0]);
1119                        page[0] = wpage[0];
1120                }
1121
1122                npages = 1;
1123        }
1124        *pfn = page_to_pfn(page[0]);
1125        return npages;
1126}
1127
1128static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
1129{
1130        if (unlikely(!(vma->vm_flags & VM_READ)))
1131                return false;
1132
1133        if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
1134                return false;
1135
1136        return true;
1137}
1138
1139/*
1140 * Pin guest page in memory and return its pfn.
1141 * @addr: host virtual address which maps memory to the guest
1142 * @atomic: whether this function can sleep
1143 * @async: whether this function need to wait IO complete if the
1144 *         host page is not in the memory
1145 * @write_fault: whether we should get a writable host page
1146 * @writable: whether it allows to map a writable host page for !@write_fault
1147 *
1148 * The function will map a writable host page for these two cases:
1149 * 1): @write_fault = true
1150 * 2): @write_fault = false && @writable, @writable will tell the caller
1151 *     whether the mapping is writable.
1152 */
1153static pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
1154                        bool write_fault, bool *writable)
1155{
1156        struct vm_area_struct *vma;
1157        pfn_t pfn = 0;
1158        int npages;
1159
1160        /* we can do it either atomically or asynchronously, not both */
1161        BUG_ON(atomic && async);
1162
1163        if (hva_to_pfn_fast(addr, atomic, async, write_fault, writable, &pfn))
1164                return pfn;
1165
1166        if (atomic)
1167                return KVM_PFN_ERR_FAULT;
1168
1169        npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
1170        if (npages == 1)
1171                return pfn;
1172
1173        down_read(&current->mm->mmap_sem);
1174        if (npages == -EHWPOISON ||
1175              (!async && check_user_page_hwpoison(addr))) {
1176                pfn = KVM_PFN_ERR_HWPOISON;
1177                goto exit;
1178        }
1179
1180        vma = find_vma_intersection(current->mm, addr, addr + 1);
1181
1182        if (vma == NULL)
1183                pfn = KVM_PFN_ERR_FAULT;
1184        else if ((vma->vm_flags & VM_PFNMAP)) {
1185                pfn = ((addr - vma->vm_start) >> PAGE_SHIFT) +
1186                        vma->vm_pgoff;
1187                BUG_ON(!kvm_is_mmio_pfn(pfn));
1188        } else {
1189                if (async && vma_is_valid(vma, write_fault))
1190                        *async = true;
1191                pfn = KVM_PFN_ERR_FAULT;
1192        }
1193exit:
1194        up_read(&current->mm->mmap_sem);
1195        return pfn;
1196}
1197
1198static pfn_t
1199__gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn, bool atomic,
1200                     bool *async, bool write_fault, bool *writable)
1201{
1202        unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
1203
1204        if (addr == KVM_HVA_ERR_RO_BAD)
1205                return KVM_PFN_ERR_RO_FAULT;
1206
1207        if (kvm_is_error_hva(addr))
1208                return KVM_PFN_ERR_BAD;
1209
1210        /* Do not map writable pfn in the readonly memslot. */
1211        if (writable && memslot_is_readonly(slot)) {
1212                *writable = false;
1213                writable = NULL;
1214        }
1215
1216        return hva_to_pfn(addr, atomic, async, write_fault,
1217                          writable);
1218}
1219
1220static pfn_t __gfn_to_pfn(struct kvm *kvm, gfn_t gfn, bool atomic, bool *async,
1221                          bool write_fault, bool *writable)
1222{
1223        struct kvm_memory_slot *slot;
1224
1225        if (async)
1226                *async = false;
1227
1228        slot = gfn_to_memslot(kvm, gfn);
1229
1230        return __gfn_to_pfn_memslot(slot, gfn, atomic, async, write_fault,
1231                                    writable);
1232}
1233
1234pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
1235{
1236        return __gfn_to_pfn(kvm, gfn, true, NULL, true, NULL);
1237}
1238EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
1239
1240pfn_t gfn_to_pfn_async(struct kvm *kvm, gfn_t gfn, bool *async,
1241                       bool write_fault, bool *writable)
1242{
1243        return __gfn_to_pfn(kvm, gfn, false, async, write_fault, writable);
1244}
1245EXPORT_SYMBOL_GPL(gfn_to_pfn_async);
1246
1247pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
1248{
1249        return __gfn_to_pfn(kvm, gfn, false, NULL, true, NULL);
1250}
1251EXPORT_SYMBOL_GPL(gfn_to_pfn);
1252
1253pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
1254                      bool *writable)
1255{
1256        return __gfn_to_pfn(kvm, gfn, false, NULL, write_fault, writable);
1257}
1258EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
1259
1260pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
1261{
1262        return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
1263}
1264
1265pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
1266{
1267        return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
1268}
1269EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
1270
1271int gfn_to_page_many_atomic(struct kvm *kvm, gfn_t gfn, struct page **pages,
1272                                                                  int nr_pages)
1273{
1274        unsigned long addr;
1275        gfn_t entry;
1276
1277        addr = gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, &entry);
1278        if (kvm_is_error_hva(addr))
1279                return -1;
1280
1281        if (entry < nr_pages)
1282                return 0;
1283
1284        return __get_user_pages_fast(addr, nr_pages, 1, pages);
1285}
1286EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
1287
1288static struct page *kvm_pfn_to_page(pfn_t pfn)
1289{
1290        if (is_error_pfn(pfn))
1291                return KVM_ERR_PTR_BAD_PAGE;
1292
1293        if (kvm_is_mmio_pfn(pfn)) {
1294                WARN_ON(1);
1295                return KVM_ERR_PTR_BAD_PAGE;
1296        }
1297
1298        return pfn_to_page(pfn);
1299}
1300
1301struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
1302{
1303        pfn_t pfn;
1304
1305        pfn = gfn_to_pfn(kvm, gfn);
1306
1307        return kvm_pfn_to_page(pfn);
1308}
1309
1310EXPORT_SYMBOL_GPL(gfn_to_page);
1311
1312void kvm_release_page_clean(struct page *page)
1313{
1314        WARN_ON(is_error_page(page));
1315
1316        kvm_release_pfn_clean(page_to_pfn(page));
1317}
1318EXPORT_SYMBOL_GPL(kvm_release_page_clean);
1319
1320void kvm_release_pfn_clean(pfn_t pfn)
1321{
1322        if (!is_error_pfn(pfn) && !kvm_is_mmio_pfn(pfn))
1323                put_page(pfn_to_page(pfn));
1324}
1325EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
1326
1327void kvm_release_page_dirty(struct page *page)
1328{
1329        WARN_ON(is_error_page(page));
1330
1331        kvm_release_pfn_dirty(page_to_pfn(page));
1332}
1333EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
1334
1335void kvm_release_pfn_dirty(pfn_t pfn)
1336{
1337        kvm_set_pfn_dirty(pfn);
1338        kvm_release_pfn_clean(pfn);
1339}
1340EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
1341
1342void kvm_set_page_dirty(struct page *page)
1343{
1344        kvm_set_pfn_dirty(page_to_pfn(page));
1345}
1346EXPORT_SYMBOL_GPL(kvm_set_page_dirty);
1347
1348void kvm_set_pfn_dirty(pfn_t pfn)
1349{
1350        if (!kvm_is_mmio_pfn(pfn)) {
1351                struct page *page = pfn_to_page(pfn);
1352                if (!PageReserved(page))
1353                        SetPageDirty(page);
1354        }
1355}
1356EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
1357
1358void kvm_set_pfn_accessed(pfn_t pfn)
1359{
1360        if (!kvm_is_mmio_pfn(pfn))
1361                mark_page_accessed(pfn_to_page(pfn));
1362}
1363EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
1364
1365void kvm_get_pfn(pfn_t pfn)
1366{
1367        if (!kvm_is_mmio_pfn(pfn))
1368                get_page(pfn_to_page(pfn));
1369}
1370EXPORT_SYMBOL_GPL(kvm_get_pfn);
1371
1372static int next_segment(unsigned long len, int offset)
1373{
1374        if (len > PAGE_SIZE - offset)
1375                return PAGE_SIZE - offset;
1376        else
1377                return len;
1378}
1379
1380int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
1381                        int len)
1382{
1383        int r;
1384        unsigned long addr;
1385
1386        addr = gfn_to_hva_read(kvm, gfn);
1387        if (kvm_is_error_hva(addr))
1388                return -EFAULT;
1389        r = kvm_read_hva(data, (void __user *)addr + offset, len);
1390        if (r)
1391                return -EFAULT;
1392        return 0;
1393}
1394EXPORT_SYMBOL_GPL(kvm_read_guest_page);
1395
1396int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
1397{
1398        gfn_t gfn = gpa >> PAGE_SHIFT;
1399        int seg;
1400        int offset = offset_in_page(gpa);
1401        int ret;
1402
1403        while ((seg = next_segment(len, offset)) != 0) {
1404                ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
1405                if (ret < 0)
1406                        return ret;
1407                offset = 0;
1408                len -= seg;
1409                data += seg;
1410                ++gfn;
1411        }
1412        return 0;
1413}
1414EXPORT_SYMBOL_GPL(kvm_read_guest);
1415
1416int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
1417                          unsigned long len)
1418{
1419        int r;
1420        unsigned long addr;
1421        gfn_t gfn = gpa >> PAGE_SHIFT;
1422        int offset = offset_in_page(gpa);
1423
1424        addr = gfn_to_hva_read(kvm, gfn);
1425        if (kvm_is_error_hva(addr))
1426                return -EFAULT;
1427        pagefault_disable();
1428        r = kvm_read_hva_atomic(data, (void __user *)addr + offset, len);
1429        pagefault_enable();
1430        if (r)
1431                return -EFAULT;
1432        return 0;
1433}
1434EXPORT_SYMBOL(kvm_read_guest_atomic);
1435
1436int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, const void *data,
1437                         int offset, int len)
1438{
1439        int r;
1440        unsigned long addr;
1441
1442        addr = gfn_to_hva(kvm, gfn);
1443        if (kvm_is_error_hva(addr))
1444                return -EFAULT;
1445        r = __copy_to_user((void __user *)addr + offset, data, len);
1446        if (r)
1447                return -EFAULT;
1448        mark_page_dirty(kvm, gfn);
1449        return 0;
1450}
1451EXPORT_SYMBOL_GPL(kvm_write_guest_page);
1452
1453int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
1454                    unsigned long len)
1455{
1456        gfn_t gfn = gpa >> PAGE_SHIFT;
1457        int seg;
1458        int offset = offset_in_page(gpa);
1459        int ret;
1460
1461        while ((seg = next_segment(len, offset)) != 0) {
1462                ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
1463                if (ret < 0)
1464                        return ret;
1465                offset = 0;
1466                len -= seg;
1467                data += seg;
1468                ++gfn;
1469        }
1470        return 0;
1471}
1472
1473int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1474                              gpa_t gpa)
1475{
1476        struct kvm_memslots *slots = kvm_memslots(kvm);
1477        int offset = offset_in_page(gpa);
1478        gfn_t gfn = gpa >> PAGE_SHIFT;
1479
1480        ghc->gpa = gpa;
1481        ghc->generation = slots->generation;
1482        ghc->memslot = gfn_to_memslot(kvm, gfn);
1483        ghc->hva = gfn_to_hva_many(ghc->memslot, gfn, NULL);
1484        if (!kvm_is_error_hva(ghc->hva))
1485                ghc->hva += offset;
1486        else
1487                return -EFAULT;
1488
1489        return 0;
1490}
1491EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
1492
1493int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1494                           void *data, unsigned long len)
1495{
1496        struct kvm_memslots *slots = kvm_memslots(kvm);
1497        int r;
1498
1499        if (slots->generation != ghc->generation)
1500                kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa);
1501
1502        if (kvm_is_error_hva(ghc->hva))
1503                return -EFAULT;
1504
1505        r = __copy_to_user((void __user *)ghc->hva, data, len);
1506        if (r)
1507                return -EFAULT;
1508        mark_page_dirty_in_slot(kvm, ghc->memslot, ghc->gpa >> PAGE_SHIFT);
1509
1510        return 0;
1511}
1512EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
1513
1514int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1515                           void *data, unsigned long len)
1516{
1517        struct kvm_memslots *slots = kvm_memslots(kvm);
1518        int r;
1519
1520        if (slots->generation != ghc->generation)
1521                kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa);
1522
1523        if (kvm_is_error_hva(ghc->hva))
1524                return -EFAULT;
1525
1526        r = __copy_from_user(data, (void __user *)ghc->hva, len);
1527        if (r)
1528                return -EFAULT;
1529
1530        return 0;
1531}
1532EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
1533
1534int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
1535{
1536        return kvm_write_guest_page(kvm, gfn, (const void *) empty_zero_page,
1537                                    offset, len);
1538}
1539EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
1540
1541int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
1542{
1543        gfn_t gfn = gpa >> PAGE_SHIFT;
1544        int seg;
1545        int offset = offset_in_page(gpa);
1546        int ret;
1547
1548        while ((seg = next_segment(len, offset)) != 0) {
1549                ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
1550                if (ret < 0)
1551                        return ret;
1552                offset = 0;
1553                len -= seg;
1554                ++gfn;
1555        }
1556        return 0;
1557}
1558EXPORT_SYMBOL_GPL(kvm_clear_guest);
1559
1560void mark_page_dirty_in_slot(struct kvm *kvm, struct kvm_memory_slot *memslot,
1561                             gfn_t gfn)
1562{
1563        if (memslot && memslot->dirty_bitmap) {
1564                unsigned long rel_gfn = gfn - memslot->base_gfn;
1565
1566                set_bit_le(rel_gfn, memslot->dirty_bitmap);
1567        }
1568}
1569
1570void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
1571{
1572        struct kvm_memory_slot *memslot;
1573
1574        memslot = gfn_to_memslot(kvm, gfn);
1575        mark_page_dirty_in_slot(kvm, memslot, gfn);
1576}
1577
1578/*
1579 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
1580 */
1581void kvm_vcpu_block(struct kvm_vcpu *vcpu)
1582{
1583        DEFINE_WAIT(wait);
1584
1585        for (;;) {
1586                prepare_to_wait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
1587
1588                if (kvm_arch_vcpu_runnable(vcpu)) {
1589                        kvm_make_request(KVM_REQ_UNHALT, vcpu);
1590                        break;
1591                }
1592                if (kvm_cpu_has_pending_timer(vcpu))
1593                        break;
1594                if (signal_pending(current))
1595                        break;
1596
1597                schedule();
1598        }
1599
1600        finish_wait(&vcpu->wq, &wait);
1601}
1602
1603#ifndef CONFIG_S390
1604/*
1605 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
1606 */
1607void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
1608{
1609        int me;
1610        int cpu = vcpu->cpu;
1611        wait_queue_head_t *wqp;
1612
1613        wqp = kvm_arch_vcpu_wq(vcpu);
1614        if (waitqueue_active(wqp)) {
1615                wake_up_interruptible(wqp);
1616                ++vcpu->stat.halt_wakeup;
1617        }
1618
1619        me = get_cpu();
1620        if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
1621                if (kvm_arch_vcpu_should_kick(vcpu))
1622                        smp_send_reschedule(cpu);
1623        put_cpu();
1624}
1625#endif /* !CONFIG_S390 */
1626
1627void kvm_resched(struct kvm_vcpu *vcpu)
1628{
1629        if (!need_resched())
1630                return;
1631        cond_resched();
1632}
1633EXPORT_SYMBOL_GPL(kvm_resched);
1634
1635bool kvm_vcpu_yield_to(struct kvm_vcpu *target)
1636{
1637        struct pid *pid;
1638        struct task_struct *task = NULL;
1639
1640        rcu_read_lock();
1641        pid = rcu_dereference(target->pid);
1642        if (pid)
1643                task = get_pid_task(target->pid, PIDTYPE_PID);
1644        rcu_read_unlock();
1645        if (!task)
1646                return false;
1647        if (task->flags & PF_VCPU) {
1648                put_task_struct(task);
1649                return false;
1650        }
1651        if (yield_to(task, 1)) {
1652                put_task_struct(task);
1653                return true;
1654        }
1655        put_task_struct(task);
1656        return false;
1657}
1658EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
1659
1660#ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
1661/*
1662 * Helper that checks whether a VCPU is eligible for directed yield.
1663 * Most eligible candidate to yield is decided by following heuristics:
1664 *
1665 *  (a) VCPU which has not done pl-exit or cpu relax intercepted recently
1666 *  (preempted lock holder), indicated by @in_spin_loop.
1667 *  Set at the beiginning and cleared at the end of interception/PLE handler.
1668 *
1669 *  (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
1670 *  chance last time (mostly it has become eligible now since we have probably
1671 *  yielded to lockholder in last iteration. This is done by toggling
1672 *  @dy_eligible each time a VCPU checked for eligibility.)
1673 *
1674 *  Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
1675 *  to preempted lock-holder could result in wrong VCPU selection and CPU
1676 *  burning. Giving priority for a potential lock-holder increases lock
1677 *  progress.
1678 *
1679 *  Since algorithm is based on heuristics, accessing another VCPU data without
1680 *  locking does not harm. It may result in trying to yield to  same VCPU, fail
1681 *  and continue with next VCPU and so on.
1682 */
1683bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
1684{
1685        bool eligible;
1686
1687        eligible = !vcpu->spin_loop.in_spin_loop ||
1688                        (vcpu->spin_loop.in_spin_loop &&
1689                         vcpu->spin_loop.dy_eligible);
1690
1691        if (vcpu->spin_loop.in_spin_loop)
1692                kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
1693
1694        return eligible;
1695}
1696#endif
1697void kvm_vcpu_on_spin(struct kvm_vcpu *me)
1698{
1699        struct kvm *kvm = me->kvm;
1700        struct kvm_vcpu *vcpu;
1701        int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
1702        int yielded = 0;
1703        int pass;
1704        int i;
1705
1706        kvm_vcpu_set_in_spin_loop(me, true);
1707        /*
1708         * We boost the priority of a VCPU that is runnable but not
1709         * currently running, because it got preempted by something
1710         * else and called schedule in __vcpu_run.  Hopefully that
1711         * VCPU is holding the lock that we need and will release it.
1712         * We approximate round-robin by starting at the last boosted VCPU.
1713         */
1714        for (pass = 0; pass < 2 && !yielded; pass++) {
1715                kvm_for_each_vcpu(i, vcpu, kvm) {
1716                        if (!pass && i <= last_boosted_vcpu) {
1717                                i = last_boosted_vcpu;
1718                                continue;
1719                        } else if (pass && i > last_boosted_vcpu)
1720                                break;
1721                        if (vcpu == me)
1722                                continue;
1723                        if (waitqueue_active(&vcpu->wq))
1724                                continue;
1725                        if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
1726                                continue;
1727                        if (kvm_vcpu_yield_to(vcpu)) {
1728                                kvm->last_boosted_vcpu = i;
1729                                yielded = 1;
1730                                break;
1731                        }
1732                }
1733        }
1734        kvm_vcpu_set_in_spin_loop(me, false);
1735
1736        /* Ensure vcpu is not eligible during next spinloop */
1737        kvm_vcpu_set_dy_eligible(me, false);
1738}
1739EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
1740
1741static int kvm_vcpu_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1742{
1743        struct kvm_vcpu *vcpu = vma->vm_file->private_data;
1744        struct page *page;
1745
1746        if (vmf->pgoff == 0)
1747                page = virt_to_page(vcpu->run);
1748#ifdef CONFIG_X86
1749        else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
1750                page = virt_to_page(vcpu->arch.pio_data);
1751#endif
1752#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
1753        else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
1754                page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
1755#endif
1756        else
1757                return kvm_arch_vcpu_fault(vcpu, vmf);
1758        get_page(page);
1759        vmf->page = page;
1760        return 0;
1761}
1762
1763static const struct vm_operations_struct kvm_vcpu_vm_ops = {
1764        .fault = kvm_vcpu_fault,
1765};
1766
1767static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
1768{
1769        vma->vm_ops = &kvm_vcpu_vm_ops;
1770        return 0;
1771}
1772
1773static int kvm_vcpu_release(struct inode *inode, struct file *filp)
1774{
1775        struct kvm_vcpu *vcpu = filp->private_data;
1776
1777        kvm_put_kvm(vcpu->kvm);
1778        return 0;
1779}
1780
1781static struct file_operations kvm_vcpu_fops = {
1782        .release        = kvm_vcpu_release,
1783        .unlocked_ioctl = kvm_vcpu_ioctl,
1784#ifdef CONFIG_COMPAT
1785        .compat_ioctl   = kvm_vcpu_compat_ioctl,
1786#endif
1787        .mmap           = kvm_vcpu_mmap,
1788        .llseek         = noop_llseek,
1789};
1790
1791/*
1792 * Allocates an inode for the vcpu.
1793 */
1794static int create_vcpu_fd(struct kvm_vcpu *vcpu)
1795{
1796        return anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, O_RDWR);
1797}
1798
1799/*
1800 * Creates some virtual cpus.  Good luck creating more than one.
1801 */
1802static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
1803{
1804        int r;
1805        struct kvm_vcpu *vcpu, *v;
1806
1807        vcpu = kvm_arch_vcpu_create(kvm, id);
1808        if (IS_ERR(vcpu))
1809                return PTR_ERR(vcpu);
1810
1811        preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
1812
1813        r = kvm_arch_vcpu_setup(vcpu);
1814        if (r)
1815                goto vcpu_destroy;
1816
1817        mutex_lock(&kvm->lock);
1818        if (!kvm_vcpu_compatible(vcpu)) {
1819                r = -EINVAL;
1820                goto unlock_vcpu_destroy;
1821        }
1822        if (atomic_read(&kvm->online_vcpus) == KVM_MAX_VCPUS) {
1823                r = -EINVAL;
1824                goto unlock_vcpu_destroy;
1825        }
1826
1827        kvm_for_each_vcpu(r, v, kvm)
1828                if (v->vcpu_id == id) {
1829                        r = -EEXIST;
1830                        goto unlock_vcpu_destroy;
1831                }
1832
1833        BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
1834
1835        /* Now it's all set up, let userspace reach it */
1836        kvm_get_kvm(kvm);
1837        r = create_vcpu_fd(vcpu);
1838        if (r < 0) {
1839                kvm_put_kvm(kvm);
1840                goto unlock_vcpu_destroy;
1841        }
1842
1843        kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
1844        smp_wmb();
1845        atomic_inc(&kvm->online_vcpus);
1846
1847        mutex_unlock(&kvm->lock);
1848        return r;
1849
1850unlock_vcpu_destroy:
1851        mutex_unlock(&kvm->lock);
1852vcpu_destroy:
1853        kvm_arch_vcpu_destroy(vcpu);
1854        return r;
1855}
1856
1857static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
1858{
1859        if (sigset) {
1860                sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
1861                vcpu->sigset_active = 1;
1862                vcpu->sigset = *sigset;
1863        } else
1864                vcpu->sigset_active = 0;
1865        return 0;
1866}
1867
1868static long kvm_vcpu_ioctl(struct file *filp,
1869                           unsigned int ioctl, unsigned long arg)
1870{
1871        struct kvm_vcpu *vcpu = filp->private_data;
1872        void __user *argp = (void __user *)arg;
1873        int r;
1874        struct kvm_fpu *fpu = NULL;
1875        struct kvm_sregs *kvm_sregs = NULL;
1876
1877        if (vcpu->kvm->mm != current->mm)
1878                return -EIO;
1879
1880#if defined(CONFIG_S390) || defined(CONFIG_PPC)
1881        /*
1882         * Special cases: vcpu ioctls that are asynchronous to vcpu execution,
1883         * so vcpu_load() would break it.
1884         */
1885        if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_INTERRUPT)
1886                return kvm_arch_vcpu_ioctl(filp, ioctl, arg);
1887#endif
1888
1889
1890        r = vcpu_load(vcpu);
1891        if (r)
1892                return r;
1893        switch (ioctl) {
1894        case KVM_RUN:
1895                r = -EINVAL;
1896                if (arg)
1897                        goto out;
1898                r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
1899                trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
1900                break;
1901        case KVM_GET_REGS: {
1902                struct kvm_regs *kvm_regs;
1903
1904                r = -ENOMEM;
1905                kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
1906                if (!kvm_regs)
1907                        goto out;
1908                r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
1909                if (r)
1910                        goto out_free1;
1911                r = -EFAULT;
1912                if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
1913                        goto out_free1;
1914                r = 0;
1915out_free1:
1916                kfree(kvm_regs);
1917                break;
1918        }
1919        case KVM_SET_REGS: {
1920                struct kvm_regs *kvm_regs;
1921
1922                r = -ENOMEM;
1923                kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
1924                if (IS_ERR(kvm_regs)) {
1925                        r = PTR_ERR(kvm_regs);
1926                        goto out;
1927                }
1928                r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
1929                if (r)
1930                        goto out_free2;
1931                r = 0;
1932out_free2:
1933                kfree(kvm_regs);
1934                break;
1935        }
1936        case KVM_GET_SREGS: {
1937                kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
1938                r = -ENOMEM;
1939                if (!kvm_sregs)
1940                        goto out;
1941                r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
1942                if (r)
1943                        goto out;
1944                r = -EFAULT;
1945                if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
1946                        goto out;
1947                r = 0;
1948                break;
1949        }
1950        case KVM_SET_SREGS: {
1951                kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
1952                if (IS_ERR(kvm_sregs)) {
1953                        r = PTR_ERR(kvm_sregs);
1954                        goto out;
1955                }
1956                r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
1957                if (r)
1958                        goto out;
1959                r = 0;
1960                break;
1961        }
1962        case KVM_GET_MP_STATE: {
1963                struct kvm_mp_state mp_state;
1964
1965                r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
1966                if (r)
1967                        goto out;
1968                r = -EFAULT;
1969                if (copy_to_user(argp, &mp_state, sizeof mp_state))
1970                        goto out;
1971                r = 0;
1972                break;
1973        }
1974        case KVM_SET_MP_STATE: {
1975                struct kvm_mp_state mp_state;
1976
1977                r = -EFAULT;
1978                if (copy_from_user(&mp_state, argp, sizeof mp_state))
1979                        goto out;
1980                r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
1981                if (r)
1982                        goto out;
1983                r = 0;
1984                break;
1985        }
1986        case KVM_TRANSLATE: {
1987                struct kvm_translation tr;
1988
1989                r = -EFAULT;
1990                if (copy_from_user(&tr, argp, sizeof tr))
1991                        goto out;
1992                r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
1993                if (r)
1994                        goto out;
1995                r = -EFAULT;
1996                if (copy_to_user(argp, &tr, sizeof tr))
1997                        goto out;
1998                r = 0;
1999                break;
2000        }
2001        case KVM_SET_GUEST_DEBUG: {
2002                struct kvm_guest_debug dbg;
2003
2004                r = -EFAULT;
2005                if (copy_from_user(&dbg, argp, sizeof dbg))
2006                        goto out;
2007                r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
2008                if (r)
2009                        goto out;
2010                r = 0;
2011                break;
2012        }
2013        case KVM_SET_SIGNAL_MASK: {
2014                struct kvm_signal_mask __user *sigmask_arg = argp;
2015                struct kvm_signal_mask kvm_sigmask;
2016                sigset_t sigset, *p;
2017
2018                p = NULL;
2019                if (argp) {
2020                        r = -EFAULT;
2021                        if (copy_from_user(&kvm_sigmask, argp,
2022                                           sizeof kvm_sigmask))
2023                                goto out;
2024                        r = -EINVAL;
2025                        if (kvm_sigmask.len != sizeof sigset)
2026                                goto out;
2027                        r = -EFAULT;
2028                        if (copy_from_user(&sigset, sigmask_arg->sigset,
2029                                           sizeof sigset))
2030                                goto out;
2031                        p = &sigset;
2032                }
2033                r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
2034                break;
2035        }
2036        case KVM_GET_FPU: {
2037                fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
2038                r = -ENOMEM;
2039                if (!fpu)
2040                        goto out;
2041                r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
2042                if (r)
2043                        goto out;
2044                r = -EFAULT;
2045                if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
2046                        goto out;
2047                r = 0;
2048                break;
2049        }
2050        case KVM_SET_FPU: {
2051                fpu = memdup_user(argp, sizeof(*fpu));
2052                if (IS_ERR(fpu)) {
2053                        r = PTR_ERR(fpu);
2054                        goto out;
2055                }
2056                r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
2057                if (r)
2058                        goto out;
2059                r = 0;
2060                break;
2061        }
2062        default:
2063                r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
2064        }
2065out:
2066        vcpu_put(vcpu);
2067        kfree(fpu);
2068        kfree(kvm_sregs);
2069        return r;
2070}
2071
2072#ifdef CONFIG_COMPAT
2073static long kvm_vcpu_compat_ioctl(struct file *filp,
2074                                  unsigned int ioctl, unsigned long arg)
2075{
2076        struct kvm_vcpu *vcpu = filp->private_data;
2077        void __user *argp = compat_ptr(arg);
2078        int r;
2079
2080        if (vcpu->kvm->mm != current->mm)
2081                return -EIO;
2082
2083        switch (ioctl) {
2084        case KVM_SET_SIGNAL_MASK: {
2085                struct kvm_signal_mask __user *sigmask_arg = argp;
2086                struct kvm_signal_mask kvm_sigmask;
2087                compat_sigset_t csigset;
2088                sigset_t sigset;
2089
2090                if (argp) {
2091                        r = -EFAULT;
2092                        if (copy_from_user(&kvm_sigmask, argp,
2093                                           sizeof kvm_sigmask))
2094                                goto out;
2095                        r = -EINVAL;
2096                        if (kvm_sigmask.len != sizeof csigset)
2097                                goto out;
2098                        r = -EFAULT;
2099                        if (copy_from_user(&csigset, sigmask_arg->sigset,
2100                                           sizeof csigset))
2101                                goto out;
2102                        sigset_from_compat(&sigset, &csigset);
2103                        r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
2104                } else
2105                        r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
2106                break;
2107        }
2108        default:
2109                r = kvm_vcpu_ioctl(filp, ioctl, arg);
2110        }
2111
2112out:
2113        return r;
2114}
2115#endif
2116
2117static long kvm_vm_ioctl(struct file *filp,
2118                           unsigned int ioctl, unsigned long arg)
2119{
2120        struct kvm *kvm = filp->private_data;
2121        void __user *argp = (void __user *)arg;
2122        int r;
2123
2124        if (kvm->mm != current->mm)
2125                return -EIO;
2126        switch (ioctl) {
2127        case KVM_CREATE_VCPU:
2128                r = kvm_vm_ioctl_create_vcpu(kvm, arg);
2129                if (r < 0)
2130                        goto out;
2131                break;
2132        case KVM_SET_USER_MEMORY_REGION: {
2133                struct kvm_userspace_memory_region kvm_userspace_mem;
2134
2135                r = -EFAULT;
2136                if (copy_from_user(&kvm_userspace_mem, argp,
2137                                                sizeof kvm_userspace_mem))
2138                        goto out;
2139
2140                r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 1);
2141                if (r)
2142                        goto out;
2143                break;
2144        }
2145        case KVM_GET_DIRTY_LOG: {
2146                struct kvm_dirty_log log;
2147
2148                r = -EFAULT;
2149                if (copy_from_user(&log, argp, sizeof log))
2150                        goto out;
2151                r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
2152                if (r)
2153                        goto out;
2154                break;
2155        }
2156#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2157        case KVM_REGISTER_COALESCED_MMIO: {
2158                struct kvm_coalesced_mmio_zone zone;
2159                r = -EFAULT;
2160                if (copy_from_user(&zone, argp, sizeof zone))
2161                        goto out;
2162                r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
2163                if (r)
2164                        goto out;
2165                r = 0;
2166                break;
2167        }
2168        case KVM_UNREGISTER_COALESCED_MMIO: {
2169                struct kvm_coalesced_mmio_zone zone;
2170                r = -EFAULT;
2171                if (copy_from_user(&zone, argp, sizeof zone))
2172                        goto out;
2173                r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
2174                if (r)
2175                        goto out;
2176                r = 0;
2177                break;
2178        }
2179#endif
2180        case KVM_IRQFD: {
2181                struct kvm_irqfd data;
2182
2183                r = -EFAULT;
2184                if (copy_from_user(&data, argp, sizeof data))
2185                        goto out;
2186                r = kvm_irqfd(kvm, &data);
2187                break;
2188        }
2189        case KVM_IOEVENTFD: {
2190                struct kvm_ioeventfd data;
2191
2192                r = -EFAULT;
2193                if (copy_from_user(&data, argp, sizeof data))
2194                        goto out;
2195                r = kvm_ioeventfd(kvm, &data);
2196                break;
2197        }
2198#ifdef CONFIG_KVM_APIC_ARCHITECTURE
2199        case KVM_SET_BOOT_CPU_ID:
2200                r = 0;
2201                mutex_lock(&kvm->lock);
2202                if (atomic_read(&kvm->online_vcpus) != 0)
2203                        r = -EBUSY;
2204                else
2205                        kvm->bsp_vcpu_id = arg;
2206                mutex_unlock(&kvm->lock);
2207                break;
2208#endif
2209#ifdef CONFIG_HAVE_KVM_MSI
2210        case KVM_SIGNAL_MSI: {
2211                struct kvm_msi msi;
2212
2213                r = -EFAULT;
2214                if (copy_from_user(&msi, argp, sizeof msi))
2215                        goto out;
2216                r = kvm_send_userspace_msi(kvm, &msi);
2217                break;
2218        }
2219#endif
2220#ifdef __KVM_HAVE_IRQ_LINE
2221        case KVM_IRQ_LINE_STATUS:
2222        case KVM_IRQ_LINE: {
2223                struct kvm_irq_level irq_event;
2224
2225                r = -EFAULT;
2226                if (copy_from_user(&irq_event, argp, sizeof irq_event))
2227                        goto out;
2228
2229                r = kvm_vm_ioctl_irq_line(kvm, &irq_event);
2230                if (r)
2231                        goto out;
2232
2233                r = -EFAULT;
2234                if (ioctl == KVM_IRQ_LINE_STATUS) {
2235                        if (copy_to_user(argp, &irq_event, sizeof irq_event))
2236                                goto out;
2237                }
2238
2239                r = 0;
2240                break;
2241        }
2242#endif
2243        default:
2244                r = kvm_arch_vm_ioctl(filp, ioctl, arg);
2245                if (r == -ENOTTY)
2246                        r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
2247        }
2248out:
2249        return r;
2250}
2251
2252#ifdef CONFIG_COMPAT
2253struct compat_kvm_dirty_log {
2254        __u32 slot;
2255        __u32 padding1;
2256        union {
2257                compat_uptr_t dirty_bitmap; /* one bit per page */
2258                __u64 padding2;
2259        };
2260};
2261
2262static long kvm_vm_compat_ioctl(struct file *filp,
2263                           unsigned int ioctl, unsigned long arg)
2264{
2265        struct kvm *kvm = filp->private_data;
2266        int r;
2267
2268        if (kvm->mm != current->mm)
2269                return -EIO;
2270        switch (ioctl) {
2271        case KVM_GET_DIRTY_LOG: {
2272                struct compat_kvm_dirty_log compat_log;
2273                struct kvm_dirty_log log;
2274
2275                r = -EFAULT;
2276                if (copy_from_user(&compat_log, (void __user *)arg,
2277                                   sizeof(compat_log)))
2278                        goto out;
2279                log.slot         = compat_log.slot;
2280                log.padding1     = compat_log.padding1;
2281                log.padding2     = compat_log.padding2;
2282                log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
2283
2284                r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
2285                if (r)
2286                        goto out;
2287                break;
2288        }
2289        default:
2290                r = kvm_vm_ioctl(filp, ioctl, arg);
2291        }
2292
2293out:
2294        return r;
2295}
2296#endif
2297
2298static int kvm_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
2299{
2300        struct page *page[1];
2301        unsigned long addr;
2302        int npages;
2303        gfn_t gfn = vmf->pgoff;
2304        struct kvm *kvm = vma->vm_file->private_data;
2305
2306        addr = gfn_to_hva(kvm, gfn);
2307        if (kvm_is_error_hva(addr))
2308                return VM_FAULT_SIGBUS;
2309
2310        npages = get_user_pages(current, current->mm, addr, 1, 1, 0, page,
2311                                NULL);
2312        if (unlikely(npages != 1))
2313                return VM_FAULT_SIGBUS;
2314
2315        vmf->page = page[0];
2316        return 0;
2317}
2318
2319static const struct vm_operations_struct kvm_vm_vm_ops = {
2320        .fault = kvm_vm_fault,
2321};
2322
2323static int kvm_vm_mmap(struct file *file, struct vm_area_struct *vma)
2324{
2325        vma->vm_ops = &kvm_vm_vm_ops;
2326        return 0;
2327}
2328
2329static struct file_operations kvm_vm_fops = {
2330        .release        = kvm_vm_release,
2331        .unlocked_ioctl = kvm_vm_ioctl,
2332#ifdef CONFIG_COMPAT
2333        .compat_ioctl   = kvm_vm_compat_ioctl,
2334#endif
2335        .mmap           = kvm_vm_mmap,
2336        .llseek         = noop_llseek,
2337};
2338
2339static int kvm_dev_ioctl_create_vm(unsigned long type)
2340{
2341        int r;
2342        struct kvm *kvm;
2343
2344        kvm = kvm_create_vm(type);
2345        if (IS_ERR(kvm))
2346                return PTR_ERR(kvm);
2347#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2348        r = kvm_coalesced_mmio_init(kvm);
2349        if (r < 0) {
2350                kvm_put_kvm(kvm);
2351                return r;
2352        }
2353#endif
2354        r = anon_inode_getfd("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
2355        if (r < 0)
2356                kvm_put_kvm(kvm);
2357
2358        return r;
2359}
2360
2361static long kvm_dev_ioctl_check_extension_generic(long arg)
2362{
2363        switch (arg) {
2364        case KVM_CAP_USER_MEMORY:
2365        case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
2366        case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
2367#ifdef CONFIG_KVM_APIC_ARCHITECTURE
2368        case KVM_CAP_SET_BOOT_CPU_ID:
2369#endif
2370        case KVM_CAP_INTERNAL_ERROR_DATA:
2371#ifdef CONFIG_HAVE_KVM_MSI
2372        case KVM_CAP_SIGNAL_MSI:
2373#endif
2374                return 1;
2375#ifdef KVM_CAP_IRQ_ROUTING
2376        case KVM_CAP_IRQ_ROUTING:
2377                return KVM_MAX_IRQ_ROUTES;
2378#endif
2379        default:
2380                break;
2381        }
2382        return kvm_dev_ioctl_check_extension(arg);
2383}
2384
2385static long kvm_dev_ioctl(struct file *filp,
2386                          unsigned int ioctl, unsigned long arg)
2387{
2388        long r = -EINVAL;
2389
2390        switch (ioctl) {
2391        case KVM_GET_API_VERSION:
2392                r = -EINVAL;
2393                if (arg)
2394                        goto out;
2395                r = KVM_API_VERSION;
2396                break;
2397        case KVM_CREATE_VM:
2398                r = kvm_dev_ioctl_create_vm(arg);
2399                break;
2400        case KVM_CHECK_EXTENSION:
2401                r = kvm_dev_ioctl_check_extension_generic(arg);
2402                break;
2403        case KVM_GET_VCPU_MMAP_SIZE:
2404                r = -EINVAL;
2405                if (arg)
2406                        goto out;
2407                r = PAGE_SIZE;     /* struct kvm_run */
2408#ifdef CONFIG_X86
2409                r += PAGE_SIZE;    /* pio data page */
2410#endif
2411#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2412                r += PAGE_SIZE;    /* coalesced mmio ring page */
2413#endif
2414                break;
2415        case KVM_TRACE_ENABLE:
2416        case KVM_TRACE_PAUSE:
2417        case KVM_TRACE_DISABLE:
2418                r = -EOPNOTSUPP;
2419                break;
2420        default:
2421                return kvm_arch_dev_ioctl(filp, ioctl, arg);
2422        }
2423out:
2424        return r;
2425}
2426
2427static struct file_operations kvm_chardev_ops = {
2428        .unlocked_ioctl = kvm_dev_ioctl,
2429        .compat_ioctl   = kvm_dev_ioctl,
2430        .llseek         = noop_llseek,
2431};
2432
2433static struct miscdevice kvm_dev = {
2434        KVM_MINOR,
2435        "kvm",
2436        &kvm_chardev_ops,
2437};
2438
2439static void hardware_enable_nolock(void *junk)
2440{
2441        int cpu = raw_smp_processor_id();
2442        int r;
2443
2444        if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
2445                return;
2446
2447        cpumask_set_cpu(cpu, cpus_hardware_enabled);
2448
2449        r = kvm_arch_hardware_enable(NULL);
2450
2451        if (r) {
2452                cpumask_clear_cpu(cpu, cpus_hardware_enabled);
2453                atomic_inc(&hardware_enable_failed);
2454                printk(KERN_INFO "kvm: enabling virtualization on "
2455                                 "CPU%d failed\n", cpu);
2456        }
2457}
2458
2459static void hardware_enable(void *junk)
2460{
2461        raw_spin_lock(&kvm_lock);
2462        hardware_enable_nolock(junk);
2463        raw_spin_unlock(&kvm_lock);
2464}
2465
2466static void hardware_disable_nolock(void *junk)
2467{
2468        int cpu = raw_smp_processor_id();
2469
2470        if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
2471                return;
2472        cpumask_clear_cpu(cpu, cpus_hardware_enabled);
2473        kvm_arch_hardware_disable(NULL);
2474}
2475
2476static void hardware_disable(void *junk)
2477{
2478        raw_spin_lock(&kvm_lock);
2479        hardware_disable_nolock(junk);
2480        raw_spin_unlock(&kvm_lock);
2481}
2482
2483static void hardware_disable_all_nolock(void)
2484{
2485        BUG_ON(!kvm_usage_count);
2486
2487        kvm_usage_count--;
2488        if (!kvm_usage_count)
2489                on_each_cpu(hardware_disable_nolock, NULL, 1);
2490}
2491
2492static void hardware_disable_all(void)
2493{
2494        raw_spin_lock(&kvm_lock);
2495        hardware_disable_all_nolock();
2496        raw_spin_unlock(&kvm_lock);
2497}
2498
2499static int hardware_enable_all(void)
2500{
2501        int r = 0;
2502
2503        raw_spin_lock(&kvm_lock);
2504
2505        kvm_usage_count++;
2506        if (kvm_usage_count == 1) {
2507                atomic_set(&hardware_enable_failed, 0);
2508                on_each_cpu(hardware_enable_nolock, NULL, 1);
2509
2510                if (atomic_read(&hardware_enable_failed)) {
2511                        hardware_disable_all_nolock();
2512                        r = -EBUSY;
2513                }
2514        }
2515
2516        raw_spin_unlock(&kvm_lock);
2517
2518        return r;
2519}
2520
2521static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
2522                           void *v)
2523{
2524        int cpu = (long)v;
2525
2526        if (!kvm_usage_count)
2527                return NOTIFY_OK;
2528
2529        val &= ~CPU_TASKS_FROZEN;
2530        switch (val) {
2531        case CPU_DYING:
2532                printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
2533                       cpu);
2534                hardware_disable(NULL);
2535                break;
2536        case CPU_STARTING:
2537                printk(KERN_INFO "kvm: enabling virtualization on CPU%d\n",
2538                       cpu);
2539                hardware_enable(NULL);
2540                break;
2541        }
2542        return NOTIFY_OK;
2543}
2544
2545
2546asmlinkage void kvm_spurious_fault(void)
2547{
2548        /* Fault while not rebooting.  We want the trace. */
2549        BUG();
2550}
2551EXPORT_SYMBOL_GPL(kvm_spurious_fault);
2552
2553static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
2554                      void *v)
2555{
2556        /*
2557         * Some (well, at least mine) BIOSes hang on reboot if
2558         * in vmx root mode.
2559         *
2560         * And Intel TXT required VMX off for all cpu when system shutdown.
2561         */
2562        printk(KERN_INFO "kvm: exiting hardware virtualization\n");
2563        kvm_rebooting = true;
2564        on_each_cpu(hardware_disable_nolock, NULL, 1);
2565        return NOTIFY_OK;
2566}
2567
2568static struct notifier_block kvm_reboot_notifier = {
2569        .notifier_call = kvm_reboot,
2570        .priority = 0,
2571};
2572
2573static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
2574{
2575        int i;
2576
2577        for (i = 0; i < bus->dev_count; i++) {
2578                struct kvm_io_device *pos = bus->range[i].dev;
2579
2580                kvm_iodevice_destructor(pos);
2581        }
2582        kfree(bus);
2583}
2584
2585int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
2586{
2587        const struct kvm_io_range *r1 = p1;
2588        const struct kvm_io_range *r2 = p2;
2589
2590        if (r1->addr < r2->addr)
2591                return -1;
2592        if (r1->addr + r1->len > r2->addr + r2->len)
2593                return 1;
2594        return 0;
2595}
2596
2597int kvm_io_bus_insert_dev(struct kvm_io_bus *bus, struct kvm_io_device *dev,
2598                          gpa_t addr, int len)
2599{
2600        bus->range[bus->dev_count++] = (struct kvm_io_range) {
2601                .addr = addr,
2602                .len = len,
2603                .dev = dev,
2604        };
2605
2606        sort(bus->range, bus->dev_count, sizeof(struct kvm_io_range),
2607                kvm_io_bus_sort_cmp, NULL);
2608
2609        return 0;
2610}
2611
2612int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
2613                             gpa_t addr, int len)
2614{
2615        struct kvm_io_range *range, key;
2616        int off;
2617
2618        key = (struct kvm_io_range) {
2619                .addr = addr,
2620                .len = len,
2621        };
2622
2623        range = bsearch(&key, bus->range, bus->dev_count,
2624                        sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
2625        if (range == NULL)
2626                return -ENOENT;
2627
2628        off = range - bus->range;
2629
2630        while (off > 0 && kvm_io_bus_sort_cmp(&key, &bus->range[off-1]) == 0)
2631                off--;
2632
2633        return off;
2634}
2635
2636/* kvm_io_bus_write - called under kvm->slots_lock */
2637int kvm_io_bus_write(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
2638                     int len, const void *val)
2639{
2640        int idx;
2641        struct kvm_io_bus *bus;
2642        struct kvm_io_range range;
2643
2644        range = (struct kvm_io_range) {
2645                .addr = addr,
2646                .len = len,
2647        };
2648
2649        bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
2650        idx = kvm_io_bus_get_first_dev(bus, addr, len);
2651        if (idx < 0)
2652                return -EOPNOTSUPP;
2653
2654        while (idx < bus->dev_count &&
2655                kvm_io_bus_sort_cmp(&range, &bus->range[idx]) == 0) {
2656                if (!kvm_iodevice_write(bus->range[idx].dev, addr, len, val))
2657                        return 0;
2658                idx++;
2659        }
2660
2661        return -EOPNOTSUPP;
2662}
2663
2664/* kvm_io_bus_read - called under kvm->slots_lock */
2665int kvm_io_bus_read(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
2666                    int len, void *val)
2667{
2668        int idx;
2669        struct kvm_io_bus *bus;
2670        struct kvm_io_range range;
2671
2672        range = (struct kvm_io_range) {
2673                .addr = addr,
2674                .len = len,
2675        };
2676
2677        bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
2678        idx = kvm_io_bus_get_first_dev(bus, addr, len);
2679        if (idx < 0)
2680                return -EOPNOTSUPP;
2681
2682        while (idx < bus->dev_count &&
2683                kvm_io_bus_sort_cmp(&range, &bus->range[idx]) == 0) {
2684                if (!kvm_iodevice_read(bus->range[idx].dev, addr, len, val))
2685                        return 0;
2686                idx++;
2687        }
2688
2689        return -EOPNOTSUPP;
2690}
2691
2692/* Caller must hold slots_lock. */
2693int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
2694                            int len, struct kvm_io_device *dev)
2695{
2696        struct kvm_io_bus *new_bus, *bus;
2697
2698        bus = kvm->buses[bus_idx];
2699        if (bus->dev_count > NR_IOBUS_DEVS - 1)
2700                return -ENOSPC;
2701
2702        new_bus = kzalloc(sizeof(*bus) + ((bus->dev_count + 1) *
2703                          sizeof(struct kvm_io_range)), GFP_KERNEL);
2704        if (!new_bus)
2705                return -ENOMEM;
2706        memcpy(new_bus, bus, sizeof(*bus) + (bus->dev_count *
2707               sizeof(struct kvm_io_range)));
2708        kvm_io_bus_insert_dev(new_bus, dev, addr, len);
2709        rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
2710        synchronize_srcu_expedited(&kvm->srcu);
2711        kfree(bus);
2712
2713        return 0;
2714}
2715
2716/* Caller must hold slots_lock. */
2717int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
2718                              struct kvm_io_device *dev)
2719{
2720        int i, r;
2721        struct kvm_io_bus *new_bus, *bus;
2722
2723        bus = kvm->buses[bus_idx];
2724        r = -ENOENT;
2725        for (i = 0; i < bus->dev_count; i++)
2726                if (bus->range[i].dev == dev) {
2727                        r = 0;
2728                        break;
2729                }
2730
2731        if (r)
2732                return r;
2733
2734        new_bus = kzalloc(sizeof(*bus) + ((bus->dev_count - 1) *
2735                          sizeof(struct kvm_io_range)), GFP_KERNEL);
2736        if (!new_bus)
2737                return -ENOMEM;
2738
2739        memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
2740        new_bus->dev_count--;
2741        memcpy(new_bus->range + i, bus->range + i + 1,
2742               (new_bus->dev_count - i) * sizeof(struct kvm_io_range));
2743
2744        rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
2745        synchronize_srcu_expedited(&kvm->srcu);
2746        kfree(bus);
2747        return r;
2748}
2749
2750static struct notifier_block kvm_cpu_notifier = {
2751        .notifier_call = kvm_cpu_hotplug,
2752};
2753
2754static int vm_stat_get(void *_offset, u64 *val)
2755{
2756        unsigned offset = (long)_offset;
2757        struct kvm *kvm;
2758
2759        *val = 0;
2760        raw_spin_lock(&kvm_lock);
2761        list_for_each_entry(kvm, &vm_list, vm_list)
2762                *val += *(u32 *)((void *)kvm + offset);
2763        raw_spin_unlock(&kvm_lock);
2764        return 0;
2765}
2766
2767DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, NULL, "%llu\n");
2768
2769static int vcpu_stat_get(void *_offset, u64 *val)
2770{
2771        unsigned offset = (long)_offset;
2772        struct kvm *kvm;
2773        struct kvm_vcpu *vcpu;
2774        int i;
2775
2776        *val = 0;
2777        raw_spin_lock(&kvm_lock);
2778        list_for_each_entry(kvm, &vm_list, vm_list)
2779                kvm_for_each_vcpu(i, vcpu, kvm)
2780                        *val += *(u32 *)((void *)vcpu + offset);
2781
2782        raw_spin_unlock(&kvm_lock);
2783        return 0;
2784}
2785
2786DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, NULL, "%llu\n");
2787
2788static const struct file_operations *stat_fops[] = {
2789        [KVM_STAT_VCPU] = &vcpu_stat_fops,
2790        [KVM_STAT_VM]   = &vm_stat_fops,
2791};
2792
2793static int kvm_init_debug(void)
2794{
2795        int r = -EFAULT;
2796        struct kvm_stats_debugfs_item *p;
2797
2798        kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
2799        if (kvm_debugfs_dir == NULL)
2800                goto out;
2801
2802        for (p = debugfs_entries; p->name; ++p) {
2803                p->dentry = debugfs_create_file(p->name, 0444, kvm_debugfs_dir,
2804                                                (void *)(long)p->offset,
2805                                                stat_fops[p->kind]);
2806                if (p->dentry == NULL)
2807                        goto out_dir;
2808        }
2809
2810        return 0;
2811
2812out_dir:
2813        debugfs_remove_recursive(kvm_debugfs_dir);
2814out:
2815        return r;
2816}
2817
2818static void kvm_exit_debug(void)
2819{
2820        struct kvm_stats_debugfs_item *p;
2821
2822        for (p = debugfs_entries; p->name; ++p)
2823                debugfs_remove(p->dentry);
2824        debugfs_remove(kvm_debugfs_dir);
2825}
2826
2827static int kvm_suspend(void)
2828{
2829        if (kvm_usage_count)
2830                hardware_disable_nolock(NULL);
2831        return 0;
2832}
2833
2834static void kvm_resume(void)
2835{
2836        if (kvm_usage_count) {
2837                WARN_ON(raw_spin_is_locked(&kvm_lock));
2838                hardware_enable_nolock(NULL);
2839        }
2840}
2841
2842static struct syscore_ops kvm_syscore_ops = {
2843        .suspend = kvm_suspend,
2844        .resume = kvm_resume,
2845};
2846
2847static inline
2848struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
2849{
2850        return container_of(pn, struct kvm_vcpu, preempt_notifier);
2851}
2852
2853static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
2854{
2855        struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
2856
2857        kvm_arch_vcpu_load(vcpu, cpu);
2858}
2859
2860static void kvm_sched_out(struct preempt_notifier *pn,
2861                          struct task_struct *next)
2862{
2863        struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
2864
2865        kvm_arch_vcpu_put(vcpu);
2866}
2867
2868int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
2869                  struct module *module)
2870{
2871        int r;
2872        int cpu;
2873
2874        r = kvm_arch_init(opaque);
2875        if (r)
2876                goto out_fail;
2877
2878        if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
2879                r = -ENOMEM;
2880                goto out_free_0;
2881        }
2882
2883        r = kvm_arch_hardware_setup();
2884        if (r < 0)
2885                goto out_free_0a;
2886
2887        for_each_online_cpu(cpu) {
2888                smp_call_function_single(cpu,
2889                                kvm_arch_check_processor_compat,
2890                                &r, 1);
2891                if (r < 0)
2892                        goto out_free_1;
2893        }
2894
2895        r = register_cpu_notifier(&kvm_cpu_notifier);
2896        if (r)
2897                goto out_free_2;
2898        register_reboot_notifier(&kvm_reboot_notifier);
2899
2900        /* A kmem cache lets us meet the alignment requirements of fx_save. */
2901        if (!vcpu_align)
2902                vcpu_align = __alignof__(struct kvm_vcpu);
2903        kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size, vcpu_align,
2904                                           0, NULL);
2905        if (!kvm_vcpu_cache) {
2906                r = -ENOMEM;
2907                goto out_free_3;
2908        }
2909
2910        r = kvm_async_pf_init();
2911        if (r)
2912                goto out_free;
2913
2914        kvm_chardev_ops.owner = module;
2915        kvm_vm_fops.owner = module;
2916        kvm_vcpu_fops.owner = module;
2917
2918        r = misc_register(&kvm_dev);
2919        if (r) {
2920                printk(KERN_ERR "kvm: misc device register failed\n");
2921                goto out_unreg;
2922        }
2923
2924        register_syscore_ops(&kvm_syscore_ops);
2925
2926        kvm_preempt_ops.sched_in = kvm_sched_in;
2927        kvm_preempt_ops.sched_out = kvm_sched_out;
2928
2929        r = kvm_init_debug();
2930        if (r) {
2931                printk(KERN_ERR "kvm: create debugfs files failed\n");
2932                goto out_undebugfs;
2933        }
2934
2935        return 0;
2936
2937out_undebugfs:
2938        unregister_syscore_ops(&kvm_syscore_ops);
2939out_unreg:
2940        kvm_async_pf_deinit();
2941out_free:
2942        kmem_cache_destroy(kvm_vcpu_cache);
2943out_free_3:
2944        unregister_reboot_notifier(&kvm_reboot_notifier);
2945        unregister_cpu_notifier(&kvm_cpu_notifier);
2946out_free_2:
2947out_free_1:
2948        kvm_arch_hardware_unsetup();
2949out_free_0a:
2950        free_cpumask_var(cpus_hardware_enabled);
2951out_free_0:
2952        kvm_arch_exit();
2953out_fail:
2954        return r;
2955}
2956EXPORT_SYMBOL_GPL(kvm_init);
2957
2958void kvm_exit(void)
2959{
2960        kvm_exit_debug();
2961        misc_deregister(&kvm_dev);
2962        kmem_cache_destroy(kvm_vcpu_cache);
2963        kvm_async_pf_deinit();
2964        unregister_syscore_ops(&kvm_syscore_ops);
2965        unregister_reboot_notifier(&kvm_reboot_notifier);
2966        unregister_cpu_notifier(&kvm_cpu_notifier);
2967        on_each_cpu(hardware_disable_nolock, NULL, 1);
2968        kvm_arch_hardware_unsetup();
2969        kvm_arch_exit();
2970        free_cpumask_var(cpus_hardware_enabled);
2971}
2972EXPORT_SYMBOL_GPL(kvm_exit);
2973
lxr.linux.no kindly hosted by Redpill Linpro AS, provider of Linux consulting and operations services since 1995.