linux/arch/x86/kvm/vmx.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 "irq.h"
  20#include "mmu.h"
  21#include "cpuid.h"
  22
  23#include <linux/kvm_host.h>
  24#include <linux/module.h>
  25#include <linux/kernel.h>
  26#include <linux/mm.h>
  27#include <linux/highmem.h>
  28#include <linux/sched.h>
  29#include <linux/moduleparam.h>
  30#include <linux/mod_devicetable.h>
  31#include <linux/ftrace_event.h>
  32#include <linux/slab.h>
  33#include <linux/tboot.h>
  34#include <linux/hrtimer.h>
  35#include "kvm_cache_regs.h"
  36#include "x86.h"
  37
  38#include <asm/io.h>
  39#include <asm/desc.h>
  40#include <asm/vmx.h>
  41#include <asm/virtext.h>
  42#include <asm/mce.h>
  43#include <asm/i387.h>
  44#include <asm/xcr.h>
  45#include <asm/perf_event.h>
  46#include <asm/debugreg.h>
  47#include <asm/kexec.h>
  48
  49#include "trace.h"
  50
  51#define __ex(x) __kvm_handle_fault_on_reboot(x)
  52#define __ex_clear(x, reg) \
  53        ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
  54
  55MODULE_AUTHOR("Qumranet");
  56MODULE_LICENSE("GPL");
  57
  58static const struct x86_cpu_id vmx_cpu_id[] = {
  59        X86_FEATURE_MATCH(X86_FEATURE_VMX),
  60        {}
  61};
  62MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
  63
  64static bool __read_mostly enable_vpid = 1;
  65module_param_named(vpid, enable_vpid, bool, 0444);
  66
  67static bool __read_mostly flexpriority_enabled = 1;
  68module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
  69
  70static bool __read_mostly enable_ept = 1;
  71module_param_named(ept, enable_ept, bool, S_IRUGO);
  72
  73static bool __read_mostly enable_unrestricted_guest = 1;
  74module_param_named(unrestricted_guest,
  75                        enable_unrestricted_guest, bool, S_IRUGO);
  76
  77static bool __read_mostly enable_ept_ad_bits = 1;
  78module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
  79
  80static bool __read_mostly emulate_invalid_guest_state = true;
  81module_param(emulate_invalid_guest_state, bool, S_IRUGO);
  82
  83static bool __read_mostly vmm_exclusive = 1;
  84module_param(vmm_exclusive, bool, S_IRUGO);
  85
  86static bool __read_mostly fasteoi = 1;
  87module_param(fasteoi, bool, S_IRUGO);
  88
  89static bool __read_mostly enable_apicv = 1;
  90module_param(enable_apicv, bool, S_IRUGO);
  91
  92static bool __read_mostly enable_shadow_vmcs = 1;
  93module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
  94/*
  95 * If nested=1, nested virtualization is supported, i.e., guests may use
  96 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
  97 * use VMX instructions.
  98 */
  99static bool __read_mostly nested = 0;
 100module_param(nested, bool, S_IRUGO);
 101
 102#define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
 103#define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST (X86_CR0_WP | X86_CR0_NE)
 104#define KVM_VM_CR0_ALWAYS_ON                                            \
 105        (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
 106#define KVM_CR4_GUEST_OWNED_BITS                                      \
 107        (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR      \
 108         | X86_CR4_OSXMMEXCPT)
 109
 110#define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
 111#define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
 112
 113#define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
 114
 115#define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
 116
 117/*
 118 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
 119 * ple_gap:    upper bound on the amount of time between two successive
 120 *             executions of PAUSE in a loop. Also indicate if ple enabled.
 121 *             According to test, this time is usually smaller than 128 cycles.
 122 * ple_window: upper bound on the amount of time a guest is allowed to execute
 123 *             in a PAUSE loop. Tests indicate that most spinlocks are held for
 124 *             less than 2^12 cycles
 125 * Time is measured based on a counter that runs at the same rate as the TSC,
 126 * refer SDM volume 3b section 21.6.13 & 22.1.3.
 127 */
 128#define KVM_VMX_DEFAULT_PLE_GAP    128
 129#define KVM_VMX_DEFAULT_PLE_WINDOW 4096
 130static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
 131module_param(ple_gap, int, S_IRUGO);
 132
 133static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
 134module_param(ple_window, int, S_IRUGO);
 135
 136extern const ulong vmx_return;
 137
 138#define NR_AUTOLOAD_MSRS 8
 139#define VMCS02_POOL_SIZE 1
 140
 141struct vmcs {
 142        u32 revision_id;
 143        u32 abort;
 144        char data[0];
 145};
 146
 147/*
 148 * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
 149 * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
 150 * loaded on this CPU (so we can clear them if the CPU goes down).
 151 */
 152struct loaded_vmcs {
 153        struct vmcs *vmcs;
 154        int cpu;
 155        int launched;
 156        struct list_head loaded_vmcss_on_cpu_link;
 157};
 158
 159struct shared_msr_entry {
 160        unsigned index;
 161        u64 data;
 162        u64 mask;
 163};
 164
 165/*
 166 * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
 167 * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
 168 * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
 169 * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
 170 * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
 171 * More than one of these structures may exist, if L1 runs multiple L2 guests.
 172 * nested_vmx_run() will use the data here to build a vmcs02: a VMCS for the
 173 * underlying hardware which will be used to run L2.
 174 * This structure is packed to ensure that its layout is identical across
 175 * machines (necessary for live migration).
 176 * If there are changes in this struct, VMCS12_REVISION must be changed.
 177 */
 178typedef u64 natural_width;
 179struct __packed vmcs12 {
 180        /* According to the Intel spec, a VMCS region must start with the
 181         * following two fields. Then follow implementation-specific data.
 182         */
 183        u32 revision_id;
 184        u32 abort;
 185
 186        u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
 187        u32 padding[7]; /* room for future expansion */
 188
 189        u64 io_bitmap_a;
 190        u64 io_bitmap_b;
 191        u64 msr_bitmap;
 192        u64 vm_exit_msr_store_addr;
 193        u64 vm_exit_msr_load_addr;
 194        u64 vm_entry_msr_load_addr;
 195        u64 tsc_offset;
 196        u64 virtual_apic_page_addr;
 197        u64 apic_access_addr;
 198        u64 ept_pointer;
 199        u64 guest_physical_address;
 200        u64 vmcs_link_pointer;
 201        u64 guest_ia32_debugctl;
 202        u64 guest_ia32_pat;
 203        u64 guest_ia32_efer;
 204        u64 guest_ia32_perf_global_ctrl;
 205        u64 guest_pdptr0;
 206        u64 guest_pdptr1;
 207        u64 guest_pdptr2;
 208        u64 guest_pdptr3;
 209        u64 guest_bndcfgs;
 210        u64 host_ia32_pat;
 211        u64 host_ia32_efer;
 212        u64 host_ia32_perf_global_ctrl;
 213        u64 padding64[8]; /* room for future expansion */
 214        /*
 215         * To allow migration of L1 (complete with its L2 guests) between
 216         * machines of different natural widths (32 or 64 bit), we cannot have
 217         * unsigned long fields with no explict size. We use u64 (aliased
 218         * natural_width) instead. Luckily, x86 is little-endian.
 219         */
 220        natural_width cr0_guest_host_mask;
 221        natural_width cr4_guest_host_mask;
 222        natural_width cr0_read_shadow;
 223        natural_width cr4_read_shadow;
 224        natural_width cr3_target_value0;
 225        natural_width cr3_target_value1;
 226        natural_width cr3_target_value2;
 227        natural_width cr3_target_value3;
 228        natural_width exit_qualification;
 229        natural_width guest_linear_address;
 230        natural_width guest_cr0;
 231        natural_width guest_cr3;
 232        natural_width guest_cr4;
 233        natural_width guest_es_base;
 234        natural_width guest_cs_base;
 235        natural_width guest_ss_base;
 236        natural_width guest_ds_base;
 237        natural_width guest_fs_base;
 238        natural_width guest_gs_base;
 239        natural_width guest_ldtr_base;
 240        natural_width guest_tr_base;
 241        natural_width guest_gdtr_base;
 242        natural_width guest_idtr_base;
 243        natural_width guest_dr7;
 244        natural_width guest_rsp;
 245        natural_width guest_rip;
 246        natural_width guest_rflags;
 247        natural_width guest_pending_dbg_exceptions;
 248        natural_width guest_sysenter_esp;
 249        natural_width guest_sysenter_eip;
 250        natural_width host_cr0;
 251        natural_width host_cr3;
 252        natural_width host_cr4;
 253        natural_width host_fs_base;
 254        natural_width host_gs_base;
 255        natural_width host_tr_base;
 256        natural_width host_gdtr_base;
 257        natural_width host_idtr_base;
 258        natural_width host_ia32_sysenter_esp;
 259        natural_width host_ia32_sysenter_eip;
 260        natural_width host_rsp;
 261        natural_width host_rip;
 262        natural_width paddingl[8]; /* room for future expansion */
 263        u32 pin_based_vm_exec_control;
 264        u32 cpu_based_vm_exec_control;
 265        u32 exception_bitmap;
 266        u32 page_fault_error_code_mask;
 267        u32 page_fault_error_code_match;
 268        u32 cr3_target_count;
 269        u32 vm_exit_controls;
 270        u32 vm_exit_msr_store_count;
 271        u32 vm_exit_msr_load_count;
 272        u32 vm_entry_controls;
 273        u32 vm_entry_msr_load_count;
 274        u32 vm_entry_intr_info_field;
 275        u32 vm_entry_exception_error_code;
 276        u32 vm_entry_instruction_len;
 277        u32 tpr_threshold;
 278        u32 secondary_vm_exec_control;
 279        u32 vm_instruction_error;
 280        u32 vm_exit_reason;
 281        u32 vm_exit_intr_info;
 282        u32 vm_exit_intr_error_code;
 283        u32 idt_vectoring_info_field;
 284        u32 idt_vectoring_error_code;
 285        u32 vm_exit_instruction_len;
 286        u32 vmx_instruction_info;
 287        u32 guest_es_limit;
 288        u32 guest_cs_limit;
 289        u32 guest_ss_limit;
 290        u32 guest_ds_limit;
 291        u32 guest_fs_limit;
 292        u32 guest_gs_limit;
 293        u32 guest_ldtr_limit;
 294        u32 guest_tr_limit;
 295        u32 guest_gdtr_limit;
 296        u32 guest_idtr_limit;
 297        u32 guest_es_ar_bytes;
 298        u32 guest_cs_ar_bytes;
 299        u32 guest_ss_ar_bytes;
 300        u32 guest_ds_ar_bytes;
 301        u32 guest_fs_ar_bytes;
 302        u32 guest_gs_ar_bytes;
 303        u32 guest_ldtr_ar_bytes;
 304        u32 guest_tr_ar_bytes;
 305        u32 guest_interruptibility_info;
 306        u32 guest_activity_state;
 307        u32 guest_sysenter_cs;
 308        u32 host_ia32_sysenter_cs;
 309        u32 vmx_preemption_timer_value;
 310        u32 padding32[7]; /* room for future expansion */
 311        u16 virtual_processor_id;
 312        u16 guest_es_selector;
 313        u16 guest_cs_selector;
 314        u16 guest_ss_selector;
 315        u16 guest_ds_selector;
 316        u16 guest_fs_selector;
 317        u16 guest_gs_selector;
 318        u16 guest_ldtr_selector;
 319        u16 guest_tr_selector;
 320        u16 host_es_selector;
 321        u16 host_cs_selector;
 322        u16 host_ss_selector;
 323        u16 host_ds_selector;
 324        u16 host_fs_selector;
 325        u16 host_gs_selector;
 326        u16 host_tr_selector;
 327};
 328
 329/*
 330 * VMCS12_REVISION is an arbitrary id that should be changed if the content or
 331 * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
 332 * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
 333 */
 334#define VMCS12_REVISION 0x11e57ed0
 335
 336/*
 337 * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
 338 * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
 339 * current implementation, 4K are reserved to avoid future complications.
 340 */
 341#define VMCS12_SIZE 0x1000
 342
 343/* Used to remember the last vmcs02 used for some recently used vmcs12s */
 344struct vmcs02_list {
 345        struct list_head list;
 346        gpa_t vmptr;
 347        struct loaded_vmcs vmcs02;
 348};
 349
 350/*
 351 * The nested_vmx structure is part of vcpu_vmx, and holds information we need
 352 * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
 353 */
 354struct nested_vmx {
 355        /* Has the level1 guest done vmxon? */
 356        bool vmxon;
 357        gpa_t vmxon_ptr;
 358
 359        /* The guest-physical address of the current VMCS L1 keeps for L2 */
 360        gpa_t current_vmptr;
 361        /* The host-usable pointer to the above */
 362        struct page *current_vmcs12_page;
 363        struct vmcs12 *current_vmcs12;
 364        struct vmcs *current_shadow_vmcs;
 365        /*
 366         * Indicates if the shadow vmcs must be updated with the
 367         * data hold by vmcs12
 368         */
 369        bool sync_shadow_vmcs;
 370
 371        /* vmcs02_list cache of VMCSs recently used to run L2 guests */
 372        struct list_head vmcs02_pool;
 373        int vmcs02_num;
 374        u64 vmcs01_tsc_offset;
 375        /* L2 must run next, and mustn't decide to exit to L1. */
 376        bool nested_run_pending;
 377        /*
 378         * Guest pages referred to in vmcs02 with host-physical pointers, so
 379         * we must keep them pinned while L2 runs.
 380         */
 381        struct page *apic_access_page;
 382        u64 msr_ia32_feature_control;
 383
 384        struct hrtimer preemption_timer;
 385        bool preemption_timer_expired;
 386
 387        /* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
 388        u64 vmcs01_debugctl;
 389};
 390
 391#define POSTED_INTR_ON  0
 392/* Posted-Interrupt Descriptor */
 393struct pi_desc {
 394        u32 pir[8];     /* Posted interrupt requested */
 395        u32 control;    /* bit 0 of control is outstanding notification bit */
 396        u32 rsvd[7];
 397} __aligned(64);
 398
 399static bool pi_test_and_set_on(struct pi_desc *pi_desc)
 400{
 401        return test_and_set_bit(POSTED_INTR_ON,
 402                        (unsigned long *)&pi_desc->control);
 403}
 404
 405static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
 406{
 407        return test_and_clear_bit(POSTED_INTR_ON,
 408                        (unsigned long *)&pi_desc->control);
 409}
 410
 411static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
 412{
 413        return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
 414}
 415
 416struct vcpu_vmx {
 417        struct kvm_vcpu       vcpu;
 418        unsigned long         host_rsp;
 419        u8                    fail;
 420        bool                  nmi_known_unmasked;
 421        u32                   exit_intr_info;
 422        u32                   idt_vectoring_info;
 423        ulong                 rflags;
 424        struct shared_msr_entry *guest_msrs;
 425        int                   nmsrs;
 426        int                   save_nmsrs;
 427        unsigned long         host_idt_base;
 428#ifdef CONFIG_X86_64
 429        u64                   msr_host_kernel_gs_base;
 430        u64                   msr_guest_kernel_gs_base;
 431#endif
 432        u32 vm_entry_controls_shadow;
 433        u32 vm_exit_controls_shadow;
 434        /*
 435         * loaded_vmcs points to the VMCS currently used in this vcpu. For a
 436         * non-nested (L1) guest, it always points to vmcs01. For a nested
 437         * guest (L2), it points to a different VMCS.
 438         */
 439        struct loaded_vmcs    vmcs01;
 440        struct loaded_vmcs   *loaded_vmcs;
 441        bool                  __launched; /* temporary, used in vmx_vcpu_run */
 442        struct msr_autoload {
 443                unsigned nr;
 444                struct vmx_msr_entry guest[NR_AUTOLOAD_MSRS];
 445                struct vmx_msr_entry host[NR_AUTOLOAD_MSRS];
 446        } msr_autoload;
 447        struct {
 448                int           loaded;
 449                u16           fs_sel, gs_sel, ldt_sel;
 450#ifdef CONFIG_X86_64
 451                u16           ds_sel, es_sel;
 452#endif
 453                int           gs_ldt_reload_needed;
 454                int           fs_reload_needed;
 455                u64           msr_host_bndcfgs;
 456        } host_state;
 457        struct {
 458                int vm86_active;
 459                ulong save_rflags;
 460                struct kvm_segment segs[8];
 461        } rmode;
 462        struct {
 463                u32 bitmask; /* 4 bits per segment (1 bit per field) */
 464                struct kvm_save_segment {
 465                        u16 selector;
 466                        unsigned long base;
 467                        u32 limit;
 468                        u32 ar;
 469                } seg[8];
 470        } segment_cache;
 471        int vpid;
 472        bool emulation_required;
 473
 474        /* Support for vnmi-less CPUs */
 475        int soft_vnmi_blocked;
 476        ktime_t entry_time;
 477        s64 vnmi_blocked_time;
 478        u32 exit_reason;
 479
 480        bool rdtscp_enabled;
 481
 482        /* Posted interrupt descriptor */
 483        struct pi_desc pi_desc;
 484
 485        /* Support for a guest hypervisor (nested VMX) */
 486        struct nested_vmx nested;
 487};
 488
 489enum segment_cache_field {
 490        SEG_FIELD_SEL = 0,
 491        SEG_FIELD_BASE = 1,
 492        SEG_FIELD_LIMIT = 2,
 493        SEG_FIELD_AR = 3,
 494
 495        SEG_FIELD_NR = 4
 496};
 497
 498static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
 499{
 500        return container_of(vcpu, struct vcpu_vmx, vcpu);
 501}
 502
 503#define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
 504#define FIELD(number, name)     [number] = VMCS12_OFFSET(name)
 505#define FIELD64(number, name)   [number] = VMCS12_OFFSET(name), \
 506                                [number##_HIGH] = VMCS12_OFFSET(name)+4
 507
 508
 509static unsigned long shadow_read_only_fields[] = {
 510        /*
 511         * We do NOT shadow fields that are modified when L0
 512         * traps and emulates any vmx instruction (e.g. VMPTRLD,
 513         * VMXON...) executed by L1.
 514         * For example, VM_INSTRUCTION_ERROR is read
 515         * by L1 if a vmx instruction fails (part of the error path).
 516         * Note the code assumes this logic. If for some reason
 517         * we start shadowing these fields then we need to
 518         * force a shadow sync when L0 emulates vmx instructions
 519         * (e.g. force a sync if VM_INSTRUCTION_ERROR is modified
 520         * by nested_vmx_failValid)
 521         */
 522        VM_EXIT_REASON,
 523        VM_EXIT_INTR_INFO,
 524        VM_EXIT_INSTRUCTION_LEN,
 525        IDT_VECTORING_INFO_FIELD,
 526        IDT_VECTORING_ERROR_CODE,
 527        VM_EXIT_INTR_ERROR_CODE,
 528        EXIT_QUALIFICATION,
 529        GUEST_LINEAR_ADDRESS,
 530        GUEST_PHYSICAL_ADDRESS
 531};
 532static int max_shadow_read_only_fields =
 533        ARRAY_SIZE(shadow_read_only_fields);
 534
 535static unsigned long shadow_read_write_fields[] = {
 536        GUEST_RIP,
 537        GUEST_RSP,
 538        GUEST_CR0,
 539        GUEST_CR3,
 540        GUEST_CR4,
 541        GUEST_INTERRUPTIBILITY_INFO,
 542        GUEST_RFLAGS,
 543        GUEST_CS_SELECTOR,
 544        GUEST_CS_AR_BYTES,
 545        GUEST_CS_LIMIT,
 546        GUEST_CS_BASE,
 547        GUEST_ES_BASE,
 548        GUEST_BNDCFGS,
 549        CR0_GUEST_HOST_MASK,
 550        CR0_READ_SHADOW,
 551        CR4_READ_SHADOW,
 552        TSC_OFFSET,
 553        EXCEPTION_BITMAP,
 554        CPU_BASED_VM_EXEC_CONTROL,
 555        VM_ENTRY_EXCEPTION_ERROR_CODE,
 556        VM_ENTRY_INTR_INFO_FIELD,
 557        VM_ENTRY_INSTRUCTION_LEN,
 558        VM_ENTRY_EXCEPTION_ERROR_CODE,
 559        HOST_FS_BASE,
 560        HOST_GS_BASE,
 561        HOST_FS_SELECTOR,
 562        HOST_GS_SELECTOR
 563};
 564static int max_shadow_read_write_fields =
 565        ARRAY_SIZE(shadow_read_write_fields);
 566
 567static const unsigned short vmcs_field_to_offset_table[] = {
 568        FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
 569        FIELD(GUEST_ES_SELECTOR, guest_es_selector),
 570        FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
 571        FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
 572        FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
 573        FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
 574        FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
 575        FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
 576        FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
 577        FIELD(HOST_ES_SELECTOR, host_es_selector),
 578        FIELD(HOST_CS_SELECTOR, host_cs_selector),
 579        FIELD(HOST_SS_SELECTOR, host_ss_selector),
 580        FIELD(HOST_DS_SELECTOR, host_ds_selector),
 581        FIELD(HOST_FS_SELECTOR, host_fs_selector),
 582        FIELD(HOST_GS_SELECTOR, host_gs_selector),
 583        FIELD(HOST_TR_SELECTOR, host_tr_selector),
 584        FIELD64(IO_BITMAP_A, io_bitmap_a),
 585        FIELD64(IO_BITMAP_B, io_bitmap_b),
 586        FIELD64(MSR_BITMAP, msr_bitmap),
 587        FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
 588        FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
 589        FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
 590        FIELD64(TSC_OFFSET, tsc_offset),
 591        FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
 592        FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
 593        FIELD64(EPT_POINTER, ept_pointer),
 594        FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
 595        FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
 596        FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
 597        FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
 598        FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
 599        FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
 600        FIELD64(GUEST_PDPTR0, guest_pdptr0),
 601        FIELD64(GUEST_PDPTR1, guest_pdptr1),
 602        FIELD64(GUEST_PDPTR2, guest_pdptr2),
 603        FIELD64(GUEST_PDPTR3, guest_pdptr3),
 604        FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
 605        FIELD64(HOST_IA32_PAT, host_ia32_pat),
 606        FIELD64(HOST_IA32_EFER, host_ia32_efer),
 607        FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
 608        FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
 609        FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
 610        FIELD(EXCEPTION_BITMAP, exception_bitmap),
 611        FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
 612        FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
 613        FIELD(CR3_TARGET_COUNT, cr3_target_count),
 614        FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
 615        FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
 616        FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
 617        FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
 618        FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
 619        FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
 620        FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
 621        FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
 622        FIELD(TPR_THRESHOLD, tpr_threshold),
 623        FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
 624        FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
 625        FIELD(VM_EXIT_REASON, vm_exit_reason),
 626        FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
 627        FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
 628        FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
 629        FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
 630        FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
 631        FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
 632        FIELD(GUEST_ES_LIMIT, guest_es_limit),
 633        FIELD(GUEST_CS_LIMIT, guest_cs_limit),
 634        FIELD(GUEST_SS_LIMIT, guest_ss_limit),
 635        FIELD(GUEST_DS_LIMIT, guest_ds_limit),
 636        FIELD(GUEST_FS_LIMIT, guest_fs_limit),
 637        FIELD(GUEST_GS_LIMIT, guest_gs_limit),
 638        FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
 639        FIELD(GUEST_TR_LIMIT, guest_tr_limit),
 640        FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
 641        FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
 642        FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
 643        FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
 644        FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
 645        FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
 646        FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
 647        FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
 648        FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
 649        FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
 650        FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
 651        FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
 652        FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
 653        FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
 654        FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
 655        FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
 656        FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
 657        FIELD(CR0_READ_SHADOW, cr0_read_shadow),
 658        FIELD(CR4_READ_SHADOW, cr4_read_shadow),
 659        FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
 660        FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
 661        FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
 662        FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
 663        FIELD(EXIT_QUALIFICATION, exit_qualification),
 664        FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
 665        FIELD(GUEST_CR0, guest_cr0),
 666        FIELD(GUEST_CR3, guest_cr3),
 667        FIELD(GUEST_CR4, guest_cr4),
 668        FIELD(GUEST_ES_BASE, guest_es_base),
 669        FIELD(GUEST_CS_BASE, guest_cs_base),
 670        FIELD(GUEST_SS_BASE, guest_ss_base),
 671        FIELD(GUEST_DS_BASE, guest_ds_base),
 672        FIELD(GUEST_FS_BASE, guest_fs_base),
 673        FIELD(GUEST_GS_BASE, guest_gs_base),
 674        FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
 675        FIELD(GUEST_TR_BASE, guest_tr_base),
 676        FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
 677        FIELD(GUEST_IDTR_BASE, guest_idtr_base),
 678        FIELD(GUEST_DR7, guest_dr7),
 679        FIELD(GUEST_RSP, guest_rsp),
 680        FIELD(GUEST_RIP, guest_rip),
 681        FIELD(GUEST_RFLAGS, guest_rflags),
 682        FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
 683        FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
 684        FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
 685        FIELD(HOST_CR0, host_cr0),
 686        FIELD(HOST_CR3, host_cr3),
 687        FIELD(HOST_CR4, host_cr4),
 688        FIELD(HOST_FS_BASE, host_fs_base),
 689        FIELD(HOST_GS_BASE, host_gs_base),
 690        FIELD(HOST_TR_BASE, host_tr_base),
 691        FIELD(HOST_GDTR_BASE, host_gdtr_base),
 692        FIELD(HOST_IDTR_BASE, host_idtr_base),
 693        FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
 694        FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
 695        FIELD(HOST_RSP, host_rsp),
 696        FIELD(HOST_RIP, host_rip),
 697};
 698static const int max_vmcs_field = ARRAY_SIZE(vmcs_field_to_offset_table);
 699
 700static inline short vmcs_field_to_offset(unsigned long field)
 701{
 702        if (field >= max_vmcs_field || vmcs_field_to_offset_table[field] == 0)
 703                return -1;
 704        return vmcs_field_to_offset_table[field];
 705}
 706
 707static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
 708{
 709        return to_vmx(vcpu)->nested.current_vmcs12;
 710}
 711
 712static struct page *nested_get_page(struct kvm_vcpu *vcpu, gpa_t addr)
 713{
 714        struct page *page = gfn_to_page(vcpu->kvm, addr >> PAGE_SHIFT);
 715        if (is_error_page(page))
 716                return NULL;
 717
 718        return page;
 719}
 720
 721static void nested_release_page(struct page *page)
 722{
 723        kvm_release_page_dirty(page);
 724}
 725
 726static void nested_release_page_clean(struct page *page)
 727{
 728        kvm_release_page_clean(page);
 729}
 730
 731static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
 732static u64 construct_eptp(unsigned long root_hpa);
 733static void kvm_cpu_vmxon(u64 addr);
 734static void kvm_cpu_vmxoff(void);
 735static bool vmx_mpx_supported(void);
 736static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr);
 737static void vmx_set_segment(struct kvm_vcpu *vcpu,
 738                            struct kvm_segment *var, int seg);
 739static void vmx_get_segment(struct kvm_vcpu *vcpu,
 740                            struct kvm_segment *var, int seg);
 741static bool guest_state_valid(struct kvm_vcpu *vcpu);
 742static u32 vmx_segment_access_rights(struct kvm_segment *var);
 743static void vmx_sync_pir_to_irr_dummy(struct kvm_vcpu *vcpu);
 744static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx);
 745static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
 746
 747static DEFINE_PER_CPU(struct vmcs *, vmxarea);
 748static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
 749/*
 750 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
 751 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
 752 */
 753static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
 754static DEFINE_PER_CPU(struct desc_ptr, host_gdt);
 755
 756static unsigned long *vmx_io_bitmap_a;
 757static unsigned long *vmx_io_bitmap_b;
 758static unsigned long *vmx_msr_bitmap_legacy;
 759static unsigned long *vmx_msr_bitmap_longmode;
 760static unsigned long *vmx_msr_bitmap_legacy_x2apic;
 761static unsigned long *vmx_msr_bitmap_longmode_x2apic;
 762static unsigned long *vmx_vmread_bitmap;
 763static unsigned long *vmx_vmwrite_bitmap;
 764
 765static bool cpu_has_load_ia32_efer;
 766static bool cpu_has_load_perf_global_ctrl;
 767
 768static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
 769static DEFINE_SPINLOCK(vmx_vpid_lock);
 770
 771static struct vmcs_config {
 772        int size;
 773        int order;
 774        u32 revision_id;
 775        u32 pin_based_exec_ctrl;
 776        u32 cpu_based_exec_ctrl;
 777        u32 cpu_based_2nd_exec_ctrl;
 778        u32 vmexit_ctrl;
 779        u32 vmentry_ctrl;
 780} vmcs_config;
 781
 782static struct vmx_capability {
 783        u32 ept;
 784        u32 vpid;
 785} vmx_capability;
 786
 787#define VMX_SEGMENT_FIELD(seg)                                  \
 788        [VCPU_SREG_##seg] = {                                   \
 789                .selector = GUEST_##seg##_SELECTOR,             \
 790                .base = GUEST_##seg##_BASE,                     \
 791                .limit = GUEST_##seg##_LIMIT,                   \
 792                .ar_bytes = GUEST_##seg##_AR_BYTES,             \
 793        }
 794
 795static const struct kvm_vmx_segment_field {
 796        unsigned selector;
 797        unsigned base;
 798        unsigned limit;
 799        unsigned ar_bytes;
 800} kvm_vmx_segment_fields[] = {
 801        VMX_SEGMENT_FIELD(CS),
 802        VMX_SEGMENT_FIELD(DS),
 803        VMX_SEGMENT_FIELD(ES),
 804        VMX_SEGMENT_FIELD(FS),
 805        VMX_SEGMENT_FIELD(GS),
 806        VMX_SEGMENT_FIELD(SS),
 807        VMX_SEGMENT_FIELD(TR),
 808        VMX_SEGMENT_FIELD(LDTR),
 809};
 810
 811static u64 host_efer;
 812
 813static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
 814
 815/*
 816 * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
 817 * away by decrementing the array size.
 818 */
 819static const u32 vmx_msr_index[] = {
 820#ifdef CONFIG_X86_64
 821        MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
 822#endif
 823        MSR_EFER, MSR_TSC_AUX, MSR_STAR,
 824};
 825
 826static inline bool is_page_fault(u32 intr_info)
 827{
 828        return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
 829                             INTR_INFO_VALID_MASK)) ==
 830                (INTR_TYPE_HARD_EXCEPTION | PF_VECTOR | INTR_INFO_VALID_MASK);
 831}
 832
 833static inline bool is_no_device(u32 intr_info)
 834{
 835        return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
 836                             INTR_INFO_VALID_MASK)) ==
 837                (INTR_TYPE_HARD_EXCEPTION | NM_VECTOR | INTR_INFO_VALID_MASK);
 838}
 839
 840static inline bool is_invalid_opcode(u32 intr_info)
 841{
 842        return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
 843                             INTR_INFO_VALID_MASK)) ==
 844                (INTR_TYPE_HARD_EXCEPTION | UD_VECTOR | INTR_INFO_VALID_MASK);
 845}
 846
 847static inline bool is_external_interrupt(u32 intr_info)
 848{
 849        return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
 850                == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
 851}
 852
 853static inline bool is_machine_check(u32 intr_info)
 854{
 855        return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
 856                             INTR_INFO_VALID_MASK)) ==
 857                (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
 858}
 859
 860static inline bool cpu_has_vmx_msr_bitmap(void)
 861{
 862        return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
 863}
 864
 865static inline bool cpu_has_vmx_tpr_shadow(void)
 866{
 867        return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
 868}
 869
 870static inline bool vm_need_tpr_shadow(struct kvm *kvm)
 871{
 872        return (cpu_has_vmx_tpr_shadow()) && (irqchip_in_kernel(kvm));
 873}
 874
 875static inline bool cpu_has_secondary_exec_ctrls(void)
 876{
 877        return vmcs_config.cpu_based_exec_ctrl &
 878                CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
 879}
 880
 881static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
 882{
 883        return vmcs_config.cpu_based_2nd_exec_ctrl &
 884                SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
 885}
 886
 887static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
 888{
 889        return vmcs_config.cpu_based_2nd_exec_ctrl &
 890                SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
 891}
 892
 893static inline bool cpu_has_vmx_apic_register_virt(void)
 894{
 895        return vmcs_config.cpu_based_2nd_exec_ctrl &
 896                SECONDARY_EXEC_APIC_REGISTER_VIRT;
 897}
 898
 899static inline bool cpu_has_vmx_virtual_intr_delivery(void)
 900{
 901        return vmcs_config.cpu_based_2nd_exec_ctrl &
 902                SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
 903}
 904
 905static inline bool cpu_has_vmx_posted_intr(void)
 906{
 907        return vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
 908}
 909
 910static inline bool cpu_has_vmx_apicv(void)
 911{
 912        return cpu_has_vmx_apic_register_virt() &&
 913                cpu_has_vmx_virtual_intr_delivery() &&
 914                cpu_has_vmx_posted_intr();
 915}
 916
 917static inline bool cpu_has_vmx_flexpriority(void)
 918{
 919        return cpu_has_vmx_tpr_shadow() &&
 920                cpu_has_vmx_virtualize_apic_accesses();
 921}
 922
 923static inline bool cpu_has_vmx_ept_execute_only(void)
 924{
 925        return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
 926}
 927
 928static inline bool cpu_has_vmx_eptp_uncacheable(void)
 929{
 930        return vmx_capability.ept & VMX_EPTP_UC_BIT;
 931}
 932
 933static inline bool cpu_has_vmx_eptp_writeback(void)
 934{
 935        return vmx_capability.ept & VMX_EPTP_WB_BIT;
 936}
 937
 938static inline bool cpu_has_vmx_ept_2m_page(void)
 939{
 940        return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
 941}
 942
 943static inline bool cpu_has_vmx_ept_1g_page(void)
 944{
 945        return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
 946}
 947
 948static inline bool cpu_has_vmx_ept_4levels(void)
 949{
 950        return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
 951}
 952
 953static inline bool cpu_has_vmx_ept_ad_bits(void)
 954{
 955        return vmx_capability.ept & VMX_EPT_AD_BIT;
 956}
 957
 958static inline bool cpu_has_vmx_invept_context(void)
 959{
 960        return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
 961}
 962
 963static inline bool cpu_has_vmx_invept_global(void)
 964{
 965        return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
 966}
 967
 968static inline bool cpu_has_vmx_invvpid_single(void)
 969{
 970        return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
 971}
 972
 973static inline bool cpu_has_vmx_invvpid_global(void)
 974{
 975        return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
 976}
 977
 978static inline bool cpu_has_vmx_ept(void)
 979{
 980        return vmcs_config.cpu_based_2nd_exec_ctrl &
 981                SECONDARY_EXEC_ENABLE_EPT;
 982}
 983
 984static inline bool cpu_has_vmx_unrestricted_guest(void)
 985{
 986        return vmcs_config.cpu_based_2nd_exec_ctrl &
 987                SECONDARY_EXEC_UNRESTRICTED_GUEST;
 988}
 989
 990static inline bool cpu_has_vmx_ple(void)
 991{
 992        return vmcs_config.cpu_based_2nd_exec_ctrl &
 993                SECONDARY_EXEC_PAUSE_LOOP_EXITING;
 994}
 995
 996static inline bool vm_need_virtualize_apic_accesses(struct kvm *kvm)
 997{
 998        return flexpriority_enabled && irqchip_in_kernel(kvm);
 999}
1000
1001static inline bool cpu_has_vmx_vpid(void)
1002{
1003        return vmcs_config.cpu_based_2nd_exec_ctrl &
1004                SECONDARY_EXEC_ENABLE_VPID;
1005}
1006
1007static inline bool cpu_has_vmx_rdtscp(void)
1008{
1009        return vmcs_config.cpu_based_2nd_exec_ctrl &
1010                SECONDARY_EXEC_RDTSCP;
1011}
1012
1013static inline bool cpu_has_vmx_invpcid(void)
1014{
1015        return vmcs_config.cpu_based_2nd_exec_ctrl &
1016                SECONDARY_EXEC_ENABLE_INVPCID;
1017}
1018
1019static inline bool cpu_has_virtual_nmis(void)
1020{
1021        return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1022}
1023
1024static inline bool cpu_has_vmx_wbinvd_exit(void)
1025{
1026        return vmcs_config.cpu_based_2nd_exec_ctrl &
1027                SECONDARY_EXEC_WBINVD_EXITING;
1028}
1029
1030static inline bool cpu_has_vmx_shadow_vmcs(void)
1031{
1032        u64 vmx_msr;
1033        rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1034        /* check if the cpu supports writing r/o exit information fields */
1035        if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1036                return false;
1037
1038        return vmcs_config.cpu_based_2nd_exec_ctrl &
1039                SECONDARY_EXEC_SHADOW_VMCS;
1040}
1041
1042static inline bool report_flexpriority(void)
1043{
1044        return flexpriority_enabled;
1045}
1046
1047static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1048{
1049        return vmcs12->cpu_based_vm_exec_control & bit;
1050}
1051
1052static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
1053{
1054        return (vmcs12->cpu_based_vm_exec_control &
1055                        CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
1056                (vmcs12->secondary_vm_exec_control & bit);
1057}
1058
1059static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12)
1060{
1061        return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
1062}
1063
1064static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
1065{
1066        return vmcs12->pin_based_vm_exec_control &
1067                PIN_BASED_VMX_PREEMPTION_TIMER;
1068}
1069
1070static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
1071{
1072        return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
1073}
1074
1075static inline bool is_exception(u32 intr_info)
1076{
1077        return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1078                == (INTR_TYPE_HARD_EXCEPTION | INTR_INFO_VALID_MASK);
1079}
1080
1081static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
1082                              u32 exit_intr_info,
1083                              unsigned long exit_qualification);
1084static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
1085                        struct vmcs12 *vmcs12,
1086                        u32 reason, unsigned long qualification);
1087
1088static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
1089{
1090        int i;
1091
1092        for (i = 0; i < vmx->nmsrs; ++i)
1093                if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
1094                        return i;
1095        return -1;
1096}
1097
1098static inline void __invvpid(int ext, u16 vpid, gva_t gva)
1099{
1100    struct {
1101        u64 vpid : 16;
1102        u64 rsvd : 48;
1103        u64 gva;
1104    } operand = { vpid, 0, gva };
1105
1106    asm volatile (__ex(ASM_VMX_INVVPID)
1107                  /* CF==1 or ZF==1 --> rc = -1 */
1108                  "; ja 1f ; ud2 ; 1:"
1109                  : : "a"(&operand), "c"(ext) : "cc", "memory");
1110}
1111
1112static inline void __invept(int ext, u64 eptp, gpa_t gpa)
1113{
1114        struct {
1115                u64 eptp, gpa;
1116        } operand = {eptp, gpa};
1117
1118        asm volatile (__ex(ASM_VMX_INVEPT)
1119                        /* CF==1 or ZF==1 --> rc = -1 */
1120                        "; ja 1f ; ud2 ; 1:\n"
1121                        : : "a" (&operand), "c" (ext) : "cc", "memory");
1122}
1123
1124static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
1125{
1126        int i;
1127
1128        i = __find_msr_index(vmx, msr);
1129        if (i >= 0)
1130                return &vmx->guest_msrs[i];
1131        return NULL;
1132}
1133
1134static void vmcs_clear(struct vmcs *vmcs)
1135{
1136        u64 phys_addr = __pa(vmcs);
1137        u8 error;
1138
1139        asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
1140                      : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1141                      : "cc", "memory");
1142        if (error)
1143                printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
1144                       vmcs, phys_addr);
1145}
1146
1147static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
1148{
1149        vmcs_clear(loaded_vmcs->vmcs);
1150        loaded_vmcs->cpu = -1;
1151        loaded_vmcs->launched = 0;
1152}
1153
1154static void vmcs_load(struct vmcs *vmcs)
1155{
1156        u64 phys_addr = __pa(vmcs);
1157        u8 error;
1158
1159        asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
1160                        : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1161                        : "cc", "memory");
1162        if (error)
1163                printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
1164                       vmcs, phys_addr);
1165}
1166
1167#ifdef CONFIG_KEXEC
1168/*
1169 * This bitmap is used to indicate whether the vmclear
1170 * operation is enabled on all cpus. All disabled by
1171 * default.
1172 */
1173static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
1174
1175static inline void crash_enable_local_vmclear(int cpu)
1176{
1177        cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
1178}
1179
1180static inline void crash_disable_local_vmclear(int cpu)
1181{
1182        cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
1183}
1184
1185static inline int crash_local_vmclear_enabled(int cpu)
1186{
1187        return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
1188}
1189
1190static void crash_vmclear_local_loaded_vmcss(void)
1191{
1192        int cpu = raw_smp_processor_id();
1193        struct loaded_vmcs *v;
1194
1195        if (!crash_local_vmclear_enabled(cpu))
1196                return;
1197
1198        list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
1199                            loaded_vmcss_on_cpu_link)
1200                vmcs_clear(v->vmcs);
1201}
1202#else
1203static inline void crash_enable_local_vmclear(int cpu) { }
1204static inline void crash_disable_local_vmclear(int cpu) { }
1205#endif /* CONFIG_KEXEC */
1206
1207static void __loaded_vmcs_clear(void *arg)
1208{
1209        struct loaded_vmcs *loaded_vmcs = arg;
1210        int cpu = raw_smp_processor_id();
1211
1212        if (loaded_vmcs->cpu != cpu)
1213                return; /* vcpu migration can race with cpu offline */
1214        if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
1215                per_cpu(current_vmcs, cpu) = NULL;
1216        crash_disable_local_vmclear(cpu);
1217        list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
1218
1219        /*
1220         * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
1221         * is before setting loaded_vmcs->vcpu to -1 which is done in
1222         * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
1223         * then adds the vmcs into percpu list before it is deleted.
1224         */
1225        smp_wmb();
1226
1227        loaded_vmcs_init(loaded_vmcs);
1228        crash_enable_local_vmclear(cpu);
1229}
1230
1231static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
1232{
1233        int cpu = loaded_vmcs->cpu;
1234
1235        if (cpu != -1)
1236                smp_call_function_single(cpu,
1237                         __loaded_vmcs_clear, loaded_vmcs, 1);
1238}
1239
1240static inline void vpid_sync_vcpu_single(struct vcpu_vmx *vmx)
1241{
1242        if (vmx->vpid == 0)
1243                return;
1244
1245        if (cpu_has_vmx_invvpid_single())
1246                __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vmx->vpid, 0);
1247}
1248
1249static inline void vpid_sync_vcpu_global(void)
1250{
1251        if (cpu_has_vmx_invvpid_global())
1252                __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
1253}
1254
1255static inline void vpid_sync_context(struct vcpu_vmx *vmx)
1256{
1257        if (cpu_has_vmx_invvpid_single())
1258                vpid_sync_vcpu_single(vmx);
1259        else
1260                vpid_sync_vcpu_global();
1261}
1262
1263static inline void ept_sync_global(void)
1264{
1265        if (cpu_has_vmx_invept_global())
1266                __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
1267}
1268
1269static inline void ept_sync_context(u64 eptp)
1270{
1271        if (enable_ept) {
1272                if (cpu_has_vmx_invept_context())
1273                        __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
1274                else
1275                        ept_sync_global();
1276        }
1277}
1278
1279static __always_inline unsigned long vmcs_readl(unsigned long field)
1280{
1281        unsigned long value;
1282
1283        asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
1284                      : "=a"(value) : "d"(field) : "cc");
1285        return value;
1286}
1287
1288static __always_inline u16 vmcs_read16(unsigned long field)
1289{
1290        return vmcs_readl(field);
1291}
1292
1293static __always_inline u32 vmcs_read32(unsigned long field)
1294{
1295        return vmcs_readl(field);
1296}
1297
1298static __always_inline u64 vmcs_read64(unsigned long field)
1299{
1300#ifdef CONFIG_X86_64
1301        return vmcs_readl(field);
1302#else
1303        return vmcs_readl(field) | ((u64)vmcs_readl(field+1) << 32);
1304#endif
1305}
1306
1307static noinline void vmwrite_error(unsigned long field, unsigned long value)
1308{
1309        printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
1310               field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
1311        dump_stack();
1312}
1313
1314static void vmcs_writel(unsigned long field, unsigned long value)
1315{
1316        u8 error;
1317
1318        asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
1319                       : "=q"(error) : "a"(value), "d"(field) : "cc");
1320        if (unlikely(error))
1321                vmwrite_error(field, value);
1322}
1323
1324static void vmcs_write16(unsigned long field, u16 value)
1325{
1326        vmcs_writel(field, value);
1327}
1328
1329static void vmcs_write32(unsigned long field, u32 value)
1330{
1331        vmcs_writel(field, value);
1332}
1333
1334static void vmcs_write64(unsigned long field, u64 value)
1335{
1336        vmcs_writel(field, value);
1337#ifndef CONFIG_X86_64
1338        asm volatile ("");
1339        vmcs_writel(field+1, value >> 32);
1340#endif
1341}
1342
1343static void vmcs_clear_bits(unsigned long field, u32 mask)
1344{
1345        vmcs_writel(field, vmcs_readl(field) & ~mask);
1346}
1347
1348static void vmcs_set_bits(unsigned long field, u32 mask)
1349{
1350        vmcs_writel(field, vmcs_readl(field) | mask);
1351}
1352
1353static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
1354{
1355        vmcs_write32(VM_ENTRY_CONTROLS, val);
1356        vmx->vm_entry_controls_shadow = val;
1357}
1358
1359static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
1360{
1361        if (vmx->vm_entry_controls_shadow != val)
1362                vm_entry_controls_init(vmx, val);
1363}
1364
1365static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
1366{
1367        return vmx->vm_entry_controls_shadow;
1368}
1369
1370
1371static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1372{
1373        vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
1374}
1375
1376static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1377{
1378        vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
1379}
1380
1381static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
1382{
1383        vmcs_write32(VM_EXIT_CONTROLS, val);
1384        vmx->vm_exit_controls_shadow = val;
1385}
1386
1387static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
1388{
1389        if (vmx->vm_exit_controls_shadow != val)
1390                vm_exit_controls_init(vmx, val);
1391}
1392
1393static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
1394{
1395        return vmx->vm_exit_controls_shadow;
1396}
1397
1398
1399static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1400{
1401        vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
1402}
1403
1404static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1405{
1406        vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
1407}
1408
1409static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
1410{
1411        vmx->segment_cache.bitmask = 0;
1412}
1413
1414static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
1415                                       unsigned field)
1416{
1417        bool ret;
1418        u32 mask = 1 << (seg * SEG_FIELD_NR + field);
1419
1420        if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
1421                vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
1422                vmx->segment_cache.bitmask = 0;
1423        }
1424        ret = vmx->segment_cache.bitmask & mask;
1425        vmx->segment_cache.bitmask |= mask;
1426        return ret;
1427}
1428
1429static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
1430{
1431        u16 *p = &vmx->segment_cache.seg[seg].selector;
1432
1433        if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
1434                *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
1435        return *p;
1436}
1437
1438static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
1439{
1440        ulong *p = &vmx->segment_cache.seg[seg].base;
1441
1442        if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
1443                *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
1444        return *p;
1445}
1446
1447static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
1448{
1449        u32 *p = &vmx->segment_cache.seg[seg].limit;
1450
1451        if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
1452                *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
1453        return *p;
1454}
1455
1456static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
1457{
1458        u32 *p = &vmx->segment_cache.seg[seg].ar;
1459
1460        if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
1461                *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
1462        return *p;
1463}
1464
1465static void update_exception_bitmap(struct kvm_vcpu *vcpu)
1466{
1467        u32 eb;
1468
1469        eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
1470             (1u << NM_VECTOR) | (1u << DB_VECTOR);
1471        if ((vcpu->guest_debug &
1472             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
1473            (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
1474                eb |= 1u << BP_VECTOR;
1475        if (to_vmx(vcpu)->rmode.vm86_active)
1476                eb = ~0;
1477        if (enable_ept)
1478                eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
1479        if (vcpu->fpu_active)
1480                eb &= ~(1u << NM_VECTOR);
1481
1482        /* When we are running a nested L2 guest and L1 specified for it a
1483         * certain exception bitmap, we must trap the same exceptions and pass
1484         * them to L1. When running L2, we will only handle the exceptions
1485         * specified above if L1 did not want them.
1486         */
1487        if (is_guest_mode(vcpu))
1488                eb |= get_vmcs12(vcpu)->exception_bitmap;
1489
1490        vmcs_write32(EXCEPTION_BITMAP, eb);
1491}
1492
1493static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1494                unsigned long entry, unsigned long exit)
1495{
1496        vm_entry_controls_clearbit(vmx, entry);
1497        vm_exit_controls_clearbit(vmx, exit);
1498}
1499
1500static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
1501{
1502        unsigned i;
1503        struct msr_autoload *m = &vmx->msr_autoload;
1504
1505        switch (msr) {
1506        case MSR_EFER:
1507                if (cpu_has_load_ia32_efer) {
1508                        clear_atomic_switch_msr_special(vmx,
1509                                        VM_ENTRY_LOAD_IA32_EFER,
1510                                        VM_EXIT_LOAD_IA32_EFER);
1511                        return;
1512                }
1513                break;
1514        case MSR_CORE_PERF_GLOBAL_CTRL:
1515                if (cpu_has_load_perf_global_ctrl) {
1516                        clear_atomic_switch_msr_special(vmx,
1517                                        VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1518                                        VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
1519                        return;
1520                }
1521                break;
1522        }
1523
1524        for (i = 0; i < m->nr; ++i)
1525                if (m->guest[i].index == msr)
1526                        break;
1527
1528        if (i == m->nr)
1529                return;
1530        --m->nr;
1531        m->guest[i] = m->guest[m->nr];
1532        m->host[i] = m->host[m->nr];
1533        vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1534        vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1535}
1536
1537static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1538                unsigned long entry, unsigned long exit,
1539                unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
1540                u64 guest_val, u64 host_val)
1541{
1542        vmcs_write64(guest_val_vmcs, guest_val);
1543        vmcs_write64(host_val_vmcs, host_val);
1544        vm_entry_controls_setbit(vmx, entry);
1545        vm_exit_controls_setbit(vmx, exit);
1546}
1547
1548static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
1549                                  u64 guest_val, u64 host_val)
1550{
1551        unsigned i;
1552        struct msr_autoload *m = &vmx->msr_autoload;
1553
1554        switch (msr) {
1555        case MSR_EFER:
1556                if (cpu_has_load_ia32_efer) {
1557                        add_atomic_switch_msr_special(vmx,
1558                                        VM_ENTRY_LOAD_IA32_EFER,
1559                                        VM_EXIT_LOAD_IA32_EFER,
1560                                        GUEST_IA32_EFER,
1561                                        HOST_IA32_EFER,
1562                                        guest_val, host_val);
1563                        return;
1564                }
1565                break;
1566        case MSR_CORE_PERF_GLOBAL_CTRL:
1567                if (cpu_has_load_perf_global_ctrl) {
1568                        add_atomic_switch_msr_special(vmx,
1569                                        VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1570                                        VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
1571                                        GUEST_IA32_PERF_GLOBAL_CTRL,
1572                                        HOST_IA32_PERF_GLOBAL_CTRL,
1573                                        guest_val, host_val);
1574                        return;
1575                }
1576                break;
1577        }
1578
1579        for (i = 0; i < m->nr; ++i)
1580                if (m->guest[i].index == msr)
1581                        break;
1582
1583        if (i == NR_AUTOLOAD_MSRS) {
1584                printk_once(KERN_WARNING "Not enough msr switch entries. "
1585                                "Can't add msr %x\n", msr);
1586                return;
1587        } else if (i == m->nr) {
1588                ++m->nr;
1589                vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
1590                vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
1591        }
1592
1593        m->guest[i].index = msr;
1594        m->guest[i].value = guest_val;
1595        m->host[i].index = msr;
1596        m->host[i].value = host_val;
1597}
1598
1599static void reload_tss(void)
1600{
1601        /*
1602         * VT restores TR but not its size.  Useless.
1603         */
1604        struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
1605        struct desc_struct *descs;
1606
1607        descs = (void *)gdt->address;
1608        descs[GDT_ENTRY_TSS].type = 9; /* available TSS */
1609        load_TR_desc();
1610}
1611
1612static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
1613{
1614        u64 guest_efer;
1615        u64 ignore_bits;
1616
1617        guest_efer = vmx->vcpu.arch.efer;
1618
1619        /*
1620         * NX is emulated; LMA and LME handled by hardware; SCE meaningless
1621         * outside long mode
1622         */
1623        ignore_bits = EFER_NX | EFER_SCE;
1624#ifdef CONFIG_X86_64
1625        ignore_bits |= EFER_LMA | EFER_LME;
1626        /* SCE is meaningful only in long mode on Intel */
1627        if (guest_efer & EFER_LMA)
1628                ignore_bits &= ~(u64)EFER_SCE;
1629#endif
1630        guest_efer &= ~ignore_bits;
1631        guest_efer |= host_efer & ignore_bits;
1632        vmx->guest_msrs[efer_offset].data = guest_efer;
1633        vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
1634
1635        clear_atomic_switch_msr(vmx, MSR_EFER);
1636        /* On ept, can't emulate nx, and must switch nx atomically */
1637        if (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX)) {
1638                guest_efer = vmx->vcpu.arch.efer;
1639                if (!(guest_efer & EFER_LMA))
1640                        guest_efer &= ~EFER_LME;
1641                add_atomic_switch_msr(vmx, MSR_EFER, guest_efer, host_efer);
1642                return false;
1643        }
1644
1645        return true;
1646}
1647
1648static unsigned long segment_base(u16 selector)
1649{
1650        struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
1651        struct desc_struct *d;
1652        unsigned long table_base;
1653        unsigned long v;
1654
1655        if (!(selector & ~3))
1656                return 0;
1657
1658        table_base = gdt->address;
1659
1660        if (selector & 4) {           /* from ldt */
1661                u16 ldt_selector = kvm_read_ldt();
1662
1663                if (!(ldt_selector & ~3))
1664                        return 0;
1665
1666                table_base = segment_base(ldt_selector);
1667        }
1668        d = (struct desc_struct *)(table_base + (selector & ~7));
1669        v = get_desc_base(d);
1670#ifdef CONFIG_X86_64
1671       if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
1672               v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
1673#endif
1674        return v;
1675}
1676
1677static inline unsigned long kvm_read_tr_base(void)
1678{
1679        u16 tr;
1680        asm("str %0" : "=g"(tr));
1681        return segment_base(tr);
1682}
1683
1684static void vmx_save_host_state(struct kvm_vcpu *vcpu)
1685{
1686        struct vcpu_vmx *vmx = to_vmx(vcpu);
1687        int i;
1688
1689        if (vmx->host_state.loaded)
1690                return;
1691
1692        vmx->host_state.loaded = 1;
1693        /*
1694         * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
1695         * allow segment selectors with cpl > 0 or ti == 1.
1696         */
1697        vmx->host_state.ldt_sel = kvm_read_ldt();
1698        vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
1699        savesegment(fs, vmx->host_state.fs_sel);
1700        if (!(vmx->host_state.fs_sel & 7)) {
1701                vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
1702                vmx->host_state.fs_reload_needed = 0;
1703        } else {
1704                vmcs_write16(HOST_FS_SELECTOR, 0);
1705                vmx->host_state.fs_reload_needed = 1;
1706        }
1707        savesegment(gs, vmx->host_state.gs_sel);
1708        if (!(vmx->host_state.gs_sel & 7))
1709                vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
1710        else {
1711                vmcs_write16(HOST_GS_SELECTOR, 0);
1712                vmx->host_state.gs_ldt_reload_needed = 1;
1713        }
1714
1715#ifdef CONFIG_X86_64
1716        savesegment(ds, vmx->host_state.ds_sel);
1717        savesegment(es, vmx->host_state.es_sel);
1718#endif
1719
1720#ifdef CONFIG_X86_64
1721        vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
1722        vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
1723#else
1724        vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
1725        vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
1726#endif
1727
1728#ifdef CONFIG_X86_64
1729        rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1730        if (is_long_mode(&vmx->vcpu))
1731                wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1732#endif
1733        if (boot_cpu_has(X86_FEATURE_MPX))
1734                rdmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
1735        for (i = 0; i < vmx->save_nmsrs; ++i)
1736                kvm_set_shared_msr(vmx->guest_msrs[i].index,
1737                                   vmx->guest_msrs[i].data,
1738                                   vmx->guest_msrs[i].mask);
1739}
1740
1741static void __vmx_load_host_state(struct vcpu_vmx *vmx)
1742{
1743        if (!vmx->host_state.loaded)
1744                return;
1745
1746        ++vmx->vcpu.stat.host_state_reload;
1747        vmx->host_state.loaded = 0;
1748#ifdef CONFIG_X86_64
1749        if (is_long_mode(&vmx->vcpu))
1750                rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1751#endif
1752        if (vmx->host_state.gs_ldt_reload_needed) {
1753                kvm_load_ldt(vmx->host_state.ldt_sel);
1754#ifdef CONFIG_X86_64
1755                load_gs_index(vmx->host_state.gs_sel);
1756#else
1757                loadsegment(gs, vmx->host_state.gs_sel);
1758#endif
1759        }
1760        if (vmx->host_state.fs_reload_needed)
1761                loadsegment(fs, vmx->host_state.fs_sel);
1762#ifdef CONFIG_X86_64
1763        if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
1764                loadsegment(ds, vmx->host_state.ds_sel);
1765                loadsegment(es, vmx->host_state.es_sel);
1766        }
1767#endif
1768        reload_tss();
1769#ifdef CONFIG_X86_64
1770        wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1771#endif
1772        if (vmx->host_state.msr_host_bndcfgs)
1773                wrmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
1774        /*
1775         * If the FPU is not active (through the host task or
1776         * the guest vcpu), then restore the cr0.TS bit.
1777         */
1778        if (!user_has_fpu() && !vmx->vcpu.guest_fpu_loaded)
1779                stts();
1780        load_gdt(&__get_cpu_var(host_gdt));
1781}
1782
1783static void vmx_load_host_state(struct vcpu_vmx *vmx)
1784{
1785        preempt_disable();
1786        __vmx_load_host_state(vmx);
1787        preempt_enable();
1788}
1789
1790/*
1791 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1792 * vcpu mutex is already taken.
1793 */
1794static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1795{
1796        struct vcpu_vmx *vmx = to_vmx(vcpu);
1797        u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
1798
1799        if (!vmm_exclusive)
1800                kvm_cpu_vmxon(phys_addr);
1801        else if (vmx->loaded_vmcs->cpu != cpu)
1802                loaded_vmcs_clear(vmx->loaded_vmcs);
1803
1804        if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
1805                per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1806                vmcs_load(vmx->loaded_vmcs->vmcs);
1807        }
1808
1809        if (vmx->loaded_vmcs->cpu != cpu) {
1810                struct desc_ptr *gdt = &__get_cpu_var(host_gdt);
1811                unsigned long sysenter_esp;
1812
1813                kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1814                local_irq_disable();
1815                crash_disable_local_vmclear(cpu);
1816
1817                /*
1818                 * Read loaded_vmcs->cpu should be before fetching
1819                 * loaded_vmcs->loaded_vmcss_on_cpu_link.
1820                 * See the comments in __loaded_vmcs_clear().
1821                 */
1822                smp_rmb();
1823
1824                list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1825                         &per_cpu(loaded_vmcss_on_cpu, cpu));
1826                crash_enable_local_vmclear(cpu);
1827                local_irq_enable();
1828
1829                /*
1830                 * Linux uses per-cpu TSS and GDT, so set these when switching
1831                 * processors.
1832                 */
1833                vmcs_writel(HOST_TR_BASE, kvm_read_tr_base()); /* 22.2.4 */
1834                vmcs_writel(HOST_GDTR_BASE, gdt->address);   /* 22.2.4 */
1835
1836                rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1837                vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1838                vmx->loaded_vmcs->cpu = cpu;
1839        }
1840}
1841
1842static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1843{
1844        __vmx_load_host_state(to_vmx(vcpu));
1845        if (!vmm_exclusive) {
1846                __loaded_vmcs_clear(to_vmx(vcpu)->loaded_vmcs);
1847                vcpu->cpu = -1;
1848                kvm_cpu_vmxoff();
1849        }
1850}
1851
1852static void vmx_fpu_activate(struct kvm_vcpu *vcpu)
1853{
1854        ulong cr0;
1855
1856        if (vcpu->fpu_active)
1857                return;
1858        vcpu->fpu_active = 1;
1859        cr0 = vmcs_readl(GUEST_CR0);
1860        cr0 &= ~(X86_CR0_TS | X86_CR0_MP);
1861        cr0 |= kvm_read_cr0_bits(vcpu, X86_CR0_TS | X86_CR0_MP);
1862        vmcs_writel(GUEST_CR0, cr0);
1863        update_exception_bitmap(vcpu);
1864        vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
1865        if (is_guest_mode(vcpu))
1866                vcpu->arch.cr0_guest_owned_bits &=
1867                        ~get_vmcs12(vcpu)->cr0_guest_host_mask;
1868        vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
1869}
1870
1871static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
1872
1873/*
1874 * Return the cr0 value that a nested guest would read. This is a combination
1875 * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
1876 * its hypervisor (cr0_read_shadow).
1877 */
1878static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
1879{
1880        return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
1881                (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
1882}
1883static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
1884{
1885        return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
1886                (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
1887}
1888
1889static void vmx_fpu_deactivate(struct kvm_vcpu *vcpu)
1890{
1891        /* Note that there is no vcpu->fpu_active = 0 here. The caller must
1892         * set this *before* calling this function.
1893         */
1894        vmx_decache_cr0_guest_bits(vcpu);
1895        vmcs_set_bits(GUEST_CR0, X86_CR0_TS | X86_CR0_MP);
1896        update_exception_bitmap(vcpu);
1897        vcpu->arch.cr0_guest_owned_bits = 0;
1898        vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
1899        if (is_guest_mode(vcpu)) {
1900                /*
1901                 * L1's specified read shadow might not contain the TS bit,
1902                 * so now that we turned on shadowing of this bit, we need to
1903                 * set this bit of the shadow. Like in nested_vmx_run we need
1904                 * nested_read_cr0(vmcs12), but vmcs12->guest_cr0 is not yet
1905                 * up-to-date here because we just decached cr0.TS (and we'll
1906                 * only update vmcs12->guest_cr0 on nested exit).
1907                 */
1908                struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1909                vmcs12->guest_cr0 = (vmcs12->guest_cr0 & ~X86_CR0_TS) |
1910                        (vcpu->arch.cr0 & X86_CR0_TS);
1911                vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
1912        } else
1913                vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0);
1914}
1915
1916static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1917{
1918        unsigned long rflags, save_rflags;
1919
1920        if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
1921                __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1922                rflags = vmcs_readl(GUEST_RFLAGS);
1923                if (to_vmx(vcpu)->rmode.vm86_active) {
1924                        rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1925                        save_rflags = to_vmx(vcpu)->rmode.save_rflags;
1926                        rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1927                }
1928                to_vmx(vcpu)->rflags = rflags;
1929        }
1930        return to_vmx(vcpu)->rflags;
1931}
1932
1933static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1934{
1935        __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1936        to_vmx(vcpu)->rflags = rflags;
1937        if (to_vmx(vcpu)->rmode.vm86_active) {
1938                to_vmx(vcpu)->rmode.save_rflags = rflags;
1939                rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1940        }
1941        vmcs_writel(GUEST_RFLAGS, rflags);
1942}
1943
1944static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1945{
1946        u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1947        int ret = 0;
1948
1949        if (interruptibility & GUEST_INTR_STATE_STI)
1950                ret |= KVM_X86_SHADOW_INT_STI;
1951        if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1952                ret |= KVM_X86_SHADOW_INT_MOV_SS;
1953
1954        return ret;
1955}
1956
1957static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1958{
1959        u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1960        u32 interruptibility = interruptibility_old;
1961
1962        interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1963
1964        if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1965                interruptibility |= GUEST_INTR_STATE_MOV_SS;
1966        else if (mask & KVM_X86_SHADOW_INT_STI)
1967                interruptibility |= GUEST_INTR_STATE_STI;
1968
1969        if ((interruptibility != interruptibility_old))
1970                vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1971}
1972
1973static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
1974{
1975        unsigned long rip;
1976
1977        rip = kvm_rip_read(vcpu);
1978        rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1979        kvm_rip_write(vcpu, rip);
1980
1981        /* skipping an emulated instruction also counts */
1982        vmx_set_interrupt_shadow(vcpu, 0);
1983}
1984
1985/*
1986 * KVM wants to inject page-faults which it got to the guest. This function
1987 * checks whether in a nested guest, we need to inject them to L1 or L2.
1988 */
1989static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned nr)
1990{
1991        struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1992
1993        if (!(vmcs12->exception_bitmap & (1u << nr)))
1994                return 0;
1995
1996        nested_vmx_vmexit(vcpu, to_vmx(vcpu)->exit_reason,
1997                          vmcs_read32(VM_EXIT_INTR_INFO),
1998                          vmcs_readl(EXIT_QUALIFICATION));
1999        return 1;
2000}
2001
2002static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
2003                                bool has_error_code, u32 error_code,
2004                                bool reinject)
2005{
2006        struct vcpu_vmx *vmx = to_vmx(vcpu);
2007        u32 intr_info = nr | INTR_INFO_VALID_MASK;
2008
2009        if (!reinject && is_guest_mode(vcpu) &&
2010            nested_vmx_check_exception(vcpu, nr))
2011                return;
2012
2013        if (has_error_code) {
2014                vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
2015                intr_info |= INTR_INFO_DELIVER_CODE_MASK;
2016        }
2017
2018        if (vmx->rmode.vm86_active) {
2019                int inc_eip = 0;
2020                if (kvm_exception_is_soft(nr))
2021                        inc_eip = vcpu->arch.event_exit_inst_len;
2022                if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
2023                        kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2024                return;
2025        }
2026
2027        if (kvm_exception_is_soft(nr)) {
2028                vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2029                             vmx->vcpu.arch.event_exit_inst_len);
2030                intr_info |= INTR_TYPE_SOFT_EXCEPTION;
2031        } else
2032                intr_info |= INTR_TYPE_HARD_EXCEPTION;
2033
2034        vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
2035}
2036
2037static bool vmx_rdtscp_supported(void)
2038{
2039        return cpu_has_vmx_rdtscp();
2040}
2041
2042static bool vmx_invpcid_supported(void)
2043{
2044        return cpu_has_vmx_invpcid() && enable_ept;
2045}
2046
2047/*
2048 * Swap MSR entry in host/guest MSR entry array.
2049 */
2050static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
2051{
2052        struct shared_msr_entry tmp;
2053
2054        tmp = vmx->guest_msrs[to];
2055        vmx->guest_msrs[to] = vmx->guest_msrs[from];
2056        vmx->guest_msrs[from] = tmp;
2057}
2058
2059static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu)
2060{
2061        unsigned long *msr_bitmap;
2062
2063        if (irqchip_in_kernel(vcpu->kvm) && apic_x2apic_mode(vcpu->arch.apic)) {
2064                if (is_long_mode(vcpu))
2065                        msr_bitmap = vmx_msr_bitmap_longmode_x2apic;
2066                else
2067                        msr_bitmap = vmx_msr_bitmap_legacy_x2apic;
2068        } else {
2069                if (is_long_mode(vcpu))
2070                        msr_bitmap = vmx_msr_bitmap_longmode;
2071                else
2072                        msr_bitmap = vmx_msr_bitmap_legacy;
2073        }
2074
2075        vmcs_write64(MSR_BITMAP, __pa(msr_bitmap));
2076}
2077
2078/*
2079 * Set up the vmcs to automatically save and restore system
2080 * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
2081 * mode, as fiddling with msrs is very expensive.
2082 */
2083static void setup_msrs(struct vcpu_vmx *vmx)
2084{
2085        int save_nmsrs, index;
2086
2087        save_nmsrs = 0;
2088#ifdef CONFIG_X86_64
2089        if (is_long_mode(&vmx->vcpu)) {
2090                index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
2091                if (index >= 0)
2092                        move_msr_up(vmx, index, save_nmsrs++);
2093                index = __find_msr_index(vmx, MSR_LSTAR);
2094                if (index >= 0)
2095                        move_msr_up(vmx, index, save_nmsrs++);
2096                index = __find_msr_index(vmx, MSR_CSTAR);
2097                if (index >= 0)
2098                        move_msr_up(vmx, index, save_nmsrs++);
2099                index = __find_msr_index(vmx, MSR_TSC_AUX);
2100                if (index >= 0 && vmx->rdtscp_enabled)
2101                        move_msr_up(vmx, index, save_nmsrs++);
2102                /*
2103                 * MSR_STAR is only needed on long mode guests, and only
2104                 * if efer.sce is enabled.
2105                 */
2106                index = __find_msr_index(vmx, MSR_STAR);
2107                if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
2108                        move_msr_up(vmx, index, save_nmsrs++);
2109        }
2110#endif
2111        index = __find_msr_index(vmx, MSR_EFER);
2112        if (index >= 0 && update_transition_efer(vmx, index))
2113                move_msr_up(vmx, index, save_nmsrs++);
2114
2115        vmx->save_nmsrs = save_nmsrs;
2116
2117        if (cpu_has_vmx_msr_bitmap())
2118                vmx_set_msr_bitmap(&vmx->vcpu);
2119}
2120
2121/*
2122 * reads and returns guest's timestamp counter "register"
2123 * guest_tsc = host_tsc + tsc_offset    -- 21.3
2124 */
2125static u64 guest_read_tsc(void)
2126{
2127        u64 host_tsc, tsc_offset;
2128
2129        rdtscll(host_tsc);
2130        tsc_offset = vmcs_read64(TSC_OFFSET);
2131        return host_tsc + tsc_offset;
2132}
2133
2134/*
2135 * Like guest_read_tsc, but always returns L1's notion of the timestamp
2136 * counter, even if a nested guest (L2) is currently running.
2137 */
2138u64 vmx_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2139{
2140        u64 tsc_offset;
2141
2142        tsc_offset = is_guest_mode(vcpu) ?
2143                to_vmx(vcpu)->nested.vmcs01_tsc_offset :
2144                vmcs_read64(TSC_OFFSET);
2145        return host_tsc + tsc_offset;
2146}
2147
2148/*
2149 * Engage any workarounds for mis-matched TSC rates.  Currently limited to
2150 * software catchup for faster rates on slower CPUs.
2151 */
2152static void vmx_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2153{
2154        if (!scale)
2155                return;
2156
2157        if (user_tsc_khz > tsc_khz) {
2158                vcpu->arch.tsc_catchup = 1;
2159                vcpu->arch.tsc_always_catchup = 1;
2160        } else
2161                WARN(1, "user requested TSC rate below hardware speed\n");
2162}
2163
2164static u64 vmx_read_tsc_offset(struct kvm_vcpu *vcpu)
2165{
2166        return vmcs_read64(TSC_OFFSET);
2167}
2168
2169/*
2170 * writes 'offset' into guest's timestamp counter offset register
2171 */
2172static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2173{
2174        if (is_guest_mode(vcpu)) {
2175                /*
2176                 * We're here if L1 chose not to trap WRMSR to TSC. According
2177                 * to the spec, this should set L1's TSC; The offset that L1
2178                 * set for L2 remains unchanged, and still needs to be added
2179                 * to the newly set TSC to get L2's TSC.
2180                 */
2181                struct vmcs12 *vmcs12;
2182                to_vmx(vcpu)->nested.vmcs01_tsc_offset = offset;
2183                /* recalculate vmcs02.TSC_OFFSET: */
2184                vmcs12 = get_vmcs12(vcpu);
2185                vmcs_write64(TSC_OFFSET, offset +
2186                        (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
2187                         vmcs12->tsc_offset : 0));
2188        } else {
2189                trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2190                                           vmcs_read64(TSC_OFFSET), offset);
2191                vmcs_write64(TSC_OFFSET, offset);
2192        }
2193}
2194
2195static void vmx_adjust_tsc_offset(struct kvm_vcpu *vcpu, s64 adjustment, bool host)
2196{
2197        u64 offset = vmcs_read64(TSC_OFFSET);
2198
2199        vmcs_write64(TSC_OFFSET, offset + adjustment);
2200        if (is_guest_mode(vcpu)) {
2201                /* Even when running L2, the adjustment needs to apply to L1 */
2202                to_vmx(vcpu)->nested.vmcs01_tsc_offset += adjustment;
2203        } else
2204                trace_kvm_write_tsc_offset(vcpu->vcpu_id, offset,
2205                                           offset + adjustment);
2206}
2207
2208static u64 vmx_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2209{
2210        return target_tsc - native_read_tsc();
2211}
2212
2213static bool guest_cpuid_has_vmx(struct kvm_vcpu *vcpu)
2214{
2215        struct kvm_cpuid_entry2 *best = kvm_find_cpuid_entry(vcpu, 1, 0);
2216        return best && (best->ecx & (1 << (X86_FEATURE_VMX & 31)));
2217}
2218
2219/*
2220 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
2221 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
2222 * all guests if the "nested" module option is off, and can also be disabled
2223 * for a single guest by disabling its VMX cpuid bit.
2224 */
2225static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
2226{
2227        return nested && guest_cpuid_has_vmx(vcpu);
2228}
2229
2230/*
2231 * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
2232 * returned for the various VMX controls MSRs when nested VMX is enabled.
2233 * The same values should also be used to verify that vmcs12 control fields are
2234 * valid during nested entry from L1 to L2.
2235 * Each of these control msrs has a low and high 32-bit half: A low bit is on
2236 * if the corresponding bit in the (32-bit) control field *must* be on, and a
2237 * bit in the high half is on if the corresponding bit in the control field
2238 * may be on. See also vmx_control_verify().
2239 * TODO: allow these variables to be modified (downgraded) by module options
2240 * or other means.
2241 */
2242static u32 nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high;
2243static u32 nested_vmx_true_procbased_ctls_low;
2244static u32 nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high;
2245static u32 nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high;
2246static u32 nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high;
2247static u32 nested_vmx_true_exit_ctls_low;
2248static u32 nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high;
2249static u32 nested_vmx_true_entry_ctls_low;
2250static u32 nested_vmx_misc_low, nested_vmx_misc_high;
2251static u32 nested_vmx_ept_caps;
2252static __init void nested_vmx_setup_ctls_msrs(void)
2253{
2254        /*
2255         * Note that as a general rule, the high half of the MSRs (bits in
2256         * the control fields which may be 1) should be initialized by the
2257         * intersection of the underlying hardware's MSR (i.e., features which
2258         * can be supported) and the list of features we want to expose -
2259         * because they are known to be properly supported in our code.
2260         * Also, usually, the low half of the MSRs (bits which must be 1) can
2261         * be set to 0, meaning that L1 may turn off any of these bits. The
2262         * reason is that if one of these bits is necessary, it will appear
2263         * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
2264         * fields of vmcs01 and vmcs02, will turn these bits off - and
2265         * nested_vmx_exit_handled() will not pass related exits to L1.
2266         * These rules have exceptions below.
2267         */
2268
2269        /* pin-based controls */
2270        rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
2271              nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high);
2272        nested_vmx_pinbased_ctls_low |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2273        nested_vmx_pinbased_ctls_high &= PIN_BASED_EXT_INTR_MASK |
2274                PIN_BASED_NMI_EXITING | PIN_BASED_VIRTUAL_NMIS;
2275        nested_vmx_pinbased_ctls_high |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2276                PIN_BASED_VMX_PREEMPTION_TIMER;
2277
2278        /* exit controls */
2279        rdmsr(MSR_IA32_VMX_EXIT_CTLS,
2280                nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high);
2281        nested_vmx_exit_ctls_low = VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
2282
2283        nested_vmx_exit_ctls_high &=
2284#ifdef CONFIG_X86_64
2285                VM_EXIT_HOST_ADDR_SPACE_SIZE |
2286#endif
2287                VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
2288        nested_vmx_exit_ctls_high |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
2289                VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
2290                VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
2291
2292        if (vmx_mpx_supported())
2293                nested_vmx_exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
2294
2295        /* We support free control of debug control saving. */
2296        nested_vmx_true_exit_ctls_low = nested_vmx_exit_ctls_low &
2297                ~VM_EXIT_SAVE_DEBUG_CONTROLS;
2298
2299        /* entry controls */
2300        rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
2301                nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high);
2302        nested_vmx_entry_ctls_low = VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
2303        nested_vmx_entry_ctls_high &=
2304#ifdef CONFIG_X86_64
2305                VM_ENTRY_IA32E_MODE |
2306#endif
2307                VM_ENTRY_LOAD_IA32_PAT;
2308        nested_vmx_entry_ctls_high |= (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR |
2309                                       VM_ENTRY_LOAD_IA32_EFER);
2310        if (vmx_mpx_supported())
2311                nested_vmx_entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
2312
2313        /* We support free control of debug control loading. */
2314        nested_vmx_true_entry_ctls_low = nested_vmx_entry_ctls_low &
2315                ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
2316
2317        /* cpu-based controls */
2318        rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
2319                nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high);
2320        nested_vmx_procbased_ctls_low = CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2321        nested_vmx_procbased_ctls_high &=
2322                CPU_BASED_VIRTUAL_INTR_PENDING |
2323                CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
2324                CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
2325                CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
2326                CPU_BASED_CR3_STORE_EXITING |
2327#ifdef CONFIG_X86_64
2328                CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
2329#endif
2330                CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
2331                CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_EXITING |
2332                CPU_BASED_RDPMC_EXITING | CPU_BASED_RDTSC_EXITING |
2333                CPU_BASED_PAUSE_EXITING |
2334                CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2335        /*
2336         * We can allow some features even when not supported by the
2337         * hardware. For example, L1 can specify an MSR bitmap - and we
2338         * can use it to avoid exits to L1 - even when L0 runs L2
2339         * without MSR bitmaps.
2340         */
2341        nested_vmx_procbased_ctls_high |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2342                CPU_BASED_USE_MSR_BITMAPS;
2343
2344        /* We support free control of CR3 access interception. */
2345        nested_vmx_true_procbased_ctls_low = nested_vmx_procbased_ctls_low &
2346                ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
2347
2348        /* secondary cpu-based controls */
2349        rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
2350                nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high);
2351        nested_vmx_secondary_ctls_low = 0;
2352        nested_vmx_secondary_ctls_high &=
2353                SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2354                SECONDARY_EXEC_UNRESTRICTED_GUEST |
2355                SECONDARY_EXEC_WBINVD_EXITING;
2356
2357        if (enable_ept) {
2358                /* nested EPT: emulate EPT also to L1 */
2359                nested_vmx_secondary_ctls_high |= SECONDARY_EXEC_ENABLE_EPT;
2360                nested_vmx_ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
2361                         VMX_EPTP_WB_BIT | VMX_EPT_2MB_PAGE_BIT |
2362                         VMX_EPT_INVEPT_BIT;
2363                nested_vmx_ept_caps &= vmx_capability.ept;
2364                /*
2365                 * For nested guests, we don't do anything specific
2366                 * for single context invalidation. Hence, only advertise
2367                 * support for global context invalidation.
2368                 */
2369                nested_vmx_ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT;
2370        } else
2371                nested_vmx_ept_caps = 0;
2372
2373        /* miscellaneous data */
2374        rdmsr(MSR_IA32_VMX_MISC, nested_vmx_misc_low, nested_vmx_misc_high);
2375        nested_vmx_misc_low &= VMX_MISC_SAVE_EFER_LMA;
2376        nested_vmx_misc_low |= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
2377                VMX_MISC_ACTIVITY_HLT;
2378        nested_vmx_misc_high = 0;
2379}
2380
2381static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
2382{
2383        /*
2384         * Bits 0 in high must be 0, and bits 1 in low must be 1.
2385         */
2386        return ((control & high) | low) == control;
2387}
2388
2389static inline u64 vmx_control_msr(u32 low, u32 high)
2390{
2391        return low | ((u64)high << 32);
2392}
2393
2394/* Returns 0 on success, non-0 otherwise. */
2395static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
2396{
2397        switch (msr_index) {
2398        case MSR_IA32_VMX_BASIC:
2399                /*
2400                 * This MSR reports some information about VMX support. We
2401                 * should return information about the VMX we emulate for the
2402                 * guest, and the VMCS structure we give it - not about the
2403                 * VMX support of the underlying hardware.
2404                 */
2405                *pdata = VMCS12_REVISION | VMX_BASIC_TRUE_CTLS |
2406                           ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
2407                           (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
2408                break;
2409        case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2410        case MSR_IA32_VMX_PINBASED_CTLS:
2411                *pdata = vmx_control_msr(nested_vmx_pinbased_ctls_low,
2412                                        nested_vmx_pinbased_ctls_high);
2413                break;
2414        case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2415                *pdata = vmx_control_msr(nested_vmx_true_procbased_ctls_low,
2416                                        nested_vmx_procbased_ctls_high);
2417                break;
2418        case MSR_IA32_VMX_PROCBASED_CTLS:
2419                *pdata = vmx_control_msr(nested_vmx_procbased_ctls_low,
2420                                        nested_vmx_procbased_ctls_high);
2421                break;
2422        case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2423                *pdata = vmx_control_msr(nested_vmx_true_exit_ctls_low,
2424                                        nested_vmx_exit_ctls_high);
2425                break;
2426        case MSR_IA32_VMX_EXIT_CTLS:
2427                *pdata = vmx_control_msr(nested_vmx_exit_ctls_low,
2428                                        nested_vmx_exit_ctls_high);
2429                break;
2430        case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
2431                *pdata = vmx_control_msr(nested_vmx_true_entry_ctls_low,
2432                                        nested_vmx_entry_ctls_high);
2433                break;
2434        case MSR_IA32_VMX_ENTRY_CTLS:
2435                *pdata = vmx_control_msr(nested_vmx_entry_ctls_low,
2436                                        nested_vmx_entry_ctls_high);
2437                break;
2438        case MSR_IA32_VMX_MISC:
2439                *pdata = vmx_control_msr(nested_vmx_misc_low,
2440                                         nested_vmx_misc_high);
2441                break;
2442        /*
2443         * These MSRs specify bits which the guest must keep fixed (on or off)
2444         * while L1 is in VMXON mode (in L1's root mode, or running an L2).
2445         * We picked the standard core2 setting.
2446         */
2447#define VMXON_CR0_ALWAYSON      (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
2448#define VMXON_CR4_ALWAYSON      X86_CR4_VMXE
2449        case MSR_IA32_VMX_CR0_FIXED0:
2450                *pdata = VMXON_CR0_ALWAYSON;
2451                break;
2452        case MSR_IA32_VMX_CR0_FIXED1:
2453                *pdata = -1ULL;
2454                break;
2455        case MSR_IA32_VMX_CR4_FIXED0:
2456                *pdata = VMXON_CR4_ALWAYSON;
2457                break;
2458        case MSR_IA32_VMX_CR4_FIXED1:
2459                *pdata = -1ULL;
2460                break;
2461        case MSR_IA32_VMX_VMCS_ENUM:
2462                *pdata = 0x2e; /* highest index: VMX_PREEMPTION_TIMER_VALUE */
2463                break;
2464        case MSR_IA32_VMX_PROCBASED_CTLS2:
2465                *pdata = vmx_control_msr(nested_vmx_secondary_ctls_low,
2466                                        nested_vmx_secondary_ctls_high);
2467                break;
2468        case MSR_IA32_VMX_EPT_VPID_CAP:
2469                /* Currently, no nested vpid support */
2470                *pdata = nested_vmx_ept_caps;
2471                break;
2472        default:
2473                return 1;
2474        }
2475
2476        return 0;
2477}
2478
2479/*
2480 * Reads an msr value (of 'msr_index') into 'pdata'.
2481 * Returns 0 on success, non-0 otherwise.
2482 * Assumes vcpu_load() was already called.
2483 */
2484static int vmx_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
2485{
2486        u64 data;
2487        struct shared_msr_entry *msr;
2488
2489        if (!pdata) {
2490                printk(KERN_ERR "BUG: get_msr called with NULL pdata\n");
2491                return -EINVAL;
2492        }
2493
2494        switch (msr_index) {
2495#ifdef CONFIG_X86_64
2496        case MSR_FS_BASE:
2497                data = vmcs_readl(GUEST_FS_BASE);
2498                break;
2499        case MSR_GS_BASE:
2500                data = vmcs_readl(GUEST_GS_BASE);
2501                break;
2502        case MSR_KERNEL_GS_BASE:
2503                vmx_load_host_state(to_vmx(vcpu));
2504                data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
2505                break;
2506#endif
2507        case MSR_EFER:
2508                return kvm_get_msr_common(vcpu, msr_index, pdata);
2509        case MSR_IA32_TSC:
2510                data = guest_read_tsc();
2511                break;
2512        case MSR_IA32_SYSENTER_CS:
2513                data = vmcs_read32(GUEST_SYSENTER_CS);
2514                break;
2515        case MSR_IA32_SYSENTER_EIP:
2516                data = vmcs_readl(GUEST_SYSENTER_EIP);
2517                break;
2518        case MSR_IA32_SYSENTER_ESP:
2519                data = vmcs_readl(GUEST_SYSENTER_ESP);
2520                break;
2521        case MSR_IA32_BNDCFGS:
2522                if (!vmx_mpx_supported())
2523                        return 1;
2524                data = vmcs_read64(GUEST_BNDCFGS);
2525                break;
2526        case MSR_IA32_FEATURE_CONTROL:
2527                if (!nested_vmx_allowed(vcpu))
2528                        return 1;
2529                data = to_vmx(vcpu)->nested.msr_ia32_feature_control;
2530                break;
2531        case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2532                if (!nested_vmx_allowed(vcpu))
2533                        return 1;
2534                return vmx_get_vmx_msr(vcpu, msr_index, pdata);
2535        case MSR_TSC_AUX:
2536                if (!to_vmx(vcpu)->rdtscp_enabled)
2537                        return 1;
2538                /* Otherwise falls through */
2539        default:
2540                msr = find_msr_entry(to_vmx(vcpu), msr_index);
2541                if (msr) {
2542                        data = msr->data;
2543                        break;
2544                }
2545                return kvm_get_msr_common(vcpu, msr_index, pdata);
2546        }
2547
2548        *pdata = data;
2549        return 0;
2550}
2551
2552static void vmx_leave_nested(struct kvm_vcpu *vcpu);
2553
2554/*
2555 * Writes msr value into into the appropriate "register".
2556 * Returns 0 on success, non-0 otherwise.
2557 * Assumes vcpu_load() was already called.
2558 */
2559static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2560{
2561        struct vcpu_vmx *vmx = to_vmx(vcpu);
2562        struct shared_msr_entry *msr;
2563        int ret = 0;
2564        u32 msr_index = msr_info->index;
2565        u64 data = msr_info->data;
2566
2567        switch (msr_index) {
2568        case MSR_EFER:
2569                ret = kvm_set_msr_common(vcpu, msr_info);
2570                break;
2571#ifdef CONFIG_X86_64
2572        case MSR_FS_BASE:
2573                vmx_segment_cache_clear(vmx);
2574                vmcs_writel(GUEST_FS_BASE, data);
2575                break;
2576        case MSR_GS_BASE:
2577                vmx_segment_cache_clear(vmx);
2578                vmcs_writel(GUEST_GS_BASE, data);
2579                break;
2580        case MSR_KERNEL_GS_BASE:
2581                vmx_load_host_state(vmx);
2582                vmx->msr_guest_kernel_gs_base = data;
2583                break;
2584#endif
2585        case MSR_IA32_SYSENTER_CS:
2586                vmcs_write32(GUEST_SYSENTER_CS, data);
2587                break;
2588        case MSR_IA32_SYSENTER_EIP:
2589                vmcs_writel(GUEST_SYSENTER_EIP, data);
2590                break;
2591        case MSR_IA32_SYSENTER_ESP:
2592                vmcs_writel(GUEST_SYSENTER_ESP, data);
2593                break;
2594        case MSR_IA32_BNDCFGS:
2595                if (!vmx_mpx_supported())
2596                        return 1;
2597                vmcs_write64(GUEST_BNDCFGS, data);
2598                break;
2599        case MSR_IA32_TSC:
2600                kvm_write_tsc(vcpu, msr_info);
2601                break;
2602        case MSR_IA32_CR_PAT:
2603                if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2604                        vmcs_write64(GUEST_IA32_PAT, data);
2605                        vcpu->arch.pat = data;
2606                        break;
2607                }
2608                ret = kvm_set_msr_common(vcpu, msr_info);
2609                break;
2610        case MSR_IA32_TSC_ADJUST:
2611                ret = kvm_set_msr_common(vcpu, msr_info);
2612                break;
2613        case MSR_IA32_FEATURE_CONTROL:
2614                if (!nested_vmx_allowed(vcpu) ||
2615                    (to_vmx(vcpu)->nested.msr_ia32_feature_control &
2616                     FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
2617                        return 1;
2618                vmx->nested.msr_ia32_feature_control = data;
2619                if (msr_info->host_initiated && data == 0)
2620                        vmx_leave_nested(vcpu);
2621                break;
2622        case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2623                return 1; /* they are read-only */
2624        case MSR_TSC_AUX:
2625                if (!vmx->rdtscp_enabled)
2626                        return 1;
2627                /* Check reserved bit, higher 32 bits should be zero */
2628                if ((data >> 32) != 0)
2629                        return 1;
2630                /* Otherwise falls through */
2631        default:
2632                msr = find_msr_entry(vmx, msr_index);
2633                if (msr) {
2634                        msr->data = data;
2635                        if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
2636                                preempt_disable();
2637                                kvm_set_shared_msr(msr->index, msr->data,
2638                                                   msr->mask);
2639                                preempt_enable();
2640                        }
2641                        break;
2642                }
2643                ret = kvm_set_msr_common(vcpu, msr_info);
2644        }
2645
2646        return ret;
2647}
2648
2649static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2650{
2651        __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
2652        switch (reg) {
2653        case VCPU_REGS_RSP:
2654                vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2655                break;
2656        case VCPU_REGS_RIP:
2657                vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2658                break;
2659        case VCPU_EXREG_PDPTR:
2660                if (enable_ept)
2661                        ept_save_pdptrs(vcpu);
2662                break;
2663        default:
2664                break;
2665        }
2666}
2667
2668static __init int cpu_has_kvm_support(void)
2669{
2670        return cpu_has_vmx();
2671}
2672
2673static __init int vmx_disabled_by_bios(void)
2674{
2675        u64 msr;
2676
2677        rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
2678        if (msr & FEATURE_CONTROL_LOCKED) {
2679                /* launched w/ TXT and VMX disabled */
2680                if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2681                        && tboot_enabled())
2682                        return 1;
2683                /* launched w/o TXT and VMX only enabled w/ TXT */
2684                if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2685                        && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2686                        && !tboot_enabled()) {
2687                        printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
2688                                "activate TXT before enabling KVM\n");
2689                        return 1;
2690                }
2691                /* launched w/o TXT and VMX disabled */
2692                if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2693                        && !tboot_enabled())
2694                        return 1;
2695        }
2696
2697        return 0;
2698}
2699
2700static void kvm_cpu_vmxon(u64 addr)
2701{
2702        asm volatile (ASM_VMX_VMXON_RAX
2703                        : : "a"(&addr), "m"(addr)
2704                        : "memory", "cc");
2705}
2706
2707static int hardware_enable(void *garbage)
2708{
2709        int cpu = raw_smp_processor_id();
2710        u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2711        u64 old, test_bits;
2712
2713        if (read_cr4() & X86_CR4_VMXE)
2714                return -EBUSY;
2715
2716        INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
2717
2718        /*
2719         * Now we can enable the vmclear operation in kdump
2720         * since the loaded_vmcss_on_cpu list on this cpu
2721         * has been initialized.
2722         *
2723         * Though the cpu is not in VMX operation now, there
2724         * is no problem to enable the vmclear operation
2725         * for the loaded_vmcss_on_cpu list is empty!
2726         */
2727        crash_enable_local_vmclear(cpu);
2728
2729        rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
2730
2731        test_bits = FEATURE_CONTROL_LOCKED;
2732        test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
2733        if (tboot_enabled())
2734                test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
2735
2736        if ((old & test_bits) != test_bits) {
2737                /* enable and lock */
2738                wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
2739        }
2740        write_cr4(read_cr4() | X86_CR4_VMXE); /* FIXME: not cpu hotplug safe */
2741
2742        if (vmm_exclusive) {
2743                kvm_cpu_vmxon(phys_addr);
2744                ept_sync_global();
2745        }
2746
2747        native_store_gdt(&__get_cpu_var(host_gdt));
2748
2749        return 0;
2750}
2751
2752static void vmclear_local_loaded_vmcss(void)
2753{
2754        int cpu = raw_smp_processor_id();
2755        struct loaded_vmcs *v, *n;
2756
2757        list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2758                                 loaded_vmcss_on_cpu_link)
2759                __loaded_vmcs_clear(v);
2760}
2761
2762
2763/* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
2764 * tricks.
2765 */
2766static void kvm_cpu_vmxoff(void)
2767{
2768        asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
2769}
2770
2771static void hardware_disable(void *garbage)
2772{
2773        if (vmm_exclusive) {
2774                vmclear_local_loaded_vmcss();
2775                kvm_cpu_vmxoff();
2776        }
2777        write_cr4(read_cr4() & ~X86_CR4_VMXE);
2778}
2779
2780static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2781                                      u32 msr, u32 *result)
2782{
2783        u32 vmx_msr_low, vmx_msr_high;
2784        u32 ctl = ctl_min | ctl_opt;
2785
2786        rdmsr(msr, vmx_msr_low, vmx_msr_high);
2787
2788        ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2789        ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
2790
2791        /* Ensure minimum (required) set of control bits are supported. */
2792        if (ctl_min & ~ctl)
2793                return -EIO;
2794
2795        *result = ctl;
2796        return 0;
2797}
2798
2799static __init bool allow_1_setting(u32 msr, u32 ctl)
2800{
2801        u32 vmx_msr_low, vmx_msr_high;
2802
2803        rdmsr(msr, vmx_msr_low, vmx_msr_high);
2804        return vmx_msr_high & ctl;
2805}
2806
2807static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
2808{
2809        u32 vmx_msr_low, vmx_msr_high;
2810        u32 min, opt, min2, opt2;
2811        u32 _pin_based_exec_control = 0;
2812        u32 _cpu_based_exec_control = 0;
2813        u32 _cpu_based_2nd_exec_control = 0;
2814        u32 _vmexit_control = 0;
2815        u32 _vmentry_control = 0;
2816
2817        min = CPU_BASED_HLT_EXITING |
2818#ifdef CONFIG_X86_64
2819              CPU_BASED_CR8_LOAD_EXITING |
2820              CPU_BASED_CR8_STORE_EXITING |
2821#endif
2822              CPU_BASED_CR3_LOAD_EXITING |
2823              CPU_BASED_CR3_STORE_EXITING |
2824              CPU_BASED_USE_IO_BITMAPS |
2825              CPU_BASED_MOV_DR_EXITING |
2826              CPU_BASED_USE_TSC_OFFSETING |
2827              CPU_BASED_MWAIT_EXITING |
2828              CPU_BASED_MONITOR_EXITING |
2829              CPU_BASED_INVLPG_EXITING |
2830              CPU_BASED_RDPMC_EXITING;
2831
2832        opt = CPU_BASED_TPR_SHADOW |
2833              CPU_BASED_USE_MSR_BITMAPS |
2834              CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2835        if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2836                                &_cpu_based_exec_control) < 0)
2837                return -EIO;
2838#ifdef CONFIG_X86_64
2839        if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2840                _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2841                                           ~CPU_BASED_CR8_STORE_EXITING;
2842#endif
2843        if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2844                min2 = 0;
2845                opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2846                        SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2847                        SECONDARY_EXEC_WBINVD_EXITING |
2848                        SECONDARY_EXEC_ENABLE_VPID |
2849                        SECONDARY_EXEC_ENABLE_EPT |
2850                        SECONDARY_EXEC_UNRESTRICTED_GUEST |
2851                        SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2852                        SECONDARY_EXEC_RDTSCP |
2853                        SECONDARY_EXEC_ENABLE_INVPCID |
2854                        SECONDARY_EXEC_APIC_REGISTER_VIRT |
2855                        SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2856                        SECONDARY_EXEC_SHADOW_VMCS;
2857                if (adjust_vmx_controls(min2, opt2,
2858                                        MSR_IA32_VMX_PROCBASED_CTLS2,
2859                                        &_cpu_based_2nd_exec_control) < 0)
2860                        return -EIO;
2861        }
2862#ifndef CONFIG_X86_64
2863        if (!(_cpu_based_2nd_exec_control &
2864                                SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2865                _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2866#endif
2867
2868        if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2869                _cpu_based_2nd_exec_control &= ~(
2870                                SECONDARY_EXEC_APIC_REGISTER_VIRT |
2871                                SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2872                                SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2873
2874        if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2875                /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2876                   enabled */
2877                _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2878                                             CPU_BASED_CR3_STORE_EXITING |
2879                                             CPU_BASED_INVLPG_EXITING);
2880                rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
2881                      vmx_capability.ept, vmx_capability.vpid);
2882        }
2883
2884        min = VM_EXIT_SAVE_DEBUG_CONTROLS;
2885#ifdef CONFIG_X86_64
2886        min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2887#endif
2888        opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
2889                VM_EXIT_ACK_INTR_ON_EXIT | VM_EXIT_CLEAR_BNDCFGS;
2890        if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2891                                &_vmexit_control) < 0)
2892                return -EIO;
2893
2894        min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2895        opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR;
2896        if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2897                                &_pin_based_exec_control) < 0)
2898                return -EIO;
2899
2900        if (!(_cpu_based_2nd_exec_control &
2901                SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) ||
2902                !(_vmexit_control & VM_EXIT_ACK_INTR_ON_EXIT))
2903                _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2904
2905        min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2906        opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
2907        if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2908                                &_vmentry_control) < 0)
2909                return -EIO;
2910
2911        rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2912
2913        /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2914        if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2915                return -EIO;
2916
2917#ifdef CONFIG_X86_64
2918        /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2919        if (vmx_msr_high & (1u<<16))
2920                return -EIO;
2921#endif
2922
2923        /* Require Write-Back (WB) memory type for VMCS accesses. */
2924        if (((vmx_msr_high >> 18) & 15) != 6)
2925                return -EIO;
2926
2927        vmcs_conf->size = vmx_msr_high & 0x1fff;
2928        vmcs_conf->order = get_order(vmcs_config.size);
2929        vmcs_conf->revision_id = vmx_msr_low;
2930
2931        vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2932        vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2933        vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2934        vmcs_conf->vmexit_ctrl         = _vmexit_control;
2935        vmcs_conf->vmentry_ctrl        = _vmentry_control;
2936
2937        cpu_has_load_ia32_efer =
2938                allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
2939                                VM_ENTRY_LOAD_IA32_EFER)
2940                && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
2941                                   VM_EXIT_LOAD_IA32_EFER);
2942
2943        cpu_has_load_perf_global_ctrl =
2944                allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
2945                                VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
2946                && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
2947                                   VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
2948
2949        /*
2950         * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
2951         * but due to arrata below it can't be used. Workaround is to use
2952         * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2953         *
2954         * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
2955         *
2956         * AAK155             (model 26)
2957         * AAP115             (model 30)
2958         * AAT100             (model 37)
2959         * BC86,AAY89,BD102   (model 44)
2960         * BA97               (model 46)
2961         *
2962         */
2963        if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
2964                switch (boot_cpu_data.x86_model) {
2965                case 26:
2966                case 30:
2967                case 37:
2968                case 44:
2969                case 46:
2970                        cpu_has_load_perf_global_ctrl = false;
2971                        printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2972                                        "does not work properly. Using workaround\n");
2973                        break;
2974                default:
2975                        break;
2976                }
2977        }
2978
2979        return 0;
2980}
2981
2982static struct vmcs *alloc_vmcs_cpu(int cpu)
2983{
2984        int node = cpu_to_node(cpu);
2985        struct page *pages;
2986        struct vmcs *vmcs;
2987
2988        pages = alloc_pages_exact_node(node, GFP_KERNEL, vmcs_config.order);
2989        if (!pages)
2990                return NULL;
2991        vmcs = page_address(pages);
2992        memset(vmcs, 0, vmcs_config.size);
2993        vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
2994        return vmcs;
2995}
2996
2997static struct vmcs *alloc_vmcs(void)
2998{
2999        return alloc_vmcs_cpu(raw_smp_processor_id());
3000}
3001
3002static void free_vmcs(struct vmcs *vmcs)
3003{
3004        free_pages((unsigned long)vmcs, vmcs_config.order);
3005}
3006
3007/*
3008 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
3009 */
3010static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
3011{
3012        if (!loaded_vmcs->vmcs)
3013                return;
3014        loaded_vmcs_clear(loaded_vmcs);
3015        free_vmcs(loaded_vmcs->vmcs);
3016        loaded_vmcs->vmcs = NULL;
3017}
3018
3019static void free_kvm_area(void)
3020{
3021        int cpu;
3022
3023        for_each_possible_cpu(cpu) {
3024                free_vmcs(per_cpu(vmxarea, cpu));
3025                per_cpu(vmxarea, cpu) = NULL;
3026        }
3027}
3028
3029static void init_vmcs_shadow_fields(void)
3030{
3031        int i, j;
3032
3033        /* No checks for read only fields yet */
3034
3035        for (i = j = 0; i < max_shadow_read_write_fields; i++) {
3036                switch (shadow_read_write_fields[i]) {
3037                case GUEST_BNDCFGS:
3038                        if (!vmx_mpx_supported())
3039                                continue;
3040                        break;
3041                default:
3042                        break;
3043                }
3044
3045                if (j < i)
3046                        shadow_read_write_fields[j] =
3047                                shadow_read_write_fields[i];
3048                j++;
3049        }
3050        max_shadow_read_write_fields = j;
3051
3052        /* shadowed fields guest access without vmexit */
3053        for (i = 0; i < max_shadow_read_write_fields; i++) {
3054                clear_bit(shadow_read_write_fields[i],
3055                          vmx_vmwrite_bitmap);
3056                clear_bit(shadow_read_write_fields[i],
3057                          vmx_vmread_bitmap);
3058        }
3059        for (i = 0; i < max_shadow_read_only_fields; i++)
3060                clear_bit(shadow_read_only_fields[i],
3061                          vmx_vmread_bitmap);
3062}
3063
3064static __init int alloc_kvm_area(void)
3065{
3066        int cpu;
3067
3068        for_each_possible_cpu(cpu) {
3069                struct vmcs *vmcs;
3070
3071                vmcs = alloc_vmcs_cpu(cpu);
3072                if (!vmcs) {
3073                        free_kvm_area();
3074                        return -ENOMEM;
3075                }
3076
3077                per_cpu(vmxarea, cpu) = vmcs;
3078        }
3079        return 0;
3080}
3081
3082static __init int hardware_setup(void)
3083{
3084        if (setup_vmcs_config(&vmcs_config) < 0)
3085                return -EIO;
3086
3087        if (boot_cpu_has(X86_FEATURE_NX))
3088                kvm_enable_efer_bits(EFER_NX);
3089
3090        if (!cpu_has_vmx_vpid())
3091                enable_vpid = 0;
3092        if (!cpu_has_vmx_shadow_vmcs())
3093                enable_shadow_vmcs = 0;
3094        if (enable_shadow_vmcs)
3095                init_vmcs_shadow_fields();
3096
3097        if (!cpu_has_vmx_ept() ||
3098            !cpu_has_vmx_ept_4levels()) {
3099                enable_ept = 0;
3100                enable_unrestricted_guest = 0;
3101                enable_ept_ad_bits = 0;
3102        }
3103
3104        if (!cpu_has_vmx_ept_ad_bits())
3105                enable_ept_ad_bits = 0;
3106
3107        if (!cpu_has_vmx_unrestricted_guest())
3108                enable_unrestricted_guest = 0;
3109
3110        if (!cpu_has_vmx_flexpriority())
3111                flexpriority_enabled = 0;
3112
3113        if (!cpu_has_vmx_tpr_shadow())
3114                kvm_x86_ops->update_cr8_intercept = NULL;
3115
3116        if (enable_ept && !cpu_has_vmx_ept_2m_page())
3117                kvm_disable_largepages();
3118
3119        if (!cpu_has_vmx_ple())
3120                ple_gap = 0;
3121
3122        if (!cpu_has_vmx_apicv())
3123                enable_apicv = 0;
3124
3125        if (enable_apicv)
3126                kvm_x86_ops->update_cr8_intercept = NULL;
3127        else {
3128                kvm_x86_ops->hwapic_irr_update = NULL;
3129                kvm_x86_ops->deliver_posted_interrupt = NULL;
3130                kvm_x86_ops->sync_pir_to_irr = vmx_sync_pir_to_irr_dummy;
3131        }
3132
3133        if (nested)
3134                nested_vmx_setup_ctls_msrs();
3135
3136        return alloc_kvm_area();
3137}
3138
3139static __exit void hardware_unsetup(void)
3140{
3141        free_kvm_area();
3142}
3143
3144static bool emulation_required(struct kvm_vcpu *vcpu)
3145{
3146        return emulate_invalid_guest_state && !guest_state_valid(vcpu);
3147}
3148
3149static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
3150                struct kvm_segment *save)
3151{
3152        if (!emulate_invalid_guest_state) {
3153                /*
3154                 * CS and SS RPL should be equal during guest entry according
3155                 * to VMX spec, but in reality it is not always so. Since vcpu
3156                 * is in the middle of the transition from real mode to
3157                 * protected mode it is safe to assume that RPL 0 is a good
3158                 * default value.
3159                 */
3160                if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
3161                        save->selector &= ~SELECTOR_RPL_MASK;
3162                save->dpl = save->selector & SELECTOR_RPL_MASK;
3163                save->s = 1;
3164        }
3165        vmx_set_segment(vcpu, save, seg);
3166}
3167
3168static void enter_pmode(struct kvm_vcpu *vcpu)
3169{
3170        unsigned long flags;
3171        struct vcpu_vmx *vmx = to_vmx(vcpu);
3172
3173        /*
3174         * Update real mode segment cache. It may be not up-to-date if sement
3175         * register was written while vcpu was in a guest mode.
3176         */
3177        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3178        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3179        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3180        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3181        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3182        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3183
3184        vmx->rmode.vm86_active = 0;
3185
3186        vmx_segment_cache_clear(vmx);
3187
3188        vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3189
3190        flags = vmcs_readl(GUEST_RFLAGS);
3191        flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
3192        flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
3193        vmcs_writel(GUEST_RFLAGS, flags);
3194
3195        vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
3196                        (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
3197
3198        update_exception_bitmap(vcpu);
3199
3200        fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3201        fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3202        fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3203        fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3204        fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3205        fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3206}
3207
3208static void fix_rmode_seg(int seg, struct kvm_segment *save)
3209{
3210        const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3211        struct kvm_segment var = *save;
3212
3213        var.dpl = 0x3;
3214        if (seg == VCPU_SREG_CS)
3215                var.type = 0x3;
3216
3217        if (!emulate_invalid_guest_state) {
3218                var.selector = var.base >> 4;
3219                var.base = var.base & 0xffff0;
3220                var.limit = 0xffff;
3221                var.g = 0;
3222                var.db = 0;
3223                var.present = 1;
3224                var.s = 1;
3225                var.l = 0;
3226                var.unusable = 0;
3227                var.type = 0x3;
3228                var.avl = 0;
3229                if (save->base & 0xf)
3230                        printk_once(KERN_WARNING "kvm: segment base is not "
3231                                        "paragraph aligned when entering "
3232                                        "protected mode (seg=%d)", seg);
3233        }
3234
3235        vmcs_write16(sf->selector, var.selector);
3236        vmcs_write32(sf->base, var.base);
3237        vmcs_write32(sf->limit, var.limit);
3238        vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
3239}
3240
3241static void enter_rmode(struct kvm_vcpu *vcpu)
3242{
3243        unsigned long flags;
3244        struct vcpu_vmx *vmx = to_vmx(vcpu);
3245
3246        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3247        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3248        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3249        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3250        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3251        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3252        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3253
3254        vmx->rmode.vm86_active = 1;
3255
3256        /*
3257         * Very old userspace does not call KVM_SET_TSS_ADDR before entering
3258         * vcpu. Warn the user that an update is overdue.
3259         */
3260        if (!vcpu->kvm->arch.tss_addr)
3261                printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
3262                             "called before entering vcpu\n");
3263
3264        vmx_segment_cache_clear(vmx);
3265
3266        vmcs_writel(GUEST_TR_BASE, vcpu->kvm->arch.tss_addr);
3267        vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
3268        vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
3269
3270        flags = vmcs_readl(GUEST_RFLAGS);
3271        vmx->rmode.save_rflags = flags;
3272
3273        flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
3274
3275        vmcs_writel(GUEST_RFLAGS, flags);
3276        vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
3277        update_exception_bitmap(vcpu);
3278
3279        fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3280        fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3281        fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3282        fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3283        fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3284        fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3285
3286        kvm_mmu_reset_context(vcpu);
3287}
3288
3289static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
3290{
3291        struct vcpu_vmx *vmx = to_vmx(vcpu);
3292        struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
3293
3294        if (!msr)
3295                return;
3296
3297        /*
3298         * Force kernel_gs_base reloading before EFER changes, as control
3299         * of this msr depends on is_long_mode().
3300         */
3301        vmx_load_host_state(to_vmx(vcpu));
3302        vcpu->arch.efer = efer;
3303        if (efer & EFER_LMA) {
3304                vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
3305                msr->data = efer;
3306        } else {
3307                vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
3308
3309                msr->data = efer & ~EFER_LME;
3310        }
3311        setup_msrs(vmx);
3312}
3313
3314#ifdef CONFIG_X86_64
3315
3316static void enter_lmode(struct kvm_vcpu *vcpu)
3317{
3318        u32 guest_tr_ar;
3319
3320        vmx_segment_cache_clear(to_vmx(vcpu));
3321
3322        guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
3323        if ((guest_tr_ar & AR_TYPE_MASK) != AR_TYPE_BUSY_64_TSS) {
3324                pr_debug_ratelimited("%s: tss fixup for long mode. \n",
3325                                     __func__);
3326                vmcs_write32(GUEST_TR_AR_BYTES,
3327                             (guest_tr_ar & ~AR_TYPE_MASK)
3328                             | AR_TYPE_BUSY_64_TSS);
3329        }
3330        vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
3331}
3332
3333static void exit_lmode(struct kvm_vcpu *vcpu)
3334{
3335        vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
3336        vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
3337}
3338
3339#endif
3340
3341static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
3342{
3343        vpid_sync_context(to_vmx(vcpu));
3344        if (enable_ept) {
3345                if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3346                        return;
3347                ept_sync_context(construct_eptp(vcpu->arch.mmu.root_hpa));
3348        }
3349}
3350
3351static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
3352{
3353        ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
3354
3355        vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
3356        vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
3357}
3358
3359static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
3360{
3361        if (enable_ept && is_paging(vcpu))
3362                vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
3363        __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
3364}
3365
3366static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
3367{
3368        ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
3369
3370        vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
3371        vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
3372}
3373
3374static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
3375{
3376        struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3377
3378        if (!test_bit(VCPU_EXREG_PDPTR,
3379                      (unsigned long *)&vcpu->arch.regs_dirty))
3380                return;
3381
3382        if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
3383                vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
3384                vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
3385                vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
3386                vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
3387        }
3388}
3389
3390static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
3391{
3392        struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3393
3394        if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
3395                mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
3396                mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
3397                mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
3398                mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
3399        }
3400
3401        __set_bit(VCPU_EXREG_PDPTR,
3402                  (unsigned long *)&vcpu->arch.regs_avail);
3403        __set_bit(VCPU_EXREG_PDPTR,
3404                  (unsigned long *)&vcpu->arch.regs_dirty);
3405}
3406
3407static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
3408
3409static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
3410                                        unsigned long cr0,
3411                                        struct kvm_vcpu *vcpu)
3412{
3413        if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
3414                vmx_decache_cr3(vcpu);
3415        if (!(cr0 & X86_CR0_PG)) {
3416                /* From paging/starting to nonpaging */
3417                vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
3418                             vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
3419                             (CPU_BASED_CR3_LOAD_EXITING |
3420                              CPU_BASED_CR3_STORE_EXITING));
3421                vcpu->arch.cr0 = cr0;
3422                vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3423        } else if (!is_paging(vcpu)) {
3424                /* From nonpaging to paging */
3425                vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
3426                             vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
3427                             ~(CPU_BASED_CR3_LOAD_EXITING |
3428                               CPU_BASED_CR3_STORE_EXITING));
3429                vcpu->arch.cr0 = cr0;
3430                vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3431        }
3432
3433        if (!(cr0 & X86_CR0_WP))
3434                *hw_cr0 &= ~X86_CR0_WP;
3435}
3436
3437static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3438{
3439        struct vcpu_vmx *vmx = to_vmx(vcpu);
3440        unsigned long hw_cr0;
3441
3442        hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
3443        if (enable_unrestricted_guest)
3444                hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3445        else {
3446                hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3447
3448                if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3449                        enter_pmode(vcpu);
3450
3451                if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3452                        enter_rmode(vcpu);
3453        }
3454
3455#ifdef CONFIG_X86_64
3456        if (vcpu->arch.efer & EFER_LME) {
3457                if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
3458                        enter_lmode(vcpu);
3459                if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
3460                        exit_lmode(vcpu);
3461        }
3462#endif
3463
3464        if (enable_ept)
3465                ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
3466
3467        if (!vcpu->fpu_active)
3468                hw_cr0 |= X86_CR0_TS | X86_CR0_MP;
3469
3470        vmcs_writel(CR0_READ_SHADOW, cr0);
3471        vmcs_writel(GUEST_CR0, hw_cr0);
3472        vcpu->arch.cr0 = cr0;
3473
3474        /* depends on vcpu->arch.cr0 to be set to a new value */
3475        vmx->emulation_required = emulation_required(vcpu);
3476}
3477
3478static u64 construct_eptp(unsigned long root_hpa)
3479{
3480        u64 eptp;
3481
3482        /* TODO write the value reading from MSR */
3483        eptp = VMX_EPT_DEFAULT_MT |
3484                VMX_EPT_DEFAULT_GAW << VMX_EPT_GAW_EPTP_SHIFT;
3485        if (enable_ept_ad_bits)
3486                eptp |= VMX_EPT_AD_ENABLE_BIT;
3487        eptp |= (root_hpa & PAGE_MASK);
3488
3489        return eptp;
3490}
3491
3492static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
3493{
3494        unsigned long guest_cr3;
3495        u64 eptp;
3496
3497        guest_cr3 = cr3;
3498        if (enable_ept) {
3499                eptp = construct_eptp(cr3);
3500                vmcs_write64(EPT_POINTER, eptp);
3501                if (is_paging(vcpu) || is_guest_mode(vcpu))
3502                        guest_cr3 = kvm_read_cr3(vcpu);
3503                else
3504                        guest_cr3 = vcpu->kvm->arch.ept_identity_map_addr;
3505                ept_load_pdptrs(vcpu);
3506        }
3507
3508        vmx_flush_tlb(vcpu);
3509        vmcs_writel(GUEST_CR3, guest_cr3);
3510}
3511
3512static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3513{
3514        unsigned long hw_cr4 = cr4 | (to_vmx(vcpu)->rmode.vm86_active ?
3515                    KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
3516
3517        if (cr4 & X86_CR4_VMXE) {
3518                /*
3519                 * To use VMXON (and later other VMX instructions), a guest
3520                 * must first be able to turn on cr4.VMXE (see handle_vmon()).
3521                 * So basically the check on whether to allow nested VMX
3522                 * is here.
3523                 */
3524                if (!nested_vmx_allowed(vcpu))
3525                        return 1;
3526        }
3527        if (to_vmx(vcpu)->nested.vmxon &&
3528            ((cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON))
3529                return 1;
3530
3531        vcpu->arch.cr4 = cr4;
3532        if (enable_ept) {
3533                if (!is_paging(vcpu)) {
3534                        hw_cr4 &= ~X86_CR4_PAE;
3535                        hw_cr4 |= X86_CR4_PSE;
3536                        /*
3537                         * SMEP/SMAP is disabled if CPU is in non-paging mode
3538                         * in hardware. However KVM always uses paging mode to
3539                         * emulate guest non-paging mode with TDP.
3540                         * To emulate this behavior, SMEP/SMAP needs to be
3541                         * manually disabled when guest switches to non-paging
3542                         * mode.
3543                         */
3544                        hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP);
3545                } else if (!(cr4 & X86_CR4_PAE)) {
3546                        hw_cr4 &= ~X86_CR4_PAE;
3547                }
3548        }
3549
3550        vmcs_writel(CR4_READ_SHADOW, cr4);
3551        vmcs_writel(GUEST_CR4, hw_cr4);
3552        return 0;
3553}
3554
3555static void vmx_get_segment(struct kvm_vcpu *vcpu,
3556                            struct kvm_segment *var, int seg)
3557{
3558        struct vcpu_vmx *vmx = to_vmx(vcpu);
3559        u32 ar;
3560
3561        if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3562                *var = vmx->rmode.segs[seg];
3563                if (seg == VCPU_SREG_TR
3564                    || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3565                        return;
3566                var->base = vmx_read_guest_seg_base(vmx, seg);
3567                var->selector = vmx_read_guest_seg_selector(vmx, seg);
3568                return;
3569        }
3570        var->base = vmx_read_guest_seg_base(vmx, seg);
3571        var->limit = vmx_read_guest_seg_limit(vmx, seg);
3572        var->selector = vmx_read_guest_seg_selector(vmx, seg);
3573        ar = vmx_read_guest_seg_ar(vmx, seg);
3574        var->unusable = (ar >> 16) & 1;
3575        var->type = ar & 15;
3576        var->s = (ar >> 4) & 1;
3577        var->dpl = (ar >> 5) & 3;
3578        /*
3579         * Some userspaces do not preserve unusable property. Since usable
3580         * segment has to be present according to VMX spec we can use present
3581         * property to amend userspace bug by making unusable segment always
3582         * nonpresent. vmx_segment_access_rights() already marks nonpresent
3583         * segment as unusable.
3584         */
3585        var->present = !var->unusable;
3586        var->avl = (ar >> 12) & 1;
3587        var->l = (ar >> 13) & 1;
3588        var->db = (ar >> 14) & 1;
3589        var->g = (ar >> 15) & 1;
3590}
3591
3592static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3593{
3594        struct kvm_segment s;
3595
3596        if (to_vmx(vcpu)->rmode.vm86_active) {
3597                vmx_get_segment(vcpu, &s, seg);
3598                return s.base;
3599        }
3600        return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3601}
3602
3603static int vmx_get_cpl(struct kvm_vcpu *vcpu)
3604{
3605        struct vcpu_vmx *vmx = to_vmx(vcpu);
3606
3607        if (unlikely(vmx->rmode.vm86_active))
3608                return 0;
3609        else {
3610                int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3611                return AR_DPL(ar);
3612        }
3613}
3614
3615static u32 vmx_segment_access_rights(struct kvm_segment *var)
3616{
3617        u32 ar;
3618
3619        if (var->unusable || !var->present)
3620                ar = 1 << 16;
3621        else {
3622                ar = var->type & 15;
3623                ar |= (var->s & 1) << 4;
3624                ar |= (var->dpl & 3) << 5;
3625                ar |= (var->present & 1) << 7;
3626                ar |= (var->avl & 1) << 12;
3627                ar |= (var->l & 1) << 13;
3628                ar |= (var->db & 1) << 14;
3629                ar |= (var->g & 1) << 15;
3630        }
3631
3632        return ar;
3633}
3634
3635static void vmx_set_segment(struct kvm_vcpu *vcpu,
3636                            struct kvm_segment *var, int seg)
3637{
3638        struct vcpu_vmx *vmx = to_vmx(vcpu);
3639        const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3640
3641        vmx_segment_cache_clear(vmx);
3642
3643        if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3644                vmx->rmode.segs[seg] = *var;
3645                if (seg == VCPU_SREG_TR)
3646                        vmcs_write16(sf->selector, var->selector);
3647                else if (var->s)
3648                        fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3649                goto out;
3650        }
3651
3652        vmcs_writel(sf->base, var->base);
3653        vmcs_write32(sf->limit, var->limit);
3654        vmcs_write16(sf->selector, var->selector);
3655
3656        /*
3657         *   Fix the "Accessed" bit in AR field of segment registers for older
3658         * qemu binaries.
3659         *   IA32 arch specifies that at the time of processor reset the
3660         * "Accessed" bit in the AR field of segment registers is 1. And qemu
3661         * is setting it to 0 in the userland code. This causes invalid guest
3662         * state vmexit when "unrestricted guest" mode is turned on.
3663         *    Fix for this setup issue in cpu_reset is being pushed in the qemu
3664         * tree. Newer qemu binaries with that qemu fix would not need this
3665         * kvm hack.
3666         */
3667        if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
3668                var->type |= 0x1; /* Accessed */
3669
3670        vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3671
3672out:
3673        vmx->emulation_required = emulation_required(vcpu);
3674}
3675
3676static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3677{
3678        u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3679
3680        *db = (ar >> 14) & 1;
3681        *l = (ar >> 13) & 1;
3682}
3683
3684static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3685{
3686        dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3687        dt->address = vmcs_readl(GUEST_IDTR_BASE);
3688}
3689
3690static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3691{
3692        vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3693        vmcs_writel(GUEST_IDTR_BASE, dt->address);
3694}
3695
3696static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3697{
3698        dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3699        dt->address = vmcs_readl(GUEST_GDTR_BASE);
3700}
3701
3702static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3703{
3704        vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3705        vmcs_writel(GUEST_GDTR_BASE, dt->address);
3706}
3707
3708static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3709{
3710        struct kvm_segment var;
3711        u32 ar;
3712
3713        vmx_get_segment(vcpu, &var, seg);
3714        var.dpl = 0x3;
3715        if (seg == VCPU_SREG_CS)
3716                var.type = 0x3;
3717        ar = vmx_segment_access_rights(&var);
3718
3719        if (var.base != (var.selector << 4))
3720                return false;
3721        if (var.limit != 0xffff)
3722                return false;
3723        if (ar != 0xf3)
3724                return false;
3725
3726        return true;
3727}
3728
3729static bool code_segment_valid(struct kvm_vcpu *vcpu)
3730{
3731        struct kvm_segment cs;
3732        unsigned int cs_rpl;
3733
3734        vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3735        cs_rpl = cs.selector & SELECTOR_RPL_MASK;
3736
3737        if (cs.unusable)
3738                return false;
3739        if (~cs.type & (AR_TYPE_CODE_MASK|AR_TYPE_ACCESSES_MASK))
3740                return false;
3741        if (!cs.s)
3742                return false;
3743        if (cs.type & AR_TYPE_WRITEABLE_MASK) {
3744                if (cs.dpl > cs_rpl)
3745                        return false;
3746        } else {
3747                if (cs.dpl != cs_rpl)
3748                        return false;
3749        }
3750        if (!cs.present)
3751                return false;
3752
3753        /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3754        return true;
3755}
3756
3757static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3758{
3759        struct kvm_segment ss;
3760        unsigned int ss_rpl;
3761
3762        vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3763        ss_rpl = ss.selector & SELECTOR_RPL_MASK;
3764
3765        if (ss.unusable)
3766                return true;
3767        if (ss.type != 3 && ss.type != 7)
3768                return false;
3769        if (!ss.s)
3770                return false;
3771        if (ss.dpl != ss_rpl) /* DPL != RPL */
3772                return false;
3773        if (!ss.present)
3774                return false;
3775
3776        return true;
3777}
3778
3779static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3780{
3781        struct kvm_segment var;
3782        unsigned int rpl;
3783
3784        vmx_get_segment(vcpu, &var, seg);
3785        rpl = var.selector & SELECTOR_RPL_MASK;
3786
3787        if (var.unusable)
3788                return true;
3789        if (!var.s)
3790                return false;
3791        if (!var.present)
3792                return false;
3793        if (~var.type & (AR_TYPE_CODE_MASK|AR_TYPE_WRITEABLE_MASK)) {
3794                if (var.dpl < rpl) /* DPL < RPL */
3795                        return false;
3796        }
3797
3798        /* TODO: Add other members to kvm_segment_field to allow checking for other access
3799         * rights flags
3800         */
3801        return true;
3802}
3803
3804static bool tr_valid(struct kvm_vcpu *vcpu)
3805{
3806        struct kvm_segment tr;
3807
3808        vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3809
3810        if (tr.unusable)
3811                return false;
3812        if (tr.selector & SELECTOR_TI_MASK)     /* TI = 1 */
3813                return false;
3814        if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3815                return false;
3816        if (!tr.present)
3817                return false;
3818
3819        return true;
3820}
3821
3822static bool ldtr_valid(struct kvm_vcpu *vcpu)
3823{
3824        struct kvm_segment ldtr;
3825
3826        vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3827
3828        if (ldtr.unusable)
3829                return true;
3830        if (ldtr.selector & SELECTOR_TI_MASK)   /* TI = 1 */
3831                return false;
3832        if (ldtr.type != 2)
3833                return false;
3834        if (!ldtr.present)
3835                return false;
3836
3837        return true;
3838}
3839
3840static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3841{
3842        struct kvm_segment cs, ss;
3843
3844        vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3845        vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3846
3847        return ((cs.selector & SELECTOR_RPL_MASK) ==
3848                 (ss.selector & SELECTOR_RPL_MASK));
3849}
3850
3851/*
3852 * Check if guest state is valid. Returns true if valid, false if
3853 * not.
3854 * We assume that registers are always usable
3855 */
3856static bool guest_state_valid(struct kvm_vcpu *vcpu)
3857{
3858        if (enable_unrestricted_guest)
3859                return true;
3860
3861        /* real mode guest state checks */
3862        if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3863                if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3864                        return false;
3865                if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3866                        return false;
3867                if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3868                        return false;
3869                if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3870                        return false;
3871                if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3872                        return false;
3873                if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3874                        return false;
3875        } else {
3876        /* protected mode guest state checks */
3877                if (!cs_ss_rpl_check(vcpu))
3878                        return false;
3879                if (!code_segment_valid(vcpu))
3880                        return false;
3881                if (!stack_segment_valid(vcpu))
3882                        return false;
3883                if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3884                        return false;
3885                if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3886                        return false;
3887                if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3888                        return false;
3889                if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3890                        return false;
3891                if (!tr_valid(vcpu))
3892                        return false;
3893                if (!ldtr_valid(vcpu))
3894                        return false;
3895        }
3896        /* TODO:
3897         * - Add checks on RIP
3898         * - Add checks on RFLAGS
3899         */
3900
3901        return true;
3902}
3903
3904static int init_rmode_tss(struct kvm *kvm)
3905{
3906        gfn_t fn;
3907        u16 data = 0;
3908        int r, idx, ret = 0;
3909
3910        idx = srcu_read_lock(&kvm->srcu);
3911        fn = kvm->arch.tss_addr >> PAGE_SHIFT;
3912        r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3913        if (r < 0)
3914                goto out;
3915        data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3916        r = kvm_write_guest_page(kvm, fn++, &data,
3917                        TSS_IOPB_BASE_OFFSET, sizeof(u16));
3918        if (r < 0)
3919                goto out;
3920        r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
3921        if (r < 0)
3922                goto out;
3923        r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3924        if (r < 0)
3925                goto out;
3926        data = ~0;
3927        r = kvm_write_guest_page(kvm, fn, &data,
3928                                 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
3929                                 sizeof(u8));
3930        if (r < 0)
3931                goto out;
3932
3933        ret = 1;
3934out:
3935        srcu_read_unlock(&kvm->srcu, idx);
3936        return ret;
3937}
3938
3939static int init_rmode_identity_map(struct kvm *kvm)
3940{
3941        int i, idx, r, ret;
3942        pfn_t identity_map_pfn;
3943        u32 tmp;
3944
3945        if (!enable_ept)
3946                return 1;
3947        if (unlikely(!kvm->arch.ept_identity_pagetable)) {
3948                printk(KERN_ERR "EPT: identity-mapping pagetable "
3949                        "haven't been allocated!\n");
3950                return 0;
3951        }
3952        if (likely(kvm->arch.ept_identity_pagetable_done))
3953                return 1;
3954        ret = 0;
3955        identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
3956        idx = srcu_read_lock(&kvm->srcu);
3957        r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
3958        if (r < 0)
3959                goto out;
3960        /* Set up identity-mapping pagetable for EPT in real mode */
3961        for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3962                tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3963                        _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3964                r = kvm_write_guest_page(kvm, identity_map_pfn,
3965                                &tmp, i * sizeof(tmp), sizeof(tmp));
3966                if (r < 0)
3967                        goto out;
3968        }
3969        kvm->arch.ept_identity_pagetable_done = true;
3970        ret = 1;
3971out:
3972        srcu_read_unlock(&kvm->srcu, idx);
3973        return ret;
3974}
3975
3976static void seg_setup(int seg)
3977{
3978        const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3979        unsigned int ar;
3980
3981        vmcs_write16(sf->selector, 0);
3982        vmcs_writel(sf->base, 0);
3983        vmcs_write32(sf->limit, 0xffff);
3984        ar = 0x93;
3985        if (seg == VCPU_SREG_CS)
3986                ar |= 0x08; /* code segment */
3987
3988        vmcs_write32(sf->ar_bytes, ar);
3989}
3990
3991static int alloc_apic_access_page(struct kvm *kvm)
3992{
3993        struct page *page;
3994        struct kvm_userspace_memory_region kvm_userspace_mem;
3995        int r = 0;
3996
3997        mutex_lock(&kvm->slots_lock);
3998        if (kvm->arch.apic_access_page)
3999                goto out;
4000        kvm_userspace_mem.slot = APIC_ACCESS_PAGE_PRIVATE_MEMSLOT;
4001        kvm_userspace_mem.flags = 0;
4002        kvm_userspace_mem.guest_phys_addr = 0xfee00000ULL;
4003        kvm_userspace_mem.memory_size = PAGE_SIZE;
4004        r = __kvm_set_memory_region(kvm, &kvm_userspace_mem);
4005        if (r)
4006                goto out;
4007
4008        page = gfn_to_page(kvm, 0xfee00);
4009        if (is_error_page(page)) {
4010                r = -EFAULT;
4011                goto out;
4012        }
4013
4014        kvm->arch.apic_access_page = page;
4015out:
4016        mutex_unlock(&kvm->slots_lock);
4017        return r;
4018}
4019
4020static int alloc_identity_pagetable(struct kvm *kvm)
4021{
4022        struct page *page;
4023        struct kvm_userspace_memory_region kvm_userspace_mem;
4024        int r = 0;
4025
4026        mutex_lock(&kvm->slots_lock);
4027        if (kvm->arch.ept_identity_pagetable)
4028                goto out;
4029        kvm_userspace_mem.slot = IDENTITY_PAGETABLE_PRIVATE_MEMSLOT;
4030        kvm_userspace_mem.flags = 0;
4031        kvm_userspace_mem.guest_phys_addr =
4032                kvm->arch.ept_identity_map_addr;
4033        kvm_userspace_mem.memory_size = PAGE_SIZE;
4034        r = __kvm_set_memory_region(kvm, &kvm_userspace_mem);
4035        if (r)
4036                goto out;
4037
4038        page = gfn_to_page(kvm, kvm->arch.ept_identity_map_addr >> PAGE_SHIFT);
4039        if (is_error_page(page)) {
4040                r = -EFAULT;
4041                goto out;
4042        }
4043
4044        kvm->arch.ept_identity_pagetable = page;
4045out:
4046        mutex_unlock(&kvm->slots_lock);
4047        return r;
4048}
4049
4050static void allocate_vpid(struct vcpu_vmx *vmx)
4051{
4052        int vpid;
4053
4054        vmx->vpid = 0;
4055        if (!enable_vpid)
4056                return;
4057        spin_lock(&vmx_vpid_lock);
4058        vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
4059        if (vpid < VMX_NR_VPIDS) {
4060                vmx->vpid = vpid;
4061                __set_bit(vpid, vmx_vpid_bitmap);
4062        }
4063        spin_unlock(&vmx_vpid_lock);
4064}
4065
4066static void free_vpid(struct vcpu_vmx *vmx)
4067{
4068        if (!enable_vpid)
4069                return;
4070        spin_lock(&vmx_vpid_lock);
4071        if (vmx->vpid != 0)
4072                __clear_bit(vmx->vpid, vmx_vpid_bitmap);
4073        spin_unlock(&vmx_vpid_lock);
4074}
4075
4076#define MSR_TYPE_R      1
4077#define MSR_TYPE_W      2
4078static void __vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
4079                                                u32 msr, int type)
4080{
4081        int f = sizeof(unsigned long);
4082
4083        if (!cpu_has_vmx_msr_bitmap())
4084                return;
4085
4086        /*
4087         * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4088         * have the write-low and read-high bitmap offsets the wrong way round.
4089         * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4090         */
4091        if (msr <= 0x1fff) {
4092                if (type & MSR_TYPE_R)
4093                        /* read-low */
4094                        __clear_bit(msr, msr_bitmap + 0x000 / f);
4095
4096                if (type & MSR_TYPE_W)
4097                        /* write-low */
4098                        __clear_bit(msr, msr_bitmap + 0x800 / f);
4099
4100        } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4101                msr &= 0x1fff;
4102                if (type & MSR_TYPE_R)
4103                        /* read-high */
4104                        __clear_bit(msr, msr_bitmap + 0x400 / f);
4105
4106                if (type & MSR_TYPE_W)
4107                        /* write-high */
4108                        __clear_bit(msr, msr_bitmap + 0xc00 / f);
4109
4110        }
4111}
4112
4113static void __vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
4114                                                u32 msr, int type)
4115{
4116        int f = sizeof(unsigned long);
4117
4118        if (!cpu_has_vmx_msr_bitmap())
4119                return;
4120
4121        /*
4122         * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4123         * have the write-low and read-high bitmap offsets the wrong way round.
4124         * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4125         */
4126        if (msr <= 0x1fff) {
4127                if (type & MSR_TYPE_R)
4128                        /* read-low */
4129                        __set_bit(msr, msr_bitmap + 0x000 / f);
4130
4131                if (type & MSR_TYPE_W)
4132                        /* write-low */
4133                        __set_bit(msr, msr_bitmap + 0x800 / f);
4134
4135        } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4136                msr &= 0x1fff;
4137                if (type & MSR_TYPE_R)
4138                        /* read-high */
4139                        __set_bit(msr, msr_bitmap + 0x400 / f);
4140
4141                if (type & MSR_TYPE_W)
4142                        /* write-high */
4143                        __set_bit(msr, msr_bitmap + 0xc00 / f);
4144
4145        }
4146}
4147
4148static void vmx_disable_intercept_for_msr(u32 msr, bool longmode_only)
4149{
4150        if (!longmode_only)
4151                __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy,
4152                                                msr, MSR_TYPE_R | MSR_TYPE_W);
4153        __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode,
4154                                                msr, MSR_TYPE_R | MSR_TYPE_W);
4155}
4156
4157static void vmx_enable_intercept_msr_read_x2apic(u32 msr)
4158{
4159        __vmx_enable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
4160                        msr, MSR_TYPE_R);
4161        __vmx_enable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
4162                        msr, MSR_TYPE_R);
4163}
4164
4165static void vmx_disable_intercept_msr_read_x2apic(u32 msr)
4166{
4167        __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
4168                        msr, MSR_TYPE_R);
4169        __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
4170                        msr, MSR_TYPE_R);
4171}
4172
4173static void vmx_disable_intercept_msr_write_x2apic(u32 msr)
4174{
4175        __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
4176                        msr, MSR_TYPE_W);
4177        __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
4178                        msr, MSR_TYPE_W);
4179}
4180
4181static int vmx_vm_has_apicv(struct kvm *kvm)
4182{
4183        return enable_apicv && irqchip_in_kernel(kvm);
4184}
4185
4186/*
4187 * Send interrupt to vcpu via posted interrupt way.
4188 * 1. If target vcpu is running(non-root mode), send posted interrupt
4189 * notification to vcpu and hardware will sync PIR to vIRR atomically.
4190 * 2. If target vcpu isn't running(root mode), kick it to pick up the
4191 * interrupt from PIR in next vmentry.
4192 */
4193static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
4194{
4195        struct vcpu_vmx *vmx = to_vmx(vcpu);
4196        int r;
4197
4198        if (pi_test_and_set_pir(vector, &vmx->pi_desc))
4199                return;
4200
4201        r = pi_test_and_set_on(&vmx->pi_desc);
4202        kvm_make_request(KVM_REQ_EVENT, vcpu);
4203#ifdef CONFIG_SMP
4204        if (!r && (vcpu->mode == IN_GUEST_MODE))
4205                apic->send_IPI_mask(get_cpu_mask(vcpu->cpu),
4206                                POSTED_INTR_VECTOR);
4207        else
4208#endif
4209                kvm_vcpu_kick(vcpu);
4210}
4211
4212static void vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
4213{
4214        struct vcpu_vmx *vmx = to_vmx(vcpu);
4215
4216        if (!pi_test_and_clear_on(&vmx->pi_desc))
4217                return;
4218
4219        kvm_apic_update_irr(vcpu, vmx->pi_desc.pir);
4220}
4221
4222static void vmx_sync_pir_to_irr_dummy(struct kvm_vcpu *vcpu)
4223{
4224        return;
4225}
4226
4227/*
4228 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4229 * will not change in the lifetime of the guest.
4230 * Note that host-state that does change is set elsewhere. E.g., host-state
4231 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4232 */
4233static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
4234{
4235        u32 low32, high32;
4236        unsigned long tmpl;
4237        struct desc_ptr dt;
4238
4239        vmcs_writel(HOST_CR0, read_cr0() & ~X86_CR0_TS);  /* 22.2.3 */
4240        vmcs_writel(HOST_CR4, read_cr4());  /* 22.2.3, 22.2.5 */
4241        vmcs_writel(HOST_CR3, read_cr3());  /* 22.2.3  FIXME: shadow tables */
4242
4243        vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
4244#ifdef CONFIG_X86_64
4245        /*
4246         * Load null selectors, so we can avoid reloading them in
4247         * __vmx_load_host_state(), in case userspace uses the null selectors
4248         * too (the expected case).
4249         */
4250        vmcs_write16(HOST_DS_SELECTOR, 0);
4251        vmcs_write16(HOST_ES_SELECTOR, 0);
4252#else
4253        vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
4254        vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
4255#endif
4256        vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
4257        vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
4258
4259        native_store_idt(&dt);
4260        vmcs_writel(HOST_IDTR_BASE, dt.address);   /* 22.2.4 */
4261        vmx->host_idt_base = dt.address;
4262
4263        vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
4264
4265        rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4266        vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4267        rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4268        vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
4269
4270        if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4271                rdmsr(MSR_IA32_CR_PAT, low32, high32);
4272                vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4273        }
4274}
4275
4276static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4277{
4278        vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
4279        if (enable_ept)
4280                vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
4281        if (is_guest_mode(&vmx->vcpu))
4282                vmx->vcpu.arch.cr4_guest_owned_bits &=
4283                        ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
4284        vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
4285}
4286
4287static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4288{
4289        u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4290
4291        if (!vmx_vm_has_apicv(vmx->vcpu.kvm))
4292                pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4293        return pin_based_exec_ctrl;
4294}
4295
4296static u32 vmx_exec_control(struct vcpu_vmx *vmx)
4297{
4298        u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4299
4300        if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4301                exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4302
4303        if (!vm_need_tpr_shadow(vmx->vcpu.kvm)) {
4304                exec_control &= ~CPU_BASED_TPR_SHADOW;
4305#ifdef CONFIG_X86_64
4306                exec_control |= CPU_BASED_CR8_STORE_EXITING |
4307                                CPU_BASED_CR8_LOAD_EXITING;
4308#endif
4309        }
4310        if (!enable_ept)
4311                exec_control |= CPU_BASED_CR3_STORE_EXITING |
4312                                CPU_BASED_CR3_LOAD_EXITING  |
4313                                CPU_BASED_INVLPG_EXITING;
4314        return exec_control;
4315}
4316
4317static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
4318{
4319        u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4320        if (!vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
4321                exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4322        if (vmx->vpid == 0)
4323                exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4324        if (!enable_ept) {
4325                exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4326                enable_unrestricted_guest = 0;
4327                /* Enable INVPCID for non-ept guests may cause performance regression. */
4328                exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
4329        }
4330        if (!enable_unrestricted_guest)
4331                exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4332        if (!ple_gap)
4333                exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4334        if (!vmx_vm_has_apicv(vmx->vcpu.kvm))
4335                exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4336                                  SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4337        exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4338        /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4339           (handle_vmptrld).
4340           We can NOT enable shadow_vmcs here because we don't have yet
4341           a current VMCS12
4342        */
4343        exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4344        return exec_control;
4345}
4346
4347static void ept_set_mmio_spte_mask(void)
4348{
4349        /*
4350         * EPT Misconfigurations can be generated if the value of bits 2:0
4351         * of an EPT paging-structure entry is 110b (write/execute).
4352         * Also, magic bits (0x3ull << 62) is set to quickly identify mmio
4353         * spte.
4354         */
4355        kvm_mmu_set_mmio_spte_mask((0x3ull << 62) | 0x6ull);
4356}
4357
4358/*
4359 * Sets up the vmcs for emulated real mode.
4360 */
4361static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
4362{
4363#ifdef CONFIG_X86_64
4364        unsigned long a;
4365#endif
4366        int i;
4367
4368        /* I/O */
4369        vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
4370        vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
4371
4372        if (enable_shadow_vmcs) {
4373                vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
4374                vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
4375        }
4376        if (cpu_has_vmx_msr_bitmap())
4377                vmcs_write64(MSR_BITMAP, __pa(vmx_msr_bitmap_legacy));
4378
4379        vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4380
4381        /* Control */
4382        vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
4383
4384        vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
4385
4386        if (cpu_has_secondary_exec_ctrls()) {
4387                vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
4388                                vmx_secondary_exec_control(vmx));
4389        }
4390
4391        if (vmx_vm_has_apicv(vmx->vcpu.kvm)) {
4392                vmcs_write64(EOI_EXIT_BITMAP0, 0);
4393                vmcs_write64(EOI_EXIT_BITMAP1, 0);
4394                vmcs_write64(EOI_EXIT_BITMAP2, 0);
4395                vmcs_write64(EOI_EXIT_BITMAP3, 0);
4396
4397                vmcs_write16(GUEST_INTR_STATUS, 0);
4398
4399                vmcs_write64(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4400                vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4401        }
4402
4403        if (ple_gap) {
4404                vmcs_write32(PLE_GAP, ple_gap);
4405                vmcs_write32(PLE_WINDOW, ple_window);
4406        }
4407
4408        vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4409        vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4410        vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
4411
4412        vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
4413        vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
4414        vmx_set_constant_host_state(vmx);
4415#ifdef CONFIG_X86_64
4416        rdmsrl(MSR_FS_BASE, a);
4417        vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
4418        rdmsrl(MSR_GS_BASE, a);
4419        vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
4420#else
4421        vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4422        vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4423#endif
4424
4425        vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4426        vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4427        vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
4428        vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4429        vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
4430
4431        if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
4432                u32 msr_low, msr_high;
4433                u64 host_pat;
4434                rdmsr(MSR_IA32_CR_PAT, msr_low, msr_high);
4435                host_pat = msr_low | ((u64) msr_high << 32);
4436                /* Write the default value follow host pat */
4437                vmcs_write64(GUEST_IA32_PAT, host_pat);
4438                /* Keep arch.pat sync with GUEST_IA32_PAT */
4439                vmx->vcpu.arch.pat = host_pat;
4440        }
4441
4442        for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
4443                u32 index = vmx_msr_index[i];
4444                u32 data_low, data_high;
4445                int j = vmx->nmsrs;
4446
4447                if (rdmsr_safe(index, &data_low, &data_high) < 0)
4448                        continue;
4449                if (wrmsr_safe(index, data_low, data_high) < 0)
4450                        continue;
4451                vmx->guest_msrs[j].index = i;
4452                vmx->guest_msrs[j].data = 0;
4453                vmx->guest_msrs[j].mask = -1ull;
4454                ++vmx->nmsrs;
4455        }
4456
4457
4458        vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
4459
4460        /* 22.2.1, 20.8.1 */
4461        vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
4462
4463        vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);
4464        set_cr4_guest_host_mask(vmx);
4465
4466        return 0;
4467}
4468
4469static void vmx_vcpu_reset(struct kvm_vcpu *vcpu)
4470{
4471        struct vcpu_vmx *vmx = to_vmx(vcpu);
4472        struct msr_data apic_base_msr;
4473
4474        vmx->rmode.vm86_active = 0;
4475
4476        vmx->soft_vnmi_blocked = 0;
4477
4478        vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4479        kvm_set_cr8(&vmx->vcpu, 0);
4480        apic_base_msr.data = 0xfee00000 | MSR_IA32_APICBASE_ENABLE;
4481        if (kvm_vcpu_is_bsp(&vmx->vcpu))
4482                apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4483        apic_base_msr.host_initiated = true;
4484        kvm_set_apic_base(&vmx->vcpu, &apic_base_msr);
4485
4486        vmx_segment_cache_clear(vmx);
4487
4488        seg_setup(VCPU_SREG_CS);
4489        vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4490        vmcs_write32(GUEST_CS_BASE, 0xffff0000);
4491
4492        seg_setup(VCPU_SREG_DS);
4493        seg_setup(VCPU_SREG_ES);
4494        seg_setup(VCPU_SREG_FS);
4495        seg_setup(VCPU_SREG_GS);
4496        seg_setup(VCPU_SREG_SS);
4497
4498        vmcs_write16(GUEST_TR_SELECTOR, 0);
4499        vmcs_writel(GUEST_TR_BASE, 0);
4500        vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4501        vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4502
4503        vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4504        vmcs_writel(GUEST_LDTR_BASE, 0);
4505        vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4506        vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4507
4508        vmcs_write32(GUEST_SYSENTER_CS, 0);
4509        vmcs_writel(GUEST_SYSENTER_ESP, 0);
4510        vmcs_writel(GUEST_SYSENTER_EIP, 0);
4511
4512        vmcs_writel(GUEST_RFLAGS, 0x02);
4513        kvm_rip_write(vcpu, 0xfff0);
4514
4515        vmcs_writel(GUEST_GDTR_BASE, 0);
4516        vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4517
4518        vmcs_writel(GUEST_IDTR_BASE, 0);
4519        vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4520
4521        vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4522        vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4523        vmcs_write32(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4524
4525        /* Special registers */
4526        vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4527
4528        setup_msrs(vmx);
4529
4530        vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
4531
4532        if (cpu_has_vmx_tpr_shadow()) {
4533                vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4534                if (vm_need_tpr_shadow(vmx->vcpu.kvm))
4535                        vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4536                                     __pa(vmx->vcpu.arch.apic->regs));
4537                vmcs_write32(TPR_THRESHOLD, 0);
4538        }
4539
4540        if (vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
4541                vmcs_write64(APIC_ACCESS_ADDR,
4542                             page_to_phys(vmx->vcpu.kvm->arch.apic_access_page));
4543
4544        if (vmx_vm_has_apicv(vcpu->kvm))
4545                memset(&vmx->pi_desc, 0, sizeof(struct pi_desc));
4546
4547        if (vmx->vpid != 0)
4548                vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4549
4550        vmx->vcpu.arch.cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4551        vmx_set_cr0(&vmx->vcpu, kvm_read_cr0(vcpu)); /* enter rmode */
4552        vmx_set_cr4(&vmx->vcpu, 0);
4553        vmx_set_efer(&vmx->vcpu, 0);
4554        vmx_fpu_activate(&vmx->vcpu);
4555        update_exception_bitmap(&vmx->vcpu);
4556
4557        vpid_sync_context(vmx);
4558}
4559
4560/*
4561 * In nested virtualization, check if L1 asked to exit on external interrupts.
4562 * For most existing hypervisors, this will always return true.
4563 */
4564static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
4565{
4566        return get_vmcs12(vcpu)->pin_based_vm_exec_control &
4567                PIN_BASED_EXT_INTR_MASK;
4568}
4569
4570/*
4571 * In nested virtualization, check if L1 has set
4572 * VM_EXIT_ACK_INTR_ON_EXIT
4573 */
4574static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
4575{
4576        return get_vmcs12(vcpu)->vm_exit_controls &
4577                VM_EXIT_ACK_INTR_ON_EXIT;
4578}
4579
4580static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
4581{
4582        return get_vmcs12(vcpu)->pin_based_vm_exec_control &
4583                PIN_BASED_NMI_EXITING;
4584}
4585
4586static void enable_irq_window(struct kvm_vcpu *vcpu)
4587{
4588        u32 cpu_based_vm_exec_control;
4589
4590        cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
4591        cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
4592        vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
4593}
4594
4595static void enable_nmi_window(struct kvm_vcpu *vcpu)
4596{
4597        u32 cpu_based_vm_exec_control;
4598
4599        if (!cpu_has_virtual_nmis() ||
4600            vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4601                enable_irq_window(vcpu);
4602                return;
4603        }
4604
4605        cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
4606        cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_NMI_PENDING;
4607        vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
4608}
4609
4610static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4611{
4612        struct vcpu_vmx *vmx = to_vmx(vcpu);
4613        uint32_t intr;
4614        int irq = vcpu->arch.interrupt.nr;
4615
4616        trace_kvm_inj_virq(irq);
4617
4618        ++vcpu->stat.irq_injections;
4619        if (vmx->rmode.vm86_active) {
4620                int inc_eip = 0;
4621                if (vcpu->arch.interrupt.soft)
4622                        inc_eip = vcpu->arch.event_exit_inst_len;
4623                if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
4624                        kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4625                return;
4626        }
4627        intr = irq | INTR_INFO_VALID_MASK;
4628        if (vcpu->arch.interrupt.soft) {
4629                intr |= INTR_TYPE_SOFT_INTR;
4630                vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4631                             vmx->vcpu.arch.event_exit_inst_len);
4632        } else
4633                intr |= INTR_TYPE_EXT_INTR;
4634        vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4635}
4636
4637static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4638{
4639        struct vcpu_vmx *vmx = to_vmx(vcpu);
4640
4641        if (is_guest_mode(vcpu))
4642                return;
4643
4644        if (!cpu_has_virtual_nmis()) {
4645                /*
4646                 * Tracking the NMI-blocked state in software is built upon
4647                 * finding the next open IRQ window. This, in turn, depends on
4648                 * well-behaving guests: They have to keep IRQs disabled at
4649                 * least as long as the NMI handler runs. Otherwise we may
4650                 * cause NMI nesting, maybe breaking the guest. But as this is
4651                 * highly unlikely, we can live with the residual risk.
4652                 */
4653                vmx->soft_vnmi_blocked = 1;
4654                vmx->vnmi_blocked_time = 0;
4655        }
4656
4657        ++vcpu->stat.nmi_injections;
4658        vmx->nmi_known_unmasked = false;
4659        if (vmx->rmode.vm86_active) {
4660                if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
4661                        kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4662                return;
4663        }
4664        vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4665                        INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4666}
4667
4668static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4669{
4670        if (!cpu_has_virtual_nmis())
4671                return to_vmx(vcpu)->soft_vnmi_blocked;
4672        if (to_vmx(vcpu)->nmi_known_unmasked)
4673                return false;
4674        return vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4675}
4676
4677static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4678{
4679        struct vcpu_vmx *vmx = to_vmx(vcpu);
4680
4681        if (!cpu_has_virtual_nmis()) {
4682                if (vmx->soft_vnmi_blocked != masked) {
4683                        vmx->soft_vnmi_blocked = masked;
4684                        vmx->vnmi_blocked_time = 0;
4685                }
4686        } else {
4687                vmx->nmi_known_unmasked = !masked;
4688                if (masked)
4689                        vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4690                                      GUEST_INTR_STATE_NMI);
4691                else
4692                        vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4693                                        GUEST_INTR_STATE_NMI);
4694        }
4695}
4696
4697static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
4698{
4699        if (to_vmx(vcpu)->nested.nested_run_pending)
4700                return 0;
4701
4702        if (!cpu_has_virtual_nmis() && to_vmx(vcpu)->soft_vnmi_blocked)
4703                return 0;
4704
4705        return  !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4706                  (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
4707                   | GUEST_INTR_STATE_NMI));
4708}
4709
4710static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
4711{
4712        return (!to_vmx(vcpu)->nested.nested_run_pending &&
4713                vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
4714                !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4715                        (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4716}
4717
4718static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4719{
4720        int ret;
4721        struct kvm_userspace_memory_region tss_mem = {
4722                .slot = TSS_PRIVATE_MEMSLOT,
4723                .guest_phys_addr = addr,
4724                .memory_size = PAGE_SIZE * 3,
4725                .flags = 0,
4726        };
4727
4728        ret = kvm_set_memory_region(kvm, &tss_mem);
4729        if (ret)
4730                return ret;
4731        kvm->arch.tss_addr = addr;
4732        if (!init_rmode_tss(kvm))
4733                return  -ENOMEM;
4734
4735        return 0;
4736}
4737
4738static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4739{
4740        switch (vec) {
4741        case BP_VECTOR:
4742                /*
4743                 * Update instruction length as we may reinject the exception
4744                 * from user space while in guest debugging mode.
4745                 */
4746                to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4747                        vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4748                if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4749                        return false;
4750                /* fall through */
4751        case DB_VECTOR:
4752                if (vcpu->guest_debug &
4753                        (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
4754                        return false;
4755                /* fall through */
4756        case DE_VECTOR:
4757        case OF_VECTOR:
4758        case BR_VECTOR:
4759        case UD_VECTOR:
4760        case DF_VECTOR:
4761        case SS_VECTOR:
4762        case GP_VECTOR:
4763        case MF_VECTOR:
4764                return true;
4765        break;
4766        }
4767        return false;
4768}
4769
4770static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4771                                  int vec, u32 err_code)
4772{
4773        /*
4774         * Instruction with address size override prefix opcode 0x67
4775         * Cause the #SS fault with 0 error code in VM86 mode.
4776         */
4777        if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4778                if (emulate_instruction(vcpu, 0) == EMULATE_DONE) {
4779                        if (vcpu->arch.halt_request) {
4780                                vcpu->arch.halt_request = 0;
4781                                return kvm_emulate_halt(vcpu);
4782                        }
4783                        return 1;
4784                }
4785                return 0;
4786        }
4787
4788        /*
4789         * Forward all other exceptions that are valid in real mode.
4790         * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4791         *        the required debugging infrastructure rework.
4792         */
4793        kvm_queue_exception(vcpu, vec);
4794        return 1;
4795}
4796
4797/*
4798 * Trigger machine check on the host. We assume all the MSRs are already set up
4799 * by the CPU and that we still run on the same CPU as the MCE occurred on.
4800 * We pass a fake environment to the machine check handler because we want
4801 * the guest to be always treated like user space, no matter what context
4802 * it used internally.
4803 */
4804static void kvm_machine_check(void)
4805{
4806#if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
4807        struct pt_regs regs = {
4808                .cs = 3, /* Fake ring 3 no matter what the guest ran on */
4809                .flags = X86_EFLAGS_IF,
4810        };
4811
4812        do_machine_check(&regs, 0);
4813#endif
4814}
4815
4816static int handle_machine_check(struct kvm_vcpu *vcpu)
4817{
4818        /* already handled by vcpu_run */
4819        return 1;
4820}
4821
4822static int handle_exception(struct kvm_vcpu *vcpu)
4823{
4824        struct vcpu_vmx *vmx = to_vmx(vcpu);
4825        struct kvm_run *kvm_run = vcpu->run;
4826        u32 intr_info, ex_no, error_code;
4827        unsigned long cr2, rip, dr6;
4828        u32 vect_info;
4829        enum emulation_result er;
4830
4831        vect_info = vmx->idt_vectoring_info;
4832        intr_info = vmx->exit_intr_info;
4833
4834        if (is_machine_check(intr_info))
4835                return handle_machine_check(vcpu);
4836
4837        if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR)
4838                return 1;  /* already handled by vmx_vcpu_run() */
4839
4840        if (is_no_device(intr_info)) {
4841                vmx_fpu_activate(vcpu);
4842                return 1;
4843        }
4844
4845        if (is_invalid_opcode(intr_info)) {
4846                er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
4847                if (er != EMULATE_DONE)
4848                        kvm_queue_exception(vcpu, UD_VECTOR);
4849                return 1;
4850        }
4851
4852        error_code = 0;
4853        if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4854                error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4855
4856        /*
4857         * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4858         * MMIO, it is better to report an internal error.
4859         * See the comments in vmx_handle_exit.
4860         */
4861        if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4862            !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4863                vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4864                vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4865                vcpu->run->internal.ndata = 2;
4866                vcpu->run->internal.data[0] = vect_info;
4867                vcpu->run->internal.data[1] = intr_info;
4868                return 0;
4869        }
4870
4871        if (is_page_fault(intr_info)) {
4872                /* EPT won't cause page fault directly */
4873                BUG_ON(enable_ept);
4874                cr2 = vmcs_readl(EXIT_QUALIFICATION);
4875                trace_kvm_page_fault(cr2, error_code);
4876
4877                if (kvm_event_needs_reinjection(vcpu))
4878                        kvm_mmu_unprotect_page_virt(vcpu, cr2);
4879                return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
4880        }
4881
4882        ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4883
4884        if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4885                return handle_rmode_exception(vcpu, ex_no, error_code);
4886
4887        switch (ex_no) {
4888        case DB_VECTOR:
4889                dr6 = vmcs_readl(EXIT_QUALIFICATION);
4890                if (!(vcpu->guest_debug &
4891                      (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4892                        vcpu->arch.dr6 &= ~15;
4893                        vcpu->arch.dr6 |= dr6 | DR6_RTM;
4894                        if (!(dr6 & ~DR6_RESERVED)) /* icebp */
4895                                skip_emulated_instruction(vcpu);
4896
4897                        kvm_queue_exception(vcpu, DB_VECTOR);
4898                        return 1;
4899                }
4900                kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
4901                kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4902                /* fall through */
4903        case BP_VECTOR:
4904                /*
4905                 * Update instruction length as we may reinject #BP from
4906                 * user space while in guest debugging mode. Reading it for
4907                 * #DB as well causes no harm, it is not used in that case.
4908                 */
4909                vmx->vcpu.arch.event_exit_inst_len =
4910                        vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4911                kvm_run->exit_reason = KVM_EXIT_DEBUG;
4912                rip = kvm_rip_read(vcpu);
4913                kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4914                kvm_run->debug.arch.exception = ex_no;
4915                break;
4916        default:
4917                kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4918                kvm_run->ex.exception = ex_no;
4919                kvm_run->ex.error_code = error_code;
4920                break;
4921        }
4922        return 0;
4923}
4924
4925static int handle_external_interrupt(struct kvm_vcpu *vcpu)
4926{
4927        ++vcpu->stat.irq_exits;
4928        return 1;
4929}
4930
4931static int handle_triple_fault(struct kvm_vcpu *vcpu)
4932{
4933        vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4934        return 0;
4935}
4936
4937static int handle_io(struct kvm_vcpu *vcpu)
4938{
4939        unsigned long exit_qualification;
4940        int size, in, string;
4941        unsigned port;
4942
4943        exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4944        string = (exit_qualification & 16) != 0;
4945        in = (exit_qualification & 8) != 0;
4946
4947        ++vcpu->stat.io_exits;
4948
4949        if (string || in)
4950                return emulate_instruction(vcpu, 0) == EMULATE_DONE;
4951
4952        port = exit_qualification >> 16;
4953        size = (exit_qualification & 7) + 1;
4954        skip_emulated_instruction(vcpu);
4955
4956        return kvm_fast_pio_out(vcpu, size, port);
4957}
4958
4959static void
4960vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4961{
4962        /*
4963         * Patch in the VMCALL instruction:
4964         */
4965        hypercall[0] = 0x0f;
4966        hypercall[1] = 0x01;
4967        hypercall[2] = 0xc1;
4968}
4969
4970static bool nested_cr0_valid(struct vmcs12 *vmcs12, unsigned long val)
4971{
4972        unsigned long always_on = VMXON_CR0_ALWAYSON;
4973
4974        if (nested_vmx_secondary_ctls_high &
4975                SECONDARY_EXEC_UNRESTRICTED_GUEST &&
4976            nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
4977                always_on &= ~(X86_CR0_PE | X86_CR0_PG);
4978        return (val & always_on) == always_on;
4979}
4980
4981/* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4982static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4983{
4984        if (is_guest_mode(vcpu)) {
4985                struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4986                unsigned long orig_val = val;
4987
4988                /*
4989                 * We get here when L2 changed cr0 in a way that did not change
4990                 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4991                 * but did change L0 shadowed bits. So we first calculate the
4992                 * effective cr0 value that L1 would like to write into the
4993                 * hardware. It consists of the L2-owned bits from the new
4994                 * value combined with the L1-owned bits from L1's guest_cr0.
4995                 */
4996                val = (val & ~vmcs12->cr0_guest_host_mask) |
4997                        (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4998
4999                if (!nested_cr0_valid(vmcs12, val))
5000                        return 1;
5001
5002                if (kvm_set_cr0(vcpu, val))
5003                        return 1;
5004                vmcs_writel(CR0_READ_SHADOW, orig_val);
5005                return 0;
5006        } else {
5007                if (to_vmx(vcpu)->nested.vmxon &&
5008                    ((val & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON))
5009                        return 1;
5010                return kvm_set_cr0(vcpu, val);
5011        }
5012}
5013
5014static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
5015{
5016        if (is_guest_mode(vcpu)) {
5017                struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5018                unsigned long orig_val = val;
5019
5020                /* analogously to handle_set_cr0 */
5021                val = (val & ~vmcs12->cr4_guest_host_mask) |
5022                        (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
5023                if (kvm_set_cr4(vcpu, val))
5024                        return 1;
5025                vmcs_writel(CR4_READ_SHADOW, orig_val);
5026                return 0;
5027        } else
5028                return kvm_set_cr4(vcpu, val);
5029}
5030
5031/* called to set cr0 as approriate for clts instruction exit. */
5032static void handle_clts(struct kvm_vcpu *vcpu)
5033{
5034        if (is_guest_mode(vcpu)) {
5035                /*
5036                 * We get here when L2 did CLTS, and L1 didn't shadow CR0.TS
5037                 * but we did (!fpu_active). We need to keep GUEST_CR0.TS on,
5038                 * just pretend it's off (also in arch.cr0 for fpu_activate).
5039                 */
5040                vmcs_writel(CR0_READ_SHADOW,
5041                        vmcs_readl(CR0_READ_SHADOW) & ~X86_CR0_TS);
5042                vcpu->arch.cr0 &= ~X86_CR0_TS;
5043        } else
5044                vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
5045}
5046
5047static int handle_cr(struct kvm_vcpu *vcpu)
5048{
5049        unsigned long exit_qualification, val;
5050        int cr;
5051        int reg;
5052        int err;
5053
5054        exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5055        cr = exit_qualification & 15;
5056        reg = (exit_qualification >> 8) & 15;
5057        switch ((exit_qualification >> 4) & 3) {
5058        case 0: /* mov to cr */
5059                val = kvm_register_readl(vcpu, reg);
5060                trace_kvm_cr_write(cr, val);
5061                switch (cr) {
5062                case 0:
5063                        err = handle_set_cr0(vcpu, val);
5064                        kvm_complete_insn_gp(vcpu, err);
5065                        return 1;
5066                case 3:
5067                        err = kvm_set_cr3(vcpu, val);
5068                        kvm_complete_insn_gp(vcpu, err);
5069                        return 1;
5070                case 4:
5071                        err = handle_set_cr4(vcpu, val);
5072                        kvm_complete_insn_gp(vcpu, err);
5073                        return 1;
5074                case 8: {
5075                                u8 cr8_prev = kvm_get_cr8(vcpu);
5076                                u8 cr8 = (u8)val;
5077                                err = kvm_set_cr8(vcpu, cr8);
5078                                kvm_complete_insn_gp(vcpu, err);
5079                                if (irqchip_in_kernel(vcpu->kvm))
5080                                        return 1;
5081                                if (cr8_prev <= cr8)
5082                                        return 1;
5083                                vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5084                                return 0;
5085                        }
5086                }
5087                break;
5088        case 2: /* clts */
5089                handle_clts(vcpu);
5090                trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
5091                skip_emulated_instruction(vcpu);
5092                vmx_fpu_activate(vcpu);
5093                return 1;
5094        case 1: /*mov from cr*/
5095                switch (cr) {
5096                case 3:
5097                        val = kvm_read_cr3(vcpu);
5098                        kvm_register_write(vcpu, reg, val);
5099                        trace_kvm_cr_read(cr, val);
5100                        skip_emulated_instruction(vcpu);
5101                        return 1;
5102                case 8:
5103                        val = kvm_get_cr8(vcpu);
5104                        kvm_register_write(vcpu, reg, val);
5105                        trace_kvm_cr_read(cr, val);
5106                        skip_emulated_instruction(vcpu);
5107                        return 1;
5108                }
5109                break;
5110        case 3: /* lmsw */
5111                val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5112                trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
5113                kvm_lmsw(vcpu, val);
5114
5115                skip_emulated_instruction(vcpu);
5116                return 1;
5117        default:
5118                break;
5119        }
5120        vcpu->run->exit_reason = 0;
5121        vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5122               (int)(exit_qualification >> 4) & 3, cr);
5123        return 0;
5124}
5125
5126static int handle_dr(struct kvm_vcpu *vcpu)
5127{
5128        unsigned long exit_qualification;
5129        int dr, reg;
5130
5131        /* Do not handle if the CPL > 0, will trigger GP on re-entry */
5132        if (!kvm_require_cpl(vcpu, 0))
5133                return 1;
5134        dr = vmcs_readl(GUEST_DR7);
5135        if (dr & DR7_GD) {
5136                /*
5137                 * As the vm-exit takes precedence over the debug trap, we
5138                 * need to emulate the latter, either for the host or the
5139                 * guest debugging itself.
5140                 */
5141                if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5142                        vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
5143                        vcpu->run->debug.arch.dr7 = dr;
5144                        vcpu->run->debug.arch.pc =
5145                                vmcs_readl(GUEST_CS_BASE) +
5146                                vmcs_readl(GUEST_RIP);
5147                        vcpu->run->debug.arch.exception = DB_VECTOR;
5148                        vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5149                        return 0;
5150                } else {
5151                        vcpu->arch.dr7 &= ~DR7_GD;
5152                        vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
5153                        vmcs_writel(GUEST_DR7, vcpu->arch.dr7);
5154                        kvm_queue_exception(vcpu, DB_VECTOR);
5155                        return 1;
5156                }
5157        }
5158
5159        if (vcpu->guest_debug == 0) {
5160                u32 cpu_based_vm_exec_control;
5161
5162                cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5163                cpu_based_vm_exec_control &= ~CPU_BASED_MOV_DR_EXITING;
5164                vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5165
5166                /*
5167                 * No more DR vmexits; force a reload of the debug registers
5168                 * and reenter on this instruction.  The next vmexit will
5169                 * retrieve the full state of the debug registers.
5170                 */
5171                vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5172                return 1;
5173        }
5174
5175        exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5176        dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5177        reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5178        if (exit_qualification & TYPE_MOV_FROM_DR) {
5179                unsigned long val;
5180
5181                if (kvm_get_dr(vcpu, dr, &val))
5182                        return 1;
5183                kvm_register_write(vcpu, reg, val);
5184        } else
5185                if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
5186                        return 1;
5187
5188        skip_emulated_instruction(vcpu);
5189        return 1;
5190}
5191
5192static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
5193{
5194        return vcpu->arch.dr6;
5195}
5196
5197static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
5198{
5199}
5200
5201static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5202{
5203        u32 cpu_based_vm_exec_control;
5204
5205        get_debugreg(vcpu->arch.db[0], 0);
5206        get_debugreg(vcpu->arch.db[1], 1);
5207        get_debugreg(vcpu->arch.db[2], 2);
5208        get_debugreg(vcpu->arch.db[3], 3);
5209        get_debugreg(vcpu->arch.dr6, 6);
5210        vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5211
5212        vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5213
5214        cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5215        cpu_based_vm_exec_control |= CPU_BASED_MOV_DR_EXITING;
5216        vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5217}
5218
5219static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5220{
5221        vmcs_writel(GUEST_DR7, val);
5222}
5223
5224static int handle_cpuid(struct kvm_vcpu *vcpu)
5225{
5226        kvm_emulate_cpuid(vcpu);
5227        return 1;
5228}
5229
5230static int handle_rdmsr(struct kvm_vcpu *vcpu)
5231{
5232        u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
5233        u64 data;
5234
5235        if (vmx_get_msr(vcpu, ecx, &data)) {
5236                trace_kvm_msr_read_ex(ecx);
5237                kvm_inject_gp(vcpu, 0);
5238                return 1;
5239        }
5240
5241        trace_kvm_msr_read(ecx, data);
5242
5243        /* FIXME: handling of bits 32:63 of rax, rdx */
5244        vcpu->arch.regs[VCPU_REGS_RAX] = data & -1u;
5245        vcpu->arch.regs[VCPU_REGS_RDX] = (data >> 32) & -1u;
5246        skip_emulated_instruction(vcpu);
5247        return 1;
5248}
5249
5250static int handle_wrmsr(struct kvm_vcpu *vcpu)
5251{
5252        struct msr_data msr;
5253        u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
5254        u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
5255                | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
5256
5257        msr.data = data;
5258        msr.index = ecx;
5259        msr.host_initiated = false;
5260        if (vmx_set_msr(vcpu, &msr) != 0) {
5261                trace_kvm_msr_write_ex(ecx, data);
5262                kvm_inject_gp(vcpu, 0);
5263                return 1;
5264        }
5265
5266        trace_kvm_msr_write(ecx, data);
5267        skip_emulated_instruction(vcpu);
5268        return 1;
5269}
5270
5271static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5272{
5273        kvm_make_request(KVM_REQ_EVENT, vcpu);
5274        return 1;
5275}
5276
5277static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5278{
5279        u32 cpu_based_vm_exec_control;
5280
5281        /* clear pending irq */
5282        cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5283        cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
5284        vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5285
5286        kvm_make_request(KVM_REQ_EVENT, vcpu);
5287
5288        ++vcpu->stat.irq_window_exits;
5289
5290        /*
5291         * If the user space waits to inject interrupts, exit as soon as
5292         * possible
5293         */
5294        if (!irqchip_in_kernel(vcpu->kvm) &&
5295            vcpu->run->request_interrupt_window &&
5296            !kvm_cpu_has_interrupt(vcpu)) {
5297                vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
5298                return 0;
5299        }
5300        return 1;
5301}
5302
5303static int handle_halt(struct kvm_vcpu *vcpu)
5304{
5305        skip_emulated_instruction(vcpu);
5306        return kvm_emulate_halt(vcpu);
5307}
5308
5309static int handle_vmcall(struct kvm_vcpu *vcpu)
5310{
5311        skip_emulated_instruction(vcpu);
5312        kvm_emulate_hypercall(vcpu);
5313        return 1;
5314}
5315
5316static int handle_invd(struct kvm_vcpu *vcpu)
5317{
5318        return emulate_instruction(vcpu, 0) == EMULATE_DONE;
5319}
5320
5321static int handle_invlpg(struct kvm_vcpu *vcpu)
5322{
5323        unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5324
5325        kvm_mmu_invlpg(vcpu, exit_qualification);
5326        skip_emulated_instruction(vcpu);
5327        return 1;
5328}
5329
5330static int handle_rdpmc(struct kvm_vcpu *vcpu)
5331{
5332        int err;
5333
5334        err = kvm_rdpmc(vcpu);
5335        kvm_complete_insn_gp(vcpu, err);
5336
5337        return 1;
5338}
5339
5340static int handle_wbinvd(struct kvm_vcpu *vcpu)
5341{
5342        skip_emulated_instruction(vcpu);
5343        kvm_emulate_wbinvd(vcpu);
5344        return 1;
5345}
5346
5347static int handle_xsetbv(struct kvm_vcpu *vcpu)
5348{
5349        u64 new_bv = kvm_read_edx_eax(vcpu);
5350        u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
5351
5352        if (kvm_set_xcr(vcpu, index, new_bv) == 0)
5353                skip_emulated_instruction(vcpu);
5354        return 1;
5355}
5356
5357static int handle_apic_access(struct kvm_vcpu *vcpu)
5358{
5359        if (likely(fasteoi)) {
5360                unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5361                int access_type, offset;
5362
5363                access_type = exit_qualification & APIC_ACCESS_TYPE;
5364                offset = exit_qualification & APIC_ACCESS_OFFSET;
5365                /*
5366                 * Sane guest uses MOV to write EOI, with written value
5367                 * not cared. So make a short-circuit here by avoiding
5368                 * heavy instruction emulation.
5369                 */
5370                if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5371                    (offset == APIC_EOI)) {
5372                        kvm_lapic_set_eoi(vcpu);
5373                        skip_emulated_instruction(vcpu);
5374                        return 1;
5375                }
5376        }
5377        return emulate_instruction(vcpu, 0) == EMULATE_DONE;
5378}
5379
5380static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5381{
5382        unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5383        int vector = exit_qualification & 0xff;
5384
5385        /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5386        kvm_apic_set_eoi_accelerated(vcpu, vector);
5387        return 1;
5388}
5389
5390static int handle_apic_write(struct kvm_vcpu *vcpu)
5391{
5392        unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5393        u32 offset = exit_qualification & 0xfff;
5394
5395        /* APIC-write VM exit is trap-like and thus no need to adjust IP */
5396        kvm_apic_write_nodecode(vcpu, offset);
5397        return 1;
5398}
5399
5400static int handle_task_switch(struct kvm_vcpu *vcpu)
5401{
5402        struct vcpu_vmx *vmx = to_vmx(vcpu);
5403        unsigned long exit_qualification;
5404        bool has_error_code = false;
5405        u32 error_code = 0;
5406        u16 tss_selector;
5407        int reason, type, idt_v, idt_index;
5408
5409        idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5410        idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5411        type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5412
5413        exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5414
5415        reason = (u32)exit_qualification >> 30;
5416        if (reason == TASK_SWITCH_GATE && idt_v) {
5417                switch (type) {
5418                case INTR_TYPE_NMI_INTR:
5419                        vcpu->arch.nmi_injected = false;
5420                        vmx_set_nmi_mask(vcpu, true);
5421                        break;
5422                case INTR_TYPE_EXT_INTR:
5423                case INTR_TYPE_SOFT_INTR:
5424                        kvm_clear_interrupt_queue(vcpu);
5425                        break;
5426                case INTR_TYPE_HARD_EXCEPTION:
5427                        if (vmx->idt_vectoring_info &
5428                            VECTORING_INFO_DELIVER_CODE_MASK) {
5429                                has_error_code = true;
5430                                error_code =
5431                                        vmcs_read32(IDT_VECTORING_ERROR_CODE);
5432                        }
5433                        /* fall through */
5434                case INTR_TYPE_SOFT_EXCEPTION:
5435                        kvm_clear_exception_queue(vcpu);
5436                        break;
5437                default:
5438                        break;
5439                }
5440        }
5441        tss_selector = exit_qualification;
5442
5443        if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5444                       type != INTR_TYPE_EXT_INTR &&
5445                       type != INTR_TYPE_NMI_INTR))
5446                skip_emulated_instruction(vcpu);
5447
5448        if (kvm_task_switch(vcpu, tss_selector,
5449                            type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
5450                            has_error_code, error_code) == EMULATE_FAIL) {
5451                vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5452                vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5453                vcpu->run->internal.ndata = 0;
5454                return 0;
5455        }
5456
5457        /* clear all local breakpoint enable flags */
5458        vmcs_writel(GUEST_DR7, vmcs_readl(GUEST_DR7) & ~0x55);
5459
5460        /*
5461         * TODO: What about debug traps on tss switch?
5462         *       Are we supposed to inject them and update dr6?
5463         */
5464
5465        return 1;
5466}
5467
5468static int handle_ept_violation(struct kvm_vcpu *vcpu)
5469{
5470        unsigned long exit_qualification;
5471        gpa_t gpa;
5472        u32 error_code;
5473        int gla_validity;
5474
5475        exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5476
5477        gla_validity = (exit_qualification >> 7) & 0x3;
5478        if (gla_validity != 0x3 && gla_validity != 0x1 && gla_validity != 0) {
5479                printk(KERN_ERR "EPT: Handling EPT violation failed!\n");
5480                printk(KERN_ERR "EPT: GPA: 0x%lx, GVA: 0x%lx\n",
5481                        (long unsigned int)vmcs_read64(GUEST_PHYSICAL_ADDRESS),
5482                        vmcs_readl(GUEST_LINEAR_ADDRESS));
5483                printk(KERN_ERR "EPT: Exit qualification is 0x%lx\n",
5484                        (long unsigned int)exit_qualification);
5485                vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
5486                vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_VIOLATION;
5487                return 0;
5488        }
5489
5490        /*
5491         * EPT violation happened while executing iret from NMI,
5492         * "blocked by NMI" bit has to be set before next VM entry.
5493         * There are errata that may cause this bit to not be set:
5494         * AAK134, BY25.
5495         */
5496        if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5497                        cpu_has_virtual_nmis() &&
5498                        (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5499                vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5500
5501        gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5502        trace_kvm_page_fault(gpa, exit_qualification);
5503
5504        /* It is a write fault? */
5505        error_code = exit_qualification & (1U << 1);
5506        /* It is a fetch fault? */
5507        error_code |= (exit_qualification & (1U << 2)) << 2;
5508        /* ept page table is present? */
5509        error_code |= (exit_qualification >> 3) & 0x1;
5510
5511        vcpu->arch.exit_qualification = exit_qualification;
5512
5513        return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5514}
5515
5516static u64 ept_rsvd_mask(u64 spte, int level)
5517{
5518        int i;
5519        u64 mask = 0;
5520
5521        for (i = 51; i > boot_cpu_data.x86_phys_bits; i--)
5522                mask |= (1ULL << i);
5523
5524        if (level > 2)
5525                /* bits 7:3 reserved */
5526                mask |= 0xf8;
5527        else if (level == 2) {
5528                if (spte & (1ULL << 7))
5529                        /* 2MB ref, bits 20:12 reserved */
5530                        mask |= 0x1ff000;
5531                else
5532                        /* bits 6:3 reserved */
5533                        mask |= 0x78;
5534        }
5535
5536        return mask;
5537}
5538
5539static void ept_misconfig_inspect_spte(struct kvm_vcpu *vcpu, u64 spte,
5540                                       int level)
5541{
5542        printk(KERN_ERR "%s: spte 0x%llx level %d\n", __func__, spte, level);
5543
5544        /* 010b (write-only) */
5545        WARN_ON((spte & 0x7) == 0x2);
5546
5547        /* 110b (write/execute) */
5548        WARN_ON((spte & 0x7) == 0x6);
5549
5550        /* 100b (execute-only) and value not supported by logical processor */
5551        if (!cpu_has_vmx_ept_execute_only())
5552                WARN_ON((spte & 0x7) == 0x4);
5553
5554        /* not 000b */
5555        if ((spte & 0x7)) {
5556                u64 rsvd_bits = spte & ept_rsvd_mask(spte, level);
5557
5558                if (rsvd_bits != 0) {
5559                        printk(KERN_ERR "%s: rsvd_bits = 0x%llx\n",
5560                                         __func__, rsvd_bits);
5561                        WARN_ON(1);
5562                }
5563
5564                if (level == 1 || (level == 2 && (spte & (1ULL << 7)))) {
5565                        u64 ept_mem_type = (spte & 0x38) >> 3;
5566
5567                        if (ept_mem_type == 2 || ept_mem_type == 3 ||
5568                            ept_mem_type == 7) {
5569                                printk(KERN_ERR "%s: ept_mem_type=0x%llx\n",
5570                                                __func__, ept_mem_type);
5571                                WARN_ON(1);
5572                        }
5573                }
5574        }
5575}
5576
5577static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5578{
5579        u64 sptes[4];
5580        int nr_sptes, i, ret;
5581        gpa_t gpa;
5582
5583        gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5584        if (!kvm_io_bus_write(vcpu->kvm, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5585                skip_emulated_instruction(vcpu);
5586                return 1;
5587        }
5588
5589        ret = handle_mmio_page_fault_common(vcpu, gpa, true);
5590        if (likely(ret == RET_MMIO_PF_EMULATE))
5591                return x86_emulate_instruction(vcpu, gpa, 0, NULL, 0) ==
5592                                              EMULATE_DONE;
5593
5594        if (unlikely(ret == RET_MMIO_PF_INVALID))
5595                return kvm_mmu_page_fault(vcpu, gpa, 0, NULL, 0);
5596
5597        if (unlikely(ret == RET_MMIO_PF_RETRY))
5598                return 1;
5599
5600        /* It is the real ept misconfig */
5601        printk(KERN_ERR "EPT: Misconfiguration.\n");
5602        printk(KERN_ERR "EPT: GPA: 0x%llx\n", gpa);
5603
5604        nr_sptes = kvm_mmu_get_spte_hierarchy(vcpu, gpa, sptes);
5605
5606        for (i = PT64_ROOT_LEVEL; i > PT64_ROOT_LEVEL - nr_sptes; --i)
5607                ept_misconfig_inspect_spte(vcpu, sptes[i-1], i);
5608
5609        vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
5610        vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
5611
5612        return 0;
5613}
5614
5615static int handle_nmi_window(struct kvm_vcpu *vcpu)
5616{
5617        u32 cpu_based_vm_exec_control;
5618
5619        /* clear pending NMI */
5620        cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5621        cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
5622        vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5623        ++vcpu->stat.nmi_window_exits;
5624        kvm_make_request(KVM_REQ_EVENT, vcpu);
5625
5626        return 1;
5627}
5628
5629static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5630{
5631        struct vcpu_vmx *vmx = to_vmx(vcpu);
5632        enum emulation_result err = EMULATE_DONE;
5633        int ret = 1;
5634        u32 cpu_exec_ctrl;
5635        bool intr_window_requested;
5636        unsigned count = 130;
5637
5638        cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5639        intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
5640
5641        while (vmx->emulation_required && count-- != 0) {
5642                if (intr_window_requested && vmx_interrupt_allowed(vcpu))
5643                        return handle_interrupt_window(&vmx->vcpu);
5644
5645                if (test_bit(KVM_REQ_EVENT, &vcpu->requests))
5646                        return 1;
5647
5648                err = emulate_instruction(vcpu, EMULTYPE_NO_REEXECUTE);
5649
5650                if (err == EMULATE_USER_EXIT) {
5651                        ++vcpu->stat.mmio_exits;
5652                        ret = 0;
5653                        goto out;
5654                }
5655
5656                if (err != EMULATE_DONE) {
5657                        vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5658                        vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5659                        vcpu->run->internal.ndata = 0;
5660                        return 0;
5661                }
5662
5663                if (vcpu->arch.halt_request) {
5664                        vcpu->arch.halt_request = 0;
5665                        ret = kvm_emulate_halt(vcpu);
5666                        goto out;
5667                }
5668
5669                if (signal_pending(current))
5670                        goto out;
5671                if (need_resched())
5672                        schedule();
5673        }
5674
5675out:
5676        return ret;
5677}
5678
5679/*
5680 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5681 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5682 */
5683static int handle_pause(struct kvm_vcpu *vcpu)
5684{
5685        skip_emulated_instruction(vcpu);
5686        kvm_vcpu_on_spin(vcpu);
5687
5688        return 1;
5689}
5690
5691static int handle_nop(struct kvm_vcpu *vcpu)
5692{
5693        skip_emulated_instruction(vcpu);
5694        return 1;
5695}
5696
5697static int handle_mwait(struct kvm_vcpu *vcpu)
5698{
5699        printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
5700        return handle_nop(vcpu);
5701}
5702
5703static int handle_monitor(struct kvm_vcpu *vcpu)
5704{
5705        printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
5706        return handle_nop(vcpu);
5707}
5708
5709/*
5710 * To run an L2 guest, we need a vmcs02 based on the L1-specified vmcs12.
5711 * We could reuse a single VMCS for all the L2 guests, but we also want the
5712 * option to allocate a separate vmcs02 for each separate loaded vmcs12 - this
5713 * allows keeping them loaded on the processor, and in the future will allow
5714 * optimizations where prepare_vmcs02 doesn't need to set all the fields on
5715 * every entry if they never change.
5716 * So we keep, in vmx->nested.vmcs02_pool, a cache of size VMCS02_POOL_SIZE
5717 * (>=0) with a vmcs02 for each recently loaded vmcs12s, most recent first.
5718 *
5719 * The following functions allocate and free a vmcs02 in this pool.
5720 */
5721
5722/* Get a VMCS from the pool to use as vmcs02 for the current vmcs12. */
5723static struct loaded_vmcs *nested_get_current_vmcs02(struct vcpu_vmx *vmx)
5724{
5725        struct vmcs02_list *item;
5726        list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
5727                if (item->vmptr == vmx->nested.current_vmptr) {
5728                        list_move(&item->list, &vmx->nested.vmcs02_pool);
5729                        return &item->vmcs02;
5730                }
5731
5732        if (vmx->nested.vmcs02_num >= max(VMCS02_POOL_SIZE, 1)) {
5733                /* Recycle the least recently used VMCS. */
5734                item = list_entry(vmx->nested.vmcs02_pool.prev,
5735                        struct vmcs02_list, list);
5736                item->vmptr = vmx->nested.current_vmptr;
5737                list_move(&item->list, &vmx->nested.vmcs02_pool);
5738                return &item->vmcs02;
5739        }
5740
5741        /* Create a new VMCS */
5742        item = kmalloc(sizeof(struct vmcs02_list), GFP_KERNEL);
5743        if (!item)
5744                return NULL;
5745        item->vmcs02.vmcs = alloc_vmcs();
5746        if (!item->vmcs02.vmcs) {
5747                kfree(item);
5748                return NULL;
5749        }
5750        loaded_vmcs_init(&item->vmcs02);
5751        item->vmptr = vmx->nested.current_vmptr;
5752        list_add(&(item->list), &(vmx->nested.vmcs02_pool));
5753        vmx->nested.vmcs02_num++;
5754        return &item->vmcs02;
5755}
5756
5757/* Free and remove from pool a vmcs02 saved for a vmcs12 (if there is one) */
5758static void nested_free_vmcs02(struct vcpu_vmx *vmx, gpa_t vmptr)
5759{
5760        struct vmcs02_list *item;
5761        list_for_each_entry(item, &vmx->nested.vmcs02_pool, list)
5762                if (item->vmptr == vmptr) {
5763                        free_loaded_vmcs(&item->vmcs02);
5764                        list_del(&item->list);
5765                        kfree(item);
5766                        vmx->nested.vmcs02_num--;
5767                        return;
5768                }
5769}
5770
5771/*
5772 * Free all VMCSs saved for this vcpu, except the one pointed by
5773 * vmx->loaded_vmcs. We must be running L1, so vmx->loaded_vmcs
5774 * must be &vmx->vmcs01.
5775 */
5776static void nested_free_all_saved_vmcss(struct vcpu_vmx *vmx)
5777{
5778        struct vmcs02_list *item, *n;
5779
5780        WARN_ON(vmx->loaded_vmcs != &vmx->vmcs01);
5781        list_for_each_entry_safe(item, n, &vmx->nested.vmcs02_pool, list) {
5782                /*
5783                 * Something will leak if the above WARN triggers.  Better than
5784                 * a use-after-free.
5785                 */
5786                if (vmx->loaded_vmcs == &item->vmcs02)
5787                        continue;
5788
5789                free_loaded_vmcs(&item->vmcs02);
5790                list_del(&item->list);
5791                kfree(item);
5792                vmx->nested.vmcs02_num--;
5793        }
5794}
5795
5796/*
5797 * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
5798 * set the success or error code of an emulated VMX instruction, as specified
5799 * by Vol 2B, VMX Instruction Reference, "Conventions".
5800 */
5801static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
5802{
5803        vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
5804                        & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
5805                            X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
5806}
5807
5808static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
5809{
5810        vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
5811                        & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
5812                            X86_EFLAGS_SF | X86_EFLAGS_OF))
5813                        | X86_EFLAGS_CF);
5814}
5815
5816static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
5817                                        u32 vm_instruction_error)
5818{
5819        if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
5820                /*
5821                 * failValid writes the error number to the current VMCS, which
5822                 * can't be done there isn't a current VMCS.
5823                 */
5824                nested_vmx_failInvalid(vcpu);
5825                return;
5826        }
5827        vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
5828                        & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
5829                            X86_EFLAGS_SF | X86_EFLAGS_OF))
5830                        | X86_EFLAGS_ZF);
5831        get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
5832        /*
5833         * We don't need to force a shadow sync because
5834         * VM_INSTRUCTION_ERROR is not shadowed
5835         */
5836}
5837
5838static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
5839{
5840        struct vcpu_vmx *vmx =
5841                container_of(timer, struct vcpu_vmx, nested.preemption_timer);
5842
5843        vmx->nested.preemption_timer_expired = true;
5844        kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
5845        kvm_vcpu_kick(&vmx->vcpu);
5846
5847        return HRTIMER_NORESTART;
5848}
5849
5850/*
5851 * Decode the memory-address operand of a vmx instruction, as recorded on an
5852 * exit caused by such an instruction (run by a guest hypervisor).
5853 * On success, returns 0. When the operand is invalid, returns 1 and throws
5854 * #UD or #GP.
5855 */
5856static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
5857                                 unsigned long exit_qualification,
5858                                 u32 vmx_instruction_info, gva_t *ret)
5859{
5860        /*
5861         * According to Vol. 3B, "Information for VM Exits Due to Instruction
5862         * Execution", on an exit, vmx_instruction_info holds most of the
5863         * addressing components of the operand. Only the displacement part
5864         * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
5865         * For how an actual address is calculated from all these components,
5866         * refer to Vol. 1, "Operand Addressing".
5867         */
5868        int  scaling = vmx_instruction_info & 3;
5869        int  addr_size = (vmx_instruction_info >> 7) & 7;
5870        bool is_reg = vmx_instruction_info & (1u << 10);
5871        int  seg_reg = (vmx_instruction_info >> 15) & 7;
5872        int  index_reg = (vmx_instruction_info >> 18) & 0xf;
5873        bool index_is_valid = !(vmx_instruction_info & (1u << 22));
5874        int  base_reg       = (vmx_instruction_info >> 23) & 0xf;
5875        bool base_is_valid  = !(vmx_instruction_info & (1u << 27));
5876
5877        if (is_reg) {
5878                kvm_queue_exception(vcpu, UD_VECTOR);
5879                return 1;
5880        }
5881
5882        /* Addr = segment_base + offset */
5883        /* offset = base + [index * scale] + displacement */
5884        *ret = vmx_get_segment_base(vcpu, seg_reg);
5885        if (base_is_valid)
5886                *ret += kvm_register_read(vcpu, base_reg);
5887        if (index_is_valid)
5888                *ret += kvm_register_read(vcpu, index_reg)<<scaling;
5889        *ret += exit_qualification; /* holds the displacement */
5890
5891        if (addr_size == 1) /* 32 bit */
5892                *ret &= 0xffffffff;
5893
5894        /*
5895         * TODO: throw #GP (and return 1) in various cases that the VM*
5896         * instructions require it - e.g., offset beyond segment limit,
5897         * unusable or unreadable/unwritable segment, non-canonical 64-bit
5898         * address, and so on. Currently these are not checked.
5899         */
5900        return 0;
5901}
5902
5903/*
5904 * This function performs the various checks including
5905 * - if it's 4KB aligned
5906 * - No bits beyond the physical address width are set
5907 * - Returns 0 on success or else 1
5908 * (Intel SDM Section 30.3)
5909 */
5910static int nested_vmx_check_vmptr(struct kvm_vcpu *vcpu, int exit_reason,
5911                                  gpa_t *vmpointer)
5912{
5913        gva_t gva;
5914        gpa_t vmptr;
5915        struct x86_exception e;
5916        struct page *page;
5917        struct vcpu_vmx *vmx = to_vmx(vcpu);
5918        int maxphyaddr = cpuid_maxphyaddr(vcpu);
5919
5920        if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
5921                        vmcs_read32(VMX_INSTRUCTION_INFO), &gva))
5922                return 1;
5923
5924        if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vmptr,
5925                                sizeof(vmptr), &e)) {
5926                kvm_inject_page_fault(vcpu, &e);
5927                return 1;
5928        }
5929
5930        switch (exit_reason) {
5931        case EXIT_REASON_VMON:
5932                /*
5933                 * SDM 3: 24.11.5
5934                 * The first 4 bytes of VMXON region contain the supported
5935                 * VMCS revision identifier
5936                 *
5937                 * Note - IA32_VMX_BASIC[48] will never be 1
5938                 * for the nested case;
5939                 * which replaces physical address width with 32
5940                 *
5941                 */
5942                if (!PAGE_ALIGNED(vmptr) || (vmptr >> maxphyaddr)) {
5943                        nested_vmx_failInvalid(vcpu);
5944                        skip_emulated_instruction(vcpu);
5945                        return 1;
5946                }
5947
5948                page = nested_get_page(vcpu, vmptr);
5949                if (page == NULL ||
5950                    *(u32 *)kmap(page) != VMCS12_REVISION) {
5951                        nested_vmx_failInvalid(vcpu);
5952                        kunmap(page);
5953                        skip_emulated_instruction(vcpu);
5954                        return 1;
5955                }
5956                kunmap(page);
5957                vmx->nested.vmxon_ptr = vmptr;
5958                break;
5959        case EXIT_REASON_VMCLEAR:
5960                if (!PAGE_ALIGNED(vmptr) || (vmptr >> maxphyaddr)) {
5961                        nested_vmx_failValid(vcpu,
5962                                             VMXERR_VMCLEAR_INVALID_ADDRESS);
5963                        skip_emulated_instruction(vcpu);
5964                        return 1;
5965                }
5966
5967                if (vmptr == vmx->nested.vmxon_ptr) {
5968                        nested_vmx_failValid(vcpu,
5969                                             VMXERR_VMCLEAR_VMXON_POINTER);
5970                        skip_emulated_instruction(vcpu);
5971                        return 1;
5972                }
5973                break;
5974        case EXIT_REASON_VMPTRLD:
5975                if (!PAGE_ALIGNED(vmptr) || (vmptr >> maxphyaddr)) {
5976                        nested_vmx_failValid(vcpu,
5977                                             VMXERR_VMPTRLD_INVALID_ADDRESS);
5978                        skip_emulated_instruction(vcpu);
5979                        return 1;
5980                }
5981
5982                if (vmptr == vmx->nested.vmxon_ptr) {
5983                        nested_vmx_failValid(vcpu,
5984                                             VMXERR_VMCLEAR_VMXON_POINTER);
5985                        skip_emulated_instruction(vcpu);
5986                        return 1;
5987                }
5988                break;
5989        default:
5990                return 1; /* shouldn't happen */
5991        }
5992
5993        if (vmpointer)
5994                *vmpointer = vmptr;
5995        return 0;
5996}
5997
5998/*
5999 * Emulate the VMXON instruction.
6000 * Currently, we just remember that VMX is active, and do not save or even
6001 * inspect the argument to VMXON (the so-called "VMXON pointer") because we
6002 * do not currently need to store anything in that guest-allocated memory
6003 * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
6004 * argument is different from the VMXON pointer (which the spec says they do).
6005 */
6006static int handle_vmon(struct kvm_vcpu *vcpu)
6007{
6008        struct kvm_segment cs;
6009        struct vcpu_vmx *vmx = to_vmx(vcpu);
6010        struct vmcs *shadow_vmcs;
6011        const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
6012                | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
6013
6014        /* The Intel VMX Instruction Reference lists a bunch of bits that
6015         * are prerequisite to running VMXON, most notably cr4.VMXE must be
6016         * set to 1 (see vmx_set_cr4() for when we allow the guest to set this).
6017         * Otherwise, we should fail with #UD. We test these now:
6018         */
6019        if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE) ||
6020            !kvm_read_cr0_bits(vcpu, X86_CR0_PE) ||
6021            (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
6022                kvm_queue_exception(vcpu, UD_VECTOR);
6023                return 1;
6024        }
6025
6026        vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
6027        if (is_long_mode(vcpu) && !cs.l) {
6028                kvm_queue_exception(vcpu, UD_VECTOR);
6029                return 1;
6030        }
6031
6032        if (vmx_get_cpl(vcpu)) {
6033                kvm_inject_gp(vcpu, 0);
6034                return 1;
6035        }
6036
6037        if (nested_vmx_check_vmptr(vcpu, EXIT_REASON_VMON, NULL))
6038                return 1;
6039
6040        if (vmx->nested.vmxon) {
6041                nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
6042                skip_emulated_instruction(vcpu);
6043                return 1;
6044        }
6045
6046        if ((vmx->nested.msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
6047                        != VMXON_NEEDED_FEATURES) {
6048                kvm_inject_gp(vcpu, 0);
6049                return 1;
6050        }
6051
6052        if (enable_shadow_vmcs) {
6053                shadow_vmcs = alloc_vmcs();
6054                if (!shadow_vmcs)
6055                        return -ENOMEM;
6056                /* mark vmcs as shadow */
6057                shadow_vmcs->revision_id |= (1u << 31);
6058                /* init shadow vmcs */
6059                vmcs_clear(shadow_vmcs);
6060                vmx->nested.current_shadow_vmcs = shadow_vmcs;
6061        }
6062
6063        INIT_LIST_HEAD(&(vmx->nested.vmcs02_pool));
6064        vmx->nested.vmcs02_num = 0;
6065
6066        hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
6067                     HRTIMER_MODE_REL);
6068        vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
6069
6070        vmx->nested.vmxon = true;
6071
6072        skip_emulated_instruction(vcpu);
6073        nested_vmx_succeed(vcpu);
6074        return 1;
6075}
6076
6077/*
6078 * Intel's VMX Instruction Reference specifies a common set of prerequisites
6079 * for running VMX instructions (except VMXON, whose prerequisites are
6080 * slightly different). It also specifies what exception to inject otherwise.
6081 */
6082static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
6083{
6084        struct kvm_segment cs;
6085        struct vcpu_vmx *vmx = to_vmx(vcpu);
6086
6087        if (!vmx->nested.vmxon) {
6088                kvm_queue_exception(vcpu, UD_VECTOR);
6089                return 0;
6090        }
6091
6092        vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
6093        if ((vmx_get_rflags(vcpu) & X86_EFLAGS_VM) ||
6094            (is_long_mode(vcpu) && !cs.l)) {
6095                kvm_queue_exception(vcpu, UD_VECTOR);
6096                return 0;
6097        }
6098
6099        if (vmx_get_cpl(vcpu)) {
6100                kvm_inject_gp(vcpu, 0);
6101                return 0;
6102        }
6103
6104        return 1;
6105}
6106
6107static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
6108{
6109        u32 exec_control;
6110        if (vmx->nested.current_vmptr == -1ull)
6111                return;
6112
6113        /* current_vmptr and current_vmcs12 are always set/reset together */
6114        if (WARN_ON(vmx->nested.current_vmcs12 == NULL))
6115                return;
6116
6117        if (enable_shadow_vmcs) {
6118                /* copy to memory all shadowed fields in case
6119                   they were modified */
6120                copy_shadow_to_vmcs12(vmx);
6121                vmx->nested.sync_shadow_vmcs = false;
6122                exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6123                exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
6124                vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
6125                vmcs_write64(VMCS_LINK_POINTER, -1ull);
6126        }
6127        kunmap(vmx->nested.current_vmcs12_page);
6128        nested_release_page(vmx->nested.current_vmcs12_page);
6129        vmx->nested.current_vmptr = -1ull;
6130        vmx->nested.current_vmcs12 = NULL;
6131}
6132
6133/*
6134 * Free whatever needs to be freed from vmx->nested when L1 goes down, or
6135 * just stops using VMX.
6136 */
6137static void free_nested(struct vcpu_vmx *vmx)
6138{
6139        if (!vmx->nested.vmxon)
6140                return;
6141
6142        vmx->nested.vmxon = false;
6143        nested_release_vmcs12(vmx);
6144        if (enable_shadow_vmcs)
6145                free_vmcs(vmx->nested.current_shadow_vmcs);
6146        /* Unpin physical memory we referred to in current vmcs02 */
6147        if (vmx->nested.apic_access_page) {
6148                nested_release_page(vmx->nested.apic_access_page);
6149                vmx->nested.apic_access_page = 0;
6150        }
6151
6152        nested_free_all_saved_vmcss(vmx);
6153}
6154
6155/* Emulate the VMXOFF instruction */
6156static int handle_vmoff(struct kvm_vcpu *vcpu)
6157{
6158        if (!nested_vmx_check_permission(vcpu))
6159                return 1;
6160        free_nested(to_vmx(vcpu));
6161        skip_emulated_instruction(vcpu);
6162        nested_vmx_succeed(vcpu);
6163        return 1;
6164}
6165
6166/* Emulate the VMCLEAR instruction */
6167static int handle_vmclear(struct kvm_vcpu *vcpu)
6168{
6169        struct vcpu_vmx *vmx = to_vmx(vcpu);
6170        gpa_t vmptr;
6171        struct vmcs12 *vmcs12;
6172        struct page *page;
6173
6174        if (!nested_vmx_check_permission(vcpu))
6175                return 1;
6176
6177        if (nested_vmx_check_vmptr(vcpu, EXIT_REASON_VMCLEAR, &vmptr))
6178                return 1;
6179
6180        if (vmptr == vmx->nested.current_vmptr)
6181                nested_release_vmcs12(vmx);
6182
6183        page = nested_get_page(vcpu, vmptr);
6184        if (page == NULL) {
6185                /*
6186                 * For accurate processor emulation, VMCLEAR beyond available
6187                 * physical memory should do nothing at all. However, it is
6188                 * possible that a nested vmx bug, not a guest hypervisor bug,
6189                 * resulted in this case, so let's shut down before doing any
6190                 * more damage:
6191                 */
6192                kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6193                return 1;
6194        }
6195        vmcs12 = kmap(page);
6196        vmcs12->launch_state = 0;
6197        kunmap(page);
6198        nested_release_page(page);
6199
6200        nested_free_vmcs02(vmx, vmptr);
6201
6202        skip_emulated_instruction(vcpu);
6203        nested_vmx_succeed(vcpu);
6204        return 1;
6205}
6206
6207static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
6208
6209/* Emulate the VMLAUNCH instruction */
6210static int handle_vmlaunch(struct kvm_vcpu *vcpu)
6211{
6212        return nested_vmx_run(vcpu, true);
6213}
6214
6215/* Emulate the VMRESUME instruction */
6216static int handle_vmresume(struct kvm_vcpu *vcpu)
6217{
6218
6219        return nested_vmx_run(vcpu, false);
6220}
6221
6222enum vmcs_field_type {
6223        VMCS_FIELD_TYPE_U16 = 0,
6224        VMCS_FIELD_TYPE_U64 = 1,
6225        VMCS_FIELD_TYPE_U32 = 2,
6226        VMCS_FIELD_TYPE_NATURAL_WIDTH = 3
6227};
6228
6229static inline int vmcs_field_type(unsigned long field)
6230{
6231        if (0x1 & field)        /* the *_HIGH fields are all 32 bit */
6232                return VMCS_FIELD_TYPE_U32;
6233        return (field >> 13) & 0x3 ;
6234}
6235
6236static inline int vmcs_field_readonly(unsigned long field)
6237{
6238        return (((field >> 10) & 0x3) == 1);
6239}
6240
6241/*
6242 * Read a vmcs12 field. Since these can have varying lengths and we return
6243 * one type, we chose the biggest type (u64) and zero-extend the return value
6244 * to that size. Note that the caller, handle_vmread, might need to use only
6245 * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
6246 * 64-bit fields are to be returned).
6247 */
6248static inline bool vmcs12_read_any(struct kvm_vcpu *vcpu,
6249                                        unsigned long field, u64 *ret)
6250{
6251        short offset = vmcs_field_to_offset(field);
6252        char *p;
6253
6254        if (offset < 0)
6255                return 0;
6256
6257        p = ((char *)(get_vmcs12(vcpu))) + offset;
6258
6259        switch (vmcs_field_type(field)) {
6260        case VMCS_FIELD_TYPE_NATURAL_WIDTH:
6261                *ret = *((natural_width *)p);
6262                return 1;
6263        case VMCS_FIELD_TYPE_U16:
6264                *ret = *((u16 *)p);
6265                return 1;
6266        case VMCS_FIELD_TYPE_U32:
6267                *ret = *((u32 *)p);
6268                return 1;
6269        case VMCS_FIELD_TYPE_U64:
6270                *ret = *((u64 *)p);
6271                return 1;
6272        default:
6273                return 0; /* can never happen. */
6274        }
6275}
6276
6277
6278static inline bool vmcs12_write_any(struct kvm_vcpu *vcpu,
6279                                    unsigned long field, u64 field_value){
6280        short offset = vmcs_field_to_offset(field);
6281        char *p = ((char *) get_vmcs12(vcpu)) + offset;
6282        if (offset < 0)
6283                return false;
6284
6285        switch (vmcs_field_type(field)) {
6286        case VMCS_FIELD_TYPE_U16:
6287                *(u16 *)p = field_value;
6288                return true;
6289        case VMCS_FIELD_TYPE_U32:
6290                *(u32 *)p = field_value;
6291                return true;
6292        case VMCS_FIELD_TYPE_U64:
6293                *(u64 *)p = field_value;
6294                return true;
6295        case VMCS_FIELD_TYPE_NATURAL_WIDTH:
6296                *(natural_width *)p = field_value;
6297                return true;
6298        default:
6299                return false; /* can never happen. */
6300        }
6301
6302}
6303
6304static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
6305{
6306        int i;
6307        unsigned long field;
6308        u64 field_value;
6309        struct vmcs *shadow_vmcs = vmx->nested.current_shadow_vmcs;
6310        const unsigned long *fields = shadow_read_write_fields;
6311        const int num_fields = max_shadow_read_write_fields;
6312
6313        vmcs_load(shadow_vmcs);
6314
6315        for (i = 0; i < num_fields; i++) {
6316                field = fields[i];
6317                switch (vmcs_field_type(field)) {
6318                case VMCS_FIELD_TYPE_U16:
6319                        field_value = vmcs_read16(field);
6320                        break;
6321                case VMCS_FIELD_TYPE_U32:
6322                        field_value = vmcs_read32(field);
6323                        break;
6324                case VMCS_FIELD_TYPE_U64:
6325                        field_value = vmcs_read64(field);
6326                        break;
6327                case VMCS_FIELD_TYPE_NATURAL_WIDTH:
6328                        field_value = vmcs_readl(field);
6329                        break;
6330                }
6331                vmcs12_write_any(&vmx->vcpu, field, field_value);
6332        }
6333
6334        vmcs_clear(shadow_vmcs);
6335        vmcs_load(vmx->loaded_vmcs->vmcs);
6336}
6337
6338static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
6339{
6340        const unsigned long *fields[] = {
6341                shadow_read_write_fields,
6342                shadow_read_only_fields
6343        };
6344        const int max_fields[] = {
6345                max_shadow_read_write_fields,
6346                max_shadow_read_only_fields
6347        };
6348        int i, q;
6349        unsigned long field;
6350        u64 field_value = 0;
6351        struct vmcs *shadow_vmcs = vmx->nested.current_shadow_vmcs;
6352
6353        vmcs_load(shadow_vmcs);
6354
6355        for (q = 0; q < ARRAY_SIZE(fields); q++) {
6356                for (i = 0; i < max_fields[q]; i++) {
6357                        field = fields[q][i];
6358                        vmcs12_read_any(&vmx->vcpu, field, &field_value);
6359
6360                        switch (vmcs_field_type(field)) {
6361                        case VMCS_FIELD_TYPE_U16:
6362                                vmcs_write16(field, (u16)field_value);
6363                                break;
6364                        case VMCS_FIELD_TYPE_U32:
6365                                vmcs_write32(field, (u32)field_value);
6366                                break;
6367                        case VMCS_FIELD_TYPE_U64:
6368                                vmcs_write64(field, (u64)field_value);
6369                                break;
6370                        case VMCS_FIELD_TYPE_NATURAL_WIDTH:
6371                                vmcs_writel(field, (long)field_value);
6372                                break;
6373                        }
6374                }
6375        }
6376
6377        vmcs_clear(shadow_vmcs);
6378        vmcs_load(vmx->loaded_vmcs->vmcs);
6379}
6380
6381/*
6382 * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
6383 * used before) all generate the same failure when it is missing.
6384 */
6385static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
6386{
6387        struct vcpu_vmx *vmx = to_vmx(vcpu);
6388        if (vmx->nested.current_vmptr == -1ull) {
6389                nested_vmx_failInvalid(vcpu);
6390                skip_emulated_instruction(vcpu);
6391                return 0;
6392        }
6393        return 1;
6394}
6395
6396static int handle_vmread(struct kvm_vcpu *vcpu)
6397{
6398        unsigned long field;
6399        u64 field_value;
6400        unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6401        u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
6402        gva_t gva = 0;
6403
6404        if (!nested_vmx_check_permission(vcpu) ||
6405            !nested_vmx_check_vmcs12(vcpu))
6406                return 1;
6407
6408        /* Decode instruction info and find the field to read */
6409        field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
6410        /* Read the field, zero-extended to a u64 field_value */
6411        if (!vmcs12_read_any(vcpu, field, &field_value)) {
6412                nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
6413                skip_emulated_instruction(vcpu);
6414                return 1;
6415        }
6416        /*
6417         * Now copy part of this value to register or memory, as requested.
6418         * Note that the number of bits actually copied is 32 or 64 depending
6419         * on the guest's mode (32 or 64 bit), not on the given field's length.
6420         */
6421        if (vmx_instruction_info & (1u << 10)) {
6422                kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
6423                        field_value);
6424        } else {
6425                if (get_vmx_mem_address(vcpu, exit_qualification,
6426                                vmx_instruction_info, &gva))
6427                        return 1;
6428                /* _system ok, as nested_vmx_check_permission verified cpl=0 */
6429                kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
6430                             &field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
6431        }
6432
6433        nested_vmx_succeed(vcpu);
6434        skip_emulated_instruction(vcpu);
6435        return 1;
6436}
6437
6438
6439static int handle_vmwrite(struct kvm_vcpu *vcpu)
6440{
6441        unsigned long field;
6442        gva_t gva;
6443        unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6444        u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
6445        /* The value to write might be 32 or 64 bits, depending on L1's long
6446         * mode, and eventually we need to write that into a field of several
6447         * possible lengths. The code below first zero-extends the value to 64
6448         * bit (field_value), and then copies only the approriate number of
6449         * bits into the vmcs12 field.
6450         */
6451        u64 field_value = 0;
6452        struct x86_exception e;
6453
6454        if (!nested_vmx_check_permission(vcpu) ||
6455            !nested_vmx_check_vmcs12(vcpu))
6456                return 1;
6457
6458        if (vmx_instruction_info & (1u << 10))
6459                field_value = kvm_register_readl(vcpu,
6460                        (((vmx_instruction_info) >> 3) & 0xf));
6461        else {
6462                if (get_vmx_mem_address(vcpu, exit_qualification,
6463                                vmx_instruction_info, &gva))
6464                        return 1;
6465                if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva,
6466                           &field_value, (is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
6467                        kvm_inject_page_fault(vcpu, &e);
6468                        return 1;
6469                }
6470        }
6471
6472
6473        field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
6474        if (vmcs_field_readonly(field)) {
6475                nested_vmx_failValid(vcpu,
6476                        VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
6477                skip_emulated_instruction(vcpu);
6478                return 1;
6479        }
6480
6481        if (!vmcs12_write_any(vcpu, field, field_value)) {
6482                nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
6483                skip_emulated_instruction(vcpu);
6484                return 1;
6485        }
6486
6487        nested_vmx_succeed(vcpu);
6488        skip_emulated_instruction(vcpu);
6489        return 1;
6490}
6491
6492/* Emulate the VMPTRLD instruction */
6493static int handle_vmptrld(struct kvm_vcpu *vcpu)
6494{
6495        struct vcpu_vmx *vmx = to_vmx(vcpu);
6496        gpa_t vmptr;
6497        u32 exec_control;
6498
6499        if (!nested_vmx_check_permission(vcpu))
6500                return 1;
6501
6502        if (nested_vmx_check_vmptr(vcpu, EXIT_REASON_VMPTRLD, &vmptr))
6503                return 1;
6504
6505        if (vmx->nested.current_vmptr != vmptr) {
6506                struct vmcs12 *new_vmcs12;
6507                struct page *page;
6508                page = nested_get_page(vcpu, vmptr);
6509                if (page == NULL) {
6510                        nested_vmx_failInvalid(vcpu);
6511                        skip_emulated_instruction(vcpu);
6512                        return 1;
6513                }
6514                new_vmcs12 = kmap(page);
6515                if (new_vmcs12->revision_id != VMCS12_REVISION) {
6516                        kunmap(page);
6517                        nested_release_page_clean(page);
6518                        nested_vmx_failValid(vcpu,
6519                                VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
6520                        skip_emulated_instruction(vcpu);
6521                        return 1;
6522                }
6523
6524                nested_release_vmcs12(vmx);
6525                vmx->nested.current_vmptr = vmptr;
6526                vmx->nested.current_vmcs12 = new_vmcs12;
6527                vmx->nested.current_vmcs12_page = page;
6528                if (enable_shadow_vmcs) {
6529                        exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6530                        exec_control |= SECONDARY_EXEC_SHADOW_VMCS;
6531                        vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
6532                        vmcs_write64(VMCS_LINK_POINTER,
6533                                     __pa(vmx->nested.current_shadow_vmcs));
6534                        vmx->nested.sync_shadow_vmcs = true;
6535                }
6536        }
6537
6538        nested_vmx_succeed(vcpu);
6539        skip_emulated_instruction(vcpu);
6540        return 1;
6541}
6542
6543/* Emulate the VMPTRST instruction */
6544static int handle_vmptrst(struct kvm_vcpu *vcpu)
6545{
6546        unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6547        u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
6548        gva_t vmcs_gva;
6549        struct x86_exception e;
6550
6551        if (!nested_vmx_check_permission(vcpu))
6552                return 1;
6553
6554        if (get_vmx_mem_address(vcpu, exit_qualification,
6555                        vmx_instruction_info, &vmcs_gva))
6556                return 1;
6557        /* ok to use *_system, as nested_vmx_check_permission verified cpl=0 */
6558        if (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva,
6559                                 (void *)&to_vmx(vcpu)->nested.current_vmptr,
6560                                 sizeof(u64), &e)) {
6561                kvm_inject_page_fault(vcpu, &e);
6562                return 1;
6563        }
6564        nested_vmx_succeed(vcpu);
6565        skip_emulated_instruction(vcpu);
6566        return 1;
6567}
6568
6569/* Emulate the INVEPT instruction */
6570static int handle_invept(struct kvm_vcpu *vcpu)
6571{
6572        u32 vmx_instruction_info, types;
6573        unsigned long type;
6574        gva_t gva;
6575        struct x86_exception e;
6576        struct {
6577                u64 eptp, gpa;
6578        } operand;
6579
6580        if (!(nested_vmx_secondary_ctls_high & SECONDARY_EXEC_ENABLE_EPT) ||
6581            !(nested_vmx_ept_caps & VMX_EPT_INVEPT_BIT)) {
6582                kvm_queue_exception(vcpu, UD_VECTOR);
6583                return 1;
6584        }
6585
6586        if (!nested_vmx_check_permission(vcpu))
6587                return 1;
6588
6589        if (!kvm_read_cr0_bits(vcpu, X86_CR0_PE)) {
6590                kvm_queue_exception(vcpu, UD_VECTOR);
6591                return 1;
6592        }
6593
6594        vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
6595        type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
6596
6597        types = (nested_vmx_ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
6598
6599        if (!(types & (1UL << type))) {
6600                nested_vmx_failValid(vcpu,
6601                                VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
6602                return 1;
6603        }
6604
6605        /* According to the Intel VMX instruction reference, the memory
6606         * operand is read even if it isn't needed (e.g., for type==global)
6607         */
6608        if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
6609                        vmx_instruction_info, &gva))
6610                return 1;
6611        if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand,
6612                                sizeof(operand), &e)) {
6613                kvm_inject_page_fault(vcpu, &e);
6614                return 1;
6615        }
6616
6617        switch (type) {
6618        case VMX_EPT_EXTENT_GLOBAL:
6619                kvm_mmu_sync_roots(vcpu);
6620                kvm_mmu_flush_tlb(vcpu);
6621                nested_vmx_succeed(vcpu);
6622                break;
6623        default:
6624                /* Trap single context invalidation invept calls */
6625                BUG_ON(1);
6626                break;
6627        }
6628
6629        skip_emulated_instruction(vcpu);
6630        return 1;
6631}
6632
6633/*
6634 * The exit handlers return 1 if the exit was handled fully and guest execution
6635 * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
6636 * to be done to userspace and return 0.
6637 */
6638static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
6639        [EXIT_REASON_EXCEPTION_NMI]           = handle_exception,
6640        [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
6641        [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
6642        [EXIT_REASON_NMI_WINDOW]              = handle_nmi_window,
6643        [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
6644        [EXIT_REASON_CR_ACCESS]               = handle_cr,
6645        [EXIT_REASON_DR_ACCESS]               = handle_dr,
6646        [EXIT_REASON_CPUID]                   = handle_cpuid,
6647        [EXIT_REASON_MSR_READ]                = handle_rdmsr,
6648        [EXIT_REASON_MSR_WRITE]               = handle_wrmsr,
6649        [EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
6650        [EXIT_REASON_HLT]                     = handle_halt,
6651        [EXIT_REASON_INVD]                    = handle_invd,
6652        [EXIT_REASON_INVLPG]                  = handle_invlpg,
6653        [EXIT_REASON_RDPMC]                   = handle_rdpmc,
6654        [EXIT_REASON_VMCALL]                  = handle_vmcall,
6655        [EXIT_REASON_VMCLEAR]                 = handle_vmclear,
6656        [EXIT_REASON_VMLAUNCH]                = handle_vmlaunch,
6657        [EXIT_REASON_VMPTRLD]                 = handle_vmptrld,
6658        [EXIT_REASON_VMPTRST]                 = handle_vmptrst,
6659        [EXIT_REASON_VMREAD]                  = handle_vmread,
6660        [EXIT_REASON_VMRESUME]                = handle_vmresume,
6661        [EXIT_REASON_VMWRITE]                 = handle_vmwrite,
6662        [EXIT_REASON_VMOFF]                   = handle_vmoff,
6663        [EXIT_REASON_VMON]                    = handle_vmon,
6664        [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
6665        [EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
6666        [EXIT_REASON_APIC_WRITE]              = handle_apic_write,
6667        [EXIT_REASON_EOI_INDUCED]             = handle_apic_eoi_induced,
6668        [EXIT_REASON_WBINVD]                  = handle_wbinvd,
6669        [EXIT_REASON_XSETBV]                  = handle_xsetbv,
6670        [EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
6671        [EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
6672        [EXIT_REASON_EPT_VIOLATION]           = handle_ept_violation,
6673        [EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
6674        [EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
6675        [EXIT_REASON_MWAIT_INSTRUCTION]       = handle_mwait,
6676        [EXIT_REASON_MONITOR_INSTRUCTION]     = handle_monitor,
6677        [EXIT_REASON_INVEPT]                  = handle_invept,
6678};
6679
6680static const int kvm_vmx_max_exit_handlers =
6681        ARRAY_SIZE(kvm_vmx_exit_handlers);
6682
6683static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
6684                                       struct vmcs12 *vmcs12)
6685{
6686        unsigned long exit_qualification;
6687        gpa_t bitmap, last_bitmap;
6688        unsigned int port;
6689        int size;
6690        u8 b;
6691
6692        if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
6693                return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
6694
6695        exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6696
6697        port = exit_qualification >> 16;
6698        size = (exit_qualification & 7) + 1;
6699
6700        last_bitmap = (gpa_t)-1;
6701        b = -1;
6702
6703        while (size > 0) {
6704                if (port < 0x8000)
6705                        bitmap = vmcs12->io_bitmap_a;
6706                else if (port < 0x10000)
6707                        bitmap = vmcs12->io_bitmap_b;
6708                else
6709                        return 1;
6710                bitmap += (port & 0x7fff) / 8;
6711
6712                if (last_bitmap != bitmap)
6713                        if (kvm_read_guest(vcpu->kvm, bitmap, &b, 1))
6714                                return 1;
6715                if (b & (1 << (port & 7)))
6716                        return 1;
6717
6718                port++;
6719                size--;
6720                last_bitmap = bitmap;
6721        }
6722
6723        return 0;
6724}
6725
6726/*
6727 * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
6728 * rather than handle it ourselves in L0. I.e., check whether L1 expressed
6729 * disinterest in the current event (read or write a specific MSR) by using an
6730 * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
6731 */
6732static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
6733        struct vmcs12 *vmcs12, u32 exit_reason)
6734{
6735        u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
6736        gpa_t bitmap;
6737
6738        if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
6739                return 1;
6740
6741        /*
6742         * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
6743         * for the four combinations of read/write and low/high MSR numbers.
6744         * First we need to figure out which of the four to use:
6745         */
6746        bitmap = vmcs12->msr_bitmap;
6747        if (exit_reason == EXIT_REASON_MSR_WRITE)
6748                bitmap += 2048;
6749        if (msr_index >= 0xc0000000) {
6750                msr_index -= 0xc0000000;
6751                bitmap += 1024;
6752        }
6753
6754        /* Then read the msr_index'th bit from this bitmap: */
6755        if (msr_index < 1024*8) {
6756                unsigned char b;
6757                if (kvm_read_guest(vcpu->kvm, bitmap + msr_index/8, &b, 1))
6758                        return 1;
6759                return 1 & (b >> (msr_index & 7));
6760        } else
6761                return 1; /* let L1 handle the wrong parameter */
6762}
6763
6764/*
6765 * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
6766 * rather than handle it ourselves in L0. I.e., check if L1 wanted to
6767 * intercept (via guest_host_mask etc.) the current event.
6768 */
6769static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
6770        struct vmcs12 *vmcs12)
6771{
6772        unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6773        int cr = exit_qualification & 15;
6774        int reg = (exit_qualification >> 8) & 15;
6775        unsigned long val = kvm_register_readl(vcpu, reg);
6776
6777        switch ((exit_qualification >> 4) & 3) {
6778        case 0: /* mov to cr */
6779                switch (cr) {
6780                case 0:
6781                        if (vmcs12->cr0_guest_host_mask &
6782                            (val ^ vmcs12->cr0_read_shadow))
6783                                return 1;
6784                        break;
6785                case 3:
6786                        if ((vmcs12->cr3_target_count >= 1 &&
6787                                        vmcs12->cr3_target_value0 == val) ||
6788                                (vmcs12->cr3_target_count >= 2 &&
6789                                        vmcs12->cr3_target_value1 == val) ||
6790                                (vmcs12->cr3_target_count >= 3 &&
6791                                        vmcs12->cr3_target_value2 == val) ||
6792                                (vmcs12->cr3_target_count >= 4 &&
6793                                        vmcs12->cr3_target_value3 == val))
6794                                return 0;
6795                        if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
6796                                return 1;
6797                        break;
6798                case 4:
6799                        if (vmcs12->cr4_guest_host_mask &
6800                            (vmcs12->cr4_read_shadow ^ val))
6801                                return 1;
6802                        break;
6803                case 8:
6804                        if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
6805                                return 1;
6806                        break;
6807                }
6808                break;
6809        case 2: /* clts */
6810                if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
6811                    (vmcs12->cr0_read_shadow & X86_CR0_TS))
6812                        return 1;
6813                break;
6814        case 1: /* mov from cr */
6815                switch (cr) {
6816                case 3:
6817                        if (vmcs12->cpu_based_vm_exec_control &
6818                            CPU_BASED_CR3_STORE_EXITING)
6819                                return 1;
6820                        break;
6821                case 8:
6822                        if (vmcs12->cpu_based_vm_exec_control &
6823                            CPU_BASED_CR8_STORE_EXITING)
6824                                return 1;
6825                        break;
6826                }
6827                break;
6828        case 3: /* lmsw */
6829                /*
6830                 * lmsw can change bits 1..3 of cr0, and only set bit 0 of
6831                 * cr0. Other attempted changes are ignored, with no exit.
6832                 */
6833                if (vmcs12->cr0_guest_host_mask & 0xe &
6834                    (val ^ vmcs12->cr0_read_shadow))
6835                        return 1;
6836                if ((vmcs12->cr0_guest_host_mask & 0x1) &&
6837                    !(vmcs12->cr0_read_shadow & 0x1) &&
6838                    (val & 0x1))
6839                        return 1;
6840                break;
6841        }
6842        return 0;
6843}
6844
6845/*
6846 * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
6847 * should handle it ourselves in L0 (and then continue L2). Only call this
6848 * when in is_guest_mode (L2).
6849 */
6850static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu)
6851{
6852        u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6853        struct vcpu_vmx *vmx = to_vmx(vcpu);
6854        struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6855        u32 exit_reason = vmx->exit_reason;
6856
6857        trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
6858                                vmcs_readl(EXIT_QUALIFICATION),
6859                                vmx->idt_vectoring_info,
6860                                intr_info,
6861                                vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
6862                                KVM_ISA_VMX);
6863
6864        if (vmx->nested.nested_run_pending)
6865                return 0;
6866
6867        if (unlikely(vmx->fail)) {
6868                pr_info_ratelimited("%s failed vm entry %x\n", __func__,
6869                                    vmcs_read32(VM_INSTRUCTION_ERROR));
6870                return 1;
6871        }
6872
6873        switch (exit_reason) {
6874        case EXIT_REASON_EXCEPTION_NMI:
6875                if (!is_exception(intr_info))
6876                        return 0;
6877                else if (is_page_fault(intr_info))
6878                        return enable_ept;
6879                else if (is_no_device(intr_info) &&
6880                         !(vmcs12->guest_cr0 & X86_CR0_TS))
6881                        return 0;
6882                return vmcs12->exception_bitmap &
6883                                (1u << (intr_info & INTR_INFO_VECTOR_MASK));
6884        case EXIT_REASON_EXTERNAL_INTERRUPT:
6885                return 0;
6886        case EXIT_REASON_TRIPLE_FAULT:
6887                return 1;
6888        case EXIT_REASON_PENDING_INTERRUPT:
6889                return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
6890        case EXIT_REASON_NMI_WINDOW:
6891                return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
6892        case EXIT_REASON_TASK_SWITCH:
6893                return 1;
6894        case EXIT_REASON_CPUID:
6895                return 1;
6896        case EXIT_REASON_HLT:
6897                return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
6898        case EXIT_REASON_INVD:
6899                return 1;
6900        case EXIT_REASON_INVLPG:
6901                return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
6902        case EXIT_REASON_RDPMC:
6903                return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
6904        case EXIT_REASON_RDTSC:
6905                return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
6906        case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
6907        case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
6908        case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
6909        case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
6910        case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
6911        case EXIT_REASON_INVEPT:
6912                /*
6913                 * VMX instructions trap unconditionally. This allows L1 to
6914                 * emulate them for its L2 guest, i.e., allows 3-level nesting!
6915                 */
6916                return 1;
6917        case EXIT_REASON_CR_ACCESS:
6918                return nested_vmx_exit_handled_cr(vcpu, vmcs12);
6919        case EXIT_REASON_DR_ACCESS:
6920                return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
6921        case EXIT_REASON_IO_INSTRUCTION:
6922                return nested_vmx_exit_handled_io(vcpu, vmcs12);
6923        case EXIT_REASON_MSR_READ:
6924        case EXIT_REASON_MSR_WRITE:
6925                return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
6926        case EXIT_REASON_INVALID_STATE:
6927                return 1;
6928        case EXIT_REASON_MWAIT_INSTRUCTION:
6929                return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
6930        case EXIT_REASON_MONITOR_INSTRUCTION:
6931                return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
6932        case EXIT_REASON_PAUSE_INSTRUCTION:
6933                return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
6934                        nested_cpu_has2(vmcs12,
6935                                SECONDARY_EXEC_PAUSE_LOOP_EXITING);
6936        case EXIT_REASON_MCE_DURING_VMENTRY:
6937                return 0;
6938        case EXIT_REASON_TPR_BELOW_THRESHOLD:
6939                return 1;
6940        case EXIT_REASON_APIC_ACCESS:
6941                return nested_cpu_has2(vmcs12,
6942                        SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
6943        case EXIT_REASON_EPT_VIOLATION:
6944                /*
6945                 * L0 always deals with the EPT violation. If nested EPT is
6946                 * used, and the nested mmu code discovers that the address is
6947                 * missing in the guest EPT table (EPT12), the EPT violation
6948                 * will be injected with nested_ept_inject_page_fault()
6949                 */
6950                return 0;
6951        case EXIT_REASON_EPT_MISCONFIG:
6952                /*
6953                 * L2 never uses directly L1's EPT, but rather L0's own EPT
6954                 * table (shadow on EPT) or a merged EPT table that L0 built
6955                 * (EPT on EPT). So any problems with the structure of the
6956                 * table is L0's fault.
6957                 */
6958                return 0;
6959        case EXIT_REASON_WBINVD:
6960                return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
6961        case EXIT_REASON_XSETBV:
6962                return 1;
6963        default:
6964                return 1;
6965        }
6966}
6967
6968static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
6969{
6970        *info1 = vmcs_readl(EXIT_QUALIFICATION);
6971        *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
6972}
6973
6974/*
6975 * The guest has exited.  See if we can fix it or if we need userspace
6976 * assistance.
6977 */
6978static int vmx_handle_exit(struct kvm_vcpu *vcpu)
6979{
6980        struct vcpu_vmx *vmx = to_vmx(vcpu);
6981        u32 exit_reason = vmx->exit_reason;
6982        u32 vectoring_info = vmx->idt_vectoring_info;
6983
6984        /* If guest state is invalid, start emulating */
6985        if (vmx->emulation_required)
6986                return handle_invalid_guest_state(vcpu);
6987
6988        if (is_guest_mode(vcpu) && nested_vmx_exit_handled(vcpu)) {
6989                nested_vmx_vmexit(vcpu, exit_reason,
6990                                  vmcs_read32(VM_EXIT_INTR_INFO),
6991                                  vmcs_readl(EXIT_QUALIFICATION));
6992                return 1;
6993        }
6994
6995        if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
6996                vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6997                vcpu->run->fail_entry.hardware_entry_failure_reason
6998                        = exit_reason;
6999                return 0;
7000        }
7001
7002        if (unlikely(vmx->fail)) {
7003                vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
7004                vcpu->run->fail_entry.hardware_entry_failure_reason
7005                        = vmcs_read32(VM_INSTRUCTION_ERROR);
7006                return 0;
7007        }
7008
7009        /*
7010         * Note:
7011         * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
7012         * delivery event since it indicates guest is accessing MMIO.
7013         * The vm-exit can be triggered again after return to guest that
7014         * will cause infinite loop.
7015         */
7016        if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
7017                        (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
7018                        exit_reason != EXIT_REASON_EPT_VIOLATION &&
7019                        exit_reason != EXIT_REASON_TASK_SWITCH)) {
7020                vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7021                vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
7022                vcpu->run->internal.ndata = 2;
7023                vcpu->run->internal.data[0] = vectoring_info;
7024                vcpu->run->internal.data[1] = exit_reason;
7025                return 0;
7026        }
7027
7028        if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked &&
7029            !(is_guest_mode(vcpu) && nested_cpu_has_virtual_nmis(
7030                                        get_vmcs12(vcpu))))) {
7031                if (vmx_interrupt_allowed(vcpu)) {
7032                        vmx->soft_vnmi_blocked = 0;
7033                } else if (vmx->vnmi_blocked_time > 1000000000LL &&
7034                           vcpu->arch.nmi_pending) {
7035                        /*
7036                         * This CPU don't support us in finding the end of an
7037                         * NMI-blocked window if the guest runs with IRQs
7038                         * disabled. So we pull the trigger after 1 s of
7039                         * futile waiting, but inform the user about this.
7040                         */
7041                        printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
7042                               "state on VCPU %d after 1 s timeout\n",
7043                               __func__, vcpu->vcpu_id);
7044                        vmx->soft_vnmi_blocked = 0;
7045                }
7046        }
7047
7048        if (exit_reason < kvm_vmx_max_exit_handlers
7049            && kvm_vmx_exit_handlers[exit_reason])
7050                return kvm_vmx_exit_handlers[exit_reason](vcpu);
7051        else {
7052                vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
7053                vcpu->run->hw.hardware_exit_reason = exit_reason;
7054        }
7055        return 0;
7056}
7057
7058static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
7059{
7060        if (irr == -1 || tpr < irr) {
7061                vmcs_write32(TPR_THRESHOLD, 0);
7062                return;
7063        }
7064
7065        vmcs_write32(TPR_THRESHOLD, irr);
7066}
7067
7068static void vmx_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
7069{
7070        u32 sec_exec_control;
7071
7072        /*
7073         * There is not point to enable virtualize x2apic without enable
7074         * apicv
7075         */
7076        if (!cpu_has_vmx_virtualize_x2apic_mode() ||
7077                                !vmx_vm_has_apicv(vcpu->kvm))
7078                return;
7079
7080        if (!vm_need_tpr_shadow(vcpu->kvm))
7081                return;
7082
7083        sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
7084
7085        if (set) {
7086                sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
7087                sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
7088        } else {
7089                sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
7090                sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
7091        }
7092        vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
7093
7094        vmx_set_msr_bitmap(vcpu);
7095}
7096
7097static void vmx_hwapic_isr_update(struct kvm *kvm, int isr)
7098{
7099        u16 status;
7100        u8 old;
7101
7102        if (!vmx_vm_has_apicv(kvm))
7103                return;
7104
7105        if (isr == -1)
7106                isr = 0;
7107
7108        status = vmcs_read16(GUEST_INTR_STATUS);
7109        old = status >> 8;
7110        if (isr != old) {
7111                status &= 0xff;
7112                status |= isr << 8;
7113                vmcs_write16(GUEST_INTR_STATUS, status);
7114        }
7115}
7116
7117static void vmx_set_rvi(int vector)
7118{
7119        u16 status;
7120        u8 old;
7121
7122        status = vmcs_read16(GUEST_INTR_STATUS);
7123        old = (u8)status & 0xff;
7124        if ((u8)vector != old) {
7125                status &= ~0xff;
7126                status |= (u8)vector;
7127                vmcs_write16(GUEST_INTR_STATUS, status);
7128        }
7129}
7130
7131static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
7132{
7133        if (max_irr == -1)
7134                return;
7135
7136        /*
7137         * If a vmexit is needed, vmx_check_nested_events handles it.
7138         */
7139        if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
7140                return;
7141
7142        if (!is_guest_mode(vcpu)) {
7143                vmx_set_rvi(max_irr);
7144                return;
7145        }
7146
7147        /*
7148         * Fall back to pre-APICv interrupt injection since L2
7149         * is run without virtual interrupt delivery.
7150         */
7151        if (!kvm_event_needs_reinjection(vcpu) &&
7152            vmx_interrupt_allowed(vcpu)) {
7153                kvm_queue_interrupt(vcpu, max_irr, false);
7154                vmx_inject_irq(vcpu);
7155        }
7156}
7157
7158static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
7159{
7160        if (!vmx_vm_has_apicv(vcpu->kvm))
7161                return;
7162
7163        vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
7164        vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
7165        vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
7166        vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
7167}
7168
7169static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
7170{
7171        u32 exit_intr_info;
7172
7173        if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
7174              || vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI))
7175                return;
7176
7177        vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
7178        exit_intr_info = vmx->exit_intr_info;
7179
7180        /* Handle machine checks before interrupts are enabled */
7181        if (is_machine_check(exit_intr_info))
7182                kvm_machine_check();
7183
7184        /* We need to handle NMIs before interrupts are enabled */
7185        if ((exit_intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR &&
7186            (exit_intr_info & INTR_INFO_VALID_MASK)) {
7187                kvm_before_handle_nmi(&vmx->vcpu);
7188                asm("int $2");
7189                kvm_after_handle_nmi(&vmx->vcpu);
7190        }
7191}
7192
7193static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
7194{
7195        u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
7196
7197        /*
7198         * If external interrupt exists, IF bit is set in rflags/eflags on the
7199         * interrupt stack frame, and interrupt will be enabled on a return
7200         * from interrupt handler.
7201         */
7202        if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
7203                        == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
7204                unsigned int vector;
7205                unsigned long entry;
7206                gate_desc *desc;
7207                struct vcpu_vmx *vmx = to_vmx(vcpu);
7208#ifdef CONFIG_X86_64
7209                unsigned long tmp;
7210#endif
7211
7212                vector =  exit_intr_info & INTR_INFO_VECTOR_MASK;
7213                desc = (gate_desc *)vmx->host_idt_base + vector;
7214                entry = gate_offset(*desc);
7215                asm volatile(
7216#ifdef CONFIG_X86_64
7217                        "mov %%" _ASM_SP ", %[sp]\n\t"
7218                        "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
7219                        "push $%c[ss]\n\t"
7220                        "push %[sp]\n\t"
7221#endif
7222                        "pushf\n\t"
7223                        "orl $0x200, (%%" _ASM_SP ")\n\t"
7224                        __ASM_SIZE(push) " $%c[cs]\n\t"
7225                        "call *%[entry]\n\t"
7226                        :
7227#ifdef CONFIG_X86_64
7228                        [sp]"=&r"(tmp)
7229#endif
7230                        :
7231                        [entry]"r"(entry),
7232                        [ss]"i"(__KERNEL_DS),
7233                        [cs]"i"(__KERNEL_CS)
7234                        );
7235        } else
7236                local_irq_enable();
7237}
7238
7239static bool vmx_mpx_supported(void)
7240{
7241        return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
7242                (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
7243}
7244
7245static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
7246{
7247        u32 exit_intr_info;
7248        bool unblock_nmi;
7249        u8 vector;
7250        bool idtv_info_valid;
7251
7252        idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
7253
7254        if (cpu_has_virtual_nmis()) {
7255                if (vmx->nmi_known_unmasked)
7256                        return;
7257                /*
7258                 * Can't use vmx->exit_intr_info since we're not sure what
7259                 * the exit reason is.
7260                 */
7261                exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
7262                unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
7263                vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
7264                /*
7265                 * SDM 3: 27.7.1.2 (September 2008)
7266                 * Re-set bit "block by NMI" before VM entry if vmexit caused by
7267                 * a guest IRET fault.
7268                 * SDM 3: 23.2.2 (September 2008)
7269                 * Bit 12 is undefined in any of the following cases:
7270                 *  If the VM exit sets the valid bit in the IDT-vectoring
7271                 *   information field.
7272                 *  If the VM exit is due to a double fault.
7273                 */
7274                if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
7275                    vector != DF_VECTOR && !idtv_info_valid)
7276                        vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
7277                                      GUEST_INTR_STATE_NMI);
7278                else
7279                        vmx->nmi_known_unmasked =
7280                                !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
7281                                  & GUEST_INTR_STATE_NMI);
7282        } else if (unlikely(vmx->soft_vnmi_blocked))
7283                vmx->vnmi_blocked_time +=
7284                        ktime_to_ns(ktime_sub(ktime_get(), vmx->entry_time));
7285}
7286
7287static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
7288                                      u32 idt_vectoring_info,
7289                                      int instr_len_field,
7290                                      int error_code_field)
7291{
7292        u8 vector;
7293        int type;
7294        bool idtv_info_valid;
7295
7296        idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
7297
7298        vcpu->arch.nmi_injected = false;
7299        kvm_clear_exception_queue(vcpu);
7300        kvm_clear_interrupt_queue(vcpu);
7301
7302        if (!idtv_info_valid)
7303                return;
7304
7305        kvm_make_request(KVM_REQ_EVENT, vcpu);
7306
7307        vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
7308        type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
7309
7310        switch (type) {
7311        case INTR_TYPE_NMI_INTR:
7312                vcpu->arch.nmi_injected = true;
7313                /*
7314                 * SDM 3: 27.7.1.2 (September 2008)
7315                 * Clear bit "block by NMI" before VM entry if a NMI
7316                 * delivery faulted.
7317                 */
7318                vmx_set_nmi_mask(vcpu, false);
7319                break;
7320        case INTR_TYPE_SOFT_EXCEPTION:
7321                vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
7322                /* fall through */
7323        case INTR_TYPE_HARD_EXCEPTION:
7324                if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
7325                        u32 err = vmcs_read32(error_code_field);
7326                        kvm_requeue_exception_e(vcpu, vector, err);
7327                } else
7328                        kvm_requeue_exception(vcpu, vector);
7329                break;
7330        case INTR_TYPE_SOFT_INTR:
7331                vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
7332                /* fall through */
7333        case INTR_TYPE_EXT_INTR:
7334                kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
7335                break;
7336        default:
7337                break;
7338        }
7339}
7340
7341static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
7342{
7343        __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
7344                                  VM_EXIT_INSTRUCTION_LEN,
7345                                  IDT_VECTORING_ERROR_CODE);
7346}
7347
7348static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
7349{
7350        __vmx_complete_interrupts(vcpu,
7351                                  vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
7352                                  VM_ENTRY_INSTRUCTION_LEN,
7353                                  VM_ENTRY_EXCEPTION_ERROR_CODE);
7354
7355        vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
7356}
7357
7358static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
7359{
7360        int i, nr_msrs;
7361        struct perf_guest_switch_msr *msrs;
7362
7363        msrs = perf_guest_get_msrs(&nr_msrs);
7364
7365        if (!msrs)
7366                return;
7367
7368        for (i = 0; i < nr_msrs; i++)
7369                if (msrs[i].host == msrs[i].guest)
7370                        clear_atomic_switch_msr(vmx, msrs[i].msr);
7371                else
7372                        add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
7373                                        msrs[i].host);
7374}
7375
7376static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
7377{
7378        struct vcpu_vmx *vmx = to_vmx(vcpu);
7379        unsigned long debugctlmsr;
7380
7381        /* Record the guest's net vcpu time for enforced NMI injections. */
7382        if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked))
7383                vmx->entry_time = ktime_get();
7384
7385        /* Don't enter VMX if guest state is invalid, let the exit handler
7386           start emulation until we arrive back to a valid state */
7387        if (vmx->emulation_required)
7388                return;
7389
7390        if (vmx->nested.sync_shadow_vmcs) {
7391                copy_vmcs12_to_shadow(vmx);
7392                vmx->nested.sync_shadow_vmcs = false;
7393        }
7394
7395        if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
7396                vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
7397        if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
7398                vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
7399
7400        /* When single-stepping over STI and MOV SS, we must clear the
7401         * corresponding interruptibility bits in the guest state. Otherwise
7402         * vmentry fails as it then expects bit 14 (BS) in pending debug
7403         * exceptions being set, but that's not correct for the guest debugging
7404         * case. */
7405        if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7406                vmx_set_interrupt_shadow(vcpu, 0);
7407
7408        atomic_switch_perf_msrs(vmx);
7409        debugctlmsr = get_debugctlmsr();
7410
7411        vmx->__launched = vmx->loaded_vmcs->launched;
7412        asm(
7413                /* Store host registers */
7414                "push %%" _ASM_DX "; push %%" _ASM_BP ";"
7415                "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
7416                "push %%" _ASM_CX " \n\t"
7417                "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
7418                "je 1f \n\t"
7419                "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
7420                __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
7421                "1: \n\t"
7422                /* Reload cr2 if changed */
7423                "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
7424                "mov %%cr2, %%" _ASM_DX " \n\t"
7425                "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
7426                "je 2f \n\t"
7427                "mov %%" _ASM_AX", %%cr2 \n\t"
7428                "2: \n\t"
7429                /* Check if vmlaunch of vmresume is needed */
7430                "cmpl $0, %c[launched](%0) \n\t"
7431                /* Load guest registers.  Don't clobber flags. */
7432                "mov %c[rax](%0), %%" _ASM_AX " \n\t"
7433                "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
7434                "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
7435                "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
7436                "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
7437                "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
7438#ifdef CONFIG_X86_64
7439                "mov %c[r8](%0),  %%r8  \n\t"
7440                "mov %c[r9](%0),  %%r9  \n\t"
7441                "mov %c[r10](%0), %%r10 \n\t"
7442                "mov %c[r11](%0), %%r11 \n\t"
7443                "mov %c[r12](%0), %%r12 \n\t"
7444                "mov %c[r13](%0), %%r13 \n\t"
7445                "mov %c[r14](%0), %%r14 \n\t"
7446                "mov %c[r15](%0), %%r15 \n\t"
7447#endif
7448                "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
7449
7450                /* Enter guest mode */
7451                "jne 1f \n\t"
7452                __ex(ASM_VMX_VMLAUNCH) "\n\t"
7453                "jmp 2f \n\t"
7454                "1: " __ex(ASM_VMX_VMRESUME) "\n\t"
7455                "2: "
7456                /* Save guest registers, load host registers, keep flags */
7457                "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
7458                "pop %0 \n\t"
7459                "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
7460                "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
7461                __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
7462                "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
7463                "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
7464                "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
7465                "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
7466#ifdef CONFIG_X86_64
7467                "mov %%r8,  %c[r8](%0) \n\t"
7468                "mov %%r9,  %c[r9](%0) \n\t"
7469                "mov %%r10, %c[r10](%0) \n\t"
7470                "mov %%r11, %c[r11](%0) \n\t"
7471                "mov %%r12, %c[r12](%0) \n\t"
7472                "mov %%r13, %c[r13](%0) \n\t"
7473                "mov %%r14, %c[r14](%0) \n\t"
7474                "mov %%r15, %c[r15](%0) \n\t"
7475#endif
7476                "mov %%cr2, %%" _ASM_AX "   \n\t"
7477                "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
7478
7479                "pop  %%" _ASM_BP "; pop  %%" _ASM_DX " \n\t"
7480                "setbe %c[fail](%0) \n\t"
7481                ".pushsection .rodata \n\t"
7482                ".global vmx_return \n\t"
7483                "vmx_return: " _ASM_PTR " 2b \n\t"
7484                ".popsection"
7485              : : "c"(vmx), "d"((unsigned long)HOST_RSP),
7486                [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
7487                [fail]"i"(offsetof(struct vcpu_vmx, fail)),
7488                [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
7489                [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
7490                [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
7491                [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
7492                [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
7493                [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
7494                [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
7495                [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
7496#ifdef CONFIG_X86_64
7497                [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
7498                [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
7499                [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
7500                [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
7501                [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
7502                [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
7503                [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
7504                [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
7505#endif
7506                [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
7507                [wordsize]"i"(sizeof(ulong))
7508              : "cc", "memory"
7509#ifdef CONFIG_X86_64
7510                , "rax", "rbx", "rdi", "rsi"
7511                , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
7512#else
7513                , "eax", "ebx", "edi", "esi"
7514#endif
7515              );
7516
7517        /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
7518        if (debugctlmsr)
7519                update_debugctlmsr(debugctlmsr);
7520
7521#ifndef CONFIG_X86_64
7522        /*
7523         * The sysexit path does not restore ds/es, so we must set them to
7524         * a reasonable value ourselves.
7525         *
7526         * We can't defer this to vmx_load_host_state() since that function
7527         * may be executed in interrupt context, which saves and restore segments
7528         * around it, nullifying its effect.
7529         */
7530        loadsegment(ds, __USER_DS);
7531        loadsegment(es, __USER_DS);
7532#endif
7533
7534        vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
7535                                  | (1 << VCPU_EXREG_RFLAGS)
7536                                  | (1 << VCPU_EXREG_PDPTR)
7537                                  | (1 << VCPU_EXREG_SEGMENTS)
7538                                  | (1 << VCPU_EXREG_CR3));
7539        vcpu->arch.regs_dirty = 0;
7540
7541        vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
7542
7543        vmx->loaded_vmcs->launched = 1;
7544
7545        vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
7546        trace_kvm_exit(vmx->exit_reason, vcpu, KVM_ISA_VMX);
7547
7548        /*
7549         * the KVM_REQ_EVENT optimization bit is only on for one entry, and if
7550         * we did not inject a still-pending event to L1 now because of
7551         * nested_run_pending, we need to re-enable this bit.
7552         */
7553        if (vmx->nested.nested_run_pending)
7554                kvm_make_request(KVM_REQ_EVENT, vcpu);
7555
7556        vmx->nested.nested_run_pending = 0;
7557
7558        vmx_complete_atomic_exit(vmx);
7559        vmx_recover_nmi_blocking(vmx);
7560        vmx_complete_interrupts(vmx);
7561}
7562
7563static void vmx_load_vmcs01(struct kvm_vcpu *vcpu)
7564{
7565        struct vcpu_vmx *vmx = to_vmx(vcpu);
7566        int cpu;
7567
7568        if (vmx->loaded_vmcs == &vmx->vmcs01)
7569                return;
7570
7571        cpu = get_cpu();
7572        vmx->loaded_vmcs = &vmx->vmcs01;
7573        vmx_vcpu_put(vcpu);
7574        vmx_vcpu_load(vcpu, cpu);
7575        vcpu->cpu = cpu;
7576        put_cpu();
7577}
7578
7579static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
7580{
7581        struct vcpu_vmx *vmx = to_vmx(vcpu);
7582
7583        free_vpid(vmx);
7584        leave_guest_mode(vcpu);
7585        vmx_load_vmcs01(vcpu);
7586        free_nested(vmx);
7587        free_loaded_vmcs(vmx->loaded_vmcs);
7588        kfree(vmx->guest_msrs);
7589        kvm_vcpu_uninit(vcpu);
7590        kmem_cache_free(kvm_vcpu_cache, vmx);
7591}
7592
7593static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
7594{
7595        int err;
7596        struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
7597        int cpu;
7598
7599        if (!vmx)
7600                return ERR_PTR(-ENOMEM);
7601
7602        allocate_vpid(vmx);
7603
7604        err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
7605        if (err)
7606                goto free_vcpu;
7607
7608        vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
7609        BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
7610                     > PAGE_SIZE);
7611
7612        err = -ENOMEM;
7613        if (!vmx->guest_msrs) {
7614                goto uninit_vcpu;
7615        }
7616
7617        vmx->loaded_vmcs = &vmx->vmcs01;
7618        vmx->loaded_vmcs->vmcs = alloc_vmcs();
7619        if (!vmx->loaded_vmcs->vmcs)
7620                goto free_msrs;
7621        if (!vmm_exclusive)
7622                kvm_cpu_vmxon(__pa(per_cpu(vmxarea, raw_smp_processor_id())));
7623        loaded_vmcs_init(vmx->loaded_vmcs);
7624        if (!vmm_exclusive)
7625                kvm_cpu_vmxoff();
7626
7627        cpu = get_cpu();
7628        vmx_vcpu_load(&vmx->vcpu, cpu);
7629        vmx->vcpu.cpu = cpu;
7630        err = vmx_vcpu_setup(vmx);
7631        vmx_vcpu_put(&vmx->vcpu);
7632        put_cpu();
7633        if (err)
7634                goto free_vmcs;
7635        if (vm_need_virtualize_apic_accesses(kvm)) {
7636                err = alloc_apic_access_page(kvm);
7637                if (err)
7638                        goto free_vmcs;
7639        }
7640
7641        if (enable_ept) {
7642                if (!kvm->arch.ept_identity_map_addr)
7643                        kvm->arch.ept_identity_map_addr =
7644                                VMX_EPT_IDENTITY_PAGETABLE_ADDR;
7645                err = -ENOMEM;
7646                if (alloc_identity_pagetable(kvm) != 0)
7647                        goto free_vmcs;
7648                if (!init_rmode_identity_map(kvm))
7649                        goto free_vmcs;
7650        }
7651
7652        vmx->nested.current_vmptr = -1ull;
7653        vmx->nested.current_vmcs12 = NULL;
7654
7655        return &vmx->vcpu;
7656
7657free_vmcs:
7658        free_loaded_vmcs(vmx->loaded_vmcs);
7659free_msrs:
7660        kfree(vmx->guest_msrs);
7661uninit_vcpu:
7662        kvm_vcpu_uninit(&vmx->vcpu);
7663free_vcpu:
7664        free_vpid(vmx);
7665        kmem_cache_free(kvm_vcpu_cache, vmx);
7666        return ERR_PTR(err);
7667}
7668
7669static void __init vmx_check_processor_compat(void *rtn)
7670{
7671        struct vmcs_config vmcs_conf;
7672
7673        *(int *)rtn = 0;
7674        if (setup_vmcs_config(&vmcs_conf) < 0)
7675                *(int *)rtn = -EIO;
7676        if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
7677                printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
7678                                smp_processor_id());
7679                *(int *)rtn = -EIO;
7680        }
7681}
7682
7683static int get_ept_level(void)
7684{
7685        return VMX_EPT_DEFAULT_GAW + 1;
7686}
7687
7688static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7689{
7690        u64 ret;
7691
7692        /* For VT-d and EPT combination
7693         * 1. MMIO: always map as UC
7694         * 2. EPT with VT-d:
7695         *   a. VT-d without snooping control feature: can't guarantee the
7696         *      result, try to trust guest.
7697         *   b. VT-d with snooping control feature: snooping control feature of
7698         *      VT-d engine can guarantee the cache correctness. Just set it
7699         *      to WB to keep consistent with host. So the same as item 3.
7700         * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
7701         *    consistent with host MTRR
7702         */
7703        if (is_mmio)
7704                ret = MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
7705        else if (kvm_arch_has_noncoherent_dma(vcpu->kvm))
7706                ret = kvm_get_guest_memory_type(vcpu, gfn) <<
7707                      VMX_EPT_MT_EPTE_SHIFT;
7708        else
7709                ret = (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT)
7710                        | VMX_EPT_IPAT_BIT;
7711
7712        return ret;
7713}
7714
7715static int vmx_get_lpage_level(void)
7716{
7717        if (enable_ept && !cpu_has_vmx_ept_1g_page())
7718                return PT_DIRECTORY_LEVEL;
7719        else
7720                /* For shadow and EPT supported 1GB page */
7721                return PT_PDPE_LEVEL;
7722}
7723
7724static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
7725{
7726        struct kvm_cpuid_entry2 *best;
7727        struct vcpu_vmx *vmx = to_vmx(vcpu);
7728        u32 exec_control;
7729
7730        vmx->rdtscp_enabled = false;
7731        if (vmx_rdtscp_supported()) {
7732                exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
7733                if (exec_control & SECONDARY_EXEC_RDTSCP) {
7734                        best = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
7735                        if (best && (best->edx & bit(X86_FEATURE_RDTSCP)))
7736                                vmx->rdtscp_enabled = true;
7737                        else {
7738                                exec_control &= ~SECONDARY_EXEC_RDTSCP;
7739                                vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
7740                                                exec_control);
7741                        }
7742                }
7743        }
7744
7745        /* Exposing INVPCID only when PCID is exposed */
7746        best = kvm_find_cpuid_entry(vcpu, 0x7, 0);
7747        if (vmx_invpcid_supported() &&
7748            best && (best->ebx & bit(X86_FEATURE_INVPCID)) &&
7749            guest_cpuid_has_pcid(vcpu)) {
7750                exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
7751                exec_control |= SECONDARY_EXEC_ENABLE_INVPCID;
7752                vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
7753                             exec_control);
7754        } else {
7755                if (cpu_has_secondary_exec_ctrls()) {
7756                        exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
7757                        exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
7758                        vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
7759                                     exec_control);
7760                }
7761                if (best)
7762                        best->ebx &= ~bit(X86_FEATURE_INVPCID);
7763        }
7764}
7765
7766static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
7767{
7768        if (func == 1 && nested)
7769                entry->ecx |= bit(X86_FEATURE_VMX);
7770}
7771
7772static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
7773                struct x86_exception *fault)
7774{
7775        struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7776        u32 exit_reason;
7777
7778        if (fault->error_code & PFERR_RSVD_MASK)
7779                exit_reason = EXIT_REASON_EPT_MISCONFIG;
7780        else
7781                exit_reason = EXIT_REASON_EPT_VIOLATION;
7782        nested_vmx_vmexit(vcpu, exit_reason, 0, vcpu->arch.exit_qualification);
7783        vmcs12->guest_physical_address = fault->address;
7784}
7785
7786/* Callbacks for nested_ept_init_mmu_context: */
7787
7788static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
7789{
7790        /* return the page table to be shadowed - in our case, EPT12 */
7791        return get_vmcs12(vcpu)->ept_pointer;
7792}
7793
7794static void nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
7795{
7796        kvm_init_shadow_ept_mmu(vcpu, &vcpu->arch.mmu,
7797                        nested_vmx_ept_caps & VMX_EPT_EXECUTE_ONLY_BIT);
7798
7799        vcpu->arch.mmu.set_cr3           = vmx_set_cr3;
7800        vcpu->arch.mmu.get_cr3           = nested_ept_get_cr3;
7801        vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
7802
7803        vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
7804}
7805
7806static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
7807{
7808        vcpu->arch.walk_mmu = &vcpu->arch.mmu;
7809}
7810
7811static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
7812                struct x86_exception *fault)
7813{
7814        struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7815
7816        WARN_ON(!is_guest_mode(vcpu));
7817
7818        /* TODO: also check PFEC_MATCH/MASK, not just EB.PF. */
7819        if (vmcs12->exception_bitmap & (1u << PF_VECTOR))
7820                nested_vmx_vmexit(vcpu, to_vmx(vcpu)->exit_reason,
7821                                  vmcs_read32(VM_EXIT_INTR_INFO),
7822                                  vmcs_readl(EXIT_QUALIFICATION));
7823        else
7824                kvm_inject_page_fault(vcpu, fault);
7825}
7826
7827static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
7828{
7829        u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
7830        struct vcpu_vmx *vmx = to_vmx(vcpu);
7831
7832        if (vcpu->arch.virtual_tsc_khz == 0)
7833                return;
7834
7835        /* Make sure short timeouts reliably trigger an immediate vmexit.
7836         * hrtimer_start does not guarantee this. */
7837        if (preemption_timeout <= 1) {
7838                vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
7839                return;
7840        }
7841
7842        preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
7843        preemption_timeout *= 1000000;
7844        do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
7845        hrtimer_start(&vmx->nested.preemption_timer,
7846                      ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
7847}
7848
7849/*
7850 * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
7851 * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
7852 * with L0's requirements for its guest (a.k.a. vmsc01), so we can run the L2
7853 * guest in a way that will both be appropriate to L1's requests, and our
7854 * needs. In addition to modifying the active vmcs (which is vmcs02), this
7855 * function also has additional necessary side-effects, like setting various
7856 * vcpu->arch fields.
7857 */
7858static void prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
7859{
7860        struct vcpu_vmx *vmx = to_vmx(vcpu);
7861        u32 exec_control;
7862
7863        vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
7864        vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
7865        vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
7866        vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
7867        vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
7868        vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
7869        vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
7870        vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
7871        vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
7872        vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
7873        vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
7874        vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
7875        vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
7876        vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
7877        vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
7878        vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
7879        vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
7880        vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
7881        vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
7882        vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
7883        vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
7884        vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
7885        vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
7886        vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
7887        vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
7888        vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
7889        vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
7890        vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
7891        vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
7892        vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
7893        vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
7894        vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
7895        vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
7896        vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
7897        vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
7898        vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
7899
7900        if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
7901                kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
7902                vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
7903        } else {
7904                kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
7905                vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
7906        }
7907        vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
7908                vmcs12->vm_entry_intr_info_field);
7909        vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
7910                vmcs12->vm_entry_exception_error_code);
7911        vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
7912                vmcs12->vm_entry_instruction_len);
7913        vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
7914                vmcs12->guest_interruptibility_info);
7915        vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
7916        vmx_set_rflags(vcpu, vmcs12->guest_rflags);
7917        vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
7918                vmcs12->guest_pending_dbg_exceptions);
7919        vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
7920        vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
7921
7922        vmcs_write64(VMCS_LINK_POINTER, -1ull);
7923
7924        exec_control = vmcs12->pin_based_vm_exec_control;
7925        exec_control |= vmcs_config.pin_based_exec_ctrl;
7926        exec_control &= ~(PIN_BASED_VMX_PREEMPTION_TIMER |
7927                          PIN_BASED_POSTED_INTR);
7928        vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
7929
7930        vmx->nested.preemption_timer_expired = false;
7931        if (nested_cpu_has_preemption_timer(vmcs12))
7932                vmx_start_preemption_timer(vcpu);
7933
7934        /*
7935         * Whether page-faults are trapped is determined by a combination of
7936         * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
7937         * If enable_ept, L0 doesn't care about page faults and we should
7938         * set all of these to L1's desires. However, if !enable_ept, L0 does
7939         * care about (at least some) page faults, and because it is not easy
7940         * (if at all possible?) to merge L0 and L1's desires, we simply ask
7941         * to exit on each and every L2 page fault. This is done by setting
7942         * MASK=MATCH=0 and (see below) EB.PF=1.
7943         * Note that below we don't need special code to set EB.PF beyond the
7944         * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
7945         * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
7946         * !enable_ept, EB.PF is 1, so the "or" will always be 1.
7947         *
7948         * A problem with this approach (when !enable_ept) is that L1 may be
7949         * injected with more page faults than it asked for. This could have
7950         * caused problems, but in practice existing hypervisors don't care.
7951         * To fix this, we will need to emulate the PFEC checking (on the L1
7952         * page tables), using walk_addr(), when injecting PFs to L1.
7953         */
7954        vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
7955                enable_ept ? vmcs12->page_fault_error_code_mask : 0);
7956        vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
7957                enable_ept ? vmcs12->page_fault_error_code_match : 0);
7958
7959        if (cpu_has_secondary_exec_ctrls()) {
7960                exec_control = vmx_secondary_exec_control(vmx);
7961                if (!vmx->rdtscp_enabled)
7962                        exec_control &= ~SECONDARY_EXEC_RDTSCP;
7963                /* Take the following fields only from vmcs12 */
7964                exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7965                                  SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
7966                                  SECONDARY_EXEC_APIC_REGISTER_VIRT);
7967                if (nested_cpu_has(vmcs12,
7968                                CPU_BASED_ACTIVATE_SECONDARY_CONTROLS))
7969                        exec_control |= vmcs12->secondary_vm_exec_control;
7970
7971                if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) {
7972                        /*
7973                         * Translate L1 physical address to host physical
7974                         * address for vmcs02. Keep the page pinned, so this
7975                         * physical address remains valid. We keep a reference
7976                         * to it so we can release it later.
7977                         */
7978                        if (vmx->nested.apic_access_page) /* shouldn't happen */
7979                                nested_release_page(vmx->nested.apic_access_page);
7980                        vmx->nested.apic_access_page =
7981                                nested_get_page(vcpu, vmcs12->apic_access_addr);
7982                        /*
7983                         * If translation failed, no matter: This feature asks
7984                         * to exit when accessing the given address, and if it
7985                         * can never be accessed, this feature won't do
7986                         * anything anyway.
7987                         */
7988                        if (!vmx->nested.apic_access_page)
7989                                exec_control &=
7990                                  ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
7991                        else
7992                                vmcs_write64(APIC_ACCESS_ADDR,
7993                                  page_to_phys(vmx->nested.apic_access_page));
7994                } else if (vm_need_virtualize_apic_accesses(vmx->vcpu.kvm)) {
7995                        exec_control |=
7996                                SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
7997                        vmcs_write64(APIC_ACCESS_ADDR,
7998                                page_to_phys(vcpu->kvm->arch.apic_access_page));
7999                }
8000
8001                vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
8002        }
8003
8004
8005        /*
8006         * Set host-state according to L0's settings (vmcs12 is irrelevant here)
8007         * Some constant fields are set here by vmx_set_constant_host_state().
8008         * Other fields are different per CPU, and will be set later when
8009         * vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
8010         */
8011        vmx_set_constant_host_state(vmx);
8012
8013        /*
8014         * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
8015         * entry, but only if the current (host) sp changed from the value
8016         * we wrote last (vmx->host_rsp). This cache is no longer relevant
8017         * if we switch vmcs, and rather than hold a separate cache per vmcs,
8018         * here we just force the write to happen on entry.
8019         */
8020        vmx->host_rsp = 0;
8021
8022        exec_control = vmx_exec_control(vmx); /* L0's desires */
8023        exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
8024        exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
8025        exec_control &= ~CPU_BASED_TPR_SHADOW;
8026        exec_control |= vmcs12->cpu_based_vm_exec_control;
8027        /*
8028         * Merging of IO and MSR bitmaps not currently supported.
8029         * Rather, exit every time.
8030         */
8031        exec_control &= ~CPU_BASED_USE_MSR_BITMAPS;
8032        exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
8033        exec_control |= CPU_BASED_UNCOND_IO_EXITING;
8034
8035        vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
8036
8037        /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
8038         * bitwise-or of what L1 wants to trap for L2, and what we want to
8039         * trap. Note that CR0.TS also needs updating - we do this later.
8040         */
8041        update_exception_bitmap(vcpu);
8042        vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
8043        vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
8044
8045        /* L2->L1 exit controls are emulated - the hardware exit is to L0 so
8046         * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
8047         * bits are further modified by vmx_set_efer() below.
8048         */
8049        vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
8050
8051        /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
8052         * emulated by vmx_set_efer(), below.
8053         */
8054        vm_entry_controls_init(vmx, 
8055                (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
8056                        ~VM_ENTRY_IA32E_MODE) |
8057                (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
8058
8059        if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT) {
8060                vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
8061                vcpu->arch.pat = vmcs12->guest_ia32_pat;
8062        } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
8063                vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
8064
8065
8066        set_cr4_guest_host_mask(vmx);
8067
8068        if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)
8069                vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
8070
8071        if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
8072                vmcs_write64(TSC_OFFSET,
8073                        vmx->nested.vmcs01_tsc_offset + vmcs12->tsc_offset);
8074        else
8075                vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset);
8076
8077        if (enable_vpid) {
8078                /*
8079                 * Trivially support vpid by letting L2s share their parent
8080                 * L1's vpid. TODO: move to a more elaborate solution, giving
8081                 * each L2 its own vpid and exposing the vpid feature to L1.
8082                 */
8083                vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
8084                vmx_flush_tlb(vcpu);
8085        }
8086
8087        if (nested_cpu_has_ept(vmcs12)) {
8088                kvm_mmu_unload(vcpu);
8089                nested_ept_init_mmu_context(vcpu);
8090        }
8091
8092        if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)
8093                vcpu->arch.efer = vmcs12->guest_ia32_efer;
8094        else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
8095                vcpu->arch.efer |= (EFER_LMA | EFER_LME);
8096        else
8097                vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
8098        /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
8099        vmx_set_efer(vcpu, vcpu->arch.efer);
8100
8101        /*
8102         * This sets GUEST_CR0 to vmcs12->guest_cr0, with possibly a modified
8103         * TS bit (for lazy fpu) and bits which we consider mandatory enabled.
8104         * The CR0_READ_SHADOW is what L2 should have expected to read given
8105         * the specifications by L1; It's not enough to take
8106         * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
8107         * have more bits than L1 expected.
8108         */
8109        vmx_set_cr0(vcpu, vmcs12->guest_cr0);
8110        vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
8111
8112        vmx_set_cr4(vcpu, vmcs12->guest_cr4);
8113        vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
8114
8115        /* shadow page tables on either EPT or shadow page tables */
8116        kvm_set_cr3(vcpu, vmcs12->guest_cr3);
8117        kvm_mmu_reset_context(vcpu);
8118
8119        if (!enable_ept)
8120                vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
8121
8122        /*
8123         * L1 may access the L2's PDPTR, so save them to construct vmcs12
8124         */
8125        if (enable_ept) {
8126                vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
8127                vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
8128                vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
8129                vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
8130        }
8131
8132        kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
8133        kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
8134}
8135
8136/*
8137 * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
8138 * for running an L2 nested guest.
8139 */
8140static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
8141{
8142        struct vmcs12 *vmcs12;
8143        struct vcpu_vmx *vmx = to_vmx(vcpu);
8144        int cpu;
8145        struct loaded_vmcs *vmcs02;
8146        bool ia32e;
8147
8148        if (!nested_vmx_check_permission(vcpu) ||
8149            !nested_vmx_check_vmcs12(vcpu))
8150                return 1;
8151
8152        skip_emulated_instruction(vcpu);
8153        vmcs12 = get_vmcs12(vcpu);
8154
8155        if (enable_shadow_vmcs)
8156                copy_shadow_to_vmcs12(vmx);
8157
8158        /*
8159         * The nested entry process starts with enforcing various prerequisites
8160         * on vmcs12 as required by the Intel SDM, and act appropriately when
8161         * they fail: As the SDM explains, some conditions should cause the
8162         * instruction to fail, while others will cause the instruction to seem
8163         * to succeed, but return an EXIT_REASON_INVALID_STATE.
8164         * To speed up the normal (success) code path, we should avoid checking
8165         * for misconfigurations which will anyway be caught by the processor
8166         * when using the merged vmcs02.
8167         */
8168        if (vmcs12->launch_state == launch) {
8169                nested_vmx_failValid(vcpu,
8170                        launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
8171                               : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
8172                return 1;
8173        }
8174
8175        if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
8176            vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT) {
8177                nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
8178                return 1;
8179        }
8180
8181        if ((vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_MSR_BITMAPS) &&
8182                        !PAGE_ALIGNED(vmcs12->msr_bitmap)) {
8183                /*TODO: Also verify bits beyond physical address width are 0*/
8184                nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
8185                return 1;
8186        }
8187
8188        if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
8189                        !PAGE_ALIGNED(vmcs12->apic_access_addr)) {
8190                /*TODO: Also verify bits beyond physical address width are 0*/
8191                nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
8192                return 1;
8193        }
8194
8195        if (vmcs12->vm_entry_msr_load_count > 0 ||
8196            vmcs12->vm_exit_msr_load_count > 0 ||
8197            vmcs12->vm_exit_msr_store_count > 0) {
8198                pr_warn_ratelimited("%s: VMCS MSR_{LOAD,STORE} unsupported\n",
8199                                    __func__);
8200                nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
8201                return 1;
8202        }
8203
8204        if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
8205                                nested_vmx_true_procbased_ctls_low,
8206                                nested_vmx_procbased_ctls_high) ||
8207            !vmx_control_verify(vmcs12->secondary_vm_exec_control,
8208              nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high) ||
8209            !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
8210              nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high) ||
8211            !vmx_control_verify(vmcs12->vm_exit_controls,
8212                                nested_vmx_true_exit_ctls_low,
8213                                nested_vmx_exit_ctls_high) ||
8214            !vmx_control_verify(vmcs12->vm_entry_controls,
8215                                nested_vmx_true_entry_ctls_low,
8216                                nested_vmx_entry_ctls_high))
8217        {
8218                nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
8219                return 1;
8220        }
8221
8222        if (((vmcs12->host_cr0 & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON) ||
8223            ((vmcs12->host_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
8224                nested_vmx_failValid(vcpu,
8225                        VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
8226                return 1;
8227        }
8228
8229        if (!nested_cr0_valid(vmcs12, vmcs12->guest_cr0) ||
8230            ((vmcs12->guest_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
8231                nested_vmx_entry_failure(vcpu, vmcs12,
8232                        EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
8233                return 1;
8234        }
8235        if (vmcs12->vmcs_link_pointer != -1ull) {
8236                nested_vmx_entry_failure(vcpu, vmcs12,
8237                        EXIT_REASON_INVALID_STATE, ENTRY_FAIL_VMCS_LINK_PTR);
8238                return 1;
8239        }
8240
8241        /*
8242         * If the load IA32_EFER VM-entry control is 1, the following checks
8243         * are performed on the field for the IA32_EFER MSR:
8244         * - Bits reserved in the IA32_EFER MSR must be 0.
8245         * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
8246         *   the IA-32e mode guest VM-exit control. It must also be identical
8247         *   to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
8248         *   CR0.PG) is 1.
8249         */
8250        if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER) {
8251                ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
8252                if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
8253                    ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
8254                    ((vmcs12->guest_cr0 & X86_CR0_PG) &&
8255                     ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME))) {
8256                        nested_vmx_entry_failure(vcpu, vmcs12,
8257                                EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
8258                        return 1;
8259                }
8260        }
8261
8262        /*
8263         * If the load IA32_EFER VM-exit control is 1, bits reserved in the
8264         * IA32_EFER MSR must be 0 in the field for that register. In addition,
8265         * the values of the LMA and LME bits in the field must each be that of
8266         * the host address-space size VM-exit control.
8267         */
8268        if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
8269                ia32e = (vmcs12->vm_exit_controls &
8270                         VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
8271                if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
8272                    ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
8273                    ia32e != !!(vmcs12->host_ia32_efer & EFER_LME)) {
8274                        nested_vmx_entry_failure(vcpu, vmcs12,
8275                                EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
8276                        return 1;
8277                }
8278        }
8279
8280        /*
8281         * We're finally done with prerequisite checking, and can start with
8282         * the nested entry.
8283         */
8284
8285        vmcs02 = nested_get_current_vmcs02(vmx);
8286        if (!vmcs02)
8287                return -ENOMEM;
8288
8289        enter_guest_mode(vcpu);
8290
8291        vmx->nested.vmcs01_tsc_offset = vmcs_read64(TSC_OFFSET);
8292
8293        if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
8294                vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
8295
8296        cpu = get_cpu();
8297        vmx->loaded_vmcs = vmcs02;
8298        vmx_vcpu_put(vcpu);
8299        vmx_vcpu_load(vcpu, cpu);
8300        vcpu->cpu = cpu;
8301        put_cpu();
8302
8303        vmx_segment_cache_clear(vmx);
8304
8305        vmcs12->launch_state = 1;
8306
8307        prepare_vmcs02(vcpu, vmcs12);
8308
8309        if (vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT)
8310                return kvm_emulate_halt(vcpu);
8311
8312        vmx->nested.nested_run_pending = 1;
8313
8314        /*
8315         * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
8316         * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
8317         * returned as far as L1 is concerned. It will only return (and set
8318         * the success flag) when L2 exits (see nested_vmx_vmexit()).
8319         */
8320        return 1;
8321}
8322
8323/*
8324 * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
8325 * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
8326 * This function returns the new value we should put in vmcs12.guest_cr0.
8327 * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
8328 *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
8329 *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
8330 *     didn't trap the bit, because if L1 did, so would L0).
8331 *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
8332 *     been modified by L2, and L1 knows it. So just leave the old value of
8333 *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
8334 *     isn't relevant, because if L0 traps this bit it can set it to anything.
8335 *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
8336 *     changed these bits, and therefore they need to be updated, but L0
8337 *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
8338 *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
8339 */
8340static inline unsigned long
8341vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
8342{
8343        return
8344        /*1*/   (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
8345        /*2*/   (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
8346        /*3*/   (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
8347                        vcpu->arch.cr0_guest_owned_bits));
8348}
8349
8350static inline unsigned long
8351vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
8352{
8353        return
8354        /*1*/   (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
8355        /*2*/   (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
8356        /*3*/   (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
8357                        vcpu->arch.cr4_guest_owned_bits));
8358}
8359
8360static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
8361                                       struct vmcs12 *vmcs12)
8362{
8363        u32 idt_vectoring;
8364        unsigned int nr;
8365
8366        if (vcpu->arch.exception.pending && vcpu->arch.exception.reinject) {
8367                nr = vcpu->arch.exception.nr;
8368                idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
8369
8370                if (kvm_exception_is_soft(nr)) {
8371                        vmcs12->vm_exit_instruction_len =
8372                                vcpu->arch.event_exit_inst_len;
8373                        idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
8374                } else
8375                        idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
8376
8377                if (vcpu->arch.exception.has_error_code) {
8378                        idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
8379                        vmcs12->idt_vectoring_error_code =
8380                                vcpu->arch.exception.error_code;
8381                }
8382
8383                vmcs12->idt_vectoring_info_field = idt_vectoring;
8384        } else if (vcpu->arch.nmi_injected) {
8385                vmcs12->idt_vectoring_info_field =
8386                        INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
8387        } else if (vcpu->arch.interrupt.pending) {
8388                nr = vcpu->arch.interrupt.nr;
8389                idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
8390
8391                if (vcpu->arch.interrupt.soft) {
8392                        idt_vectoring |= INTR_TYPE_SOFT_INTR;
8393                        vmcs12->vm_entry_instruction_len =
8394                                vcpu->arch.event_exit_inst_len;
8395                } else
8396                        idt_vectoring |= INTR_TYPE_EXT_INTR;
8397
8398                vmcs12->idt_vectoring_info_field = idt_vectoring;
8399        }
8400}
8401
8402static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
8403{
8404        struct vcpu_vmx *vmx = to_vmx(vcpu);
8405
8406        if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
8407            vmx->nested.preemption_timer_expired) {
8408                if (vmx->nested.nested_run_pending)
8409                        return -EBUSY;
8410                nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
8411                return 0;
8412        }
8413
8414        if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
8415                if (vmx->nested.nested_run_pending ||
8416                    vcpu->arch.interrupt.pending)
8417                        return -EBUSY;
8418                nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
8419                                  NMI_VECTOR | INTR_TYPE_NMI_INTR |
8420                                  INTR_INFO_VALID_MASK, 0);
8421                /*
8422                 * The NMI-triggered VM exit counts as injection:
8423                 * clear this one and block further NMIs.
8424                 */
8425                vcpu->arch.nmi_pending = 0;
8426                vmx_set_nmi_mask(vcpu, true);
8427                return 0;
8428        }
8429
8430        if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
8431            nested_exit_on_intr(vcpu)) {
8432                if (vmx->nested.nested_run_pending)
8433                        return -EBUSY;
8434                nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
8435        }
8436
8437        return 0;
8438}
8439
8440static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
8441{
8442        ktime_t remaining =
8443                hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
8444        u64 value;
8445
8446        if (ktime_to_ns(remaining) <= 0)
8447                return 0;
8448
8449        value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
8450        do_div(value, 1000000);
8451        return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
8452}
8453
8454/*
8455 * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
8456 * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
8457 * and this function updates it to reflect the changes to the guest state while
8458 * L2 was running (and perhaps made some exits which were handled directly by L0
8459 * without going back to L1), and to reflect the exit reason.
8460 * Note that we do not have to copy here all VMCS fields, just those that
8461 * could have changed by the L2 guest or the exit - i.e., the guest-state and
8462 * exit-information fields only. Other fields are modified by L1 with VMWRITE,
8463 * which already writes to vmcs12 directly.
8464 */
8465static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
8466                           u32 exit_reason, u32 exit_intr_info,
8467                           unsigned long exit_qualification)
8468{
8469        /* update guest state fields: */
8470        vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
8471        vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
8472
8473        vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
8474        vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
8475        vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
8476
8477        vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
8478        vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
8479        vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
8480        vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
8481        vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
8482        vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
8483        vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
8484        vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
8485        vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
8486        vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
8487        vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
8488        vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
8489        vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
8490        vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
8491        vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
8492        vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
8493        vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
8494        vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
8495        vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
8496        vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
8497        vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
8498        vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
8499        vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
8500        vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
8501        vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
8502        vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
8503        vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
8504        vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
8505        vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
8506        vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
8507        vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
8508        vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
8509        vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
8510        vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
8511        vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
8512        vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
8513
8514        vmcs12->guest_interruptibility_info =
8515                vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
8516        vmcs12->guest_pending_dbg_exceptions =
8517                vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
8518        if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
8519                vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
8520        else
8521                vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
8522
8523        if (nested_cpu_has_preemption_timer(vmcs12)) {
8524                if (vmcs12->vm_exit_controls &
8525                    VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
8526                        vmcs12->vmx_preemption_timer_value =
8527                                vmx_get_preemption_timer_value(vcpu);
8528                hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
8529        }
8530
8531        /*
8532         * In some cases (usually, nested EPT), L2 is allowed to change its
8533         * own CR3 without exiting. If it has changed it, we must keep it.
8534         * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
8535         * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
8536         *
8537         * Additionally, restore L2's PDPTR to vmcs12.
8538         */
8539        if (enable_ept) {
8540                vmcs12->guest_cr3 = vmcs_read64(GUEST_CR3);
8541                vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
8542                vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
8543                vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
8544                vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
8545        }
8546
8547        vmcs12->vm_entry_controls =
8548                (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
8549                (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
8550
8551        if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
8552                kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
8553                vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
8554        }
8555
8556        /* TODO: These cannot have changed unless we have MSR bitmaps and
8557         * the relevant bit asks not to trap the change */
8558        if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
8559                vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
8560        if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
8561                vmcs12->guest_ia32_efer = vcpu->arch.efer;
8562        vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
8563        vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
8564        vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
8565        if (vmx_mpx_supported())
8566                vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
8567
8568        /* update exit information fields: */
8569
8570        vmcs12->vm_exit_reason = exit_reason;
8571        vmcs12->exit_qualification = exit_qualification;
8572
8573        vmcs12->vm_exit_intr_info = exit_intr_info;
8574        if ((vmcs12->vm_exit_intr_info &
8575             (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
8576            (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK))
8577                vmcs12->vm_exit_intr_error_code =
8578                        vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
8579        vmcs12->idt_vectoring_info_field = 0;
8580        vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
8581        vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8582
8583        if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
8584                /* vm_entry_intr_info_field is cleared on exit. Emulate this
8585                 * instead of reading the real value. */
8586                vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
8587
8588                /*
8589                 * Transfer the event that L0 or L1 may wanted to inject into
8590                 * L2 to IDT_VECTORING_INFO_FIELD.
8591                 */
8592                vmcs12_save_pending_event(vcpu, vmcs12);
8593        }
8594
8595        /*
8596         * Drop what we picked up for L2 via vmx_complete_interrupts. It is
8597         * preserved above and would only end up incorrectly in L1.
8598         */
8599        vcpu->arch.nmi_injected = false;
8600        kvm_clear_exception_queue(vcpu);
8601        kvm_clear_interrupt_queue(vcpu);
8602}
8603
8604/*
8605 * A part of what we need to when the nested L2 guest exits and we want to
8606 * run its L1 parent, is to reset L1's guest state to the host state specified
8607 * in vmcs12.
8608 * This function is to be called not only on normal nested exit, but also on
8609 * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
8610 * Failures During or After Loading Guest State").
8611 * This function should be called when the active VMCS is L1's (vmcs01).
8612 */
8613static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
8614                                   struct vmcs12 *vmcs12)
8615{
8616        struct kvm_segment seg;
8617
8618        if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
8619                vcpu->arch.efer = vmcs12->host_ia32_efer;
8620        else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
8621                vcpu->arch.efer |= (EFER_LMA | EFER_LME);
8622        else
8623                vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
8624        vmx_set_efer(vcpu, vcpu->arch.efer);
8625
8626        kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
8627        kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
8628        vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
8629        /*
8630         * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
8631         * actually changed, because it depends on the current state of
8632         * fpu_active (which may have changed).
8633         * Note that vmx_set_cr0 refers to efer set above.
8634         */
8635        vmx_set_cr0(vcpu, vmcs12->host_cr0);
8636        /*
8637         * If we did fpu_activate()/fpu_deactivate() during L2's run, we need
8638         * to apply the same changes to L1's vmcs. We just set cr0 correctly,
8639         * but we also need to update cr0_guest_host_mask and exception_bitmap.
8640         */
8641        update_exception_bitmap(vcpu);
8642        vcpu->arch.cr0_guest_owned_bits = (vcpu->fpu_active ? X86_CR0_TS : 0);
8643        vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
8644
8645        /*
8646         * Note that CR4_GUEST_HOST_MASK is already set in the original vmcs01
8647         * (KVM doesn't change it)- no reason to call set_cr4_guest_host_mask();
8648         */
8649        vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
8650        kvm_set_cr4(vcpu, vmcs12->host_cr4);
8651
8652        nested_ept_uninit_mmu_context(vcpu);
8653
8654        kvm_set_cr3(vcpu, vmcs12->host_cr3);
8655        kvm_mmu_reset_context(vcpu);
8656
8657        if (!enable_ept)
8658                vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
8659
8660        if (enable_vpid) {
8661                /*
8662                 * Trivially support vpid by letting L2s share their parent
8663                 * L1's vpid. TODO: move to a more elaborate solution, giving
8664                 * each L2 its own vpid and exposing the vpid feature to L1.
8665                 */
8666                vmx_flush_tlb(vcpu);
8667        }
8668
8669
8670        vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
8671        vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
8672        vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
8673        vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
8674        vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
8675
8676        /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1.  */
8677        if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
8678                vmcs_write64(GUEST_BNDCFGS, 0);
8679
8680        if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
8681                vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
8682                vcpu->arch.pat = vmcs12->host_ia32_pat;
8683        }
8684        if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
8685                vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
8686                        vmcs12->host_ia32_perf_global_ctrl);
8687
8688        /* Set L1 segment info according to Intel SDM
8689            27.5.2 Loading Host Segment and Descriptor-Table Registers */
8690        seg = (struct kvm_segment) {
8691                .base = 0,
8692                .limit = 0xFFFFFFFF,
8693                .selector = vmcs12->host_cs_selector,
8694                .type = 11,
8695                .present = 1,
8696                .s = 1,
8697                .g = 1
8698        };
8699        if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
8700                seg.l = 1;
8701        else
8702                seg.db = 1;
8703        vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
8704        seg = (struct kvm_segment) {
8705                .base = 0,
8706                .limit = 0xFFFFFFFF,
8707                .type = 3,
8708                .present = 1,
8709                .s = 1,
8710                .db = 1,
8711                .g = 1
8712        };
8713        seg.selector = vmcs12->host_ds_selector;
8714        vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
8715        seg.selector = vmcs12->host_es_selector;
8716        vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
8717        seg.selector = vmcs12->host_ss_selector;
8718        vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
8719        seg.selector = vmcs12->host_fs_selector;
8720        seg.base = vmcs12->host_fs_base;
8721        vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
8722        seg.selector = vmcs12->host_gs_selector;
8723        seg.base = vmcs12->host_gs_base;
8724        vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
8725        seg = (struct kvm_segment) {
8726                .base = vmcs12->host_tr_base,
8727                .limit = 0x67,
8728                .selector = vmcs12->host_tr_selector,
8729                .type = 11,
8730                .present = 1
8731        };
8732        vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
8733
8734        kvm_set_dr(vcpu, 7, 0x400);
8735        vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
8736}
8737
8738/*
8739 * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
8740 * and modify vmcs12 to make it see what it would expect to see there if
8741 * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
8742 */
8743static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
8744                              u32 exit_intr_info,
8745                              unsigned long exit_qualification)
8746{
8747        struct vcpu_vmx *vmx = to_vmx(vcpu);
8748        struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8749
8750        /* trying to cancel vmlaunch/vmresume is a bug */
8751        WARN_ON_ONCE(vmx->nested.nested_run_pending);
8752
8753        leave_guest_mode(vcpu);
8754        prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
8755                       exit_qualification);
8756
8757        vmx_load_vmcs01(vcpu);
8758
8759        if ((exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
8760            && nested_exit_intr_ack_set(vcpu)) {
8761                int irq = kvm_cpu_get_interrupt(vcpu);
8762                WARN_ON(irq < 0);
8763                vmcs12->vm_exit_intr_info = irq |
8764                        INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
8765        }
8766
8767        trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
8768                                       vmcs12->exit_qualification,
8769                                       vmcs12->idt_vectoring_info_field,
8770                                       vmcs12->vm_exit_intr_info,
8771                                       vmcs12->vm_exit_intr_error_code,
8772                                       KVM_ISA_VMX);
8773
8774        vm_entry_controls_init(vmx, vmcs_read32(VM_ENTRY_CONTROLS));
8775        vm_exit_controls_init(vmx, vmcs_read32(VM_EXIT_CONTROLS));
8776        vmx_segment_cache_clear(vmx);
8777
8778        /* if no vmcs02 cache requested, remove the one we used */
8779        if (VMCS02_POOL_SIZE == 0)
8780                nested_free_vmcs02(vmx, vmx->nested.current_vmptr);
8781
8782        load_vmcs12_host_state(vcpu, vmcs12);
8783
8784        /* Update TSC_OFFSET if TSC was changed while L2 ran */
8785        vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset);
8786
8787        /* This is needed for same reason as it was needed in prepare_vmcs02 */
8788        vmx->host_rsp = 0;
8789
8790        /* Unpin physical memory we referred to in vmcs02 */
8791        if (vmx->nested.apic_access_page) {
8792                nested_release_page(vmx->nested.apic_access_page);
8793                vmx->nested.apic_access_page = 0;
8794        }
8795
8796        /*
8797         * Exiting from L2 to L1, we're now back to L1 which thinks it just
8798         * finished a VMLAUNCH or VMRESUME instruction, so we need to set the
8799         * success or failure flag accordingly.
8800         */
8801        if (unlikely(vmx->fail)) {
8802                vmx->fail = 0;
8803                nested_vmx_failValid(vcpu, vmcs_read32(VM_INSTRUCTION_ERROR));
8804        } else
8805                nested_vmx_succeed(vcpu);
8806        if (enable_shadow_vmcs)
8807                vmx->nested.sync_shadow_vmcs = true;
8808
8809        /* in case we halted in L2 */
8810        vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
8811}
8812
8813/*
8814 * Forcibly leave nested mode in order to be able to reset the VCPU later on.
8815 */
8816static void vmx_leave_nested(struct kvm_vcpu *vcpu)
8817{
8818        if (is_guest_mode(vcpu))
8819                nested_vmx_vmexit(vcpu, -1, 0, 0);
8820        free_nested(to_vmx(vcpu));
8821}
8822
8823/*
8824 * L1's failure to enter L2 is a subset of a normal exit, as explained in
8825 * 23.7 "VM-entry failures during or after loading guest state" (this also
8826 * lists the acceptable exit-reason and exit-qualification parameters).
8827 * It should only be called before L2 actually succeeded to run, and when
8828 * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
8829 */
8830static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
8831                        struct vmcs12 *vmcs12,
8832                        u32 reason, unsigned long qualification)
8833{
8834        load_vmcs12_host_state(vcpu, vmcs12);
8835        vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
8836        vmcs12->exit_qualification = qualification;
8837        nested_vmx_succeed(vcpu);
8838        if (enable_shadow_vmcs)
8839                to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
8840}
8841
8842static int vmx_check_intercept(struct kvm_vcpu *vcpu,
8843                               struct x86_instruction_info *info,
8844                               enum x86_intercept_stage stage)
8845{
8846        return X86EMUL_CONTINUE;
8847}
8848
8849static struct kvm_x86_ops vmx_x86_ops = {
8850        .cpu_has_kvm_support = cpu_has_kvm_support,
8851        .disabled_by_bios = vmx_disabled_by_bios,
8852        .hardware_setup = hardware_setup,
8853        .hardware_unsetup = hardware_unsetup,
8854        .check_processor_compatibility = vmx_check_processor_compat,
8855        .hardware_enable = hardware_enable,
8856        .hardware_disable = hardware_disable,
8857        .cpu_has_accelerated_tpr = report_flexpriority,
8858
8859        .vcpu_create = vmx_create_vcpu,
8860        .vcpu_free = vmx_free_vcpu,
8861        .vcpu_reset = vmx_vcpu_reset,
8862
8863        .prepare_guest_switch = vmx_save_host_state,
8864        .vcpu_load = vmx_vcpu_load,
8865        .vcpu_put = vmx_vcpu_put,
8866
8867        .update_db_bp_intercept = update_exception_bitmap,
8868        .get_msr = vmx_get_msr,
8869        .set_msr = vmx_set_msr,
8870        .get_segment_base = vmx_get_segment_base,
8871        .get_segment = vmx_get_segment,
8872        .set_segment = vmx_set_segment,
8873        .get_cpl = vmx_get_cpl,
8874        .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
8875        .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
8876        .decache_cr3 = vmx_decache_cr3,
8877        .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
8878        .set_cr0 = vmx_set_cr0,
8879        .set_cr3 = vmx_set_cr3,
8880        .set_cr4 = vmx_set_cr4,
8881        .set_efer = vmx_set_efer,
8882        .get_idt = vmx_get_idt,
8883        .set_idt = vmx_set_idt,
8884        .get_gdt = vmx_get_gdt,
8885        .set_gdt = vmx_set_gdt,
8886        .get_dr6 = vmx_get_dr6,
8887        .set_dr6 = vmx_set_dr6,
8888        .set_dr7 = vmx_set_dr7,
8889        .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
8890        .cache_reg = vmx_cache_reg,
8891        .get_rflags = vmx_get_rflags,
8892        .set_rflags = vmx_set_rflags,
8893        .fpu_activate = vmx_fpu_activate,
8894        .fpu_deactivate = vmx_fpu_deactivate,
8895
8896        .tlb_flush = vmx_flush_tlb,
8897
8898        .run = vmx_vcpu_run,
8899        .handle_exit = vmx_handle_exit,
8900        .skip_emulated_instruction = skip_emulated_instruction,
8901        .set_interrupt_shadow = vmx_set_interrupt_shadow,
8902        .get_interrupt_shadow = vmx_get_interrupt_shadow,
8903        .patch_hypercall = vmx_patch_hypercall,
8904        .set_irq = vmx_inject_irq,
8905        .set_nmi = vmx_inject_nmi,
8906        .queue_exception = vmx_queue_exception,
8907        .cancel_injection = vmx_cancel_injection,
8908        .interrupt_allowed = vmx_interrupt_allowed,
8909        .nmi_allowed = vmx_nmi_allowed,
8910        .get_nmi_mask = vmx_get_nmi_mask,
8911        .set_nmi_mask = vmx_set_nmi_mask,
8912        .enable_nmi_window = enable_nmi_window,
8913        .enable_irq_window = enable_irq_window,
8914        .update_cr8_intercept = update_cr8_intercept,
8915        .set_virtual_x2apic_mode = vmx_set_virtual_x2apic_mode,
8916        .vm_has_apicv = vmx_vm_has_apicv,
8917        .load_eoi_exitmap = vmx_load_eoi_exitmap,
8918        .hwapic_irr_update = vmx_hwapic_irr_update,
8919        .hwapic_isr_update = vmx_hwapic_isr_update,
8920        .sync_pir_to_irr = vmx_sync_pir_to_irr,
8921        .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
8922
8923        .set_tss_addr = vmx_set_tss_addr,
8924        .get_tdp_level = get_ept_level,
8925        .get_mt_mask = vmx_get_mt_mask,
8926
8927        .get_exit_info = vmx_get_exit_info,
8928
8929        .get_lpage_level = vmx_get_lpage_level,
8930
8931        .cpuid_update = vmx_cpuid_update,
8932
8933        .rdtscp_supported = vmx_rdtscp_supported,
8934        .invpcid_supported = vmx_invpcid_supported,
8935
8936        .set_supported_cpuid = vmx_set_supported_cpuid,
8937
8938        .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
8939
8940        .set_tsc_khz = vmx_set_tsc_khz,
8941        .read_tsc_offset = vmx_read_tsc_offset,
8942        .write_tsc_offset = vmx_write_tsc_offset,
8943        .adjust_tsc_offset = vmx_adjust_tsc_offset,
8944        .compute_tsc_offset = vmx_compute_tsc_offset,
8945        .read_l1_tsc = vmx_read_l1_tsc,
8946
8947        .set_tdp_cr3 = vmx_set_cr3,
8948
8949        .check_intercept = vmx_check_intercept,
8950        .handle_external_intr = vmx_handle_external_intr,
8951        .mpx_supported = vmx_mpx_supported,
8952
8953        .check_nested_events = vmx_check_nested_events,
8954};
8955
8956static int __init vmx_init(void)
8957{
8958        int r, i, msr;
8959
8960        rdmsrl_safe(MSR_EFER, &host_efer);
8961
8962        for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
8963                kvm_define_shared_msr(i, vmx_msr_index[i]);
8964
8965        vmx_io_bitmap_a = (unsigned long *)__get_free_page(GFP_KERNEL);
8966        if (!vmx_io_bitmap_a)
8967                return -ENOMEM;
8968
8969        r = -ENOMEM;
8970
8971        vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL);
8972        if (!vmx_io_bitmap_b)
8973                goto out;
8974
8975        vmx_msr_bitmap_legacy = (unsigned long *)__get_free_page(GFP_KERNEL);
8976        if (!vmx_msr_bitmap_legacy)
8977                goto out1;
8978
8979        vmx_msr_bitmap_legacy_x2apic =
8980                                (unsigned long *)__get_free_page(GFP_KERNEL);
8981        if (!vmx_msr_bitmap_legacy_x2apic)
8982                goto out2;
8983
8984        vmx_msr_bitmap_longmode = (unsigned long *)__get_free_page(GFP_KERNEL);
8985        if (!vmx_msr_bitmap_longmode)
8986                goto out3;
8987
8988        vmx_msr_bitmap_longmode_x2apic =
8989                                (unsigned long *)__get_free_page(GFP_KERNEL);
8990        if (!vmx_msr_bitmap_longmode_x2apic)
8991                goto out4;
8992        vmx_vmread_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
8993        if (!vmx_vmread_bitmap)
8994                goto out5;
8995
8996        vmx_vmwrite_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
8997        if (!vmx_vmwrite_bitmap)
8998                goto out6;
8999
9000        memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
9001        memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
9002
9003        /*
9004         * Allow direct access to the PC debug port (it is often used for I/O
9005         * delays, but the vmexits simply slow things down).
9006         */
9007        memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE);
9008        clear_bit(0x80, vmx_io_bitmap_a);
9009
9010        memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE);
9011
9012        memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE);
9013        memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE);
9014
9015        set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
9016
9017        r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
9018                     __alignof__(struct vcpu_vmx), THIS_MODULE);
9019        if (r)
9020                goto out7;
9021
9022#ifdef CONFIG_KEXEC
9023        rcu_assign_pointer(crash_vmclear_loaded_vmcss,
9024                           crash_vmclear_local_loaded_vmcss);
9025#endif
9026
9027        vmx_disable_intercept_for_msr(MSR_FS_BASE, false);
9028        vmx_disable_intercept_for_msr(MSR_GS_BASE, false);
9029        vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true);
9030        vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false);
9031        vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false);
9032        vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false);
9033        vmx_disable_intercept_for_msr(MSR_IA32_BNDCFGS, true);
9034
9035        memcpy(vmx_msr_bitmap_legacy_x2apic,
9036                        vmx_msr_bitmap_legacy, PAGE_SIZE);
9037        memcpy(vmx_msr_bitmap_longmode_x2apic,
9038                        vmx_msr_bitmap_longmode, PAGE_SIZE);
9039
9040        if (enable_apicv) {
9041                for (msr = 0x800; msr <= 0x8ff; msr++)
9042                        vmx_disable_intercept_msr_read_x2apic(msr);
9043
9044                /* According SDM, in x2apic mode, the whole id reg is used.
9045                 * But in KVM, it only use the highest eight bits. Need to
9046                 * intercept it */
9047                vmx_enable_intercept_msr_read_x2apic(0x802);
9048                /* TMCCT */
9049                vmx_enable_intercept_msr_read_x2apic(0x839);
9050                /* TPR */
9051                vmx_disable_intercept_msr_write_x2apic(0x808);
9052                /* EOI */
9053                vmx_disable_intercept_msr_write_x2apic(0x80b);
9054                /* SELF-IPI */
9055                vmx_disable_intercept_msr_write_x2apic(0x83f);
9056        }
9057
9058        if (enable_ept) {
9059                kvm_mmu_set_mask_ptes(0ull,
9060                        (enable_ept_ad_bits) ? VMX_EPT_ACCESS_BIT : 0ull,
9061                        (enable_ept_ad_bits) ? VMX_EPT_DIRTY_BIT : 0ull,
9062                        0ull, VMX_EPT_EXECUTABLE_MASK);
9063                ept_set_mmio_spte_mask();
9064                kvm_enable_tdp();
9065        } else
9066                kvm_disable_tdp();
9067
9068        return 0;
9069
9070out7:
9071        free_page((unsigned long)vmx_vmwrite_bitmap);
9072out6:
9073        free_page((unsigned long)vmx_vmread_bitmap);
9074out5:
9075        free_page((unsigned long)vmx_msr_bitmap_longmode_x2apic);
9076out4:
9077        free_page((unsigned long)vmx_msr_bitmap_longmode);
9078out3:
9079        free_page((unsigned long)vmx_msr_bitmap_legacy_x2apic);
9080out2:
9081        free_page((unsigned long)vmx_msr_bitmap_legacy);
9082out1:
9083        free_page((unsigned long)vmx_io_bitmap_b);
9084out:
9085        free_page((unsigned long)vmx_io_bitmap_a);
9086        return r;
9087}
9088
9089static void __exit vmx_exit(void)
9090{
9091        free_page((unsigned long)vmx_msr_bitmap_legacy_x2apic);
9092        free_page((unsigned long)vmx_msr_bitmap_longmode_x2apic);
9093        free_page((unsigned long)vmx_msr_bitmap_legacy);
9094        free_page((unsigned long)vmx_msr_bitmap_longmode);
9095        free_page((unsigned long)vmx_io_bitmap_b);
9096        free_page((unsigned long)vmx_io_bitmap_a);
9097        free_page((unsigned long)vmx_vmwrite_bitmap);
9098        free_page((unsigned long)vmx_vmread_bitmap);
9099
9100#ifdef CONFIG_KEXEC
9101        rcu_assign_pointer(crash_vmclear_loaded_vmcss, NULL);
9102        synchronize_rcu();
9103#endif
9104
9105        kvm_exit();
9106}
9107
9108module_init(vmx_init)
9109module_exit(vmx_exit)
9110