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