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