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