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