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