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/ioctl.h>
  56#include <asm/uaccess.h>
  57#include <asm/pgtable.h>
  58
  59#include "coalesced_mmio.h"
  60#include "async_pf.h"
  61#include "vfio.h"
  62
  63#define CREATE_TRACE_POINTS
  64#include <trace/events/kvm.h>
  65
  66/* Worst case buffer size needed for holding an integer. */
  67#define ITOA_MAX_LEN 12
  68
  69MODULE_AUTHOR("Qumranet");
  70MODULE_LICENSE("GPL");
  71
  72/* Architectures should define their poll value according to the halt latency */
  73unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
  74module_param(halt_poll_ns, uint, S_IRUGO | S_IWUSR);
  75EXPORT_SYMBOL_GPL(halt_poll_ns);
  76
  77/* Default doubles per-vcpu halt_poll_ns. */
  78unsigned int halt_poll_ns_grow = 2;
  79module_param(halt_poll_ns_grow, uint, S_IRUGO | S_IWUSR);
  80EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
  81
  82/* Default resets per-vcpu halt_poll_ns . */
  83unsigned int halt_poll_ns_shrink;
  84module_param(halt_poll_ns_shrink, uint, S_IRUGO | S_IWUSR);
  85EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
  86
  87/*
  88 * Ordering of locks:
  89 *
  90 *      kvm->lock --> kvm->slots_lock --> kvm->irq_lock
  91 */
  92
  93DEFINE_SPINLOCK(kvm_lock);
  94static DEFINE_RAW_SPINLOCK(kvm_count_lock);
  95LIST_HEAD(vm_list);
  96
  97static cpumask_var_t cpus_hardware_enabled;
  98static int kvm_usage_count;
  99static atomic_t hardware_enable_failed;
 100
 101struct kmem_cache *kvm_vcpu_cache;
 102EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
 103
 104static __read_mostly struct preempt_ops kvm_preempt_ops;
 105
 106struct dentry *kvm_debugfs_dir;
 107EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
 108
 109static int kvm_debugfs_num_entries;
 110static const struct file_operations *stat_fops_per_vm[];
 111
 112static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
 113                           unsigned long arg);
 114#ifdef CONFIG_COMPAT
 115static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
 116                                  unsigned long arg);
 117#endif
 118static int hardware_enable_all(void);
 119static void hardware_disable_all(void);
 120
 121static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
 122
 123static void kvm_release_pfn_dirty(kvm_pfn_t pfn);
 124static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot, gfn_t gfn);
 125
 126__visible bool kvm_rebooting;
 127EXPORT_SYMBOL_GPL(kvm_rebooting);
 128
 129static bool largepages_enabled = true;
 130
 131bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
 132{
 133        if (pfn_valid(pfn))
 134                return PageReserved(pfn_to_page(pfn));
 135
 136        return true;
 137}
 138
 139/*
 140 * Switches to specified vcpu, until a matching vcpu_put()
 141 */
 142int vcpu_load(struct kvm_vcpu *vcpu)
 143{
 144        int cpu;
 145
 146        if (mutex_lock_killable(&vcpu->mutex))
 147                return -EINTR;
 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}
 154EXPORT_SYMBOL_GPL(vcpu_load);
 155
 156void vcpu_put(struct kvm_vcpu *vcpu)
 157{
 158        preempt_disable();
 159        kvm_arch_vcpu_put(vcpu);
 160        preempt_notifier_unregister(&vcpu->preempt_notifier);
 161        preempt_enable();
 162        mutex_unlock(&vcpu->mutex);
 163}
 164EXPORT_SYMBOL_GPL(vcpu_put);
 165
 166static void ack_flush(void *_completed)
 167{
 168}
 169
 170bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
 171{
 172        int i, cpu, me;
 173        cpumask_var_t cpus;
 174        bool called = true;
 175        struct kvm_vcpu *vcpu;
 176
 177        zalloc_cpumask_var(&cpus, GFP_ATOMIC);
 178
 179        me = get_cpu();
 180        kvm_for_each_vcpu(i, vcpu, kvm) {
 181                kvm_make_request(req, vcpu);
 182                cpu = vcpu->cpu;
 183
 184                /* Set ->requests bit before we read ->mode */
 185                smp_mb();
 186
 187                if (cpus != NULL && cpu != -1 && cpu != me &&
 188                      kvm_vcpu_exiting_guest_mode(vcpu) != OUTSIDE_GUEST_MODE)
 189                        cpumask_set_cpu(cpu, cpus);
 190        }
 191        if (unlikely(cpus == NULL))
 192                smp_call_function_many(cpu_online_mask, ack_flush, NULL, 1);
 193        else if (!cpumask_empty(cpus))
 194                smp_call_function_many(cpus, ack_flush, NULL, 1);
 195        else
 196                called = false;
 197        put_cpu();
 198        free_cpumask_var(cpus);
 199        return called;
 200}
 201
 202#ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
 203void kvm_flush_remote_tlbs(struct kvm *kvm)
 204{
 205        long dirty_count = kvm->tlbs_dirty;
 206
 207        smp_mb();
 208        if (kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
 209                ++kvm->stat.remote_tlb_flush;
 210        cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
 211}
 212EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
 213#endif
 214
 215void kvm_reload_remote_mmus(struct kvm *kvm)
 216{
 217        kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
 218}
 219
 220void kvm_make_mclock_inprogress_request(struct kvm *kvm)
 221{
 222        kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
 223}
 224
 225void kvm_make_scan_ioapic_request(struct kvm *kvm)
 226{
 227        kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
 228}
 229
 230int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
 231{
 232        struct page *page;
 233        int r;
 234
 235        mutex_init(&vcpu->mutex);
 236        vcpu->cpu = -1;
 237        vcpu->kvm = kvm;
 238        vcpu->vcpu_id = id;
 239        vcpu->pid = NULL;
 240        vcpu->halt_poll_ns = 0;
 241        init_waitqueue_head(&vcpu->wq);
 242        kvm_async_pf_vcpu_init(vcpu);
 243
 244        vcpu->pre_pcpu = -1;
 245        INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
 246
 247        page = alloc_page(GFP_KERNEL | __GFP_ZERO);
 248        if (!page) {
 249                r = -ENOMEM;
 250                goto fail;
 251        }
 252        vcpu->run = page_address(page);
 253
 254        kvm_vcpu_set_in_spin_loop(vcpu, false);
 255        kvm_vcpu_set_dy_eligible(vcpu, false);
 256        vcpu->preempted = false;
 257
 258        r = kvm_arch_vcpu_init(vcpu);
 259        if (r < 0)
 260                goto fail_free_run;
 261        return 0;
 262
 263fail_free_run:
 264        free_page((unsigned long)vcpu->run);
 265fail:
 266        return r;
 267}
 268EXPORT_SYMBOL_GPL(kvm_vcpu_init);
 269
 270void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
 271{
 272        put_pid(vcpu->pid);
 273        kvm_arch_vcpu_uninit(vcpu);
 274        free_page((unsigned long)vcpu->run);
 275}
 276EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
 277
 278#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
 279static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
 280{
 281        return container_of(mn, struct kvm, mmu_notifier);
 282}
 283
 284static void kvm_mmu_notifier_invalidate_page(struct mmu_notifier *mn,
 285                                             struct mm_struct *mm,
 286                                             unsigned long address)
 287{
 288        struct kvm *kvm = mmu_notifier_to_kvm(mn);
 289        int need_tlb_flush, idx;
 290
 291        /*
 292         * When ->invalidate_page runs, the linux pte has been zapped
 293         * already but the page is still allocated until
 294         * ->invalidate_page returns. So if we increase the sequence
 295         * here the kvm page fault will notice if the spte can't be
 296         * established because the page is going to be freed. If
 297         * instead the kvm page fault establishes the spte before
 298         * ->invalidate_page runs, kvm_unmap_hva will release it
 299         * before returning.
 300         *
 301         * The sequence increase only need to be seen at spin_unlock
 302         * time, and not at spin_lock time.
 303         *
 304         * Increasing the sequence after the spin_unlock would be
 305         * unsafe because the kvm page fault could then establish the
 306         * pte after kvm_unmap_hva returned, without noticing the page
 307         * is going to be freed.
 308         */
 309        idx = srcu_read_lock(&kvm->srcu);
 310        spin_lock(&kvm->mmu_lock);
 311
 312        kvm->mmu_notifier_seq++;
 313        need_tlb_flush = kvm_unmap_hva(kvm, address) | kvm->tlbs_dirty;
 314        /* we've to flush the tlb before the pages can be freed */
 315        if (need_tlb_flush)
 316                kvm_flush_remote_tlbs(kvm);
 317
 318        spin_unlock(&kvm->mmu_lock);
 319
 320        kvm_arch_mmu_notifier_invalidate_page(kvm, address);
 321
 322        srcu_read_unlock(&kvm->srcu, idx);
 323}
 324
 325static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
 326                                        struct mm_struct *mm,
 327                                        unsigned long address,
 328                                        pte_t pte)
 329{
 330        struct kvm *kvm = mmu_notifier_to_kvm(mn);
 331        int idx;
 332
 333        idx = srcu_read_lock(&kvm->srcu);
 334        spin_lock(&kvm->mmu_lock);
 335        kvm->mmu_notifier_seq++;
 336        kvm_set_spte_hva(kvm, address, pte);
 337        spin_unlock(&kvm->mmu_lock);
 338        srcu_read_unlock(&kvm->srcu, idx);
 339}
 340
 341static void kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
 342                                                    struct mm_struct *mm,
 343                                                    unsigned long start,
 344                                                    unsigned long end)
 345{
 346        struct kvm *kvm = mmu_notifier_to_kvm(mn);
 347        int need_tlb_flush = 0, idx;
 348
 349        idx = srcu_read_lock(&kvm->srcu);
 350        spin_lock(&kvm->mmu_lock);
 351        /*
 352         * The count increase must become visible at unlock time as no
 353         * spte can be established without taking the mmu_lock and
 354         * count is also read inside the mmu_lock critical section.
 355         */
 356        kvm->mmu_notifier_count++;
 357        need_tlb_flush = kvm_unmap_hva_range(kvm, start, end);
 358        need_tlb_flush |= kvm->tlbs_dirty;
 359        /* we've to flush the tlb before the pages can be freed */
 360        if (need_tlb_flush)
 361                kvm_flush_remote_tlbs(kvm);
 362
 363        spin_unlock(&kvm->mmu_lock);
 364        srcu_read_unlock(&kvm->srcu, idx);
 365}
 366
 367static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
 368                                                  struct mm_struct *mm,
 369                                                  unsigned long start,
 370                                                  unsigned long end)
 371{
 372        struct kvm *kvm = mmu_notifier_to_kvm(mn);
 373
 374        spin_lock(&kvm->mmu_lock);
 375        /*
 376         * This sequence increase will notify the kvm page fault that
 377         * the page that is going to be mapped in the spte could have
 378         * been freed.
 379         */
 380        kvm->mmu_notifier_seq++;
 381        smp_wmb();
 382        /*
 383         * The above sequence increase must be visible before the
 384         * below count decrease, which is ensured by the smp_wmb above
 385         * in conjunction with the smp_rmb in mmu_notifier_retry().
 386         */
 387        kvm->mmu_notifier_count--;
 388        spin_unlock(&kvm->mmu_lock);
 389
 390        BUG_ON(kvm->mmu_notifier_count < 0);
 391}
 392
 393static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
 394                                              struct mm_struct *mm,
 395                                              unsigned long address)
 396{
 397        struct kvm *kvm = mmu_notifier_to_kvm(mn);
 398        int young, idx;
 399
 400        idx = srcu_read_lock(&kvm->srcu);
 401        spin_lock(&kvm->mmu_lock);
 402
 403        young = kvm_age_hva(kvm, address);
 404        if (young)
 405                kvm_flush_remote_tlbs(kvm);
 406
 407        spin_unlock(&kvm->mmu_lock);
 408        srcu_read_unlock(&kvm->srcu, idx);
 409
 410        return young;
 411}
 412
 413static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
 414                                       struct mm_struct *mm,
 415                                       unsigned long address)
 416{
 417        struct kvm *kvm = mmu_notifier_to_kvm(mn);
 418        int young, idx;
 419
 420        idx = srcu_read_lock(&kvm->srcu);
 421        spin_lock(&kvm->mmu_lock);
 422        young = kvm_test_age_hva(kvm, address);
 423        spin_unlock(&kvm->mmu_lock);
 424        srcu_read_unlock(&kvm->srcu, idx);
 425
 426        return young;
 427}
 428
 429static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
 430                                     struct mm_struct *mm)
 431{
 432        struct kvm *kvm = mmu_notifier_to_kvm(mn);
 433        int idx;
 434
 435        idx = srcu_read_lock(&kvm->srcu);
 436        kvm_arch_flush_shadow_all(kvm);
 437        srcu_read_unlock(&kvm->srcu, idx);
 438}
 439
 440static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
 441        .invalidate_page        = kvm_mmu_notifier_invalidate_page,
 442        .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
 443        .invalidate_range_end   = kvm_mmu_notifier_invalidate_range_end,
 444        .clear_flush_young      = kvm_mmu_notifier_clear_flush_young,
 445        .test_young             = kvm_mmu_notifier_test_young,
 446        .change_pte             = kvm_mmu_notifier_change_pte,
 447        .release                = kvm_mmu_notifier_release,
 448};
 449
 450static int kvm_init_mmu_notifier(struct kvm *kvm)
 451{
 452        kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
 453        return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
 454}
 455
 456#else  /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
 457
 458static int kvm_init_mmu_notifier(struct kvm *kvm)
 459{
 460        return 0;
 461}
 462
 463#endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
 464
 465static struct kvm_memslots *kvm_alloc_memslots(void)
 466{
 467        int i;
 468        struct kvm_memslots *slots;
 469
 470        slots = kvm_kvzalloc(sizeof(struct kvm_memslots));
 471        if (!slots)
 472                return NULL;
 473
 474        /*
 475         * Init kvm generation close to the maximum to easily test the
 476         * code of handling generation number wrap-around.
 477         */
 478        slots->generation = -150;
 479        for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
 480                slots->id_to_index[i] = slots->memslots[i].id = i;
 481
 482        return slots;
 483}
 484
 485static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
 486{
 487        if (!memslot->dirty_bitmap)
 488                return;
 489
 490        kvfree(memslot->dirty_bitmap);
 491        memslot->dirty_bitmap = NULL;
 492}
 493
 494/*
 495 * Free any memory in @free but not in @dont.
 496 */
 497static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
 498                              struct kvm_memory_slot *dont)
 499{
 500        if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
 501                kvm_destroy_dirty_bitmap(free);
 502
 503        kvm_arch_free_memslot(kvm, free, dont);
 504
 505        free->npages = 0;
 506}
 507
 508static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
 509{
 510        struct kvm_memory_slot *memslot;
 511
 512        if (!slots)
 513                return;
 514
 515        kvm_for_each_memslot(memslot, slots)
 516                kvm_free_memslot(kvm, memslot, NULL);
 517
 518        kvfree(slots);
 519}
 520
 521static void kvm_destroy_vm_debugfs(struct kvm *kvm)
 522{
 523        int i;
 524
 525        if (!kvm->debugfs_dentry)
 526                return;
 527
 528        debugfs_remove_recursive(kvm->debugfs_dentry);
 529
 530        if (kvm->debugfs_stat_data) {
 531                for (i = 0; i < kvm_debugfs_num_entries; i++)
 532                        kfree(kvm->debugfs_stat_data[i]);
 533                kfree(kvm->debugfs_stat_data);
 534        }
 535}
 536
 537static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
 538{
 539        char dir_name[ITOA_MAX_LEN * 2];
 540        struct kvm_stat_data *stat_data;
 541        struct kvm_stats_debugfs_item *p;
 542
 543        if (!debugfs_initialized())
 544                return 0;
 545
 546        snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
 547        kvm->debugfs_dentry = debugfs_create_dir(dir_name,
 548                                                 kvm_debugfs_dir);
 549        if (!kvm->debugfs_dentry)
 550                return -ENOMEM;
 551
 552        kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
 553                                         sizeof(*kvm->debugfs_stat_data),
 554                                         GFP_KERNEL);
 555        if (!kvm->debugfs_stat_data)
 556                return -ENOMEM;
 557
 558        for (p = debugfs_entries; p->name; p++) {
 559                stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL);
 560                if (!stat_data)
 561                        return -ENOMEM;
 562
 563                stat_data->kvm = kvm;
 564                stat_data->offset = p->offset;
 565                kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
 566                if (!debugfs_create_file(p->name, 0444,
 567                                         kvm->debugfs_dentry,
 568                                         stat_data,
 569                                         stat_fops_per_vm[p->kind]))
 570                        return -ENOMEM;
 571        }
 572        return 0;
 573}
 574
 575static struct kvm *kvm_create_vm(unsigned long type)
 576{
 577        int r, i;
 578        struct kvm *kvm = kvm_arch_alloc_vm();
 579
 580        if (!kvm)
 581                return ERR_PTR(-ENOMEM);
 582
 583        spin_lock_init(&kvm->mmu_lock);
 584        atomic_inc(&current->mm->mm_count);
 585        kvm->mm = current->mm;
 586        kvm_eventfd_init(kvm);
 587        mutex_init(&kvm->lock);
 588        mutex_init(&kvm->irq_lock);
 589        mutex_init(&kvm->slots_lock);
 590        atomic_set(&kvm->users_count, 1);
 591        INIT_LIST_HEAD(&kvm->devices);
 592
 593        r = kvm_arch_init_vm(kvm, type);
 594        if (r)
 595                goto out_err_no_disable;
 596
 597        r = hardware_enable_all();
 598        if (r)
 599                goto out_err_no_disable;
 600
 601#ifdef CONFIG_HAVE_KVM_IRQFD
 602        INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
 603#endif
 604
 605        BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
 606
 607        r = -ENOMEM;
 608        for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
 609                kvm->memslots[i] = kvm_alloc_memslots();
 610                if (!kvm->memslots[i])
 611                        goto out_err_no_srcu;
 612        }
 613
 614        if (init_srcu_struct(&kvm->srcu))
 615                goto out_err_no_srcu;
 616        if (init_srcu_struct(&kvm->irq_srcu))
 617                goto out_err_no_irq_srcu;
 618        for (i = 0; i < KVM_NR_BUSES; i++) {
 619                kvm->buses[i] = kzalloc(sizeof(struct kvm_io_bus),
 620                                        GFP_KERNEL);
 621                if (!kvm->buses[i])
 622                        goto out_err;
 623        }
 624
 625        r = kvm_init_mmu_notifier(kvm);
 626        if (r)
 627                goto out_err;
 628
 629        spin_lock(&kvm_lock);
 630        list_add(&kvm->vm_list, &vm_list);
 631        spin_unlock(&kvm_lock);
 632
 633        return kvm;
 634
 635out_err:
 636        cleanup_srcu_struct(&kvm->irq_srcu);
 637out_err_no_irq_srcu:
 638        cleanup_srcu_struct(&kvm->srcu);
 639out_err_no_srcu:
 640        hardware_disable_all();
 641out_err_no_disable:
 642        for (i = 0; i < KVM_NR_BUSES; i++)
 643                kfree(kvm->buses[i]);
 644        for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
 645                kvm_free_memslots(kvm, kvm->memslots[i]);
 646        kvm_arch_free_vm(kvm);
 647        mmdrop(current->mm);
 648        return ERR_PTR(r);
 649}
 650
 651/*
 652 * Avoid using vmalloc for a small buffer.
 653 * Should not be used when the size is statically known.
 654 */
 655void *kvm_kvzalloc(unsigned long size)
 656{
 657        if (size > PAGE_SIZE)
 658                return vzalloc(size);
 659        else
 660                return kzalloc(size, GFP_KERNEL);
 661}
 662
 663static void kvm_destroy_devices(struct kvm *kvm)
 664{
 665        struct list_head *node, *tmp;
 666
 667        list_for_each_safe(node, tmp, &kvm->devices) {
 668                struct kvm_device *dev =
 669                        list_entry(node, struct kvm_device, vm_node);
 670
 671                list_del(node);
 672                dev->ops->destroy(dev);
 673        }
 674}
 675
 676static void kvm_destroy_vm(struct kvm *kvm)
 677{
 678        int i;
 679        struct mm_struct *mm = kvm->mm;
 680
 681        kvm_destroy_vm_debugfs(kvm);
 682        kvm_arch_sync_events(kvm);
 683        spin_lock(&kvm_lock);
 684        list_del(&kvm->vm_list);
 685        spin_unlock(&kvm_lock);
 686        kvm_free_irq_routing(kvm);
 687        for (i = 0; i < KVM_NR_BUSES; i++)
 688                kvm_io_bus_destroy(kvm->buses[i]);
 689        kvm_coalesced_mmio_free(kvm);
 690#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
 691        mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
 692#else
 693        kvm_arch_flush_shadow_all(kvm);
 694#endif
 695        kvm_arch_destroy_vm(kvm);
 696        kvm_destroy_devices(kvm);
 697        for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
 698                kvm_free_memslots(kvm, kvm->memslots[i]);
 699        cleanup_srcu_struct(&kvm->irq_srcu);
 700        cleanup_srcu_struct(&kvm->srcu);
 701        kvm_arch_free_vm(kvm);
 702        hardware_disable_all();
 703        mmdrop(mm);
 704}
 705
 706void kvm_get_kvm(struct kvm *kvm)
 707{
 708        atomic_inc(&kvm->users_count);
 709}
 710EXPORT_SYMBOL_GPL(kvm_get_kvm);
 711
 712void kvm_put_kvm(struct kvm *kvm)
 713{
 714        if (atomic_dec_and_test(&kvm->users_count))
 715                kvm_destroy_vm(kvm);
 716}
 717EXPORT_SYMBOL_GPL(kvm_put_kvm);
 718
 719
 720static int kvm_vm_release(struct inode *inode, struct file *filp)
 721{
 722        struct kvm *kvm = filp->private_data;
 723
 724        kvm_irqfd_release(kvm);
 725
 726        kvm_put_kvm(kvm);
 727        return 0;
 728}
 729
 730/*
 731 * Allocation size is twice as large as the actual dirty bitmap size.
 732 * See x86's kvm_vm_ioctl_get_dirty_log() why this is needed.
 733 */
 734static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
 735{
 736#ifndef CONFIG_S390
 737        unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
 738
 739        memslot->dirty_bitmap = kvm_kvzalloc(dirty_bytes);
 740        if (!memslot->dirty_bitmap)
 741                return -ENOMEM;
 742
 743#endif /* !CONFIG_S390 */
 744        return 0;
 745}
 746
 747/*
 748 * Insert memslot and re-sort memslots based on their GFN,
 749 * so binary search could be used to lookup GFN.
 750 * Sorting algorithm takes advantage of having initially
 751 * sorted array and known changed memslot position.
 752 */
 753static void update_memslots(struct kvm_memslots *slots,
 754                            struct kvm_memory_slot *new)
 755{
 756        int id = new->id;
 757        int i = slots->id_to_index[id];
 758        struct kvm_memory_slot *mslots = slots->memslots;
 759
 760        WARN_ON(mslots[i].id != id);
 761        if (!new->npages) {
 762                WARN_ON(!mslots[i].npages);
 763                if (mslots[i].npages)
 764                        slots->used_slots--;
 765        } else {
 766                if (!mslots[i].npages)
 767                        slots->used_slots++;
 768        }
 769
 770        while (i < KVM_MEM_SLOTS_NUM - 1 &&
 771               new->base_gfn <= mslots[i + 1].base_gfn) {
 772                if (!mslots[i + 1].npages)
 773                        break;
 774                mslots[i] = mslots[i + 1];
 775                slots->id_to_index[mslots[i].id] = i;
 776                i++;
 777        }
 778
 779        /*
 780         * The ">=" is needed when creating a slot with base_gfn == 0,
 781         * so that it moves before all those with base_gfn == npages == 0.
 782         *
 783         * On the other hand, if new->npages is zero, the above loop has
 784         * already left i pointing to the beginning of the empty part of
 785         * mslots, and the ">=" would move the hole backwards in this
 786         * case---which is wrong.  So skip the loop when deleting a slot.
 787         */
 788        if (new->npages) {
 789                while (i > 0 &&
 790                       new->base_gfn >= mslots[i - 1].base_gfn) {
 791                        mslots[i] = mslots[i - 1];
 792                        slots->id_to_index[mslots[i].id] = i;
 793                        i--;
 794                }
 795        } else
 796                WARN_ON_ONCE(i != slots->used_slots);
 797
 798        mslots[i] = *new;
 799        slots->id_to_index[mslots[i].id] = i;
 800}
 801
 802static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
 803{
 804        u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
 805
 806#ifdef __KVM_HAVE_READONLY_MEM
 807        valid_flags |= KVM_MEM_READONLY;
 808#endif
 809
 810        if (mem->flags & ~valid_flags)
 811                return -EINVAL;
 812
 813        return 0;
 814}
 815
 816static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
 817                int as_id, struct kvm_memslots *slots)
 818{
 819        struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
 820
 821        /*
 822         * Set the low bit in the generation, which disables SPTE caching
 823         * until the end of synchronize_srcu_expedited.
 824         */
 825        WARN_ON(old_memslots->generation & 1);
 826        slots->generation = old_memslots->generation + 1;
 827
 828        rcu_assign_pointer(kvm->memslots[as_id], slots);
 829        synchronize_srcu_expedited(&kvm->srcu);
 830
 831        /*
 832         * Increment the new memslot generation a second time. This prevents
 833         * vm exits that race with memslot updates from caching a memslot
 834         * generation that will (potentially) be valid forever.
 835         */
 836        slots->generation++;
 837
 838        kvm_arch_memslots_updated(kvm, slots);
 839
 840        return old_memslots;
 841}
 842
 843/*
 844 * Allocate some memory and give it an address in the guest physical address
 845 * space.
 846 *
 847 * Discontiguous memory is allowed, mostly for framebuffers.
 848 *
 849 * Must be called holding kvm->slots_lock for write.
 850 */
 851int __kvm_set_memory_region(struct kvm *kvm,
 852                            const struct kvm_userspace_memory_region *mem)
 853{
 854        int r;
 855        gfn_t base_gfn;
 856        unsigned long npages;
 857        struct kvm_memory_slot *slot;
 858        struct kvm_memory_slot old, new;
 859        struct kvm_memslots *slots = NULL, *old_memslots;
 860        int as_id, id;
 861        enum kvm_mr_change change;
 862
 863        r = check_memory_region_flags(mem);
 864        if (r)
 865                goto out;
 866
 867        r = -EINVAL;
 868        as_id = mem->slot >> 16;
 869        id = (u16)mem->slot;
 870
 871        /* General sanity checks */
 872        if (mem->memory_size & (PAGE_SIZE - 1))
 873                goto out;
 874        if (mem->guest_phys_addr & (PAGE_SIZE - 1))
 875                goto out;
 876        /* We can read the guest memory with __xxx_user() later on. */
 877        if ((id < KVM_USER_MEM_SLOTS) &&
 878            ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
 879             !access_ok(VERIFY_WRITE,
 880                        (void __user *)(unsigned long)mem->userspace_addr,
 881                        mem->memory_size)))
 882                goto out;
 883        if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
 884                goto out;
 885        if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
 886                goto out;
 887
 888        slot = id_to_memslot(__kvm_memslots(kvm, as_id), id);
 889        base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
 890        npages = mem->memory_size >> PAGE_SHIFT;
 891
 892        if (npages > KVM_MEM_MAX_NR_PAGES)
 893                goto out;
 894
 895        new = old = *slot;
 896
 897        new.id = id;
 898        new.base_gfn = base_gfn;
 899        new.npages = npages;
 900        new.flags = mem->flags;
 901
 902        if (npages) {
 903                if (!old.npages)
 904                        change = KVM_MR_CREATE;
 905                else { /* Modify an existing slot. */
 906                        if ((mem->userspace_addr != old.userspace_addr) ||
 907                            (npages != old.npages) ||
 908                            ((new.flags ^ old.flags) & KVM_MEM_READONLY))
 909                                goto out;
 910
 911                        if (base_gfn != old.base_gfn)
 912                                change = KVM_MR_MOVE;
 913                        else if (new.flags != old.flags)
 914                                change = KVM_MR_FLAGS_ONLY;
 915                        else { /* Nothing to change. */
 916                                r = 0;
 917                                goto out;
 918                        }
 919                }
 920        } else {
 921                if (!old.npages)
 922                        goto out;
 923
 924                change = KVM_MR_DELETE;
 925                new.base_gfn = 0;
 926                new.flags = 0;
 927        }
 928
 929        if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
 930                /* Check for overlaps */
 931                r = -EEXIST;
 932                kvm_for_each_memslot(slot, __kvm_memslots(kvm, as_id)) {
 933                        if ((slot->id >= KVM_USER_MEM_SLOTS) ||
 934                            (slot->id == id))
 935                                continue;
 936                        if (!((base_gfn + npages <= slot->base_gfn) ||
 937                              (base_gfn >= slot->base_gfn + slot->npages)))
 938                                goto out;
 939                }
 940        }
 941
 942        /* Free page dirty bitmap if unneeded */
 943        if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
 944                new.dirty_bitmap = NULL;
 945
 946        r = -ENOMEM;
 947        if (change == KVM_MR_CREATE) {
 948                new.userspace_addr = mem->userspace_addr;
 949
 950                if (kvm_arch_create_memslot(kvm, &new, npages))
 951                        goto out_free;
 952        }
 953
 954        /* Allocate page dirty bitmap if needed */
 955        if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
 956                if (kvm_create_dirty_bitmap(&new) < 0)
 957                        goto out_free;
 958        }
 959
 960        slots = kvm_kvzalloc(sizeof(struct kvm_memslots));
 961        if (!slots)
 962                goto out_free;
 963        memcpy(slots, __kvm_memslots(kvm, as_id), sizeof(struct kvm_memslots));
 964
 965        if ((change == KVM_MR_DELETE) || (change == KVM_MR_MOVE)) {
 966                slot = id_to_memslot(slots, id);
 967                slot->flags |= KVM_MEMSLOT_INVALID;
 968
 969                old_memslots = install_new_memslots(kvm, as_id, slots);
 970
 971                /* slot was deleted or moved, clear iommu mapping */
 972                kvm_iommu_unmap_pages(kvm, &old);
 973                /* From this point no new shadow pages pointing to a deleted,
 974                 * or moved, memslot will be created.
 975                 *
 976                 * validation of sp->gfn happens in:
 977                 *      - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
 978                 *      - kvm_is_visible_gfn (mmu_check_roots)
 979                 */
 980                kvm_arch_flush_shadow_memslot(kvm, slot);
 981
 982                /*
 983                 * We can re-use the old_memslots from above, the only difference
 984                 * from the currently installed memslots is the invalid flag.  This
 985                 * will get overwritten by update_memslots anyway.
 986                 */
 987                slots = old_memslots;
 988        }
 989
 990        r = kvm_arch_prepare_memory_region(kvm, &new, mem, change);
 991        if (r)
 992                goto out_slots;
 993
 994        /* actual memory is freed via old in kvm_free_memslot below */
 995        if (change == KVM_MR_DELETE) {
 996                new.dirty_bitmap = NULL;
 997                memset(&new.arch, 0, sizeof(new.arch));
 998        }
 999
1000        update_memslots(slots, &new);
1001        old_memslots = install_new_memslots(kvm, as_id, slots);
1002
1003        kvm_arch_commit_memory_region(kvm, mem, &old, &new, change);
1004
1005        kvm_free_memslot(kvm, &old, &new);
1006        kvfree(old_memslots);
1007
1008        /*
1009         * IOMMU mapping:  New slots need to be mapped.  Old slots need to be
1010         * un-mapped and re-mapped if their base changes.  Since base change
1011         * unmapping is handled above with slot deletion, mapping alone is
1012         * needed here.  Anything else the iommu might care about for existing
1013         * slots (size changes, userspace addr changes and read-only flag
1014         * changes) is disallowed above, so any other attribute changes getting
1015         * here can be skipped.
1016         */
1017        if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
1018                r = kvm_iommu_map_pages(kvm, &new);
1019                return r;
1020        }
1021
1022        return 0;
1023
1024out_slots:
1025        kvfree(slots);
1026out_free:
1027        kvm_free_memslot(kvm, &new, &old);
1028out:
1029        return r;
1030}
1031EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1032
1033int kvm_set_memory_region(struct kvm *kvm,
1034                          const struct kvm_userspace_memory_region *mem)
1035{
1036        int r;
1037
1038        mutex_lock(&kvm->slots_lock);
1039        r = __kvm_set_memory_region(kvm, mem);
1040        mutex_unlock(&kvm->slots_lock);
1041        return r;
1042}
1043EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1044
1045static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1046                                          struct kvm_userspace_memory_region *mem)
1047{
1048        if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
1049                return -EINVAL;
1050
1051        return kvm_set_memory_region(kvm, mem);
1052}
1053
1054int kvm_get_dirty_log(struct kvm *kvm,
1055                        struct kvm_dirty_log *log, int *is_dirty)
1056{
1057        struct kvm_memslots *slots;
1058        struct kvm_memory_slot *memslot;
1059        int r, i, as_id, id;
1060        unsigned long n;
1061        unsigned long any = 0;
1062
1063        r = -EINVAL;
1064        as_id = log->slot >> 16;
1065        id = (u16)log->slot;
1066        if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1067                goto out;
1068
1069        slots = __kvm_memslots(kvm, as_id);
1070        memslot = id_to_memslot(slots, id);
1071        r = -ENOENT;
1072        if (!memslot->dirty_bitmap)
1073                goto out;
1074
1075        n = kvm_dirty_bitmap_bytes(memslot);
1076
1077        for (i = 0; !any && i < n/sizeof(long); ++i)
1078                any = memslot->dirty_bitmap[i];
1079
1080        r = -EFAULT;
1081        if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
1082                goto out;
1083
1084        if (any)
1085                *is_dirty = 1;
1086
1087        r = 0;
1088out:
1089        return r;
1090}
1091EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
1092
1093#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1094/**
1095 * kvm_get_dirty_log_protect - get a snapshot of dirty pages, and if any pages
1096 *      are dirty write protect them for next write.
1097 * @kvm:        pointer to kvm instance
1098 * @log:        slot id and address to which we copy the log
1099 * @is_dirty:   flag set if any page is dirty
1100 *
1101 * We need to keep it in mind that VCPU threads can write to the bitmap
1102 * concurrently. So, to avoid losing track of dirty pages we keep the
1103 * following order:
1104 *
1105 *    1. Take a snapshot of the bit and clear it if needed.
1106 *    2. Write protect the corresponding page.
1107 *    3. Copy the snapshot to the userspace.
1108 *    4. Upon return caller flushes TLB's if needed.
1109 *
1110 * Between 2 and 4, the guest may write to the page using the remaining TLB
1111 * entry.  This is not a problem because the page is reported dirty using
1112 * the snapshot taken before and step 4 ensures that writes done after
1113 * exiting to userspace will be logged for the next call.
1114 *
1115 */
1116int kvm_get_dirty_log_protect(struct kvm *kvm,
1117                        struct kvm_dirty_log *log, bool *is_dirty)
1118{
1119        struct kvm_memslots *slots;
1120        struct kvm_memory_slot *memslot;
1121        int r, i, as_id, id;
1122        unsigned long n;
1123        unsigned long *dirty_bitmap;
1124        unsigned long *dirty_bitmap_buffer;
1125
1126        r = -EINVAL;
1127        as_id = log->slot >> 16;
1128        id = (u16)log->slot;
1129        if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1130                goto out;
1131
1132        slots = __kvm_memslots(kvm, as_id);
1133        memslot = id_to_memslot(slots, id);
1134
1135        dirty_bitmap = memslot->dirty_bitmap;
1136        r = -ENOENT;
1137        if (!dirty_bitmap)
1138                goto out;
1139
1140        n = kvm_dirty_bitmap_bytes(memslot);
1141
1142        dirty_bitmap_buffer = dirty_bitmap + n / sizeof(long);
1143        memset(dirty_bitmap_buffer, 0, n);
1144
1145        spin_lock(&kvm->mmu_lock);
1146        *is_dirty = false;
1147        for (i = 0; i < n / sizeof(long); i++) {
1148                unsigned long mask;
1149                gfn_t offset;
1150
1151                if (!dirty_bitmap[i])
1152                        continue;
1153
1154                *is_dirty = true;
1155
1156                mask = xchg(&dirty_bitmap[i], 0);
1157                dirty_bitmap_buffer[i] = mask;
1158
1159                if (mask) {
1160                        offset = i * BITS_PER_LONG;
1161                        kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1162                                                                offset, mask);
1163                }
1164        }
1165
1166        spin_unlock(&kvm->mmu_lock);
1167
1168        r = -EFAULT;
1169        if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
1170                goto out;
1171
1172        r = 0;
1173out:
1174        return r;
1175}
1176EXPORT_SYMBOL_GPL(kvm_get_dirty_log_protect);
1177#endif
1178
1179bool kvm_largepages_enabled(void)
1180{
1181        return largepages_enabled;
1182}
1183
1184void kvm_disable_largepages(void)
1185{
1186        largepages_enabled = false;
1187}
1188EXPORT_SYMBOL_GPL(kvm_disable_largepages);
1189
1190struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1191{
1192        return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1193}
1194EXPORT_SYMBOL_GPL(gfn_to_memslot);
1195
1196struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1197{
1198        return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1199}
1200
1201int kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
1202{
1203        struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
1204
1205        if (!memslot || memslot->id >= KVM_USER_MEM_SLOTS ||
1206              memslot->flags & KVM_MEMSLOT_INVALID)
1207                return 0;
1208
1209        return 1;
1210}
1211EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1212
1213unsigned long kvm_host_page_size(struct kvm *kvm, gfn_t gfn)
1214{
1215        struct vm_area_struct *vma;
1216        unsigned long addr, size;
1217
1218        size = PAGE_SIZE;
1219
1220        addr = gfn_to_hva(kvm, gfn);
1221        if (kvm_is_error_hva(addr))
1222                return PAGE_SIZE;
1223
1224        down_read(&current->mm->mmap_sem);
1225        vma = find_vma(current->mm, addr);
1226        if (!vma)
1227                goto out;
1228
1229        size = vma_kernel_pagesize(vma);
1230
1231out:
1232        up_read(&current->mm->mmap_sem);
1233
1234        return size;
1235}
1236
1237static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1238{
1239        return slot->flags & KVM_MEM_READONLY;
1240}
1241
1242static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1243                                       gfn_t *nr_pages, bool write)
1244{
1245        if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1246                return KVM_HVA_ERR_BAD;
1247
1248        if (memslot_is_readonly(slot) && write)
1249                return KVM_HVA_ERR_RO_BAD;
1250
1251        if (nr_pages)
1252                *nr_pages = slot->npages - (gfn - slot->base_gfn);
1253
1254        return __gfn_to_hva_memslot(slot, gfn);
1255}
1256
1257static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1258                                     gfn_t *nr_pages)
1259{
1260        return __gfn_to_hva_many(slot, gfn, nr_pages, true);
1261}
1262
1263unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
1264                                        gfn_t gfn)
1265{
1266        return gfn_to_hva_many(slot, gfn, NULL);
1267}
1268EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1269
1270unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1271{
1272        return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
1273}
1274EXPORT_SYMBOL_GPL(gfn_to_hva);
1275
1276unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1277{
1278        return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
1279}
1280EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1281
1282/*
1283 * If writable is set to false, the hva returned by this function is only
1284 * allowed to be read.
1285 */
1286unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1287                                      gfn_t gfn, bool *writable)
1288{
1289        unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
1290
1291        if (!kvm_is_error_hva(hva) && writable)
1292                *writable = !memslot_is_readonly(slot);
1293
1294        return hva;
1295}
1296
1297unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
1298{
1299        struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1300
1301        return gfn_to_hva_memslot_prot(slot, gfn, writable);
1302}
1303
1304unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
1305{
1306        struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1307
1308        return gfn_to_hva_memslot_prot(slot, gfn, writable);
1309}
1310
1311static int get_user_page_nowait(struct task_struct *tsk, struct mm_struct *mm,
1312        unsigned long start, int write, struct page **page)
1313{
1314        int flags = FOLL_TOUCH | FOLL_NOWAIT | FOLL_HWPOISON | FOLL_GET;
1315
1316        if (write)
1317                flags |= FOLL_WRITE;
1318
1319        return __get_user_pages(tsk, mm, start, 1, flags, page, NULL, NULL);
1320}
1321
1322static inline int check_user_page_hwpoison(unsigned long addr)
1323{
1324        int rc, flags = FOLL_TOUCH | FOLL_HWPOISON | FOLL_WRITE;
1325
1326        rc = __get_user_pages(current, current->mm, addr, 1,
1327                              flags, NULL, NULL, NULL);
1328        return rc == -EHWPOISON;
1329}
1330
1331/*
1332 * The atomic path to get the writable pfn which will be stored in @pfn,
1333 * true indicates success, otherwise false is returned.
1334 */
1335static bool hva_to_pfn_fast(unsigned long addr, bool atomic, bool *async,
1336                            bool write_fault, bool *writable, kvm_pfn_t *pfn)
1337{
1338        struct page *page[1];
1339        int npages;
1340
1341        if (!(async || atomic))
1342                return false;
1343
1344        /*
1345         * Fast pin a writable pfn only if it is a write fault request
1346         * or the caller allows to map a writable pfn for a read fault
1347         * request.
1348         */
1349        if (!(write_fault || writable))
1350                return false;
1351
1352        npages = __get_user_pages_fast(addr, 1, 1, page);
1353        if (npages == 1) {
1354                *pfn = page_to_pfn(page[0]);
1355
1356                if (writable)
1357                        *writable = true;
1358                return true;
1359        }
1360
1361        return false;
1362}
1363
1364/*
1365 * The slow path to get the pfn of the specified host virtual address,
1366 * 1 indicates success, -errno is returned if error is detected.
1367 */
1368static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
1369                           bool *writable, kvm_pfn_t *pfn)
1370{
1371        struct page *page[1];
1372        int npages = 0;
1373
1374        might_sleep();
1375
1376        if (writable)
1377                *writable = write_fault;
1378
1379        if (async) {
1380                down_read(&current->mm->mmap_sem);
1381                npages = get_user_page_nowait(current, current->mm,
1382                                              addr, write_fault, page);
1383                up_read(&current->mm->mmap_sem);
1384        } else
1385                npages = __get_user_pages_unlocked(current, current->mm, addr, 1,
1386                                                   write_fault, 0, page,
1387                                                   FOLL_TOUCH|FOLL_HWPOISON);
1388        if (npages != 1)
1389                return npages;
1390
1391        /* map read fault as writable if possible */
1392        if (unlikely(!write_fault) && writable) {
1393                struct page *wpage[1];
1394
1395                npages = __get_user_pages_fast(addr, 1, 1, wpage);
1396                if (npages == 1) {
1397                        *writable = true;
1398                        put_page(page[0]);
1399                        page[0] = wpage[0];
1400                }
1401
1402                npages = 1;
1403        }
1404        *pfn = page_to_pfn(page[0]);
1405        return npages;
1406}
1407
1408static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
1409{
1410        if (unlikely(!(vma->vm_flags & VM_READ)))
1411                return false;
1412
1413        if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
1414                return false;
1415
1416        return true;
1417}
1418
1419static int hva_to_pfn_remapped(struct vm_area_struct *vma,
1420                               unsigned long addr, bool *async,
1421                               bool write_fault, kvm_pfn_t *p_pfn)
1422{
1423        unsigned long pfn;
1424        int r;
1425
1426        r = follow_pfn(vma, addr, &pfn);
1427        if (r) {
1428                /*
1429                 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
1430                 * not call the fault handler, so do it here.
1431                 */
1432                r = fixup_user_fault(current, current->mm, addr,
1433                                     (write_fault ? FAULT_FLAG_WRITE : 0));
1434                if (r)
1435                        return r;
1436
1437                r = follow_pfn(vma, addr, &pfn);
1438                if (r)
1439                        return r;
1440
1441        }
1442
1443
1444        /*
1445         * Get a reference here because callers of *hva_to_pfn* and
1446         * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
1447         * returned pfn.  This is only needed if the VMA has VM_MIXEDMAP
1448         * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
1449         * simply do nothing for reserved pfns.
1450         *
1451         * Whoever called remap_pfn_range is also going to call e.g.
1452         * unmap_mapping_range before the underlying pages are freed,
1453         * causing a call to our MMU notifier.
1454         */ 
1455        kvm_get_pfn(pfn);
1456
1457        *p_pfn = pfn;
1458        return 0;
1459}
1460
1461/*
1462 * Pin guest page in memory and return its pfn.
1463 * @addr: host virtual address which maps memory to the guest
1464 * @atomic: whether this function can sleep
1465 * @async: whether this function need to wait IO complete if the
1466 *         host page is not in the memory
1467 * @write_fault: whether we should get a writable host page
1468 * @writable: whether it allows to map a writable host page for !@write_fault
1469 *
1470 * The function will map a writable host page for these two cases:
1471 * 1): @write_fault = true
1472 * 2): @write_fault = false && @writable, @writable will tell the caller
1473 *     whether the mapping is writable.
1474 */
1475static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
1476                        bool write_fault, bool *writable)
1477{
1478        struct vm_area_struct *vma;
1479        kvm_pfn_t pfn = 0;
1480        int npages, r;
1481
1482        /* we can do it either atomically or asynchronously, not both */
1483        BUG_ON(atomic && async);
1484
1485        if (hva_to_pfn_fast(addr, atomic, async, write_fault, writable, &pfn))
1486                return pfn;
1487
1488        if (atomic)
1489                return KVM_PFN_ERR_FAULT;
1490
1491        npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
1492        if (npages == 1)
1493                return pfn;
1494
1495        down_read(&current->mm->mmap_sem);
1496        if (npages == -EHWPOISON ||
1497              (!async && check_user_page_hwpoison(addr))) {
1498                pfn = KVM_PFN_ERR_HWPOISON;
1499                goto exit;
1500        }
1501
1502retry:
1503        vma = find_vma_intersection(current->mm, addr, addr + 1);
1504
1505        if (vma == NULL)
1506                pfn = KVM_PFN_ERR_FAULT;
1507        else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
1508                r = hva_to_pfn_remapped(vma, addr, async, write_fault, &pfn);
1509                if (r == -EAGAIN)
1510                        goto retry;
1511                if (r < 0)
1512                        pfn = KVM_PFN_ERR_FAULT;
1513        } else {
1514                if (async && vma_is_valid(vma, write_fault))
1515                        *async = true;
1516                pfn = KVM_PFN_ERR_FAULT;
1517        }
1518exit:
1519        up_read(&current->mm->mmap_sem);
1520        return pfn;
1521}
1522
1523kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
1524                               bool atomic, bool *async, bool write_fault,
1525                               bool *writable)
1526{
1527        unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
1528
1529        if (addr == KVM_HVA_ERR_RO_BAD)
1530                return KVM_PFN_ERR_RO_FAULT;
1531
1532        if (kvm_is_error_hva(addr))
1533                return KVM_PFN_NOSLOT;
1534
1535        /* Do not map writable pfn in the readonly memslot. */
1536        if (writable && memslot_is_readonly(slot)) {
1537                *writable = false;
1538                writable = NULL;
1539        }
1540
1541        return hva_to_pfn(addr, atomic, async, write_fault,
1542                          writable);
1543}
1544EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
1545
1546kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
1547                      bool *writable)
1548{
1549        return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
1550                                    write_fault, writable);
1551}
1552EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
1553
1554kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
1555{
1556        return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
1557}
1558EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
1559
1560kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
1561{
1562        return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
1563}
1564EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
1565
1566kvm_pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
1567{
1568        return gfn_to_pfn_memslot_atomic(gfn_to_memslot(kvm, gfn), gfn);
1569}
1570EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
1571
1572kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
1573{
1574        return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1575}
1576EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
1577
1578kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
1579{
1580        return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
1581}
1582EXPORT_SYMBOL_GPL(gfn_to_pfn);
1583
1584kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
1585{
1586        return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1587}
1588EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
1589
1590int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1591                            struct page **pages, int nr_pages)
1592{
1593        unsigned long addr;
1594        gfn_t entry;
1595
1596        addr = gfn_to_hva_many(slot, gfn, &entry);
1597        if (kvm_is_error_hva(addr))
1598                return -1;
1599
1600        if (entry < nr_pages)
1601                return 0;
1602
1603        return __get_user_pages_fast(addr, nr_pages, 1, pages);
1604}
1605EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
1606
1607static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
1608{
1609        if (is_error_noslot_pfn(pfn))
1610                return KVM_ERR_PTR_BAD_PAGE;
1611
1612        if (kvm_is_reserved_pfn(pfn)) {
1613                WARN_ON(1);
1614                return KVM_ERR_PTR_BAD_PAGE;
1615        }
1616
1617        return pfn_to_page(pfn);
1618}
1619
1620struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
1621{
1622        kvm_pfn_t pfn;
1623
1624        pfn = gfn_to_pfn(kvm, gfn);
1625
1626        return kvm_pfn_to_page(pfn);
1627}
1628EXPORT_SYMBOL_GPL(gfn_to_page);
1629
1630struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
1631{
1632        kvm_pfn_t pfn;
1633
1634        pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
1635
1636        return kvm_pfn_to_page(pfn);
1637}
1638EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
1639
1640void kvm_release_page_clean(struct page *page)
1641{
1642        WARN_ON(is_error_page(page));
1643
1644        kvm_release_pfn_clean(page_to_pfn(page));
1645}
1646EXPORT_SYMBOL_GPL(kvm_release_page_clean);
1647
1648void kvm_release_pfn_clean(kvm_pfn_t pfn)
1649{
1650        if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
1651                put_page(pfn_to_page(pfn));
1652}
1653EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
1654
1655void kvm_release_page_dirty(struct page *page)
1656{
1657        WARN_ON(is_error_page(page));
1658
1659        kvm_release_pfn_dirty(page_to_pfn(page));
1660}
1661EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
1662
1663static void kvm_release_pfn_dirty(kvm_pfn_t pfn)
1664{
1665        kvm_set_pfn_dirty(pfn);
1666        kvm_release_pfn_clean(pfn);
1667}
1668
1669void kvm_set_pfn_dirty(kvm_pfn_t pfn)
1670{
1671        if (!kvm_is_reserved_pfn(pfn)) {
1672                struct page *page = pfn_to_page(pfn);
1673
1674                if (!PageReserved(page))
1675                        SetPageDirty(page);
1676        }
1677}
1678EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
1679
1680void kvm_set_pfn_accessed(kvm_pfn_t pfn)
1681{
1682        if (!kvm_is_reserved_pfn(pfn))
1683                mark_page_accessed(pfn_to_page(pfn));
1684}
1685EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
1686
1687void kvm_get_pfn(kvm_pfn_t pfn)
1688{
1689        if (!kvm_is_reserved_pfn(pfn))
1690                get_page(pfn_to_page(pfn));
1691}
1692EXPORT_SYMBOL_GPL(kvm_get_pfn);
1693
1694static int next_segment(unsigned long len, int offset)
1695{
1696        if (len > PAGE_SIZE - offset)
1697                return PAGE_SIZE - offset;
1698        else
1699                return len;
1700}
1701
1702static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
1703                                 void *data, int offset, int len)
1704{
1705        int r;
1706        unsigned long addr;
1707
1708        addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
1709        if (kvm_is_error_hva(addr))
1710                return -EFAULT;
1711        r = __copy_from_user(data, (void __user *)addr + offset, len);
1712        if (r)
1713                return -EFAULT;
1714        return 0;
1715}
1716
1717int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
1718                        int len)
1719{
1720        struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1721
1722        return __kvm_read_guest_page(slot, gfn, data, offset, len);
1723}
1724EXPORT_SYMBOL_GPL(kvm_read_guest_page);
1725
1726int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
1727                             int offset, int len)
1728{
1729        struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1730
1731        return __kvm_read_guest_page(slot, gfn, data, offset, len);
1732}
1733EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
1734
1735int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
1736{
1737        gfn_t gfn = gpa >> PAGE_SHIFT;
1738        int seg;
1739        int offset = offset_in_page(gpa);
1740        int ret;
1741
1742        while ((seg = next_segment(len, offset)) != 0) {
1743                ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
1744                if (ret < 0)
1745                        return ret;
1746                offset = 0;
1747                len -= seg;
1748                data += seg;
1749                ++gfn;
1750        }
1751        return 0;
1752}
1753EXPORT_SYMBOL_GPL(kvm_read_guest);
1754
1755int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
1756{
1757        gfn_t gfn = gpa >> PAGE_SHIFT;
1758        int seg;
1759        int offset = offset_in_page(gpa);
1760        int ret;
1761
1762        while ((seg = next_segment(len, offset)) != 0) {
1763                ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
1764                if (ret < 0)
1765                        return ret;
1766                offset = 0;
1767                len -= seg;
1768                data += seg;
1769                ++gfn;
1770        }
1771        return 0;
1772}
1773EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
1774
1775static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1776                                   void *data, int offset, unsigned long len)
1777{
1778        int r;
1779        unsigned long addr;
1780
1781        addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
1782        if (kvm_is_error_hva(addr))
1783                return -EFAULT;
1784        pagefault_disable();
1785        r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
1786        pagefault_enable();
1787        if (r)
1788                return -EFAULT;
1789        return 0;
1790}
1791
1792int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
1793                          unsigned long len)
1794{
1795        gfn_t gfn = gpa >> PAGE_SHIFT;
1796        struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1797        int offset = offset_in_page(gpa);
1798
1799        return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
1800}
1801EXPORT_SYMBOL_GPL(kvm_read_guest_atomic);
1802
1803int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
1804                               void *data, unsigned long len)
1805{
1806        gfn_t gfn = gpa >> PAGE_SHIFT;
1807        struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1808        int offset = offset_in_page(gpa);
1809
1810        return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
1811}
1812EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
1813
1814static int __kvm_write_guest_page(struct kvm_memory_slot *memslot, gfn_t gfn,
1815                                  const void *data, int offset, int len)
1816{
1817        int r;
1818        unsigned long addr;
1819
1820        addr = gfn_to_hva_memslot(memslot, gfn);
1821        if (kvm_is_error_hva(addr))
1822                return -EFAULT;
1823        r = __copy_to_user((void __user *)addr + offset, data, len);
1824        if (r)
1825                return -EFAULT;
1826        mark_page_dirty_in_slot(memslot, gfn);
1827        return 0;
1828}
1829
1830int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
1831                         const void *data, int offset, int len)
1832{
1833        struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1834
1835        return __kvm_write_guest_page(slot, gfn, data, offset, len);
1836}
1837EXPORT_SYMBOL_GPL(kvm_write_guest_page);
1838
1839int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
1840                              const void *data, int offset, int len)
1841{
1842        struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1843
1844        return __kvm_write_guest_page(slot, gfn, data, offset, len);
1845}
1846EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
1847
1848int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
1849                    unsigned long len)
1850{
1851        gfn_t gfn = gpa >> PAGE_SHIFT;
1852        int seg;
1853        int offset = offset_in_page(gpa);
1854        int ret;
1855
1856        while ((seg = next_segment(len, offset)) != 0) {
1857                ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
1858                if (ret < 0)
1859                        return ret;
1860                offset = 0;
1861                len -= seg;
1862                data += seg;
1863                ++gfn;
1864        }
1865        return 0;
1866}
1867EXPORT_SYMBOL_GPL(kvm_write_guest);
1868
1869int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
1870                         unsigned long len)
1871{
1872        gfn_t gfn = gpa >> PAGE_SHIFT;
1873        int seg;
1874        int offset = offset_in_page(gpa);
1875        int ret;
1876
1877        while ((seg = next_segment(len, offset)) != 0) {
1878                ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
1879                if (ret < 0)
1880                        return ret;
1881                offset = 0;
1882                len -= seg;
1883                data += seg;
1884                ++gfn;
1885        }
1886        return 0;
1887}
1888EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
1889
1890int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1891                              gpa_t gpa, unsigned long len)
1892{
1893        struct kvm_memslots *slots = kvm_memslots(kvm);
1894        int offset = offset_in_page(gpa);
1895        gfn_t start_gfn = gpa >> PAGE_SHIFT;
1896        gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
1897        gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
1898        gfn_t nr_pages_avail;
1899
1900        ghc->gpa = gpa;
1901        ghc->generation = slots->generation;
1902        ghc->len = len;
1903        ghc->memslot = gfn_to_memslot(kvm, start_gfn);
1904        ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn, NULL);
1905        if (!kvm_is_error_hva(ghc->hva) && nr_pages_needed <= 1) {
1906                ghc->hva += offset;
1907        } else {
1908                /*
1909                 * If the requested region crosses two memslots, we still
1910                 * verify that the entire region is valid here.
1911                 */
1912                while (start_gfn <= end_gfn) {
1913                        ghc->memslot = gfn_to_memslot(kvm, start_gfn);
1914                        ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
1915                                                   &nr_pages_avail);
1916                        if (kvm_is_error_hva(ghc->hva))
1917                                return -EFAULT;
1918                        start_gfn += nr_pages_avail;
1919                }
1920                /* Use the slow path for cross page reads and writes. */
1921                ghc->memslot = NULL;
1922        }
1923        return 0;
1924}
1925EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
1926
1927int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1928                           void *data, unsigned long len)
1929{
1930        struct kvm_memslots *slots = kvm_memslots(kvm);
1931        int r;
1932
1933        BUG_ON(len > ghc->len);
1934
1935        if (slots->generation != ghc->generation)
1936                kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa, ghc->len);
1937
1938        if (unlikely(!ghc->memslot))
1939                return kvm_write_guest(kvm, ghc->gpa, data, len);
1940
1941        if (kvm_is_error_hva(ghc->hva))
1942                return -EFAULT;
1943
1944        r = __copy_to_user((void __user *)ghc->hva, data, len);
1945        if (r)
1946                return -EFAULT;
1947        mark_page_dirty_in_slot(ghc->memslot, ghc->gpa >> PAGE_SHIFT);
1948
1949        return 0;
1950}
1951EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
1952
1953int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1954                           void *data, unsigned long len)
1955{
1956        struct kvm_memslots *slots = kvm_memslots(kvm);
1957        int r;
1958
1959        BUG_ON(len > ghc->len);
1960
1961        if (slots->generation != ghc->generation)
1962                kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa, ghc->len);
1963
1964        if (unlikely(!ghc->memslot))
1965                return kvm_read_guest(kvm, ghc->gpa, data, len);
1966
1967        if (kvm_is_error_hva(ghc->hva))
1968                return -EFAULT;
1969
1970        r = __copy_from_user(data, (void __user *)ghc->hva, len);
1971        if (r)
1972                return -EFAULT;
1973
1974        return 0;
1975}
1976EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
1977
1978int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
1979{
1980        const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
1981
1982        return kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
1983}
1984EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
1985
1986int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
1987{
1988        gfn_t gfn = gpa >> PAGE_SHIFT;
1989        int seg;
1990        int offset = offset_in_page(gpa);
1991        int ret;
1992
1993        while ((seg = next_segment(len, offset)) != 0) {
1994                ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
1995                if (ret < 0)
1996                        return ret;
1997                offset = 0;
1998                len -= seg;
1999                ++gfn;
2000        }
2001        return 0;
2002}
2003EXPORT_SYMBOL_GPL(kvm_clear_guest);
2004
2005static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot,
2006                                    gfn_t gfn)
2007{
2008        if (memslot && memslot->dirty_bitmap) {
2009                unsigned long rel_gfn = gfn - memslot->base_gfn;
2010
2011                set_bit_le(rel_gfn, memslot->dirty_bitmap);
2012        }
2013}
2014
2015void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2016{
2017        struct kvm_memory_slot *memslot;
2018
2019        memslot = gfn_to_memslot(kvm, gfn);
2020        mark_page_dirty_in_slot(memslot, gfn);
2021}
2022EXPORT_SYMBOL_GPL(mark_page_dirty);
2023
2024void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2025{
2026        struct kvm_memory_slot *memslot;
2027
2028        memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2029        mark_page_dirty_in_slot(memslot, gfn);
2030}
2031EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2032
2033static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2034{
2035        unsigned int old, val, grow;
2036
2037        old = val = vcpu->halt_poll_ns;
2038        grow = READ_ONCE(halt_poll_ns_grow);
2039        /* 10us base */
2040        if (val == 0 && grow)
2041                val = 10000;
2042        else
2043                val *= grow;
2044
2045        if (val > halt_poll_ns)
2046                val = halt_poll_ns;
2047
2048        vcpu->halt_poll_ns = val;
2049        trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
2050}
2051
2052static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2053{
2054        unsigned int old, val, shrink;
2055
2056        old = val = vcpu->halt_poll_ns;
2057        shrink = READ_ONCE(halt_poll_ns_shrink);
2058        if (shrink == 0)
2059                val = 0;
2060        else
2061                val /= shrink;
2062
2063        vcpu->halt_poll_ns = val;
2064        trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
2065}
2066
2067static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
2068{
2069        if (kvm_arch_vcpu_runnable(vcpu)) {
2070                kvm_make_request(KVM_REQ_UNHALT, vcpu);
2071                return -EINTR;
2072        }
2073        if (kvm_cpu_has_pending_timer(vcpu))
2074                return -EINTR;
2075        if (signal_pending(current))
2076                return -EINTR;
2077
2078        return 0;
2079}
2080
2081/*
2082 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
2083 */
2084void kvm_vcpu_block(struct kvm_vcpu *vcpu)
2085{
2086        ktime_t start, cur;
2087        DEFINE_WAIT(wait);
2088        bool waited = false;
2089        u64 block_ns;
2090
2091        start = cur = ktime_get();
2092        if (vcpu->halt_poll_ns) {
2093                ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
2094
2095                ++vcpu->stat.halt_attempted_poll;
2096                do {
2097                        /*
2098                         * This sets KVM_REQ_UNHALT if an interrupt
2099                         * arrives.
2100                         */
2101                        if (kvm_vcpu_check_block(vcpu) < 0) {
2102                                ++vcpu->stat.halt_successful_poll;
2103                                goto out;
2104                        }
2105                        cur = ktime_get();
2106                } while (single_task_running() && (ktime_compare(cur, stop) < 0));
2107        }
2108
2109        kvm_arch_vcpu_blocking(vcpu);
2110
2111        for (;;) {
2112                prepare_to_wait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
2113
2114                if (kvm_vcpu_check_block(vcpu) < 0)
2115                        break;
2116
2117                waited = true;
2118                schedule();
2119        }
2120
2121        finish_wait(&vcpu->wq, &wait);
2122        cur = ktime_get();
2123
2124        kvm_arch_vcpu_unblocking(vcpu);
2125out:
2126        block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
2127
2128        if (halt_poll_ns) {
2129                if (block_ns <= vcpu->halt_poll_ns)
2130                        ;
2131                /* we had a long block, shrink polling */
2132                else if (vcpu->halt_poll_ns && block_ns > halt_poll_ns)
2133                        shrink_halt_poll_ns(vcpu);
2134                /* we had a short halt and our poll time is too small */
2135                else if (vcpu->halt_poll_ns < halt_poll_ns &&
2136                        block_ns < halt_poll_ns)
2137                        grow_halt_poll_ns(vcpu);
2138        } else
2139                vcpu->halt_poll_ns = 0;
2140
2141        trace_kvm_vcpu_wakeup(block_ns, waited);
2142}
2143EXPORT_SYMBOL_GPL(kvm_vcpu_block);
2144
2145#ifndef CONFIG_S390
2146void kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
2147{
2148        wait_queue_head_t *wqp;
2149
2150        wqp = kvm_arch_vcpu_wq(vcpu);
2151        if (waitqueue_active(wqp)) {
2152                wake_up_interruptible(wqp);
2153                ++vcpu->stat.halt_wakeup;
2154        }
2155
2156}
2157EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
2158
2159/*
2160 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
2161 */
2162void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
2163{
2164        int me;
2165        int cpu = vcpu->cpu;
2166
2167        kvm_vcpu_wake_up(vcpu);
2168        me = get_cpu();
2169        if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
2170                if (kvm_arch_vcpu_should_kick(vcpu))
2171                        smp_send_reschedule(cpu);
2172        put_cpu();
2173}
2174EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
2175#endif /* !CONFIG_S390 */
2176
2177int kvm_vcpu_yield_to(struct kvm_vcpu *target)
2178{
2179        struct pid *pid;
2180        struct task_struct *task = NULL;
2181        int ret = 0;
2182
2183        rcu_read_lock();
2184        pid = rcu_dereference(target->pid);
2185        if (pid)
2186                task = get_pid_task(pid, PIDTYPE_PID);
2187        rcu_read_unlock();
2188        if (!task)
2189                return ret;
2190        ret = yield_to(task, 1);
2191        put_task_struct(task);
2192
2193        return ret;
2194}
2195EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
2196
2197/*
2198 * Helper that checks whether a VCPU is eligible for directed yield.
2199 * Most eligible candidate to yield is decided by following heuristics:
2200 *
2201 *  (a) VCPU which has not done pl-exit or cpu relax intercepted recently
2202 *  (preempted lock holder), indicated by @in_spin_loop.
2203 *  Set at the beiginning and cleared at the end of interception/PLE handler.
2204 *
2205 *  (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
2206 *  chance last time (mostly it has become eligible now since we have probably
2207 *  yielded to lockholder in last iteration. This is done by toggling
2208 *  @dy_eligible each time a VCPU checked for eligibility.)
2209 *
2210 *  Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
2211 *  to preempted lock-holder could result in wrong VCPU selection and CPU
2212 *  burning. Giving priority for a potential lock-holder increases lock
2213 *  progress.
2214 *
2215 *  Since algorithm is based on heuristics, accessing another VCPU data without
2216 *  locking does not harm. It may result in trying to yield to  same VCPU, fail
2217 *  and continue with next VCPU and so on.
2218 */
2219static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
2220{
2221#ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
2222        bool eligible;
2223
2224        eligible = !vcpu->spin_loop.in_spin_loop ||
2225                    vcpu->spin_loop.dy_eligible;
2226
2227        if (vcpu->spin_loop.in_spin_loop)
2228                kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
2229
2230        return eligible;
2231#else
2232        return true;
2233#endif
2234}
2235
2236void kvm_vcpu_on_spin(struct kvm_vcpu *me)
2237{
2238        struct kvm *kvm = me->kvm;
2239        struct kvm_vcpu *vcpu;
2240        int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
2241        int yielded = 0;
2242        int try = 3;
2243        int pass;
2244        int i;
2245
2246        kvm_vcpu_set_in_spin_loop(me, true);
2247        /*
2248         * We boost the priority of a VCPU that is runnable but not
2249         * currently running, because it got preempted by something
2250         * else and called schedule in __vcpu_run.  Hopefully that
2251         * VCPU is holding the lock that we need and will release it.
2252         * We approximate round-robin by starting at the last boosted VCPU.
2253         */
2254        for (pass = 0; pass < 2 && !yielded && try; pass++) {
2255                kvm_for_each_vcpu(i, vcpu, kvm) {
2256                        if (!pass && i <= last_boosted_vcpu) {
2257                                i = last_boosted_vcpu;
2258                                continue;
2259                        } else if (pass && i > last_boosted_vcpu)
2260                                break;
2261                        if (!ACCESS_ONCE(vcpu->preempted))
2262                                continue;
2263                        if (vcpu == me)
2264                                continue;
2265                        if (waitqueue_active(&vcpu->wq) && !kvm_arch_vcpu_runnable(vcpu))
2266                                continue;
2267                        if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
2268                                continue;
2269
2270                        yielded = kvm_vcpu_yield_to(vcpu);
2271                        if (yielded > 0) {
2272                                kvm->last_boosted_vcpu = i;
2273                                break;
2274                        } else if (yielded < 0) {
2275                                try--;
2276                                if (!try)
2277                                        break;
2278                        }
2279                }
2280        }
2281        kvm_vcpu_set_in_spin_loop(me, false);
2282
2283        /* Ensure vcpu is not eligible during next spinloop */
2284        kvm_vcpu_set_dy_eligible(me, false);
2285}
2286EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
2287
2288static int kvm_vcpu_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
2289{
2290        struct kvm_vcpu *vcpu = vma->vm_file->private_data;
2291        struct page *page;
2292
2293        if (vmf->pgoff == 0)
2294                page = virt_to_page(vcpu->run);
2295#ifdef CONFIG_X86
2296        else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
2297                page = virt_to_page(vcpu->arch.pio_data);
2298#endif
2299#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2300        else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
2301                page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
2302#endif
2303        else
2304                return kvm_arch_vcpu_fault(vcpu, vmf);
2305        get_page(page);
2306        vmf->page = page;
2307        return 0;
2308}
2309
2310static const struct vm_operations_struct kvm_vcpu_vm_ops = {
2311        .fault = kvm_vcpu_fault,
2312};
2313
2314static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
2315{
2316        vma->vm_ops = &kvm_vcpu_vm_ops;
2317        return 0;
2318}
2319
2320static int kvm_vcpu_release(struct inode *inode, struct file *filp)
2321{
2322        struct kvm_vcpu *vcpu = filp->private_data;
2323
2324        debugfs_remove_recursive(vcpu->debugfs_dentry);
2325        kvm_put_kvm(vcpu->kvm);
2326        return 0;
2327}
2328
2329static struct file_operations kvm_vcpu_fops = {
2330        .release        = kvm_vcpu_release,
2331        .unlocked_ioctl = kvm_vcpu_ioctl,
2332#ifdef CONFIG_COMPAT
2333        .compat_ioctl   = kvm_vcpu_compat_ioctl,
2334#endif
2335        .mmap           = kvm_vcpu_mmap,
2336        .llseek         = noop_llseek,
2337};
2338
2339/*
2340 * Allocates an inode for the vcpu.
2341 */
2342static int create_vcpu_fd(struct kvm_vcpu *vcpu)
2343{
2344        return anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
2345}
2346
2347static int kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
2348{
2349        char dir_name[ITOA_MAX_LEN * 2];
2350        int ret;
2351
2352        if (!kvm_arch_has_vcpu_debugfs())
2353                return 0;
2354
2355        if (!debugfs_initialized())
2356                return 0;
2357
2358        snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
2359        vcpu->debugfs_dentry = debugfs_create_dir(dir_name,
2360                                                                vcpu->kvm->debugfs_dentry);
2361        if (!vcpu->debugfs_dentry)
2362                return -ENOMEM;
2363
2364        ret = kvm_arch_create_vcpu_debugfs(vcpu);
2365        if (ret < 0) {
2366                debugfs_remove_recursive(vcpu->debugfs_dentry);
2367                return ret;
2368        }
2369
2370        return 0;
2371}
2372
2373/*
2374 * Creates some virtual cpus.  Good luck creating more than one.
2375 */
2376static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
2377{
2378        int r;
2379        struct kvm_vcpu *vcpu, *v;
2380
2381        if (id >= KVM_MAX_VCPU_ID)
2382                return -EINVAL;
2383
2384        vcpu = kvm_arch_vcpu_create(kvm, id);
2385        if (IS_ERR(vcpu))
2386                return PTR_ERR(vcpu);
2387
2388        preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
2389
2390        r = kvm_arch_vcpu_setup(vcpu);
2391        if (r)
2392                goto vcpu_destroy;
2393
2394        r = kvm_create_vcpu_debugfs(vcpu);
2395        if (r)
2396                goto vcpu_destroy;
2397
2398        mutex_lock(&kvm->lock);
2399        if (!kvm_vcpu_compatible(vcpu)) {
2400                r = -EINVAL;
2401                goto unlock_vcpu_destroy;
2402        }
2403        if (atomic_read(&kvm->online_vcpus) == KVM_MAX_VCPUS) {
2404                r = -EINVAL;
2405                goto unlock_vcpu_destroy;
2406        }
2407
2408        kvm_for_each_vcpu(r, v, kvm)
2409                if (v->vcpu_id == id) {
2410                        r = -EEXIST;
2411                        goto unlock_vcpu_destroy;
2412                }
2413
2414        BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
2415
2416        /* Now it's all set up, let userspace reach it */
2417        kvm_get_kvm(kvm);
2418        r = create_vcpu_fd(vcpu);
2419        if (r < 0) {
2420                kvm_put_kvm(kvm);
2421                goto unlock_vcpu_destroy;
2422        }
2423
2424        kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
2425
2426        /*
2427         * Pairs with smp_rmb() in kvm_get_vcpu.  Write kvm->vcpus
2428         * before kvm->online_vcpu's incremented value.
2429         */
2430        smp_wmb();
2431        atomic_inc(&kvm->online_vcpus);
2432
2433        mutex_unlock(&kvm->lock);
2434        kvm_arch_vcpu_postcreate(vcpu);
2435        return r;
2436
2437unlock_vcpu_destroy:
2438        mutex_unlock(&kvm->lock);
2439        debugfs_remove_recursive(vcpu->debugfs_dentry);
2440vcpu_destroy:
2441        kvm_arch_vcpu_destroy(vcpu);
2442        return r;
2443}
2444
2445static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
2446{
2447        if (sigset) {
2448                sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
2449                vcpu->sigset_active = 1;
2450                vcpu->sigset = *sigset;
2451        } else
2452                vcpu->sigset_active = 0;
2453        return 0;
2454}
2455
2456static long kvm_vcpu_ioctl(struct file *filp,
2457                           unsigned int ioctl, unsigned long arg)
2458{
2459        struct kvm_vcpu *vcpu = filp->private_data;
2460        void __user *argp = (void __user *)arg;
2461        int r;
2462        struct kvm_fpu *fpu = NULL;
2463        struct kvm_sregs *kvm_sregs = NULL;
2464
2465        if (vcpu->kvm->mm != current->mm)
2466                return -EIO;
2467
2468        if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
2469                return -EINVAL;
2470
2471#if defined(CONFIG_S390) || defined(CONFIG_PPC) || defined(CONFIG_MIPS)
2472        /*
2473         * Special cases: vcpu ioctls that are asynchronous to vcpu execution,
2474         * so vcpu_load() would break it.
2475         */
2476        if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_INTERRUPT)
2477                return kvm_arch_vcpu_ioctl(filp, ioctl, arg);
2478#endif
2479
2480
2481        r = vcpu_load(vcpu);
2482        if (r)
2483                return r;
2484        switch (ioctl) {
2485        case KVM_RUN:
2486                r = -EINVAL;
2487                if (arg)
2488                        goto out;
2489                if (unlikely(vcpu->pid != current->pids[PIDTYPE_PID].pid)) {
2490                        /* The thread running this VCPU changed. */
2491                        struct pid *oldpid = vcpu->pid;
2492                        struct pid *newpid = get_task_pid(current, PIDTYPE_PID);
2493
2494                        rcu_assign_pointer(vcpu->pid, newpid);
2495                        if (oldpid)
2496                                synchronize_rcu();
2497                        put_pid(oldpid);
2498                }
2499                r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
2500                trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
2501                break;
2502        case KVM_GET_REGS: {
2503                struct kvm_regs *kvm_regs;
2504
2505                r = -ENOMEM;
2506                kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
2507                if (!kvm_regs)
2508                        goto out;
2509                r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
2510                if (r)
2511                        goto out_free1;
2512                r = -EFAULT;
2513                if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
2514                        goto out_free1;
2515                r = 0;
2516out_free1:
2517                kfree(kvm_regs);
2518                break;
2519        }
2520        case KVM_SET_REGS: {
2521                struct kvm_regs *kvm_regs;
2522
2523                r = -ENOMEM;
2524                kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
2525                if (IS_ERR(kvm_regs)) {
2526                        r = PTR_ERR(kvm_regs);
2527                        goto out;
2528                }
2529                r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
2530                kfree(kvm_regs);
2531                break;
2532        }
2533        case KVM_GET_SREGS: {
2534                kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
2535                r = -ENOMEM;
2536                if (!kvm_sregs)
2537                        goto out;
2538                r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
2539                if (r)
2540                        goto out;
2541                r = -EFAULT;
2542                if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
2543                        goto out;
2544                r = 0;
2545                break;
2546        }
2547        case KVM_SET_SREGS: {
2548                kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
2549                if (IS_ERR(kvm_sregs)) {
2550                        r = PTR_ERR(kvm_sregs);
2551                        kvm_sregs = NULL;
2552                        goto out;
2553                }
2554                r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
2555                break;
2556        }
2557        case KVM_GET_MP_STATE: {
2558                struct kvm_mp_state mp_state;
2559
2560                r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
2561                if (r)
2562                        goto out;
2563                r = -EFAULT;
2564                if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
2565                        goto out;
2566                r = 0;
2567                break;
2568        }
2569        case KVM_SET_MP_STATE: {
2570                struct kvm_mp_state mp_state;
2571
2572                r = -EFAULT;
2573                if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
2574                        goto out;
2575                r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
2576                break;
2577        }
2578        case KVM_TRANSLATE: {
2579                struct kvm_translation tr;
2580
2581                r = -EFAULT;
2582                if (copy_from_user(&tr, argp, sizeof(tr)))
2583                        goto out;
2584                r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
2585                if (r)
2586                        goto out;
2587                r = -EFAULT;
2588                if (copy_to_user(argp, &tr, sizeof(tr)))
2589                        goto out;
2590                r = 0;
2591                break;
2592        }
2593        case KVM_SET_GUEST_DEBUG: {
2594                struct kvm_guest_debug dbg;
2595
2596                r = -EFAULT;
2597                if (copy_from_user(&dbg, argp, sizeof(dbg)))
2598                        goto out;
2599                r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
2600                break;
2601        }
2602        case KVM_SET_SIGNAL_MASK: {
2603                struct kvm_signal_mask __user *sigmask_arg = argp;
2604                struct kvm_signal_mask kvm_sigmask;
2605                sigset_t sigset, *p;
2606
2607                p = NULL;
2608                if (argp) {
2609                        r = -EFAULT;
2610                        if (copy_from_user(&kvm_sigmask, argp,
2611                                           sizeof(kvm_sigmask)))
2612                                goto out;
2613                        r = -EINVAL;
2614                        if (kvm_sigmask.len != sizeof(sigset))
2615                                goto out;
2616                        r = -EFAULT;
2617                        if (copy_from_user(&sigset, sigmask_arg->sigset,
2618                                           sizeof(sigset)))
2619                                goto out;
2620                        p = &sigset;
2621                }
2622                r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
2623                break;
2624        }
2625        case KVM_GET_FPU: {
2626                fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
2627                r = -ENOMEM;
2628                if (!fpu)
2629                        goto out;
2630                r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
2631                if (r)
2632                        goto out;
2633                r = -EFAULT;
2634                if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
2635                        goto out;
2636                r = 0;
2637                break;
2638        }
2639        case KVM_SET_FPU: {
2640                fpu = memdup_user(argp, sizeof(*fpu));
2641                if (IS_ERR(fpu)) {
2642                        r = PTR_ERR(fpu);
2643                        fpu = NULL;
2644                        goto out;
2645                }
2646                r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
2647                break;
2648        }
2649        default:
2650                r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
2651        }
2652out:
2653        vcpu_put(vcpu);
2654        kfree(fpu);
2655        kfree(kvm_sregs);
2656        return r;
2657}
2658
2659#ifdef CONFIG_COMPAT
2660static long kvm_vcpu_compat_ioctl(struct file *filp,
2661                                  unsigned int ioctl, unsigned long arg)
2662{
2663        struct kvm_vcpu *vcpu = filp->private_data;
2664        void __user *argp = compat_ptr(arg);
2665        int r;
2666
2667        if (vcpu->kvm->mm != current->mm)
2668                return -EIO;
2669
2670        switch (ioctl) {
2671        case KVM_SET_SIGNAL_MASK: {
2672                struct kvm_signal_mask __user *sigmask_arg = argp;
2673                struct kvm_signal_mask kvm_sigmask;
2674                compat_sigset_t csigset;
2675                sigset_t sigset;
2676
2677                if (argp) {
2678                        r = -EFAULT;
2679                        if (copy_from_user(&kvm_sigmask, argp,
2680                                           sizeof(kvm_sigmask)))
2681                                goto out;
2682                        r = -EINVAL;
2683                        if (kvm_sigmask.len != sizeof(csigset))
2684                                goto out;
2685                        r = -EFAULT;
2686                        if (copy_from_user(&csigset, sigmask_arg->sigset,
2687                                           sizeof(csigset)))
2688                                goto out;
2689                        sigset_from_compat(&sigset, &csigset);
2690                        r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
2691                } else
2692                        r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
2693                break;
2694        }
2695        default:
2696                r = kvm_vcpu_ioctl(filp, ioctl, arg);
2697        }
2698
2699out:
2700        return r;
2701}
2702#endif
2703
2704static int kvm_device_ioctl_attr(struct kvm_device *dev,
2705                                 int (*accessor)(struct kvm_device *dev,
2706                                                 struct kvm_device_attr *attr),
2707                                 unsigned long arg)
2708{
2709        struct kvm_device_attr attr;
2710
2711        if (!accessor)
2712                return -EPERM;
2713
2714        if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
2715                return -EFAULT;
2716
2717        return accessor(dev, &attr);
2718}
2719
2720static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
2721                             unsigned long arg)
2722{
2723        struct kvm_device *dev = filp->private_data;
2724
2725        switch (ioctl) {
2726        case KVM_SET_DEVICE_ATTR:
2727                return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
2728        case KVM_GET_DEVICE_ATTR:
2729                return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
2730        case KVM_HAS_DEVICE_ATTR:
2731                return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
2732        default:
2733                if (dev->ops->ioctl)
2734                        return dev->ops->ioctl(dev, ioctl, arg);
2735
2736                return -ENOTTY;
2737        }
2738}
2739
2740static int kvm_device_release(struct inode *inode, struct file *filp)
2741{
2742        struct kvm_device *dev = filp->private_data;
2743        struct kvm *kvm = dev->kvm;
2744
2745        kvm_put_kvm(kvm);
2746        return 0;
2747}
2748
2749static const struct file_operations kvm_device_fops = {
2750        .unlocked_ioctl = kvm_device_ioctl,
2751#ifdef CONFIG_COMPAT
2752        .compat_ioctl = kvm_device_ioctl,
2753#endif
2754        .release = kvm_device_release,
2755};
2756
2757struct kvm_device *kvm_device_from_filp(struct file *filp)
2758{
2759        if (filp->f_op != &kvm_device_fops)
2760                return NULL;
2761
2762        return filp->private_data;
2763}
2764
2765static struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
2766#ifdef CONFIG_KVM_MPIC
2767        [KVM_DEV_TYPE_FSL_MPIC_20]      = &kvm_mpic_ops,
2768        [KVM_DEV_TYPE_FSL_MPIC_42]      = &kvm_mpic_ops,
2769#endif
2770
2771#ifdef CONFIG_KVM_XICS
2772        [KVM_DEV_TYPE_XICS]             = &kvm_xics_ops,
2773#endif
2774};
2775
2776int kvm_register_device_ops(struct kvm_device_ops *ops, u32 type)
2777{
2778        if (type >= ARRAY_SIZE(kvm_device_ops_table))
2779                return -ENOSPC;
2780
2781        if (kvm_device_ops_table[type] != NULL)
2782                return -EEXIST;
2783
2784        kvm_device_ops_table[type] = ops;
2785        return 0;
2786}
2787
2788void kvm_unregister_device_ops(u32 type)
2789{
2790        if (kvm_device_ops_table[type] != NULL)
2791                kvm_device_ops_table[type] = NULL;
2792}
2793
2794static int kvm_ioctl_create_device(struct kvm *kvm,
2795                                   struct kvm_create_device *cd)
2796{
2797        struct kvm_device_ops *ops = NULL;
2798        struct kvm_device *dev;
2799        bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
2800        int ret;
2801
2802        if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
2803                return -ENODEV;
2804
2805        ops = kvm_device_ops_table[cd->type];
2806        if (ops == NULL)
2807                return -ENODEV;
2808
2809        if (test)
2810                return 0;
2811
2812        dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2813        if (!dev)
2814                return -ENOMEM;
2815
2816        dev->ops = ops;
2817        dev->kvm = kvm;
2818
2819        ret = ops->create(dev, cd->type);
2820        if (ret < 0) {
2821                kfree(dev);
2822                return ret;
2823        }
2824
2825        ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
2826        if (ret < 0) {
2827                ops->destroy(dev);
2828                return ret;
2829        }
2830
2831        list_add(&dev->vm_node, &kvm->devices);
2832        kvm_get_kvm(kvm);
2833        cd->fd = ret;
2834        return 0;
2835}
2836
2837static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
2838{
2839        switch (arg) {
2840        case KVM_CAP_USER_MEMORY:
2841        case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
2842        case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
2843        case KVM_CAP_INTERNAL_ERROR_DATA:
2844#ifdef CONFIG_HAVE_KVM_MSI
2845        case KVM_CAP_SIGNAL_MSI:
2846#endif
2847#ifdef CONFIG_HAVE_KVM_IRQFD
2848        case KVM_CAP_IRQFD:
2849        case KVM_CAP_IRQFD_RESAMPLE:
2850#endif
2851        case KVM_CAP_IOEVENTFD_ANY_LENGTH:
2852        case KVM_CAP_CHECK_EXTENSION_VM:
2853                return 1;
2854#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
2855        case KVM_CAP_IRQ_ROUTING:
2856                return KVM_MAX_IRQ_ROUTES;
2857#endif
2858#if KVM_ADDRESS_SPACE_NUM > 1
2859        case KVM_CAP_MULTI_ADDRESS_SPACE:
2860                return KVM_ADDRESS_SPACE_NUM;
2861#endif
2862        case KVM_CAP_MAX_VCPU_ID:
2863                return KVM_MAX_VCPU_ID;
2864        default:
2865                break;
2866        }
2867        return kvm_vm_ioctl_check_extension(kvm, arg);
2868}
2869
2870static long kvm_vm_ioctl(struct file *filp,
2871                           unsigned int ioctl, unsigned long arg)
2872{
2873        struct kvm *kvm = filp->private_data;
2874        void __user *argp = (void __user *)arg;
2875        int r;
2876
2877        if (kvm->mm != current->mm)
2878                return -EIO;
2879        switch (ioctl) {
2880        case KVM_CREATE_VCPU:
2881                r = kvm_vm_ioctl_create_vcpu(kvm, arg);
2882                break;
2883        case KVM_SET_USER_MEMORY_REGION: {
2884                struct kvm_userspace_memory_region kvm_userspace_mem;
2885
2886                r = -EFAULT;
2887                if (copy_from_user(&kvm_userspace_mem, argp,
2888                                                sizeof(kvm_userspace_mem)))
2889                        goto out;
2890
2891                r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
2892                break;
2893        }
2894        case KVM_GET_DIRTY_LOG: {
2895                struct kvm_dirty_log log;
2896
2897                r = -EFAULT;
2898                if (copy_from_user(&log, argp, sizeof(log)))
2899                        goto out;
2900                r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
2901                break;
2902        }
2903#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
2904        case KVM_REGISTER_COALESCED_MMIO: {
2905                struct kvm_coalesced_mmio_zone zone;
2906
2907                r = -EFAULT;
2908                if (copy_from_user(&zone, argp, sizeof(zone)))
2909                        goto out;
2910                r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
2911                break;
2912        }
2913        case KVM_UNREGISTER_COALESCED_MMIO: {
2914                struct kvm_coalesced_mmio_zone zone;
2915
2916                r = -EFAULT;
2917                if (copy_from_user(&zone, argp, sizeof(zone)))
2918                        goto out;
2919                r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
2920                break;
2921        }
2922#endif
2923        case KVM_IRQFD: {
2924                struct kvm_irqfd data;
2925
2926                r = -EFAULT;
2927                if (copy_from_user(&data, argp, sizeof(data)))
2928                        goto out;
2929                r = kvm_irqfd(kvm, &data);
2930                break;
2931        }
2932        case KVM_IOEVENTFD: {
2933                struct kvm_ioeventfd data;
2934
2935                r = -EFAULT;
2936                if (copy_from_user(&data, argp, sizeof(data)))
2937                        goto out;
2938                r = kvm_ioeventfd(kvm, &data);
2939                break;
2940        }
2941#ifdef CONFIG_HAVE_KVM_MSI
2942        case KVM_SIGNAL_MSI: {
2943                struct kvm_msi msi;
2944
2945                r = -EFAULT;
2946                if (copy_from_user(&msi, argp, sizeof(msi)))
2947                        goto out;
2948                r = kvm_send_userspace_msi(kvm, &msi);
2949                break;
2950        }
2951#endif
2952#ifdef __KVM_HAVE_IRQ_LINE
2953        case KVM_IRQ_LINE_STATUS:
2954        case KVM_IRQ_LINE: {
2955                struct kvm_irq_level irq_event;
2956
2957                r = -EFAULT;
2958                if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
2959                        goto out;
2960
2961                r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
2962                                        ioctl == KVM_IRQ_LINE_STATUS);
2963                if (r)
2964                        goto out;
2965
2966                r = -EFAULT;
2967                if (ioctl == KVM_IRQ_LINE_STATUS) {
2968                        if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
2969                                goto out;
2970                }
2971
2972                r = 0;
2973                break;
2974        }
2975#endif
2976#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
2977        case KVM_SET_GSI_ROUTING: {
2978                struct kvm_irq_routing routing;
2979                struct kvm_irq_routing __user *urouting;
2980                struct kvm_irq_routing_entry *entries = NULL;
2981
2982                r = -EFAULT;
2983                if (copy_from_user(&routing, argp, sizeof(routing)))
2984                        goto out;
2985                r = -EINVAL;
2986                if (routing.nr > KVM_MAX_IRQ_ROUTES)
2987                        goto out;
2988                if (routing.flags)
2989                        goto out;
2990                if (routing.nr) {
2991                        r = -ENOMEM;
2992                        entries = vmalloc(routing.nr * sizeof(*entries));
2993                        if (!entries)
2994                                goto out;
2995                        r = -EFAULT;
2996                        urouting = argp;
2997                        if (copy_from_user(entries, urouting->entries,
2998                                           routing.nr * sizeof(*entries)))
2999                                goto out_free_irq_routing;
3000                }
3001                r = kvm_set_irq_routing(kvm, entries, routing.nr,
3002                                        routing.flags);
3003out_free_irq_routing:
3004                vfree(entries);
3005                break;
3006        }
3007#endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
3008        case KVM_CREATE_DEVICE: {
3009                struct kvm_create_device cd;
3010
3011                r = -EFAULT;
3012                if (copy_from_user(&cd, argp, sizeof(cd)))
3013                        goto out;
3014
3015                r = kvm_ioctl_create_device(kvm, &cd);
3016                if (r)
3017                        goto out;
3018
3019                r = -EFAULT;
3020                if (copy_to_user(argp, &cd, sizeof(cd)))
3021                        goto out;
3022
3023                r = 0;
3024                break;
3025        }
3026        case KVM_CHECK_EXTENSION:
3027                r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
3028                break;
3029        default:
3030                r = kvm_arch_vm_ioctl(filp, ioctl, arg);
3031        }
3032out:
3033        return r;
3034}
3035
3036#ifdef CONFIG_COMPAT
3037struct compat_kvm_dirty_log {
3038        __u32 slot;
3039        __u32 padding1;
3040        union {
3041                compat_uptr_t dirty_bitmap; /* one bit per page */
3042                __u64 padding2;
3043        };
3044};
3045
3046static long kvm_vm_compat_ioctl(struct file *filp,
3047                           unsigned int ioctl, unsigned long arg)
3048{
3049        struct kvm *kvm = filp->private_data;
3050        int r;
3051
3052        if (kvm->mm != current->mm)
3053                return -EIO;
3054        switch (ioctl) {
3055        case KVM_GET_DIRTY_LOG: {
3056                struct compat_kvm_dirty_log compat_log;
3057                struct kvm_dirty_log log;
3058
3059                r = -EFAULT;
3060                if (copy_from_user(&compat_log, (void __user *)arg,
3061                                   sizeof(compat_log)))
3062                        goto out;
3063                log.slot         = compat_log.slot;
3064                log.padding1     = compat_log.padding1;
3065                log.padding2     = compat_log.padding2;
3066                log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
3067
3068                r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
3069                break;
3070        }
3071        default:
3072                r = kvm_vm_ioctl(filp, ioctl, arg);
3073        }
3074
3075out:
3076        return r;
3077}
3078#endif
3079
3080static struct file_operations kvm_vm_fops = {
3081        .release        = kvm_vm_release,
3082        .unlocked_ioctl = kvm_vm_ioctl,
3083#ifdef CONFIG_COMPAT
3084        .compat_ioctl   = kvm_vm_compat_ioctl,
3085#endif
3086        .llseek         = noop_llseek,
3087};
3088
3089static int kvm_dev_ioctl_create_vm(unsigned long type)
3090{
3091        int r;
3092        struct kvm *kvm;
3093        struct file *file;
3094
3095        kvm = kvm_create_vm(type);
3096        if (IS_ERR(kvm))
3097                return PTR_ERR(kvm);
3098#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
3099        r = kvm_coalesced_mmio_init(kvm);
3100        if (r < 0) {
3101                kvm_put_kvm(kvm);
3102                return r;
3103        }
3104#endif
3105        r = get_unused_fd_flags(O_CLOEXEC);
3106        if (r < 0) {
3107                kvm_put_kvm(kvm);
3108                return r;
3109        }
3110        file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
3111        if (IS_ERR(file)) {
3112                put_unused_fd(r);
3113                kvm_put_kvm(kvm);
3114                return PTR_ERR(file);
3115        }
3116
3117        if (kvm_create_vm_debugfs(kvm, r) < 0) {
3118                put_unused_fd(r);
3119                fput(file);
3120                return -ENOMEM;
3121        }
3122
3123        fd_install(r, file);
3124        return r;
3125}
3126
3127static long kvm_dev_ioctl(struct file *filp,
3128                          unsigned int ioctl, unsigned long arg)
3129{
3130        long r = -EINVAL;
3131
3132        switch (ioctl) {
3133        case KVM_GET_API_VERSION:
3134                if (arg)
3135                        goto out;
3136                r = KVM_API_VERSION;
3137                break;
3138        case KVM_CREATE_VM:
3139                r = kvm_dev_ioctl_create_vm(arg);
3140                break;
3141        case KVM_CHECK_EXTENSION:
3142                r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
3143                break;
3144        case KVM_GET_VCPU_MMAP_SIZE:
3145                if (arg)
3146                        goto out;
3147                r = PAGE_SIZE;     /* struct kvm_run */
3148#ifdef CONFIG_X86
3149                r += PAGE_SIZE;    /* pio data page */
3150#endif
3151#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
3152                r += PAGE_SIZE;    /* coalesced mmio ring page */
3153#endif
3154                break;
3155        case KVM_TRACE_ENABLE:
3156        case KVM_TRACE_PAUSE:
3157        case KVM_TRACE_DISABLE:
3158                r = -EOPNOTSUPP;
3159                break;
3160        default:
3161                return kvm_arch_dev_ioctl(filp, ioctl, arg);
3162        }
3163out:
3164        return r;
3165}
3166
3167static struct file_operations kvm_chardev_ops = {
3168        .unlocked_ioctl = kvm_dev_ioctl,
3169        .compat_ioctl   = kvm_dev_ioctl,
3170        .llseek         = noop_llseek,
3171};
3172
3173static struct miscdevice kvm_dev = {
3174        KVM_MINOR,
3175        "kvm",
3176        &kvm_chardev_ops,
3177};
3178
3179static void hardware_enable_nolock(void *junk)
3180{
3181        int cpu = raw_smp_processor_id();
3182        int r;
3183
3184        if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
3185                return;
3186
3187        cpumask_set_cpu(cpu, cpus_hardware_enabled);
3188
3189        r = kvm_arch_hardware_enable();
3190
3191        if (r) {
3192                cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3193                atomic_inc(&hardware_enable_failed);
3194                pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
3195        }
3196}
3197
3198static void hardware_enable(void)
3199{
3200        raw_spin_lock(&kvm_count_lock);
3201        if (kvm_usage_count)
3202                hardware_enable_nolock(NULL);
3203        raw_spin_unlock(&kvm_count_lock);
3204}
3205
3206static void hardware_disable_nolock(void *junk)
3207{
3208        int cpu = raw_smp_processor_id();
3209
3210        if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
3211                return;
3212        cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3213        kvm_arch_hardware_disable();
3214}
3215
3216static void hardware_disable(void)
3217{
3218        raw_spin_lock(&kvm_count_lock);
3219        if (kvm_usage_count)
3220                hardware_disable_nolock(NULL);
3221        raw_spin_unlock(&kvm_count_lock);
3222}
3223
3224static void hardware_disable_all_nolock(void)
3225{
3226        BUG_ON(!kvm_usage_count);
3227
3228        kvm_usage_count--;
3229        if (!kvm_usage_count)
3230                on_each_cpu(hardware_disable_nolock, NULL, 1);
3231}
3232
3233static void hardware_disable_all(void)
3234{
3235        int count;
3236        char count_string[20];
3237        char event_string[] = "EVENT=terminate";
3238        char *envp[] = { event_string, count_string, NULL };
3239
3240        raw_spin_lock(&kvm_count_lock);
3241        hardware_disable_all_nolock();
3242        count = kvm_usage_count;
3243        raw_spin_unlock(&kvm_count_lock);
3244
3245        sprintf(count_string, "COUNT=%d", count);
3246        kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, envp);
3247}
3248
3249static int hardware_enable_all(void)
3250{
3251        int r = 0;
3252        int count;
3253
3254        raw_spin_lock(&kvm_count_lock);
3255
3256        count = ++kvm_usage_count;
3257        if (kvm_usage_count == 1) {
3258                atomic_set(&hardware_enable_failed, 0);
3259                on_each_cpu(hardware_enable_nolock, NULL, 1);
3260
3261                if (atomic_read(&hardware_enable_failed)) {
3262                        hardware_disable_all_nolock();
3263                        r = -EBUSY;
3264                }
3265        }
3266
3267        raw_spin_unlock(&kvm_count_lock);
3268
3269        if (r == 0) {
3270                char count_string[20];
3271                char event_string[] = "EVENT=create";
3272                char *envp[] = { event_string, count_string, NULL };
3273
3274                sprintf(count_string, "COUNT=%d", count);
3275                kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, envp);
3276        }
3277        return r;
3278}
3279
3280static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
3281                           void *v)
3282{
3283        val &= ~CPU_TASKS_FROZEN;
3284        switch (val) {
3285        case CPU_DYING:
3286                hardware_disable();
3287                break;
3288        case CPU_STARTING:
3289                hardware_enable();
3290                break;
3291        }
3292        return NOTIFY_OK;
3293}
3294
3295static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
3296                      void *v)
3297{
3298        /*
3299         * Some (well, at least mine) BIOSes hang on reboot if
3300         * in vmx root mode.
3301         *
3302         * And Intel TXT required VMX off for all cpu when system shutdown.
3303         */
3304        pr_info("kvm: exiting hardware virtualization\n");
3305        kvm_rebooting = true;
3306        on_each_cpu(hardware_disable_nolock, NULL, 1);
3307        return NOTIFY_OK;
3308}
3309
3310static struct notifier_block kvm_reboot_notifier = {
3311        .notifier_call = kvm_reboot,
3312        .priority = 0,
3313};
3314
3315static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
3316{
3317        int i;
3318
3319        for (i = 0; i < bus->dev_count; i++) {
3320                struct kvm_io_device *pos = bus->range[i].dev;
3321
3322                kvm_iodevice_destructor(pos);
3323        }
3324        kfree(bus);
3325}
3326
3327static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
3328                                 const struct kvm_io_range *r2)
3329{
3330        gpa_t addr1 = r1->addr;
3331        gpa_t addr2 = r2->addr;
3332
3333        if (addr1 < addr2)
3334                return -1;
3335
3336        /* If r2->len == 0, match the exact address.  If r2->len != 0,
3337         * accept any overlapping write.  Any order is acceptable for
3338         * overlapping ranges, because kvm_io_bus_get_first_dev ensures
3339         * we process all of them.
3340         */
3341        if (r2->len) {
3342                addr1 += r1->len;
3343                addr2 += r2->len;
3344        }
3345
3346        if (addr1 > addr2)
3347                return 1;
3348
3349        return 0;
3350}
3351
3352static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
3353{
3354        return kvm_io_bus_cmp(p1, p2);
3355}
3356
3357static int kvm_io_bus_insert_dev(struct kvm_io_bus *bus, struct kvm_io_device *dev,
3358                          gpa_t addr, int len)
3359{
3360        bus->range[bus->dev_count++] = (struct kvm_io_range) {
3361                .addr = addr,
3362                .len = len,
3363                .dev = dev,
3364        };
3365
3366        sort(bus->range, bus->dev_count, sizeof(struct kvm_io_range),
3367                kvm_io_bus_sort_cmp, NULL);
3368
3369        return 0;
3370}
3371
3372static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
3373                             gpa_t addr, int len)
3374{
3375        struct kvm_io_range *range, key;
3376        int off;
3377
3378        key = (struct kvm_io_range) {
3379                .addr = addr,
3380                .len = len,
3381        };
3382
3383        range = bsearch(&key, bus->range, bus->dev_count,
3384                        sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
3385        if (range == NULL)
3386                return -ENOENT;
3387
3388        off = range - bus->range;
3389
3390        while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
3391                off--;
3392
3393        return off;
3394}
3395
3396static int __kvm_io_bus_write(struct kvm_io_bus *bus,
3397                              struct kvm_io_range *range, const void *val)
3398{
3399        int idx;
3400
3401        idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3402        if (idx < 0)
3403                return -EOPNOTSUPP;
3404
3405        while (idx < bus->dev_count &&
3406                kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3407                if (!kvm_iodevice_write(bus->range[idx].dev, range->addr,
3408                                        range->len, val))
3409                        return idx;
3410                idx++;
3411        }
3412
3413        return -EOPNOTSUPP;
3414}
3415
3416/* kvm_io_bus_write - called under kvm->slots_lock */
3417int kvm_io_bus_write(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
3418                     int len, const void *val)
3419{
3420        struct kvm_io_bus *bus;
3421        struct kvm_io_range range;
3422        int r;
3423
3424        range = (struct kvm_io_range) {
3425                .addr = addr,
3426                .len = len,
3427        };
3428
3429        bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
3430        r = __kvm_io_bus_write(bus, &range, val);
3431        return r < 0 ? r : 0;
3432}
3433
3434/* kvm_io_bus_write_cookie - called under kvm->slots_lock */
3435int kvm_io_bus_write_cookie(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
3436                            int len, const void *val, long cookie)
3437{
3438        struct kvm_io_bus *bus;
3439        struct kvm_io_range range;
3440
3441        range = (struct kvm_io_range) {
3442                .addr = addr,
3443                .len = len,
3444        };
3445
3446        bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
3447
3448        /* First try the device referenced by cookie. */
3449        if ((cookie >= 0) && (cookie < bus->dev_count) &&
3450            (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
3451                if (!kvm_iodevice_write(bus->range[cookie].dev, addr, len,
3452                                        val))
3453                        return cookie;
3454
3455        /*
3456         * cookie contained garbage; fall back to search and return the
3457         * correct cookie value.
3458         */
3459        return __kvm_io_bus_write(bus, &range, val);
3460}
3461
3462static int __kvm_io_bus_read(struct kvm_io_bus *bus, struct kvm_io_range *range,
3463                             void *val)
3464{
3465        int idx;
3466
3467        idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
3468        if (idx < 0)
3469                return -EOPNOTSUPP;
3470
3471        while (idx < bus->dev_count &&
3472                kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
3473                if (!kvm_iodevice_read(bus->range[idx].dev, range->addr,
3474                                       range->len, val))
3475                        return idx;
3476                idx++;
3477        }
3478
3479        return -EOPNOTSUPP;
3480}
3481EXPORT_SYMBOL_GPL(kvm_io_bus_write);
3482
3483/* kvm_io_bus_read - called under kvm->slots_lock */
3484int kvm_io_bus_read(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
3485                    int len, void *val)
3486{
3487        struct kvm_io_bus *bus;
3488        struct kvm_io_range range;
3489        int r;
3490
3491        range = (struct kvm_io_range) {
3492                .addr = addr,
3493                .len = len,
3494        };
3495
3496        bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
3497        r = __kvm_io_bus_read(bus, &range, val);
3498        return r < 0 ? r : 0;
3499}
3500
3501
3502/* Caller must hold slots_lock. */
3503int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
3504                            int len, struct kvm_io_device *dev)
3505{
3506        struct kvm_io_bus *new_bus, *bus;
3507
3508        bus = kvm->buses[bus_idx];
3509        /* exclude ioeventfd which is limited by maximum fd */
3510        if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
3511                return -ENOSPC;
3512
3513        new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count + 1) *
3514                          sizeof(struct kvm_io_range)), GFP_KERNEL);
3515        if (!new_bus)
3516                return -ENOMEM;
3517        memcpy(new_bus, bus, sizeof(*bus) + (bus->dev_count *
3518               sizeof(struct kvm_io_range)));
3519        kvm_io_bus_insert_dev(new_bus, dev, addr, len);
3520        rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3521        synchronize_srcu_expedited(&kvm->srcu);
3522        kfree(bus);
3523
3524        return 0;
3525}
3526
3527/* Caller must hold slots_lock. */
3528int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
3529                              struct kvm_io_device *dev)
3530{
3531        int i, r;
3532        struct kvm_io_bus *new_bus, *bus;
3533
3534        bus = kvm->buses[bus_idx];
3535        r = -ENOENT;
3536        for (i = 0; i < bus->dev_count; i++)
3537                if (bus->range[i].dev == dev) {
3538                        r = 0;
3539                        break;
3540                }
3541
3542        if (r)
3543                return r;
3544
3545        new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count - 1) *
3546                          sizeof(struct kvm_io_range)), GFP_KERNEL);
3547        if (!new_bus)
3548                return -ENOMEM;
3549
3550        memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
3551        new_bus->dev_count--;
3552        memcpy(new_bus->range + i, bus->range + i + 1,
3553               (new_bus->dev_count - i) * sizeof(struct kvm_io_range));
3554
3555        rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
3556        synchronize_srcu_expedited(&kvm->srcu);
3557        kfree(bus);
3558        return r;
3559}
3560
3561static struct notifier_block kvm_cpu_notifier = {
3562        .notifier_call = kvm_cpu_hotplug,
3563};
3564
3565static int kvm_debugfs_open(struct inode *inode, struct file *file,
3566                           int (*get)(void *, u64 *), int (*set)(void *, u64),
3567                           const char *fmt)
3568{
3569        struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
3570                                          inode->i_private;
3571
3572        /* The debugfs files are a reference to the kvm struct which
3573         * is still valid when kvm_destroy_vm is called.
3574         * To avoid the race between open and the removal of the debugfs
3575         * directory we test against the users count.
3576         */
3577        if (!atomic_add_unless(&stat_data->kvm->users_count, 1, 0))
3578                return -ENOENT;
3579
3580        if (simple_attr_open(inode, file, get, set, fmt)) {
3581                kvm_put_kvm(stat_data->kvm);
3582                return -ENOMEM;
3583        }
3584
3585        return 0;
3586}
3587
3588static int kvm_debugfs_release(struct inode *inode, struct file *file)
3589{
3590        struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
3591                                          inode->i_private;
3592
3593        simple_attr_release(inode, file);
3594        kvm_put_kvm(stat_data->kvm);
3595
3596        return 0;
3597}
3598
3599static int vm_stat_get_per_vm(void *data, u64 *val)
3600{
3601        struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3602
3603        *val = *(ulong *)((void *)stat_data->kvm + stat_data->offset);
3604
3605        return 0;
3606}
3607
3608static int vm_stat_get_per_vm_open(struct inode *inode, struct file *file)
3609{
3610        __simple_attr_check_format("%llu\n", 0ull);
3611        return kvm_debugfs_open(inode, file, vm_stat_get_per_vm,
3612                                NULL, "%llu\n");
3613}
3614
3615static const struct file_operations vm_stat_get_per_vm_fops = {
3616        .owner   = THIS_MODULE,
3617        .open    = vm_stat_get_per_vm_open,
3618        .release = kvm_debugfs_release,
3619        .read    = simple_attr_read,
3620        .write   = simple_attr_write,
3621        .llseek  = generic_file_llseek,
3622};
3623
3624static int vcpu_stat_get_per_vm(void *data, u64 *val)
3625{
3626        int i;
3627        struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
3628        struct kvm_vcpu *vcpu;
3629
3630        *val = 0;
3631
3632        kvm_for_each_vcpu(i, vcpu, stat_data->kvm)
3633                *val += *(u64 *)((void *)vcpu + stat_data->offset);
3634
3635        return 0;
3636}
3637
3638static int vcpu_stat_get_per_vm_open(struct inode *inode, struct file *file)
3639{
3640        __simple_attr_check_format("%llu\n", 0ull);
3641        return kvm_debugfs_open(inode, file, vcpu_stat_get_per_vm,
3642                                 NULL, "%llu\n");
3643}
3644
3645static const struct file_operations vcpu_stat_get_per_vm_fops = {
3646        .owner   = THIS_MODULE,
3647        .open    = vcpu_stat_get_per_vm_open,
3648        .release = kvm_debugfs_release,
3649        .read    = simple_attr_read,
3650        .write   = simple_attr_write,
3651        .llseek  = generic_file_llseek,
3652};
3653
3654static const struct file_operations *stat_fops_per_vm[] = {
3655        [KVM_STAT_VCPU] = &vcpu_stat_get_per_vm_fops,
3656        [KVM_STAT_VM]   = &vm_stat_get_per_vm_fops,
3657};
3658
3659static int vm_stat_get(void *_offset, u64 *val)
3660{
3661        unsigned offset = (long)_offset;
3662        struct kvm *kvm;
3663        struct kvm_stat_data stat_tmp = {.offset = offset};
3664        u64 tmp_val;
3665
3666        *val = 0;
3667        spin_lock(&kvm_lock);
3668        list_for_each_entry(kvm, &vm_list, vm_list) {
3669                stat_tmp.kvm = kvm;
3670                vm_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
3671                *val += tmp_val;
3672        }
3673        spin_unlock(&kvm_lock);
3674        return 0;
3675}
3676
3677DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, NULL, "%llu\n");
3678
3679static int vcpu_stat_get(void *_offset, u64 *val)
3680{
3681        unsigned offset = (long)_offset;
3682        struct kvm *kvm;
3683        struct kvm_stat_data stat_tmp = {.offset = offset};
3684        u64 tmp_val;
3685
3686        *val = 0;
3687        spin_lock(&kvm_lock);
3688        list_for_each_entry(kvm, &vm_list, vm_list) {
3689                stat_tmp.kvm = kvm;
3690                vcpu_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
3691                *val += tmp_val;
3692        }
3693        spin_unlock(&kvm_lock);
3694        return 0;
3695}
3696
3697DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, NULL, "%llu\n");
3698
3699static const struct file_operations *stat_fops[] = {
3700        [KVM_STAT_VCPU] = &vcpu_stat_fops,
3701        [KVM_STAT_VM]   = &vm_stat_fops,
3702};
3703
3704static int kvm_init_debug(void)
3705{
3706        int r = -EEXIST;
3707        struct kvm_stats_debugfs_item *p;
3708
3709        kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
3710        if (kvm_debugfs_dir == NULL)
3711                goto out;
3712
3713        kvm_debugfs_num_entries = 0;
3714        for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
3715                if (!debugfs_create_file(p->name, 0444, kvm_debugfs_dir,
3716                                         (void *)(long)p->offset,
3717                                         stat_fops[p->kind]))
3718                        goto out_dir;
3719        }
3720
3721        return 0;
3722
3723out_dir:
3724        debugfs_remove_recursive(kvm_debugfs_dir);
3725out:
3726        return r;
3727}
3728
3729static int kvm_suspend(void)
3730{
3731        if (kvm_usage_count)
3732                hardware_disable_nolock(NULL);
3733        return 0;
3734}
3735
3736static void kvm_resume(void)
3737{
3738        if (kvm_usage_count) {
3739                WARN_ON(raw_spin_is_locked(&kvm_count_lock));
3740                hardware_enable_nolock(NULL);
3741        }
3742}
3743
3744static struct syscore_ops kvm_syscore_ops = {
3745        .suspend = kvm_suspend,
3746        .resume = kvm_resume,
3747};
3748
3749static inline
3750struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
3751{
3752        return container_of(pn, struct kvm_vcpu, preempt_notifier);
3753}
3754
3755static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
3756{
3757        struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
3758
3759        if (vcpu->preempted)
3760                vcpu->preempted = false;
3761
3762        kvm_arch_sched_in(vcpu, cpu);
3763
3764        kvm_arch_vcpu_load(vcpu, cpu);
3765}
3766
3767static void kvm_sched_out(struct preempt_notifier *pn,
3768                          struct task_struct *next)
3769{
3770        struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
3771
3772        if (current->state == TASK_RUNNING)
3773                vcpu->preempted = true;
3774        kvm_arch_vcpu_put(vcpu);
3775}
3776
3777int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
3778                  struct module *module)
3779{
3780        int r;
3781        int cpu;
3782
3783        r = kvm_arch_init(opaque);
3784        if (r)
3785                goto out_fail;
3786
3787        /*
3788         * kvm_arch_init makes sure there's at most one caller
3789         * for architectures that support multiple implementations,
3790         * like intel and amd on x86.
3791         * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
3792         * conflicts in case kvm is already setup for another implementation.
3793         */
3794        r = kvm_irqfd_init();
3795        if (r)
3796                goto out_irqfd;
3797
3798        if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
3799                r = -ENOMEM;
3800                goto out_free_0;
3801        }
3802
3803        r = kvm_arch_hardware_setup();
3804        if (r < 0)
3805                goto out_free_0a;
3806
3807        for_each_online_cpu(cpu) {
3808                smp_call_function_single(cpu,
3809                                kvm_arch_check_processor_compat,
3810                                &r, 1);
3811                if (r < 0)
3812                        goto out_free_1;
3813        }
3814
3815        r = register_cpu_notifier(&kvm_cpu_notifier);
3816        if (r)
3817                goto out_free_2;
3818        register_reboot_notifier(&kvm_reboot_notifier);
3819
3820        /* A kmem cache lets us meet the alignment requirements of fx_save. */
3821        if (!vcpu_align)
3822                vcpu_align = __alignof__(struct kvm_vcpu);
3823        kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size, vcpu_align,
3824                                           0, NULL);
3825        if (!kvm_vcpu_cache) {
3826                r = -ENOMEM;
3827                goto out_free_3;
3828        }
3829
3830        r = kvm_async_pf_init();
3831        if (r)
3832                goto out_free;
3833
3834        kvm_chardev_ops.owner = module;
3835        kvm_vm_fops.owner = module;
3836        kvm_vcpu_fops.owner = module;
3837
3838        r = misc_register(&kvm_dev);
3839        if (r) {
3840                pr_err("kvm: misc device register failed\n");
3841                goto out_unreg;
3842        }
3843
3844        register_syscore_ops(&kvm_syscore_ops);
3845
3846        kvm_preempt_ops.sched_in = kvm_sched_in;
3847        kvm_preempt_ops.sched_out = kvm_sched_out;
3848
3849        r = kvm_init_debug();
3850        if (r) {
3851                pr_err("kvm: create debugfs files failed\n");
3852                goto out_undebugfs;
3853        }
3854
3855        r = kvm_vfio_ops_init();
3856        WARN_ON(r);
3857
3858        return 0;
3859
3860out_undebugfs:
3861        unregister_syscore_ops(&kvm_syscore_ops);
3862        misc_deregister(&kvm_dev);
3863out_unreg:
3864        kvm_async_pf_deinit();
3865out_free:
3866        kmem_cache_destroy(kvm_vcpu_cache);
3867out_free_3:
3868        unregister_reboot_notifier(&kvm_reboot_notifier);
3869        unregister_cpu_notifier(&kvm_cpu_notifier);
3870out_free_2:
3871out_free_1:
3872        kvm_arch_hardware_unsetup();
3873out_free_0a:
3874        free_cpumask_var(cpus_hardware_enabled);
3875out_free_0:
3876        kvm_irqfd_exit();
3877out_irqfd:
3878        kvm_arch_exit();
3879out_fail:
3880        return r;
3881}
3882EXPORT_SYMBOL_GPL(kvm_init);
3883
3884void kvm_exit(void)
3885{
3886        debugfs_remove_recursive(kvm_debugfs_dir);
3887        misc_deregister(&kvm_dev);
3888        kmem_cache_destroy(kvm_vcpu_cache);
3889        kvm_async_pf_deinit();
3890        unregister_syscore_ops(&kvm_syscore_ops);
3891        unregister_reboot_notifier(&kvm_reboot_notifier);
3892        unregister_cpu_notifier(&kvm_cpu_notifier);
3893        on_each_cpu(hardware_disable_nolock, NULL, 1);
3894        kvm_arch_hardware_unsetup();
3895        kvm_arch_exit();
3896        kvm_irqfd_exit();
3897        free_cpumask_var(cpus_hardware_enabled);
3898        kvm_vfio_ops_exit();
3899}
3900EXPORT_SYMBOL_GPL(kvm_exit);
3901