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