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