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