OSDN Git Service

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