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