blob: fa2abed1a14dabd6a781bd7b184f0a05981ebd9b [file] [log] [blame]
xjb04a4022021-11-25 15:01:52 +08001/*
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/sched/smt.h>
31#include <linux/moduleparam.h>
32#include <linux/mod_devicetable.h>
33#include <linux/trace_events.h>
34#include <linux/slab.h>
35#include <linux/tboot.h>
36#include <linux/hrtimer.h>
37#include <linux/frame.h>
38#include <linux/nospec.h>
39#include "kvm_cache_regs.h"
40#include "x86.h"
41
42#include <asm/asm.h>
43#include <asm/cpu.h>
44#include <asm/io.h>
45#include <asm/desc.h>
46#include <asm/vmx.h>
47#include <asm/virtext.h>
48#include <asm/mce.h>
49#include <asm/fpu/internal.h>
50#include <asm/perf_event.h>
51#include <asm/debugreg.h>
52#include <asm/kexec.h>
53#include <asm/apic.h>
54#include <asm/irq_remapping.h>
55#include <asm/mmu_context.h>
56#include <asm/spec-ctrl.h>
57#include <asm/mshyperv.h>
58
59#include "trace.h"
60#include "pmu.h"
61#include "vmx_evmcs.h"
62
63#define __ex(x) __kvm_handle_fault_on_reboot(x)
64#define __ex_clear(x, reg) \
65 ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
66
67MODULE_AUTHOR("Qumranet");
68MODULE_LICENSE("GPL");
69
70static const struct x86_cpu_id vmx_cpu_id[] = {
71 X86_FEATURE_MATCH(X86_FEATURE_VMX),
72 {}
73};
74MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
75
76static bool __read_mostly enable_vpid = 1;
77module_param_named(vpid, enable_vpid, bool, 0444);
78
79static bool __read_mostly enable_vnmi = 1;
80module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
81
82static bool __read_mostly flexpriority_enabled = 1;
83module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
84
85static bool __read_mostly enable_ept = 1;
86module_param_named(ept, enable_ept, bool, S_IRUGO);
87
88static bool __read_mostly enable_unrestricted_guest = 1;
89module_param_named(unrestricted_guest,
90 enable_unrestricted_guest, bool, S_IRUGO);
91
92static bool __read_mostly enable_ept_ad_bits = 1;
93module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
94
95static bool __read_mostly emulate_invalid_guest_state = true;
96module_param(emulate_invalid_guest_state, bool, S_IRUGO);
97
98static bool __read_mostly fasteoi = 1;
99module_param(fasteoi, bool, S_IRUGO);
100
101static bool __read_mostly enable_apicv = 1;
102module_param(enable_apicv, bool, S_IRUGO);
103
104static bool __read_mostly enable_shadow_vmcs = 1;
105module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
106/*
107 * If nested=1, nested virtualization is supported, i.e., guests may use
108 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
109 * use VMX instructions.
110 */
111static bool __read_mostly nested = 0;
112module_param(nested, bool, S_IRUGO);
113
114static u64 __read_mostly host_xss;
115
116static bool __read_mostly enable_pml = 1;
117module_param_named(pml, enable_pml, bool, S_IRUGO);
118
119#define MSR_TYPE_R 1
120#define MSR_TYPE_W 2
121#define MSR_TYPE_RW 3
122
123#define MSR_BITMAP_MODE_X2APIC 1
124#define MSR_BITMAP_MODE_X2APIC_APICV 2
125
126#define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
127
128/* Guest_tsc -> host_tsc conversion requires 64-bit division. */
129static int __read_mostly cpu_preemption_timer_multi;
130static bool __read_mostly enable_preemption_timer = 1;
131#ifdef CONFIG_X86_64
132module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
133#endif
134
135#define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
136#define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
137#define KVM_VM_CR0_ALWAYS_ON \
138 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | \
139 X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
140#define KVM_CR4_GUEST_OWNED_BITS \
141 (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \
142 | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_TSD)
143
144#define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
145#define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
146#define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
147
148#define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
149
150#define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
151
152/*
153 * Hyper-V requires all of these, so mark them as supported even though
154 * they are just treated the same as all-context.
155 */
156#define VMX_VPID_EXTENT_SUPPORTED_MASK \
157 (VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT | \
158 VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT | \
159 VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT | \
160 VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
161
162/*
163 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
164 * ple_gap: upper bound on the amount of time between two successive
165 * executions of PAUSE in a loop. Also indicate if ple enabled.
166 * According to test, this time is usually smaller than 128 cycles.
167 * ple_window: upper bound on the amount of time a guest is allowed to execute
168 * in a PAUSE loop. Tests indicate that most spinlocks are held for
169 * less than 2^12 cycles
170 * Time is measured based on a counter that runs at the same rate as the TSC,
171 * refer SDM volume 3b section 21.6.13 & 22.1.3.
172 */
173static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
174module_param(ple_gap, uint, 0444);
175
176static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
177module_param(ple_window, uint, 0444);
178
179/* Default doubles per-vcpu window every exit. */
180static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
181module_param(ple_window_grow, uint, 0444);
182
183/* Default resets per-vcpu window every exit to ple_window. */
184static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
185module_param(ple_window_shrink, uint, 0444);
186
187/* Default is to compute the maximum so we can never overflow. */
188static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
189module_param(ple_window_max, uint, 0444);
190
191extern const ulong vmx_return;
192
193static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
194static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
195static DEFINE_MUTEX(vmx_l1d_flush_mutex);
196
197/* Storage for pre module init parameter parsing */
198static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
199
200static const struct {
201 const char *option;
202 bool for_parse;
203} vmentry_l1d_param[] = {
204 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
205 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
206 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
207 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
208 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
209 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
210};
211
212#define L1D_CACHE_ORDER 4
213static void *vmx_l1d_flush_pages;
214
215static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
216{
217 struct page *page;
218 unsigned int i;
219
220 if (!enable_ept) {
221 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
222 return 0;
223 }
224
225 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
226 u64 msr;
227
228 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
229 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
230 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
231 return 0;
232 }
233 }
234
235 /* If set to auto use the default l1tf mitigation method */
236 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
237 switch (l1tf_mitigation) {
238 case L1TF_MITIGATION_OFF:
239 l1tf = VMENTER_L1D_FLUSH_NEVER;
240 break;
241 case L1TF_MITIGATION_FLUSH_NOWARN:
242 case L1TF_MITIGATION_FLUSH:
243 case L1TF_MITIGATION_FLUSH_NOSMT:
244 l1tf = VMENTER_L1D_FLUSH_COND;
245 break;
246 case L1TF_MITIGATION_FULL:
247 case L1TF_MITIGATION_FULL_FORCE:
248 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
249 break;
250 }
251 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
252 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
253 }
254
255 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
256 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
257 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
258 if (!page)
259 return -ENOMEM;
260 vmx_l1d_flush_pages = page_address(page);
261
262 /*
263 * Initialize each page with a different pattern in
264 * order to protect against KSM in the nested
265 * virtualization case.
266 */
267 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
268 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
269 PAGE_SIZE);
270 }
271 }
272
273 l1tf_vmx_mitigation = l1tf;
274
275 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
276 static_branch_enable(&vmx_l1d_should_flush);
277 else
278 static_branch_disable(&vmx_l1d_should_flush);
279
280 if (l1tf == VMENTER_L1D_FLUSH_COND)
281 static_branch_enable(&vmx_l1d_flush_cond);
282 else
283 static_branch_disable(&vmx_l1d_flush_cond);
284 return 0;
285}
286
287static int vmentry_l1d_flush_parse(const char *s)
288{
289 unsigned int i;
290
291 if (s) {
292 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
293 if (vmentry_l1d_param[i].for_parse &&
294 sysfs_streq(s, vmentry_l1d_param[i].option))
295 return i;
296 }
297 }
298 return -EINVAL;
299}
300
301static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
302{
303 int l1tf, ret;
304
305 l1tf = vmentry_l1d_flush_parse(s);
306 if (l1tf < 0)
307 return l1tf;
308
309 if (!boot_cpu_has(X86_BUG_L1TF))
310 return 0;
311
312 /*
313 * Has vmx_init() run already? If not then this is the pre init
314 * parameter parsing. In that case just store the value and let
315 * vmx_init() do the proper setup after enable_ept has been
316 * established.
317 */
318 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
319 vmentry_l1d_flush_param = l1tf;
320 return 0;
321 }
322
323 mutex_lock(&vmx_l1d_flush_mutex);
324 ret = vmx_setup_l1d_flush(l1tf);
325 mutex_unlock(&vmx_l1d_flush_mutex);
326 return ret;
327}
328
329static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
330{
331 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
332 return sprintf(s, "???\n");
333
334 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
335}
336
337static const struct kernel_param_ops vmentry_l1d_flush_ops = {
338 .set = vmentry_l1d_flush_set,
339 .get = vmentry_l1d_flush_get,
340};
341module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
342
343enum ept_pointers_status {
344 EPT_POINTERS_CHECK = 0,
345 EPT_POINTERS_MATCH = 1,
346 EPT_POINTERS_MISMATCH = 2
347};
348
349struct kvm_vmx {
350 struct kvm kvm;
351
352 unsigned int tss_addr;
353 bool ept_identity_pagetable_done;
354 gpa_t ept_identity_map_addr;
355
356 enum ept_pointers_status ept_pointers_match;
357 spinlock_t ept_pointer_lock;
358};
359
360#define NR_AUTOLOAD_MSRS 8
361
362struct vmcs_hdr {
363 u32 revision_id:31;
364 u32 shadow_vmcs:1;
365};
366
367struct vmcs {
368 struct vmcs_hdr hdr;
369 u32 abort;
370 char data[0];
371};
372
373/*
374 * vmcs_host_state tracks registers that are loaded from the VMCS on VMEXIT
375 * and whose values change infrequently, but are not constant. I.e. this is
376 * used as a write-through cache of the corresponding VMCS fields.
377 */
378struct vmcs_host_state {
379 unsigned long cr3; /* May not match real cr3 */
380 unsigned long cr4; /* May not match real cr4 */
381 unsigned long gs_base;
382 unsigned long fs_base;
383
384 u16 fs_sel, gs_sel, ldt_sel;
385#ifdef CONFIG_X86_64
386 u16 ds_sel, es_sel;
387#endif
388};
389
390/*
391 * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
392 * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
393 * loaded on this CPU (so we can clear them if the CPU goes down).
394 */
395struct loaded_vmcs {
396 struct vmcs *vmcs;
397 struct vmcs *shadow_vmcs;
398 int cpu;
399 bool launched;
400 bool nmi_known_unmasked;
401 bool hv_timer_armed;
402 /* Support for vnmi-less CPUs */
403 int soft_vnmi_blocked;
404 ktime_t entry_time;
405 s64 vnmi_blocked_time;
406 unsigned long *msr_bitmap;
407 struct list_head loaded_vmcss_on_cpu_link;
408 struct vmcs_host_state host_state;
409};
410
411struct shared_msr_entry {
412 unsigned index;
413 u64 data;
414 u64 mask;
415};
416
417/*
418 * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
419 * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
420 * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
421 * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
422 * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
423 * More than one of these structures may exist, if L1 runs multiple L2 guests.
424 * nested_vmx_run() will use the data here to build the vmcs02: a VMCS for the
425 * underlying hardware which will be used to run L2.
426 * This structure is packed to ensure that its layout is identical across
427 * machines (necessary for live migration).
428 *
429 * IMPORTANT: Changing the layout of existing fields in this structure
430 * will break save/restore compatibility with older kvm releases. When
431 * adding new fields, either use space in the reserved padding* arrays
432 * or add the new fields to the end of the structure.
433 */
434typedef u64 natural_width;
435struct __packed vmcs12 {
436 /* According to the Intel spec, a VMCS region must start with the
437 * following two fields. Then follow implementation-specific data.
438 */
439 struct vmcs_hdr hdr;
440 u32 abort;
441
442 u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
443 u32 padding[7]; /* room for future expansion */
444
445 u64 io_bitmap_a;
446 u64 io_bitmap_b;
447 u64 msr_bitmap;
448 u64 vm_exit_msr_store_addr;
449 u64 vm_exit_msr_load_addr;
450 u64 vm_entry_msr_load_addr;
451 u64 tsc_offset;
452 u64 virtual_apic_page_addr;
453 u64 apic_access_addr;
454 u64 posted_intr_desc_addr;
455 u64 ept_pointer;
456 u64 eoi_exit_bitmap0;
457 u64 eoi_exit_bitmap1;
458 u64 eoi_exit_bitmap2;
459 u64 eoi_exit_bitmap3;
460 u64 xss_exit_bitmap;
461 u64 guest_physical_address;
462 u64 vmcs_link_pointer;
463 u64 guest_ia32_debugctl;
464 u64 guest_ia32_pat;
465 u64 guest_ia32_efer;
466 u64 guest_ia32_perf_global_ctrl;
467 u64 guest_pdptr0;
468 u64 guest_pdptr1;
469 u64 guest_pdptr2;
470 u64 guest_pdptr3;
471 u64 guest_bndcfgs;
472 u64 host_ia32_pat;
473 u64 host_ia32_efer;
474 u64 host_ia32_perf_global_ctrl;
475 u64 vmread_bitmap;
476 u64 vmwrite_bitmap;
477 u64 vm_function_control;
478 u64 eptp_list_address;
479 u64 pml_address;
480 u64 padding64[3]; /* room for future expansion */
481 /*
482 * To allow migration of L1 (complete with its L2 guests) between
483 * machines of different natural widths (32 or 64 bit), we cannot have
484 * unsigned long fields with no explict size. We use u64 (aliased
485 * natural_width) instead. Luckily, x86 is little-endian.
486 */
487 natural_width cr0_guest_host_mask;
488 natural_width cr4_guest_host_mask;
489 natural_width cr0_read_shadow;
490 natural_width cr4_read_shadow;
491 natural_width cr3_target_value0;
492 natural_width cr3_target_value1;
493 natural_width cr3_target_value2;
494 natural_width cr3_target_value3;
495 natural_width exit_qualification;
496 natural_width guest_linear_address;
497 natural_width guest_cr0;
498 natural_width guest_cr3;
499 natural_width guest_cr4;
500 natural_width guest_es_base;
501 natural_width guest_cs_base;
502 natural_width guest_ss_base;
503 natural_width guest_ds_base;
504 natural_width guest_fs_base;
505 natural_width guest_gs_base;
506 natural_width guest_ldtr_base;
507 natural_width guest_tr_base;
508 natural_width guest_gdtr_base;
509 natural_width guest_idtr_base;
510 natural_width guest_dr7;
511 natural_width guest_rsp;
512 natural_width guest_rip;
513 natural_width guest_rflags;
514 natural_width guest_pending_dbg_exceptions;
515 natural_width guest_sysenter_esp;
516 natural_width guest_sysenter_eip;
517 natural_width host_cr0;
518 natural_width host_cr3;
519 natural_width host_cr4;
520 natural_width host_fs_base;
521 natural_width host_gs_base;
522 natural_width host_tr_base;
523 natural_width host_gdtr_base;
524 natural_width host_idtr_base;
525 natural_width host_ia32_sysenter_esp;
526 natural_width host_ia32_sysenter_eip;
527 natural_width host_rsp;
528 natural_width host_rip;
529 natural_width paddingl[8]; /* room for future expansion */
530 u32 pin_based_vm_exec_control;
531 u32 cpu_based_vm_exec_control;
532 u32 exception_bitmap;
533 u32 page_fault_error_code_mask;
534 u32 page_fault_error_code_match;
535 u32 cr3_target_count;
536 u32 vm_exit_controls;
537 u32 vm_exit_msr_store_count;
538 u32 vm_exit_msr_load_count;
539 u32 vm_entry_controls;
540 u32 vm_entry_msr_load_count;
541 u32 vm_entry_intr_info_field;
542 u32 vm_entry_exception_error_code;
543 u32 vm_entry_instruction_len;
544 u32 tpr_threshold;
545 u32 secondary_vm_exec_control;
546 u32 vm_instruction_error;
547 u32 vm_exit_reason;
548 u32 vm_exit_intr_info;
549 u32 vm_exit_intr_error_code;
550 u32 idt_vectoring_info_field;
551 u32 idt_vectoring_error_code;
552 u32 vm_exit_instruction_len;
553 u32 vmx_instruction_info;
554 u32 guest_es_limit;
555 u32 guest_cs_limit;
556 u32 guest_ss_limit;
557 u32 guest_ds_limit;
558 u32 guest_fs_limit;
559 u32 guest_gs_limit;
560 u32 guest_ldtr_limit;
561 u32 guest_tr_limit;
562 u32 guest_gdtr_limit;
563 u32 guest_idtr_limit;
564 u32 guest_es_ar_bytes;
565 u32 guest_cs_ar_bytes;
566 u32 guest_ss_ar_bytes;
567 u32 guest_ds_ar_bytes;
568 u32 guest_fs_ar_bytes;
569 u32 guest_gs_ar_bytes;
570 u32 guest_ldtr_ar_bytes;
571 u32 guest_tr_ar_bytes;
572 u32 guest_interruptibility_info;
573 u32 guest_activity_state;
574 u32 guest_sysenter_cs;
575 u32 host_ia32_sysenter_cs;
576 u32 vmx_preemption_timer_value;
577 u32 padding32[7]; /* room for future expansion */
578 u16 virtual_processor_id;
579 u16 posted_intr_nv;
580 u16 guest_es_selector;
581 u16 guest_cs_selector;
582 u16 guest_ss_selector;
583 u16 guest_ds_selector;
584 u16 guest_fs_selector;
585 u16 guest_gs_selector;
586 u16 guest_ldtr_selector;
587 u16 guest_tr_selector;
588 u16 guest_intr_status;
589 u16 host_es_selector;
590 u16 host_cs_selector;
591 u16 host_ss_selector;
592 u16 host_ds_selector;
593 u16 host_fs_selector;
594 u16 host_gs_selector;
595 u16 host_tr_selector;
596 u16 guest_pml_index;
597};
598
599/*
600 * For save/restore compatibility, the vmcs12 field offsets must not change.
601 */
602#define CHECK_OFFSET(field, loc) \
603 BUILD_BUG_ON_MSG(offsetof(struct vmcs12, field) != (loc), \
604 "Offset of " #field " in struct vmcs12 has changed.")
605
606static inline void vmx_check_vmcs12_offsets(void) {
607 CHECK_OFFSET(hdr, 0);
608 CHECK_OFFSET(abort, 4);
609 CHECK_OFFSET(launch_state, 8);
610 CHECK_OFFSET(io_bitmap_a, 40);
611 CHECK_OFFSET(io_bitmap_b, 48);
612 CHECK_OFFSET(msr_bitmap, 56);
613 CHECK_OFFSET(vm_exit_msr_store_addr, 64);
614 CHECK_OFFSET(vm_exit_msr_load_addr, 72);
615 CHECK_OFFSET(vm_entry_msr_load_addr, 80);
616 CHECK_OFFSET(tsc_offset, 88);
617 CHECK_OFFSET(virtual_apic_page_addr, 96);
618 CHECK_OFFSET(apic_access_addr, 104);
619 CHECK_OFFSET(posted_intr_desc_addr, 112);
620 CHECK_OFFSET(ept_pointer, 120);
621 CHECK_OFFSET(eoi_exit_bitmap0, 128);
622 CHECK_OFFSET(eoi_exit_bitmap1, 136);
623 CHECK_OFFSET(eoi_exit_bitmap2, 144);
624 CHECK_OFFSET(eoi_exit_bitmap3, 152);
625 CHECK_OFFSET(xss_exit_bitmap, 160);
626 CHECK_OFFSET(guest_physical_address, 168);
627 CHECK_OFFSET(vmcs_link_pointer, 176);
628 CHECK_OFFSET(guest_ia32_debugctl, 184);
629 CHECK_OFFSET(guest_ia32_pat, 192);
630 CHECK_OFFSET(guest_ia32_efer, 200);
631 CHECK_OFFSET(guest_ia32_perf_global_ctrl, 208);
632 CHECK_OFFSET(guest_pdptr0, 216);
633 CHECK_OFFSET(guest_pdptr1, 224);
634 CHECK_OFFSET(guest_pdptr2, 232);
635 CHECK_OFFSET(guest_pdptr3, 240);
636 CHECK_OFFSET(guest_bndcfgs, 248);
637 CHECK_OFFSET(host_ia32_pat, 256);
638 CHECK_OFFSET(host_ia32_efer, 264);
639 CHECK_OFFSET(host_ia32_perf_global_ctrl, 272);
640 CHECK_OFFSET(vmread_bitmap, 280);
641 CHECK_OFFSET(vmwrite_bitmap, 288);
642 CHECK_OFFSET(vm_function_control, 296);
643 CHECK_OFFSET(eptp_list_address, 304);
644 CHECK_OFFSET(pml_address, 312);
645 CHECK_OFFSET(cr0_guest_host_mask, 344);
646 CHECK_OFFSET(cr4_guest_host_mask, 352);
647 CHECK_OFFSET(cr0_read_shadow, 360);
648 CHECK_OFFSET(cr4_read_shadow, 368);
649 CHECK_OFFSET(cr3_target_value0, 376);
650 CHECK_OFFSET(cr3_target_value1, 384);
651 CHECK_OFFSET(cr3_target_value2, 392);
652 CHECK_OFFSET(cr3_target_value3, 400);
653 CHECK_OFFSET(exit_qualification, 408);
654 CHECK_OFFSET(guest_linear_address, 416);
655 CHECK_OFFSET(guest_cr0, 424);
656 CHECK_OFFSET(guest_cr3, 432);
657 CHECK_OFFSET(guest_cr4, 440);
658 CHECK_OFFSET(guest_es_base, 448);
659 CHECK_OFFSET(guest_cs_base, 456);
660 CHECK_OFFSET(guest_ss_base, 464);
661 CHECK_OFFSET(guest_ds_base, 472);
662 CHECK_OFFSET(guest_fs_base, 480);
663 CHECK_OFFSET(guest_gs_base, 488);
664 CHECK_OFFSET(guest_ldtr_base, 496);
665 CHECK_OFFSET(guest_tr_base, 504);
666 CHECK_OFFSET(guest_gdtr_base, 512);
667 CHECK_OFFSET(guest_idtr_base, 520);
668 CHECK_OFFSET(guest_dr7, 528);
669 CHECK_OFFSET(guest_rsp, 536);
670 CHECK_OFFSET(guest_rip, 544);
671 CHECK_OFFSET(guest_rflags, 552);
672 CHECK_OFFSET(guest_pending_dbg_exceptions, 560);
673 CHECK_OFFSET(guest_sysenter_esp, 568);
674 CHECK_OFFSET(guest_sysenter_eip, 576);
675 CHECK_OFFSET(host_cr0, 584);
676 CHECK_OFFSET(host_cr3, 592);
677 CHECK_OFFSET(host_cr4, 600);
678 CHECK_OFFSET(host_fs_base, 608);
679 CHECK_OFFSET(host_gs_base, 616);
680 CHECK_OFFSET(host_tr_base, 624);
681 CHECK_OFFSET(host_gdtr_base, 632);
682 CHECK_OFFSET(host_idtr_base, 640);
683 CHECK_OFFSET(host_ia32_sysenter_esp, 648);
684 CHECK_OFFSET(host_ia32_sysenter_eip, 656);
685 CHECK_OFFSET(host_rsp, 664);
686 CHECK_OFFSET(host_rip, 672);
687 CHECK_OFFSET(pin_based_vm_exec_control, 744);
688 CHECK_OFFSET(cpu_based_vm_exec_control, 748);
689 CHECK_OFFSET(exception_bitmap, 752);
690 CHECK_OFFSET(page_fault_error_code_mask, 756);
691 CHECK_OFFSET(page_fault_error_code_match, 760);
692 CHECK_OFFSET(cr3_target_count, 764);
693 CHECK_OFFSET(vm_exit_controls, 768);
694 CHECK_OFFSET(vm_exit_msr_store_count, 772);
695 CHECK_OFFSET(vm_exit_msr_load_count, 776);
696 CHECK_OFFSET(vm_entry_controls, 780);
697 CHECK_OFFSET(vm_entry_msr_load_count, 784);
698 CHECK_OFFSET(vm_entry_intr_info_field, 788);
699 CHECK_OFFSET(vm_entry_exception_error_code, 792);
700 CHECK_OFFSET(vm_entry_instruction_len, 796);
701 CHECK_OFFSET(tpr_threshold, 800);
702 CHECK_OFFSET(secondary_vm_exec_control, 804);
703 CHECK_OFFSET(vm_instruction_error, 808);
704 CHECK_OFFSET(vm_exit_reason, 812);
705 CHECK_OFFSET(vm_exit_intr_info, 816);
706 CHECK_OFFSET(vm_exit_intr_error_code, 820);
707 CHECK_OFFSET(idt_vectoring_info_field, 824);
708 CHECK_OFFSET(idt_vectoring_error_code, 828);
709 CHECK_OFFSET(vm_exit_instruction_len, 832);
710 CHECK_OFFSET(vmx_instruction_info, 836);
711 CHECK_OFFSET(guest_es_limit, 840);
712 CHECK_OFFSET(guest_cs_limit, 844);
713 CHECK_OFFSET(guest_ss_limit, 848);
714 CHECK_OFFSET(guest_ds_limit, 852);
715 CHECK_OFFSET(guest_fs_limit, 856);
716 CHECK_OFFSET(guest_gs_limit, 860);
717 CHECK_OFFSET(guest_ldtr_limit, 864);
718 CHECK_OFFSET(guest_tr_limit, 868);
719 CHECK_OFFSET(guest_gdtr_limit, 872);
720 CHECK_OFFSET(guest_idtr_limit, 876);
721 CHECK_OFFSET(guest_es_ar_bytes, 880);
722 CHECK_OFFSET(guest_cs_ar_bytes, 884);
723 CHECK_OFFSET(guest_ss_ar_bytes, 888);
724 CHECK_OFFSET(guest_ds_ar_bytes, 892);
725 CHECK_OFFSET(guest_fs_ar_bytes, 896);
726 CHECK_OFFSET(guest_gs_ar_bytes, 900);
727 CHECK_OFFSET(guest_ldtr_ar_bytes, 904);
728 CHECK_OFFSET(guest_tr_ar_bytes, 908);
729 CHECK_OFFSET(guest_interruptibility_info, 912);
730 CHECK_OFFSET(guest_activity_state, 916);
731 CHECK_OFFSET(guest_sysenter_cs, 920);
732 CHECK_OFFSET(host_ia32_sysenter_cs, 924);
733 CHECK_OFFSET(vmx_preemption_timer_value, 928);
734 CHECK_OFFSET(virtual_processor_id, 960);
735 CHECK_OFFSET(posted_intr_nv, 962);
736 CHECK_OFFSET(guest_es_selector, 964);
737 CHECK_OFFSET(guest_cs_selector, 966);
738 CHECK_OFFSET(guest_ss_selector, 968);
739 CHECK_OFFSET(guest_ds_selector, 970);
740 CHECK_OFFSET(guest_fs_selector, 972);
741 CHECK_OFFSET(guest_gs_selector, 974);
742 CHECK_OFFSET(guest_ldtr_selector, 976);
743 CHECK_OFFSET(guest_tr_selector, 978);
744 CHECK_OFFSET(guest_intr_status, 980);
745 CHECK_OFFSET(host_es_selector, 982);
746 CHECK_OFFSET(host_cs_selector, 984);
747 CHECK_OFFSET(host_ss_selector, 986);
748 CHECK_OFFSET(host_ds_selector, 988);
749 CHECK_OFFSET(host_fs_selector, 990);
750 CHECK_OFFSET(host_gs_selector, 992);
751 CHECK_OFFSET(host_tr_selector, 994);
752 CHECK_OFFSET(guest_pml_index, 996);
753}
754
755/*
756 * VMCS12_REVISION is an arbitrary id that should be changed if the content or
757 * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
758 * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
759 *
760 * IMPORTANT: Changing this value will break save/restore compatibility with
761 * older kvm releases.
762 */
763#define VMCS12_REVISION 0x11e57ed0
764
765/*
766 * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
767 * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
768 * current implementation, 4K are reserved to avoid future complications.
769 */
770#define VMCS12_SIZE 0x1000
771
772/*
773 * VMCS12_MAX_FIELD_INDEX is the highest index value used in any
774 * supported VMCS12 field encoding.
775 */
776#define VMCS12_MAX_FIELD_INDEX 0x17
777
778struct nested_vmx_msrs {
779 /*
780 * We only store the "true" versions of the VMX capability MSRs. We
781 * generate the "non-true" versions by setting the must-be-1 bits
782 * according to the SDM.
783 */
784 u32 procbased_ctls_low;
785 u32 procbased_ctls_high;
786 u32 secondary_ctls_low;
787 u32 secondary_ctls_high;
788 u32 pinbased_ctls_low;
789 u32 pinbased_ctls_high;
790 u32 exit_ctls_low;
791 u32 exit_ctls_high;
792 u32 entry_ctls_low;
793 u32 entry_ctls_high;
794 u32 misc_low;
795 u32 misc_high;
796 u32 ept_caps;
797 u32 vpid_caps;
798 u64 basic;
799 u64 cr0_fixed0;
800 u64 cr0_fixed1;
801 u64 cr4_fixed0;
802 u64 cr4_fixed1;
803 u64 vmcs_enum;
804 u64 vmfunc_controls;
805};
806
807/*
808 * The nested_vmx structure is part of vcpu_vmx, and holds information we need
809 * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
810 */
811struct nested_vmx {
812 /* Has the level1 guest done vmxon? */
813 bool vmxon;
814 gpa_t vmxon_ptr;
815 bool pml_full;
816
817 /* The guest-physical address of the current VMCS L1 keeps for L2 */
818 gpa_t current_vmptr;
819 /*
820 * Cache of the guest's VMCS, existing outside of guest memory.
821 * Loaded from guest memory during VMPTRLD. Flushed to guest
822 * memory during VMCLEAR and VMPTRLD.
823 */
824 struct vmcs12 *cached_vmcs12;
825 /*
826 * Cache of the guest's shadow VMCS, existing outside of guest
827 * memory. Loaded from guest memory during VM entry. Flushed
828 * to guest memory during VM exit.
829 */
830 struct vmcs12 *cached_shadow_vmcs12;
831 /*
832 * Indicates if the shadow vmcs must be updated with the
833 * data hold by vmcs12
834 */
835 bool sync_shadow_vmcs;
836 bool dirty_vmcs12;
837
838 bool change_vmcs01_virtual_apic_mode;
839
840 /* L2 must run next, and mustn't decide to exit to L1. */
841 bool nested_run_pending;
842
843 struct loaded_vmcs vmcs02;
844
845 /*
846 * Guest pages referred to in the vmcs02 with host-physical
847 * pointers, so we must keep them pinned while L2 runs.
848 */
849 struct page *apic_access_page;
850 struct page *virtual_apic_page;
851 struct page *pi_desc_page;
852 struct pi_desc *pi_desc;
853 bool pi_pending;
854 u16 posted_intr_nv;
855
856 struct hrtimer preemption_timer;
857 bool preemption_timer_expired;
858
859 /* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
860 u64 vmcs01_debugctl;
861 u64 vmcs01_guest_bndcfgs;
862
863 u16 vpid02;
864 u16 last_vpid;
865
866 struct nested_vmx_msrs msrs;
867
868 /* SMM related state */
869 struct {
870 /* in VMX operation on SMM entry? */
871 bool vmxon;
872 /* in guest mode on SMM entry? */
873 bool guest_mode;
874 } smm;
875};
876
877#define POSTED_INTR_ON 0
878#define POSTED_INTR_SN 1
879
880/* Posted-Interrupt Descriptor */
881struct pi_desc {
882 u32 pir[8]; /* Posted interrupt requested */
883 union {
884 struct {
885 /* bit 256 - Outstanding Notification */
886 u16 on : 1,
887 /* bit 257 - Suppress Notification */
888 sn : 1,
889 /* bit 271:258 - Reserved */
890 rsvd_1 : 14;
891 /* bit 279:272 - Notification Vector */
892 u8 nv;
893 /* bit 287:280 - Reserved */
894 u8 rsvd_2;
895 /* bit 319:288 - Notification Destination */
896 u32 ndst;
897 };
898 u64 control;
899 };
900 u32 rsvd[6];
901} __aligned(64);
902
903static bool pi_test_and_set_on(struct pi_desc *pi_desc)
904{
905 return test_and_set_bit(POSTED_INTR_ON,
906 (unsigned long *)&pi_desc->control);
907}
908
909static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
910{
911 return test_and_clear_bit(POSTED_INTR_ON,
912 (unsigned long *)&pi_desc->control);
913}
914
915static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
916{
917 return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
918}
919
920static inline void pi_clear_sn(struct pi_desc *pi_desc)
921{
922 return clear_bit(POSTED_INTR_SN,
923 (unsigned long *)&pi_desc->control);
924}
925
926static inline void pi_set_sn(struct pi_desc *pi_desc)
927{
928 return set_bit(POSTED_INTR_SN,
929 (unsigned long *)&pi_desc->control);
930}
931
932static inline void pi_clear_on(struct pi_desc *pi_desc)
933{
934 clear_bit(POSTED_INTR_ON,
935 (unsigned long *)&pi_desc->control);
936}
937
938static inline int pi_test_on(struct pi_desc *pi_desc)
939{
940 return test_bit(POSTED_INTR_ON,
941 (unsigned long *)&pi_desc->control);
942}
943
944static inline int pi_test_sn(struct pi_desc *pi_desc)
945{
946 return test_bit(POSTED_INTR_SN,
947 (unsigned long *)&pi_desc->control);
948}
949
950struct vmx_msrs {
951 unsigned int nr;
952 struct vmx_msr_entry val[NR_AUTOLOAD_MSRS];
953};
954
955struct vcpu_vmx {
956 struct kvm_vcpu vcpu;
957 unsigned long host_rsp;
958 u8 fail;
959 u8 msr_bitmap_mode;
960 u32 exit_intr_info;
961 u32 idt_vectoring_info;
962 ulong rflags;
963 struct shared_msr_entry *guest_msrs;
964 int nmsrs;
965 int save_nmsrs;
966 bool guest_msrs_dirty;
967 unsigned long host_idt_base;
968#ifdef CONFIG_X86_64
969 u64 msr_host_kernel_gs_base;
970 u64 msr_guest_kernel_gs_base;
971#endif
972
973 u64 spec_ctrl;
974
975 u32 vm_entry_controls_shadow;
976 u32 vm_exit_controls_shadow;
977 u32 secondary_exec_control;
978
979 /*
980 * loaded_vmcs points to the VMCS currently used in this vcpu. For a
981 * non-nested (L1) guest, it always points to vmcs01. For a nested
982 * guest (L2), it points to a different VMCS. loaded_cpu_state points
983 * to the VMCS whose state is loaded into the CPU registers that only
984 * need to be switched when transitioning to/from the kernel; a NULL
985 * value indicates that host state is loaded.
986 */
987 struct loaded_vmcs vmcs01;
988 struct loaded_vmcs *loaded_vmcs;
989 struct loaded_vmcs *loaded_cpu_state;
990 bool __launched; /* temporary, used in vmx_vcpu_run */
991 struct msr_autoload {
992 struct vmx_msrs guest;
993 struct vmx_msrs host;
994 } msr_autoload;
995
996 struct {
997 int vm86_active;
998 ulong save_rflags;
999 struct kvm_segment segs[8];
1000 } rmode;
1001 struct {
1002 u32 bitmask; /* 4 bits per segment (1 bit per field) */
1003 struct kvm_save_segment {
1004 u16 selector;
1005 unsigned long base;
1006 u32 limit;
1007 u32 ar;
1008 } seg[8];
1009 } segment_cache;
1010 int vpid;
1011 bool emulation_required;
1012
1013 u32 exit_reason;
1014
1015 /* Posted interrupt descriptor */
1016 struct pi_desc pi_desc;
1017
1018 /* Support for a guest hypervisor (nested VMX) */
1019 struct nested_vmx nested;
1020
1021 /* Dynamic PLE window. */
1022 int ple_window;
1023 bool ple_window_dirty;
1024
1025 bool req_immediate_exit;
1026
1027 /* Support for PML */
1028#define PML_ENTITY_NUM 512
1029 struct page *pml_pg;
1030
1031 /* apic deadline value in host tsc */
1032 u64 hv_deadline_tsc;
1033
1034 u64 current_tsc_ratio;
1035
1036 u32 host_pkru;
1037
1038 unsigned long host_debugctlmsr;
1039
1040 /*
1041 * Only bits masked by msr_ia32_feature_control_valid_bits can be set in
1042 * msr_ia32_feature_control. FEATURE_CONTROL_LOCKED is always included
1043 * in msr_ia32_feature_control_valid_bits.
1044 */
1045 u64 msr_ia32_feature_control;
1046 u64 msr_ia32_feature_control_valid_bits;
1047 u64 ept_pointer;
1048};
1049
1050enum segment_cache_field {
1051 SEG_FIELD_SEL = 0,
1052 SEG_FIELD_BASE = 1,
1053 SEG_FIELD_LIMIT = 2,
1054 SEG_FIELD_AR = 3,
1055
1056 SEG_FIELD_NR = 4
1057};
1058
1059static inline struct kvm_vmx *to_kvm_vmx(struct kvm *kvm)
1060{
1061 return container_of(kvm, struct kvm_vmx, kvm);
1062}
1063
1064static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
1065{
1066 return container_of(vcpu, struct vcpu_vmx, vcpu);
1067}
1068
1069static struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
1070{
1071 return &(to_vmx(vcpu)->pi_desc);
1072}
1073
1074#define ROL16(val, n) ((u16)(((u16)(val) << (n)) | ((u16)(val) >> (16 - (n)))))
1075#define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
1076#define FIELD(number, name) [ROL16(number, 6)] = VMCS12_OFFSET(name)
1077#define FIELD64(number, name) \
1078 FIELD(number, name), \
1079 [ROL16(number##_HIGH, 6)] = VMCS12_OFFSET(name) + sizeof(u32)
1080
1081
1082static u16 shadow_read_only_fields[] = {
1083#define SHADOW_FIELD_RO(x) x,
1084#include "vmx_shadow_fields.h"
1085};
1086static int max_shadow_read_only_fields =
1087 ARRAY_SIZE(shadow_read_only_fields);
1088
1089static u16 shadow_read_write_fields[] = {
1090#define SHADOW_FIELD_RW(x) x,
1091#include "vmx_shadow_fields.h"
1092};
1093static int max_shadow_read_write_fields =
1094 ARRAY_SIZE(shadow_read_write_fields);
1095
1096static const unsigned short vmcs_field_to_offset_table[] = {
1097 FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
1098 FIELD(POSTED_INTR_NV, posted_intr_nv),
1099 FIELD(GUEST_ES_SELECTOR, guest_es_selector),
1100 FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
1101 FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
1102 FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
1103 FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
1104 FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
1105 FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
1106 FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
1107 FIELD(GUEST_INTR_STATUS, guest_intr_status),
1108 FIELD(GUEST_PML_INDEX, guest_pml_index),
1109 FIELD(HOST_ES_SELECTOR, host_es_selector),
1110 FIELD(HOST_CS_SELECTOR, host_cs_selector),
1111 FIELD(HOST_SS_SELECTOR, host_ss_selector),
1112 FIELD(HOST_DS_SELECTOR, host_ds_selector),
1113 FIELD(HOST_FS_SELECTOR, host_fs_selector),
1114 FIELD(HOST_GS_SELECTOR, host_gs_selector),
1115 FIELD(HOST_TR_SELECTOR, host_tr_selector),
1116 FIELD64(IO_BITMAP_A, io_bitmap_a),
1117 FIELD64(IO_BITMAP_B, io_bitmap_b),
1118 FIELD64(MSR_BITMAP, msr_bitmap),
1119 FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
1120 FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
1121 FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
1122 FIELD64(PML_ADDRESS, pml_address),
1123 FIELD64(TSC_OFFSET, tsc_offset),
1124 FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
1125 FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
1126 FIELD64(POSTED_INTR_DESC_ADDR, posted_intr_desc_addr),
1127 FIELD64(VM_FUNCTION_CONTROL, vm_function_control),
1128 FIELD64(EPT_POINTER, ept_pointer),
1129 FIELD64(EOI_EXIT_BITMAP0, eoi_exit_bitmap0),
1130 FIELD64(EOI_EXIT_BITMAP1, eoi_exit_bitmap1),
1131 FIELD64(EOI_EXIT_BITMAP2, eoi_exit_bitmap2),
1132 FIELD64(EOI_EXIT_BITMAP3, eoi_exit_bitmap3),
1133 FIELD64(EPTP_LIST_ADDRESS, eptp_list_address),
1134 FIELD64(VMREAD_BITMAP, vmread_bitmap),
1135 FIELD64(VMWRITE_BITMAP, vmwrite_bitmap),
1136 FIELD64(XSS_EXIT_BITMAP, xss_exit_bitmap),
1137 FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
1138 FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
1139 FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
1140 FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
1141 FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
1142 FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
1143 FIELD64(GUEST_PDPTR0, guest_pdptr0),
1144 FIELD64(GUEST_PDPTR1, guest_pdptr1),
1145 FIELD64(GUEST_PDPTR2, guest_pdptr2),
1146 FIELD64(GUEST_PDPTR3, guest_pdptr3),
1147 FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
1148 FIELD64(HOST_IA32_PAT, host_ia32_pat),
1149 FIELD64(HOST_IA32_EFER, host_ia32_efer),
1150 FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
1151 FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
1152 FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
1153 FIELD(EXCEPTION_BITMAP, exception_bitmap),
1154 FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
1155 FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
1156 FIELD(CR3_TARGET_COUNT, cr3_target_count),
1157 FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
1158 FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
1159 FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
1160 FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
1161 FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
1162 FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
1163 FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
1164 FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
1165 FIELD(TPR_THRESHOLD, tpr_threshold),
1166 FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
1167 FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
1168 FIELD(VM_EXIT_REASON, vm_exit_reason),
1169 FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
1170 FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
1171 FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
1172 FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
1173 FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
1174 FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
1175 FIELD(GUEST_ES_LIMIT, guest_es_limit),
1176 FIELD(GUEST_CS_LIMIT, guest_cs_limit),
1177 FIELD(GUEST_SS_LIMIT, guest_ss_limit),
1178 FIELD(GUEST_DS_LIMIT, guest_ds_limit),
1179 FIELD(GUEST_FS_LIMIT, guest_fs_limit),
1180 FIELD(GUEST_GS_LIMIT, guest_gs_limit),
1181 FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
1182 FIELD(GUEST_TR_LIMIT, guest_tr_limit),
1183 FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
1184 FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
1185 FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
1186 FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
1187 FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
1188 FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
1189 FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
1190 FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
1191 FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
1192 FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
1193 FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
1194 FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
1195 FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
1196 FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
1197 FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
1198 FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
1199 FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
1200 FIELD(CR0_READ_SHADOW, cr0_read_shadow),
1201 FIELD(CR4_READ_SHADOW, cr4_read_shadow),
1202 FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
1203 FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
1204 FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
1205 FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
1206 FIELD(EXIT_QUALIFICATION, exit_qualification),
1207 FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
1208 FIELD(GUEST_CR0, guest_cr0),
1209 FIELD(GUEST_CR3, guest_cr3),
1210 FIELD(GUEST_CR4, guest_cr4),
1211 FIELD(GUEST_ES_BASE, guest_es_base),
1212 FIELD(GUEST_CS_BASE, guest_cs_base),
1213 FIELD(GUEST_SS_BASE, guest_ss_base),
1214 FIELD(GUEST_DS_BASE, guest_ds_base),
1215 FIELD(GUEST_FS_BASE, guest_fs_base),
1216 FIELD(GUEST_GS_BASE, guest_gs_base),
1217 FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
1218 FIELD(GUEST_TR_BASE, guest_tr_base),
1219 FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
1220 FIELD(GUEST_IDTR_BASE, guest_idtr_base),
1221 FIELD(GUEST_DR7, guest_dr7),
1222 FIELD(GUEST_RSP, guest_rsp),
1223 FIELD(GUEST_RIP, guest_rip),
1224 FIELD(GUEST_RFLAGS, guest_rflags),
1225 FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
1226 FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
1227 FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
1228 FIELD(HOST_CR0, host_cr0),
1229 FIELD(HOST_CR3, host_cr3),
1230 FIELD(HOST_CR4, host_cr4),
1231 FIELD(HOST_FS_BASE, host_fs_base),
1232 FIELD(HOST_GS_BASE, host_gs_base),
1233 FIELD(HOST_TR_BASE, host_tr_base),
1234 FIELD(HOST_GDTR_BASE, host_gdtr_base),
1235 FIELD(HOST_IDTR_BASE, host_idtr_base),
1236 FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
1237 FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
1238 FIELD(HOST_RSP, host_rsp),
1239 FIELD(HOST_RIP, host_rip),
1240};
1241
1242static inline short vmcs_field_to_offset(unsigned long field)
1243{
1244 const size_t size = ARRAY_SIZE(vmcs_field_to_offset_table);
1245 unsigned short offset;
1246 unsigned index;
1247
1248 if (field >> 15)
1249 return -ENOENT;
1250
1251 index = ROL16(field, 6);
1252 if (index >= size)
1253 return -ENOENT;
1254
1255 index = array_index_nospec(index, size);
1256 offset = vmcs_field_to_offset_table[index];
1257 if (offset == 0)
1258 return -ENOENT;
1259 return offset;
1260}
1261
1262static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
1263{
1264 return to_vmx(vcpu)->nested.cached_vmcs12;
1265}
1266
1267static inline struct vmcs12 *get_shadow_vmcs12(struct kvm_vcpu *vcpu)
1268{
1269 return to_vmx(vcpu)->nested.cached_shadow_vmcs12;
1270}
1271
1272static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu);
1273static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
1274static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa);
1275static bool vmx_xsaves_supported(void);
1276static void vmx_set_segment(struct kvm_vcpu *vcpu,
1277 struct kvm_segment *var, int seg);
1278static void vmx_get_segment(struct kvm_vcpu *vcpu,
1279 struct kvm_segment *var, int seg);
1280static bool guest_state_valid(struct kvm_vcpu *vcpu);
1281static u32 vmx_segment_access_rights(struct kvm_segment *var);
1282static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
1283static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu);
1284static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked);
1285static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
1286 u16 error_code);
1287static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu);
1288static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
1289 u32 msr, int type);
1290
1291static DEFINE_PER_CPU(struct vmcs *, vmxarea);
1292static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
1293/*
1294 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
1295 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
1296 */
1297static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
1298
1299/*
1300 * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
1301 * can find which vCPU should be waken up.
1302 */
1303static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
1304static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
1305
1306enum {
1307 VMX_VMREAD_BITMAP,
1308 VMX_VMWRITE_BITMAP,
1309 VMX_BITMAP_NR
1310};
1311
1312static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
1313
1314#define vmx_vmread_bitmap (vmx_bitmap[VMX_VMREAD_BITMAP])
1315#define vmx_vmwrite_bitmap (vmx_bitmap[VMX_VMWRITE_BITMAP])
1316
1317static bool cpu_has_load_ia32_efer;
1318static bool cpu_has_load_perf_global_ctrl;
1319
1320static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
1321static DEFINE_SPINLOCK(vmx_vpid_lock);
1322
1323static struct vmcs_config {
1324 int size;
1325 int order;
1326 u32 basic_cap;
1327 u32 revision_id;
1328 u32 pin_based_exec_ctrl;
1329 u32 cpu_based_exec_ctrl;
1330 u32 cpu_based_2nd_exec_ctrl;
1331 u32 vmexit_ctrl;
1332 u32 vmentry_ctrl;
1333 struct nested_vmx_msrs nested;
1334} vmcs_config;
1335
1336static struct vmx_capability {
1337 u32 ept;
1338 u32 vpid;
1339} vmx_capability;
1340
1341#define VMX_SEGMENT_FIELD(seg) \
1342 [VCPU_SREG_##seg] = { \
1343 .selector = GUEST_##seg##_SELECTOR, \
1344 .base = GUEST_##seg##_BASE, \
1345 .limit = GUEST_##seg##_LIMIT, \
1346 .ar_bytes = GUEST_##seg##_AR_BYTES, \
1347 }
1348
1349static const struct kvm_vmx_segment_field {
1350 unsigned selector;
1351 unsigned base;
1352 unsigned limit;
1353 unsigned ar_bytes;
1354} kvm_vmx_segment_fields[] = {
1355 VMX_SEGMENT_FIELD(CS),
1356 VMX_SEGMENT_FIELD(DS),
1357 VMX_SEGMENT_FIELD(ES),
1358 VMX_SEGMENT_FIELD(FS),
1359 VMX_SEGMENT_FIELD(GS),
1360 VMX_SEGMENT_FIELD(SS),
1361 VMX_SEGMENT_FIELD(TR),
1362 VMX_SEGMENT_FIELD(LDTR),
1363};
1364
1365static u64 host_efer;
1366
1367static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
1368
1369/*
1370 * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
1371 * away by decrementing the array size.
1372 */
1373static const u32 vmx_msr_index[] = {
1374#ifdef CONFIG_X86_64
1375 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
1376#endif
1377 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
1378};
1379
1380DEFINE_STATIC_KEY_FALSE(enable_evmcs);
1381
1382#define current_evmcs ((struct hv_enlightened_vmcs *)this_cpu_read(current_vmcs))
1383
1384#define KVM_EVMCS_VERSION 1
1385
1386#if IS_ENABLED(CONFIG_HYPERV)
1387static bool __read_mostly enlightened_vmcs = true;
1388module_param(enlightened_vmcs, bool, 0444);
1389
1390static inline void evmcs_write64(unsigned long field, u64 value)
1391{
1392 u16 clean_field;
1393 int offset = get_evmcs_offset(field, &clean_field);
1394
1395 if (offset < 0)
1396 return;
1397
1398 *(u64 *)((char *)current_evmcs + offset) = value;
1399
1400 current_evmcs->hv_clean_fields &= ~clean_field;
1401}
1402
1403static inline void evmcs_write32(unsigned long field, u32 value)
1404{
1405 u16 clean_field;
1406 int offset = get_evmcs_offset(field, &clean_field);
1407
1408 if (offset < 0)
1409 return;
1410
1411 *(u32 *)((char *)current_evmcs + offset) = value;
1412 current_evmcs->hv_clean_fields &= ~clean_field;
1413}
1414
1415static inline void evmcs_write16(unsigned long field, u16 value)
1416{
1417 u16 clean_field;
1418 int offset = get_evmcs_offset(field, &clean_field);
1419
1420 if (offset < 0)
1421 return;
1422
1423 *(u16 *)((char *)current_evmcs + offset) = value;
1424 current_evmcs->hv_clean_fields &= ~clean_field;
1425}
1426
1427static inline u64 evmcs_read64(unsigned long field)
1428{
1429 int offset = get_evmcs_offset(field, NULL);
1430
1431 if (offset < 0)
1432 return 0;
1433
1434 return *(u64 *)((char *)current_evmcs + offset);
1435}
1436
1437static inline u32 evmcs_read32(unsigned long field)
1438{
1439 int offset = get_evmcs_offset(field, NULL);
1440
1441 if (offset < 0)
1442 return 0;
1443
1444 return *(u32 *)((char *)current_evmcs + offset);
1445}
1446
1447static inline u16 evmcs_read16(unsigned long field)
1448{
1449 int offset = get_evmcs_offset(field, NULL);
1450
1451 if (offset < 0)
1452 return 0;
1453
1454 return *(u16 *)((char *)current_evmcs + offset);
1455}
1456
1457static inline void evmcs_touch_msr_bitmap(void)
1458{
1459 if (unlikely(!current_evmcs))
1460 return;
1461
1462 if (current_evmcs->hv_enlightenments_control.msr_bitmap)
1463 current_evmcs->hv_clean_fields &=
1464 ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP;
1465}
1466
1467static void evmcs_load(u64 phys_addr)
1468{
1469 struct hv_vp_assist_page *vp_ap =
1470 hv_get_vp_assist_page(smp_processor_id());
1471
1472 vp_ap->current_nested_vmcs = phys_addr;
1473 vp_ap->enlighten_vmentry = 1;
1474}
1475
1476static void evmcs_sanitize_exec_ctrls(struct vmcs_config *vmcs_conf)
1477{
1478 /*
1479 * Enlightened VMCSv1 doesn't support these:
1480 *
1481 * POSTED_INTR_NV = 0x00000002,
1482 * GUEST_INTR_STATUS = 0x00000810,
1483 * APIC_ACCESS_ADDR = 0x00002014,
1484 * POSTED_INTR_DESC_ADDR = 0x00002016,
1485 * EOI_EXIT_BITMAP0 = 0x0000201c,
1486 * EOI_EXIT_BITMAP1 = 0x0000201e,
1487 * EOI_EXIT_BITMAP2 = 0x00002020,
1488 * EOI_EXIT_BITMAP3 = 0x00002022,
1489 */
1490 vmcs_conf->pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
1491 vmcs_conf->cpu_based_2nd_exec_ctrl &=
1492 ~SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1493 vmcs_conf->cpu_based_2nd_exec_ctrl &=
1494 ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1495 vmcs_conf->cpu_based_2nd_exec_ctrl &=
1496 ~SECONDARY_EXEC_APIC_REGISTER_VIRT;
1497
1498 /*
1499 * GUEST_PML_INDEX = 0x00000812,
1500 * PML_ADDRESS = 0x0000200e,
1501 */
1502 vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_ENABLE_PML;
1503
1504 /* VM_FUNCTION_CONTROL = 0x00002018, */
1505 vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_ENABLE_VMFUNC;
1506
1507 /*
1508 * EPTP_LIST_ADDRESS = 0x00002024,
1509 * VMREAD_BITMAP = 0x00002026,
1510 * VMWRITE_BITMAP = 0x00002028,
1511 */
1512 vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_SHADOW_VMCS;
1513
1514 /*
1515 * TSC_MULTIPLIER = 0x00002032,
1516 */
1517 vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_TSC_SCALING;
1518
1519 /*
1520 * PLE_GAP = 0x00004020,
1521 * PLE_WINDOW = 0x00004022,
1522 */
1523 vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1524
1525 /*
1526 * VMX_PREEMPTION_TIMER_VALUE = 0x0000482E,
1527 */
1528 vmcs_conf->pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
1529
1530 /*
1531 * GUEST_IA32_PERF_GLOBAL_CTRL = 0x00002808,
1532 * HOST_IA32_PERF_GLOBAL_CTRL = 0x00002c04,
1533 */
1534 vmcs_conf->vmexit_ctrl &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
1535 vmcs_conf->vmentry_ctrl &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
1536
1537 /*
1538 * Currently unsupported in KVM:
1539 * GUEST_IA32_RTIT_CTL = 0x00002814,
1540 */
1541}
1542
1543/* check_ept_pointer() should be under protection of ept_pointer_lock. */
1544static void check_ept_pointer_match(struct kvm *kvm)
1545{
1546 struct kvm_vcpu *vcpu;
1547 u64 tmp_eptp = INVALID_PAGE;
1548 int i;
1549
1550 kvm_for_each_vcpu(i, vcpu, kvm) {
1551 if (!VALID_PAGE(tmp_eptp)) {
1552 tmp_eptp = to_vmx(vcpu)->ept_pointer;
1553 } else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
1554 to_kvm_vmx(kvm)->ept_pointers_match
1555 = EPT_POINTERS_MISMATCH;
1556 return;
1557 }
1558 }
1559
1560 to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
1561}
1562
1563static int vmx_hv_remote_flush_tlb(struct kvm *kvm)
1564{
1565 int ret;
1566
1567 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
1568
1569 if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
1570 check_ept_pointer_match(kvm);
1571
1572 if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
1573 ret = -ENOTSUPP;
1574 goto out;
1575 }
1576
1577 /*
1578 * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs the address of the
1579 * base of EPT PML4 table, strip off EPT configuration information.
1580 */
1581 ret = hyperv_flush_guest_mapping(
1582 to_vmx(kvm_get_vcpu(kvm, 0))->ept_pointer & PAGE_MASK);
1583
1584out:
1585 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
1586 return ret;
1587}
1588#else /* !IS_ENABLED(CONFIG_HYPERV) */
1589static inline void evmcs_write64(unsigned long field, u64 value) {}
1590static inline void evmcs_write32(unsigned long field, u32 value) {}
1591static inline void evmcs_write16(unsigned long field, u16 value) {}
1592static inline u64 evmcs_read64(unsigned long field) { return 0; }
1593static inline u32 evmcs_read32(unsigned long field) { return 0; }
1594static inline u16 evmcs_read16(unsigned long field) { return 0; }
1595static inline void evmcs_load(u64 phys_addr) {}
1596static inline void evmcs_sanitize_exec_ctrls(struct vmcs_config *vmcs_conf) {}
1597static inline void evmcs_touch_msr_bitmap(void) {}
1598#endif /* IS_ENABLED(CONFIG_HYPERV) */
1599
1600static inline bool is_exception_n(u32 intr_info, u8 vector)
1601{
1602 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1603 INTR_INFO_VALID_MASK)) ==
1604 (INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
1605}
1606
1607static inline bool is_debug(u32 intr_info)
1608{
1609 return is_exception_n(intr_info, DB_VECTOR);
1610}
1611
1612static inline bool is_breakpoint(u32 intr_info)
1613{
1614 return is_exception_n(intr_info, BP_VECTOR);
1615}
1616
1617static inline bool is_page_fault(u32 intr_info)
1618{
1619 return is_exception_n(intr_info, PF_VECTOR);
1620}
1621
1622static inline bool is_no_device(u32 intr_info)
1623{
1624 return is_exception_n(intr_info, NM_VECTOR);
1625}
1626
1627static inline bool is_invalid_opcode(u32 intr_info)
1628{
1629 return is_exception_n(intr_info, UD_VECTOR);
1630}
1631
1632static inline bool is_gp_fault(u32 intr_info)
1633{
1634 return is_exception_n(intr_info, GP_VECTOR);
1635}
1636
1637static inline bool is_external_interrupt(u32 intr_info)
1638{
1639 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1640 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
1641}
1642
1643static inline bool is_machine_check(u32 intr_info)
1644{
1645 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1646 INTR_INFO_VALID_MASK)) ==
1647 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
1648}
1649
1650/* Undocumented: icebp/int1 */
1651static inline bool is_icebp(u32 intr_info)
1652{
1653 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1654 == (INTR_TYPE_PRIV_SW_EXCEPTION | INTR_INFO_VALID_MASK);
1655}
1656
1657static inline bool cpu_has_vmx_msr_bitmap(void)
1658{
1659 return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
1660}
1661
1662static inline bool cpu_has_vmx_tpr_shadow(void)
1663{
1664 return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
1665}
1666
1667static inline bool cpu_need_tpr_shadow(struct kvm_vcpu *vcpu)
1668{
1669 return cpu_has_vmx_tpr_shadow() && lapic_in_kernel(vcpu);
1670}
1671
1672static inline bool cpu_has_secondary_exec_ctrls(void)
1673{
1674 return vmcs_config.cpu_based_exec_ctrl &
1675 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1676}
1677
1678static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
1679{
1680 return vmcs_config.cpu_based_2nd_exec_ctrl &
1681 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1682}
1683
1684static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
1685{
1686 return vmcs_config.cpu_based_2nd_exec_ctrl &
1687 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
1688}
1689
1690static inline bool cpu_has_vmx_apic_register_virt(void)
1691{
1692 return vmcs_config.cpu_based_2nd_exec_ctrl &
1693 SECONDARY_EXEC_APIC_REGISTER_VIRT;
1694}
1695
1696static inline bool cpu_has_vmx_virtual_intr_delivery(void)
1697{
1698 return vmcs_config.cpu_based_2nd_exec_ctrl &
1699 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1700}
1701
1702static inline bool cpu_has_vmx_encls_vmexit(void)
1703{
1704 return vmcs_config.cpu_based_2nd_exec_ctrl &
1705 SECONDARY_EXEC_ENCLS_EXITING;
1706}
1707
1708/*
1709 * Comment's format: document - errata name - stepping - processor name.
1710 * Refer from
1711 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
1712 */
1713static u32 vmx_preemption_cpu_tfms[] = {
1714/* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
17150x000206E6,
1716/* 323056.pdf - AAX65 - C2 - Xeon L3406 */
1717/* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
1718/* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
17190x00020652,
1720/* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
17210x00020655,
1722/* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
1723/* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
1724/*
1725 * 320767.pdf - AAP86 - B1 -
1726 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
1727 */
17280x000106E5,
1729/* 321333.pdf - AAM126 - C0 - Xeon 3500 */
17300x000106A0,
1731/* 321333.pdf - AAM126 - C1 - Xeon 3500 */
17320x000106A1,
1733/* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
17340x000106A4,
1735 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
1736 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
1737 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
17380x000106A5,
1739};
1740
1741static inline bool cpu_has_broken_vmx_preemption_timer(void)
1742{
1743 u32 eax = cpuid_eax(0x00000001), i;
1744
1745 /* Clear the reserved bits */
1746 eax &= ~(0x3U << 14 | 0xfU << 28);
1747 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
1748 if (eax == vmx_preemption_cpu_tfms[i])
1749 return true;
1750
1751 return false;
1752}
1753
1754static inline bool cpu_has_vmx_preemption_timer(void)
1755{
1756 return vmcs_config.pin_based_exec_ctrl &
1757 PIN_BASED_VMX_PREEMPTION_TIMER;
1758}
1759
1760static inline bool cpu_has_vmx_posted_intr(void)
1761{
1762 return IS_ENABLED(CONFIG_X86_LOCAL_APIC) &&
1763 vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
1764}
1765
1766static inline bool cpu_has_vmx_apicv(void)
1767{
1768 return cpu_has_vmx_apic_register_virt() &&
1769 cpu_has_vmx_virtual_intr_delivery() &&
1770 cpu_has_vmx_posted_intr();
1771}
1772
1773static inline bool cpu_has_vmx_flexpriority(void)
1774{
1775 return cpu_has_vmx_tpr_shadow() &&
1776 cpu_has_vmx_virtualize_apic_accesses();
1777}
1778
1779static inline bool cpu_has_vmx_ept_execute_only(void)
1780{
1781 return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
1782}
1783
1784static inline bool cpu_has_vmx_ept_2m_page(void)
1785{
1786 return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
1787}
1788
1789static inline bool cpu_has_vmx_ept_1g_page(void)
1790{
1791 return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
1792}
1793
1794static inline bool cpu_has_vmx_ept_4levels(void)
1795{
1796 return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
1797}
1798
1799static inline bool cpu_has_vmx_ept_mt_wb(void)
1800{
1801 return vmx_capability.ept & VMX_EPTP_WB_BIT;
1802}
1803
1804static inline bool cpu_has_vmx_ept_5levels(void)
1805{
1806 return vmx_capability.ept & VMX_EPT_PAGE_WALK_5_BIT;
1807}
1808
1809static inline bool cpu_has_vmx_ept_ad_bits(void)
1810{
1811 return vmx_capability.ept & VMX_EPT_AD_BIT;
1812}
1813
1814static inline bool cpu_has_vmx_invept_context(void)
1815{
1816 return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
1817}
1818
1819static inline bool cpu_has_vmx_invept_global(void)
1820{
1821 return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
1822}
1823
1824static inline bool cpu_has_vmx_invvpid_individual_addr(void)
1825{
1826 return vmx_capability.vpid & VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT;
1827}
1828
1829static inline bool cpu_has_vmx_invvpid_single(void)
1830{
1831 return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
1832}
1833
1834static inline bool cpu_has_vmx_invvpid_global(void)
1835{
1836 return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
1837}
1838
1839static inline bool cpu_has_vmx_invvpid(void)
1840{
1841 return vmx_capability.vpid & VMX_VPID_INVVPID_BIT;
1842}
1843
1844static inline bool cpu_has_vmx_ept(void)
1845{
1846 return vmcs_config.cpu_based_2nd_exec_ctrl &
1847 SECONDARY_EXEC_ENABLE_EPT;
1848}
1849
1850static inline bool cpu_has_vmx_unrestricted_guest(void)
1851{
1852 return vmcs_config.cpu_based_2nd_exec_ctrl &
1853 SECONDARY_EXEC_UNRESTRICTED_GUEST;
1854}
1855
1856static inline bool cpu_has_vmx_ple(void)
1857{
1858 return vmcs_config.cpu_based_2nd_exec_ctrl &
1859 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1860}
1861
1862static inline bool cpu_has_vmx_basic_inout(void)
1863{
1864 return (((u64)vmcs_config.basic_cap << 32) & VMX_BASIC_INOUT);
1865}
1866
1867static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
1868{
1869 return flexpriority_enabled && lapic_in_kernel(vcpu);
1870}
1871
1872static inline bool cpu_has_vmx_vpid(void)
1873{
1874 return vmcs_config.cpu_based_2nd_exec_ctrl &
1875 SECONDARY_EXEC_ENABLE_VPID;
1876}
1877
1878static inline bool cpu_has_vmx_rdtscp(void)
1879{
1880 return vmcs_config.cpu_based_2nd_exec_ctrl &
1881 SECONDARY_EXEC_RDTSCP;
1882}
1883
1884static inline bool cpu_has_vmx_invpcid(void)
1885{
1886 return vmcs_config.cpu_based_2nd_exec_ctrl &
1887 SECONDARY_EXEC_ENABLE_INVPCID;
1888}
1889
1890static inline bool cpu_has_virtual_nmis(void)
1891{
1892 return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1893}
1894
1895static inline bool cpu_has_vmx_wbinvd_exit(void)
1896{
1897 return vmcs_config.cpu_based_2nd_exec_ctrl &
1898 SECONDARY_EXEC_WBINVD_EXITING;
1899}
1900
1901static inline bool cpu_has_vmx_shadow_vmcs(void)
1902{
1903 u64 vmx_msr;
1904 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1905 /* check if the cpu supports writing r/o exit information fields */
1906 if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1907 return false;
1908
1909 return vmcs_config.cpu_based_2nd_exec_ctrl &
1910 SECONDARY_EXEC_SHADOW_VMCS;
1911}
1912
1913static inline bool cpu_has_vmx_pml(void)
1914{
1915 return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
1916}
1917
1918static inline bool cpu_has_vmx_tsc_scaling(void)
1919{
1920 return vmcs_config.cpu_based_2nd_exec_ctrl &
1921 SECONDARY_EXEC_TSC_SCALING;
1922}
1923
1924static inline bool cpu_has_vmx_vmfunc(void)
1925{
1926 return vmcs_config.cpu_based_2nd_exec_ctrl &
1927 SECONDARY_EXEC_ENABLE_VMFUNC;
1928}
1929
1930static bool vmx_umip_emulated(void)
1931{
1932 return vmcs_config.cpu_based_2nd_exec_ctrl &
1933 SECONDARY_EXEC_DESC;
1934}
1935
1936static inline bool report_flexpriority(void)
1937{
1938 return flexpriority_enabled;
1939}
1940
1941static inline unsigned nested_cpu_vmx_misc_cr3_count(struct kvm_vcpu *vcpu)
1942{
1943 return vmx_misc_cr3_count(to_vmx(vcpu)->nested.msrs.misc_low);
1944}
1945
1946/*
1947 * Do the virtual VMX capability MSRs specify that L1 can use VMWRITE
1948 * to modify any valid field of the VMCS, or are the VM-exit
1949 * information fields read-only?
1950 */
1951static inline bool nested_cpu_has_vmwrite_any_field(struct kvm_vcpu *vcpu)
1952{
1953 return to_vmx(vcpu)->nested.msrs.misc_low &
1954 MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS;
1955}
1956
1957static inline bool nested_cpu_has_zero_length_injection(struct kvm_vcpu *vcpu)
1958{
1959 return to_vmx(vcpu)->nested.msrs.misc_low & VMX_MISC_ZERO_LEN_INS;
1960}
1961
1962static inline bool nested_cpu_supports_monitor_trap_flag(struct kvm_vcpu *vcpu)
1963{
1964 return to_vmx(vcpu)->nested.msrs.procbased_ctls_high &
1965 CPU_BASED_MONITOR_TRAP_FLAG;
1966}
1967
1968static inline bool nested_cpu_has_vmx_shadow_vmcs(struct kvm_vcpu *vcpu)
1969{
1970 return to_vmx(vcpu)->nested.msrs.secondary_ctls_high &
1971 SECONDARY_EXEC_SHADOW_VMCS;
1972}
1973
1974static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1975{
1976 return vmcs12->cpu_based_vm_exec_control & bit;
1977}
1978
1979static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
1980{
1981 return (vmcs12->cpu_based_vm_exec_control &
1982 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
1983 (vmcs12->secondary_vm_exec_control & bit);
1984}
1985
1986static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
1987{
1988 return vmcs12->pin_based_vm_exec_control &
1989 PIN_BASED_VMX_PREEMPTION_TIMER;
1990}
1991
1992static inline bool nested_cpu_has_nmi_exiting(struct vmcs12 *vmcs12)
1993{
1994 return vmcs12->pin_based_vm_exec_control & PIN_BASED_NMI_EXITING;
1995}
1996
1997static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12)
1998{
1999 return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
2000}
2001
2002static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
2003{
2004 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
2005}
2006
2007static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
2008{
2009 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
2010}
2011
2012static inline bool nested_cpu_has_pml(struct vmcs12 *vmcs12)
2013{
2014 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML);
2015}
2016
2017static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
2018{
2019 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
2020}
2021
2022static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
2023{
2024 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
2025}
2026
2027static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
2028{
2029 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
2030}
2031
2032static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
2033{
2034 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2035}
2036
2037static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
2038{
2039 return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
2040}
2041
2042static inline bool nested_cpu_has_vmfunc(struct vmcs12 *vmcs12)
2043{
2044 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VMFUNC);
2045}
2046
2047static inline bool nested_cpu_has_eptp_switching(struct vmcs12 *vmcs12)
2048{
2049 return nested_cpu_has_vmfunc(vmcs12) &&
2050 (vmcs12->vm_function_control &
2051 VMX_VMFUNC_EPTP_SWITCHING);
2052}
2053
2054static inline bool nested_cpu_has_shadow_vmcs(struct vmcs12 *vmcs12)
2055{
2056 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_SHADOW_VMCS);
2057}
2058
2059static inline bool is_nmi(u32 intr_info)
2060{
2061 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
2062 == (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
2063}
2064
2065static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
2066 u32 exit_intr_info,
2067 unsigned long exit_qualification);
2068static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
2069 struct vmcs12 *vmcs12,
2070 u32 reason, unsigned long qualification);
2071
2072static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
2073{
2074 int i;
2075
2076 for (i = 0; i < vmx->nmsrs; ++i)
2077 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
2078 return i;
2079 return -1;
2080}
2081
2082static inline void __invvpid(unsigned long ext, u16 vpid, gva_t gva)
2083{
2084 struct {
2085 u64 vpid : 16;
2086 u64 rsvd : 48;
2087 u64 gva;
2088 } operand = { vpid, 0, gva };
2089 bool error;
2090
2091 asm volatile (__ex(ASM_VMX_INVVPID) CC_SET(na)
2092 : CC_OUT(na) (error) : "a"(&operand), "c"(ext)
2093 : "memory");
2094 BUG_ON(error);
2095}
2096
2097static inline void __invept(unsigned long ext, u64 eptp, gpa_t gpa)
2098{
2099 struct {
2100 u64 eptp, gpa;
2101 } operand = {eptp, gpa};
2102 bool error;
2103
2104 asm volatile (__ex(ASM_VMX_INVEPT) CC_SET(na)
2105 : CC_OUT(na) (error) : "a" (&operand), "c" (ext)
2106 : "memory");
2107 BUG_ON(error);
2108}
2109
2110static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
2111{
2112 int i;
2113
2114 i = __find_msr_index(vmx, msr);
2115 if (i >= 0)
2116 return &vmx->guest_msrs[i];
2117 return NULL;
2118}
2119
2120static void vmcs_clear(struct vmcs *vmcs)
2121{
2122 u64 phys_addr = __pa(vmcs);
2123 bool error;
2124
2125 asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) CC_SET(na)
2126 : CC_OUT(na) (error) : "a"(&phys_addr), "m"(phys_addr)
2127 : "memory");
2128 if (unlikely(error))
2129 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
2130 vmcs, phys_addr);
2131}
2132
2133static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
2134{
2135 vmcs_clear(loaded_vmcs->vmcs);
2136 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
2137 vmcs_clear(loaded_vmcs->shadow_vmcs);
2138 loaded_vmcs->cpu = -1;
2139 loaded_vmcs->launched = 0;
2140}
2141
2142static void vmcs_load(struct vmcs *vmcs)
2143{
2144 u64 phys_addr = __pa(vmcs);
2145 bool error;
2146
2147 if (static_branch_unlikely(&enable_evmcs))
2148 return evmcs_load(phys_addr);
2149
2150 asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) CC_SET(na)
2151 : CC_OUT(na) (error) : "a"(&phys_addr), "m"(phys_addr)
2152 : "memory");
2153 if (unlikely(error))
2154 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
2155 vmcs, phys_addr);
2156}
2157
2158#ifdef CONFIG_KEXEC_CORE
2159/*
2160 * This bitmap is used to indicate whether the vmclear
2161 * operation is enabled on all cpus. All disabled by
2162 * default.
2163 */
2164static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
2165
2166static inline void crash_enable_local_vmclear(int cpu)
2167{
2168 cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
2169}
2170
2171static inline void crash_disable_local_vmclear(int cpu)
2172{
2173 cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
2174}
2175
2176static inline int crash_local_vmclear_enabled(int cpu)
2177{
2178 return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
2179}
2180
2181static void crash_vmclear_local_loaded_vmcss(void)
2182{
2183 int cpu = raw_smp_processor_id();
2184 struct loaded_vmcs *v;
2185
2186 if (!crash_local_vmclear_enabled(cpu))
2187 return;
2188
2189 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
2190 loaded_vmcss_on_cpu_link)
2191 vmcs_clear(v->vmcs);
2192}
2193#else
2194static inline void crash_enable_local_vmclear(int cpu) { }
2195static inline void crash_disable_local_vmclear(int cpu) { }
2196#endif /* CONFIG_KEXEC_CORE */
2197
2198static void __loaded_vmcs_clear(void *arg)
2199{
2200 struct loaded_vmcs *loaded_vmcs = arg;
2201 int cpu = raw_smp_processor_id();
2202
2203 if (loaded_vmcs->cpu != cpu)
2204 return; /* vcpu migration can race with cpu offline */
2205 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
2206 per_cpu(current_vmcs, cpu) = NULL;
2207 crash_disable_local_vmclear(cpu);
2208 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
2209
2210 /*
2211 * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
2212 * is before setting loaded_vmcs->vcpu to -1 which is done in
2213 * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
2214 * then adds the vmcs into percpu list before it is deleted.
2215 */
2216 smp_wmb();
2217
2218 loaded_vmcs_init(loaded_vmcs);
2219 crash_enable_local_vmclear(cpu);
2220}
2221
2222static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
2223{
2224 int cpu = loaded_vmcs->cpu;
2225
2226 if (cpu != -1)
2227 smp_call_function_single(cpu,
2228 __loaded_vmcs_clear, loaded_vmcs, 1);
2229}
2230
2231static inline bool vpid_sync_vcpu_addr(int vpid, gva_t addr)
2232{
2233 if (vpid == 0)
2234 return true;
2235
2236 if (cpu_has_vmx_invvpid_individual_addr()) {
2237 __invvpid(VMX_VPID_EXTENT_INDIVIDUAL_ADDR, vpid, addr);
2238 return true;
2239 }
2240
2241 return false;
2242}
2243
2244static inline void vpid_sync_vcpu_single(int vpid)
2245{
2246 if (vpid == 0)
2247 return;
2248
2249 if (cpu_has_vmx_invvpid_single())
2250 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
2251}
2252
2253static inline void vpid_sync_vcpu_global(void)
2254{
2255 if (cpu_has_vmx_invvpid_global())
2256 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
2257}
2258
2259static inline void vpid_sync_context(int vpid)
2260{
2261 if (cpu_has_vmx_invvpid_single())
2262 vpid_sync_vcpu_single(vpid);
2263 else
2264 vpid_sync_vcpu_global();
2265}
2266
2267static inline void ept_sync_global(void)
2268{
2269 __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
2270}
2271
2272static inline void ept_sync_context(u64 eptp)
2273{
2274 if (cpu_has_vmx_invept_context())
2275 __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
2276 else
2277 ept_sync_global();
2278}
2279
2280static __always_inline void vmcs_check16(unsigned long field)
2281{
2282 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
2283 "16-bit accessor invalid for 64-bit field");
2284 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2285 "16-bit accessor invalid for 64-bit high field");
2286 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2287 "16-bit accessor invalid for 32-bit high field");
2288 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2289 "16-bit accessor invalid for natural width field");
2290}
2291
2292static __always_inline void vmcs_check32(unsigned long field)
2293{
2294 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2295 "32-bit accessor invalid for 16-bit field");
2296 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2297 "32-bit accessor invalid for natural width field");
2298}
2299
2300static __always_inline void vmcs_check64(unsigned long field)
2301{
2302 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2303 "64-bit accessor invalid for 16-bit field");
2304 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2305 "64-bit accessor invalid for 64-bit high field");
2306 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2307 "64-bit accessor invalid for 32-bit field");
2308 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2309 "64-bit accessor invalid for natural width field");
2310}
2311
2312static __always_inline void vmcs_checkl(unsigned long field)
2313{
2314 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2315 "Natural width accessor invalid for 16-bit field");
2316 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
2317 "Natural width accessor invalid for 64-bit field");
2318 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2319 "Natural width accessor invalid for 64-bit high field");
2320 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2321 "Natural width accessor invalid for 32-bit field");
2322}
2323
2324static __always_inline unsigned long __vmcs_readl(unsigned long field)
2325{
2326 unsigned long value;
2327
2328 asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
2329 : "=a"(value) : "d"(field) : "cc");
2330 return value;
2331}
2332
2333static __always_inline u16 vmcs_read16(unsigned long field)
2334{
2335 vmcs_check16(field);
2336 if (static_branch_unlikely(&enable_evmcs))
2337 return evmcs_read16(field);
2338 return __vmcs_readl(field);
2339}
2340
2341static __always_inline u32 vmcs_read32(unsigned long field)
2342{
2343 vmcs_check32(field);
2344 if (static_branch_unlikely(&enable_evmcs))
2345 return evmcs_read32(field);
2346 return __vmcs_readl(field);
2347}
2348
2349static __always_inline u64 vmcs_read64(unsigned long field)
2350{
2351 vmcs_check64(field);
2352 if (static_branch_unlikely(&enable_evmcs))
2353 return evmcs_read64(field);
2354#ifdef CONFIG_X86_64
2355 return __vmcs_readl(field);
2356#else
2357 return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
2358#endif
2359}
2360
2361static __always_inline unsigned long vmcs_readl(unsigned long field)
2362{
2363 vmcs_checkl(field);
2364 if (static_branch_unlikely(&enable_evmcs))
2365 return evmcs_read64(field);
2366 return __vmcs_readl(field);
2367}
2368
2369static noinline void vmwrite_error(unsigned long field, unsigned long value)
2370{
2371 printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
2372 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
2373 dump_stack();
2374}
2375
2376static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
2377{
2378 bool error;
2379
2380 asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) CC_SET(na)
2381 : CC_OUT(na) (error) : "a"(value), "d"(field));
2382 if (unlikely(error))
2383 vmwrite_error(field, value);
2384}
2385
2386static __always_inline void vmcs_write16(unsigned long field, u16 value)
2387{
2388 vmcs_check16(field);
2389 if (static_branch_unlikely(&enable_evmcs))
2390 return evmcs_write16(field, value);
2391
2392 __vmcs_writel(field, value);
2393}
2394
2395static __always_inline void vmcs_write32(unsigned long field, u32 value)
2396{
2397 vmcs_check32(field);
2398 if (static_branch_unlikely(&enable_evmcs))
2399 return evmcs_write32(field, value);
2400
2401 __vmcs_writel(field, value);
2402}
2403
2404static __always_inline void vmcs_write64(unsigned long field, u64 value)
2405{
2406 vmcs_check64(field);
2407 if (static_branch_unlikely(&enable_evmcs))
2408 return evmcs_write64(field, value);
2409
2410 __vmcs_writel(field, value);
2411#ifndef CONFIG_X86_64
2412 asm volatile ("");
2413 __vmcs_writel(field+1, value >> 32);
2414#endif
2415}
2416
2417static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
2418{
2419 vmcs_checkl(field);
2420 if (static_branch_unlikely(&enable_evmcs))
2421 return evmcs_write64(field, value);
2422
2423 __vmcs_writel(field, value);
2424}
2425
2426static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
2427{
2428 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
2429 "vmcs_clear_bits does not support 64-bit fields");
2430 if (static_branch_unlikely(&enable_evmcs))
2431 return evmcs_write32(field, evmcs_read32(field) & ~mask);
2432
2433 __vmcs_writel(field, __vmcs_readl(field) & ~mask);
2434}
2435
2436static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
2437{
2438 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
2439 "vmcs_set_bits does not support 64-bit fields");
2440 if (static_branch_unlikely(&enable_evmcs))
2441 return evmcs_write32(field, evmcs_read32(field) | mask);
2442
2443 __vmcs_writel(field, __vmcs_readl(field) | mask);
2444}
2445
2446static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
2447{
2448 vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
2449}
2450
2451static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
2452{
2453 vmcs_write32(VM_ENTRY_CONTROLS, val);
2454 vmx->vm_entry_controls_shadow = val;
2455}
2456
2457static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
2458{
2459 if (vmx->vm_entry_controls_shadow != val)
2460 vm_entry_controls_init(vmx, val);
2461}
2462
2463static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
2464{
2465 return vmx->vm_entry_controls_shadow;
2466}
2467
2468
2469static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
2470{
2471 vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
2472}
2473
2474static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
2475{
2476 vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
2477}
2478
2479static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
2480{
2481 vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
2482}
2483
2484static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
2485{
2486 vmcs_write32(VM_EXIT_CONTROLS, val);
2487 vmx->vm_exit_controls_shadow = val;
2488}
2489
2490static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
2491{
2492 if (vmx->vm_exit_controls_shadow != val)
2493 vm_exit_controls_init(vmx, val);
2494}
2495
2496static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
2497{
2498 return vmx->vm_exit_controls_shadow;
2499}
2500
2501
2502static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
2503{
2504 vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
2505}
2506
2507static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
2508{
2509 vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
2510}
2511
2512static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
2513{
2514 vmx->segment_cache.bitmask = 0;
2515}
2516
2517static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
2518 unsigned field)
2519{
2520 bool ret;
2521 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
2522
2523 if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
2524 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
2525 vmx->segment_cache.bitmask = 0;
2526 }
2527 ret = vmx->segment_cache.bitmask & mask;
2528 vmx->segment_cache.bitmask |= mask;
2529 return ret;
2530}
2531
2532static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
2533{
2534 u16 *p = &vmx->segment_cache.seg[seg].selector;
2535
2536 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
2537 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
2538 return *p;
2539}
2540
2541static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
2542{
2543 ulong *p = &vmx->segment_cache.seg[seg].base;
2544
2545 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
2546 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
2547 return *p;
2548}
2549
2550static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
2551{
2552 u32 *p = &vmx->segment_cache.seg[seg].limit;
2553
2554 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
2555 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
2556 return *p;
2557}
2558
2559static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
2560{
2561 u32 *p = &vmx->segment_cache.seg[seg].ar;
2562
2563 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
2564 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
2565 return *p;
2566}
2567
2568static void update_exception_bitmap(struct kvm_vcpu *vcpu)
2569{
2570 u32 eb;
2571
2572 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
2573 (1u << DB_VECTOR) | (1u << AC_VECTOR);
2574 /*
2575 * Guest access to VMware backdoor ports could legitimately
2576 * trigger #GP because of TSS I/O permission bitmap.
2577 * We intercept those #GP and allow access to them anyway
2578 * as VMware does.
2579 */
2580 if (enable_vmware_backdoor)
2581 eb |= (1u << GP_VECTOR);
2582 if ((vcpu->guest_debug &
2583 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
2584 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
2585 eb |= 1u << BP_VECTOR;
2586 if (to_vmx(vcpu)->rmode.vm86_active)
2587 eb = ~0;
2588 if (enable_ept)
2589 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
2590
2591 /* When we are running a nested L2 guest and L1 specified for it a
2592 * certain exception bitmap, we must trap the same exceptions and pass
2593 * them to L1. When running L2, we will only handle the exceptions
2594 * specified above if L1 did not want them.
2595 */
2596 if (is_guest_mode(vcpu))
2597 eb |= get_vmcs12(vcpu)->exception_bitmap;
2598
2599 vmcs_write32(EXCEPTION_BITMAP, eb);
2600}
2601
2602/*
2603 * Check if MSR is intercepted for currently loaded MSR bitmap.
2604 */
2605static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
2606{
2607 unsigned long *msr_bitmap;
2608 int f = sizeof(unsigned long);
2609
2610 if (!cpu_has_vmx_msr_bitmap())
2611 return true;
2612
2613 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
2614
2615 if (msr <= 0x1fff) {
2616 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2617 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2618 msr &= 0x1fff;
2619 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2620 }
2621
2622 return true;
2623}
2624
2625/*
2626 * Check if MSR is intercepted for L01 MSR bitmap.
2627 */
2628static bool msr_write_intercepted_l01(struct kvm_vcpu *vcpu, u32 msr)
2629{
2630 unsigned long *msr_bitmap;
2631 int f = sizeof(unsigned long);
2632
2633 if (!cpu_has_vmx_msr_bitmap())
2634 return true;
2635
2636 msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
2637
2638 if (msr <= 0x1fff) {
2639 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2640 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2641 msr &= 0x1fff;
2642 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2643 }
2644
2645 return true;
2646}
2647
2648static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2649 unsigned long entry, unsigned long exit)
2650{
2651 vm_entry_controls_clearbit(vmx, entry);
2652 vm_exit_controls_clearbit(vmx, exit);
2653}
2654
2655static int find_msr(struct vmx_msrs *m, unsigned int msr)
2656{
2657 unsigned int i;
2658
2659 for (i = 0; i < m->nr; ++i) {
2660 if (m->val[i].index == msr)
2661 return i;
2662 }
2663 return -ENOENT;
2664}
2665
2666static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
2667{
2668 int i;
2669 struct msr_autoload *m = &vmx->msr_autoload;
2670
2671 switch (msr) {
2672 case MSR_EFER:
2673 if (cpu_has_load_ia32_efer) {
2674 clear_atomic_switch_msr_special(vmx,
2675 VM_ENTRY_LOAD_IA32_EFER,
2676 VM_EXIT_LOAD_IA32_EFER);
2677 return;
2678 }
2679 break;
2680 case MSR_CORE_PERF_GLOBAL_CTRL:
2681 if (cpu_has_load_perf_global_ctrl) {
2682 clear_atomic_switch_msr_special(vmx,
2683 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2684 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
2685 return;
2686 }
2687 break;
2688 }
2689 i = find_msr(&m->guest, msr);
2690 if (i < 0)
2691 goto skip_guest;
2692 --m->guest.nr;
2693 m->guest.val[i] = m->guest.val[m->guest.nr];
2694 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2695
2696skip_guest:
2697 i = find_msr(&m->host, msr);
2698 if (i < 0)
2699 return;
2700
2701 --m->host.nr;
2702 m->host.val[i] = m->host.val[m->host.nr];
2703 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2704}
2705
2706static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2707 unsigned long entry, unsigned long exit,
2708 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
2709 u64 guest_val, u64 host_val)
2710{
2711 vmcs_write64(guest_val_vmcs, guest_val);
2712 vmcs_write64(host_val_vmcs, host_val);
2713 vm_entry_controls_setbit(vmx, entry);
2714 vm_exit_controls_setbit(vmx, exit);
2715}
2716
2717static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
2718 u64 guest_val, u64 host_val, bool entry_only)
2719{
2720 int i, j = 0;
2721 struct msr_autoload *m = &vmx->msr_autoload;
2722
2723 switch (msr) {
2724 case MSR_EFER:
2725 if (cpu_has_load_ia32_efer) {
2726 add_atomic_switch_msr_special(vmx,
2727 VM_ENTRY_LOAD_IA32_EFER,
2728 VM_EXIT_LOAD_IA32_EFER,
2729 GUEST_IA32_EFER,
2730 HOST_IA32_EFER,
2731 guest_val, host_val);
2732 return;
2733 }
2734 break;
2735 case MSR_CORE_PERF_GLOBAL_CTRL:
2736 if (cpu_has_load_perf_global_ctrl) {
2737 add_atomic_switch_msr_special(vmx,
2738 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2739 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
2740 GUEST_IA32_PERF_GLOBAL_CTRL,
2741 HOST_IA32_PERF_GLOBAL_CTRL,
2742 guest_val, host_val);
2743 return;
2744 }
2745 break;
2746 case MSR_IA32_PEBS_ENABLE:
2747 /* PEBS needs a quiescent period after being disabled (to write
2748 * a record). Disabling PEBS through VMX MSR swapping doesn't
2749 * provide that period, so a CPU could write host's record into
2750 * guest's memory.
2751 */
2752 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
2753 }
2754
2755 i = find_msr(&m->guest, msr);
2756 if (!entry_only)
2757 j = find_msr(&m->host, msr);
2758
2759 if ((i < 0 && m->guest.nr == NR_AUTOLOAD_MSRS) ||
2760 (j < 0 && m->host.nr == NR_AUTOLOAD_MSRS)) {
2761 printk_once(KERN_WARNING "Not enough msr switch entries. "
2762 "Can't add msr %x\n", msr);
2763 return;
2764 }
2765 if (i < 0) {
2766 i = m->guest.nr++;
2767 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2768 }
2769 m->guest.val[i].index = msr;
2770 m->guest.val[i].value = guest_val;
2771
2772 if (entry_only)
2773 return;
2774
2775 if (j < 0) {
2776 j = m->host.nr++;
2777 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2778 }
2779 m->host.val[j].index = msr;
2780 m->host.val[j].value = host_val;
2781}
2782
2783static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
2784{
2785 u64 guest_efer = vmx->vcpu.arch.efer;
2786 u64 ignore_bits = 0;
2787
2788 /* Shadow paging assumes NX to be available. */
2789 if (!enable_ept)
2790 guest_efer |= EFER_NX;
2791
2792 /*
2793 * LMA and LME handled by hardware; SCE meaningless outside long mode.
2794 */
2795 ignore_bits |= EFER_SCE;
2796#ifdef CONFIG_X86_64
2797 ignore_bits |= EFER_LMA | EFER_LME;
2798 /* SCE is meaningful only in long mode on Intel */
2799 if (guest_efer & EFER_LMA)
2800 ignore_bits &= ~(u64)EFER_SCE;
2801#endif
2802
2803 clear_atomic_switch_msr(vmx, MSR_EFER);
2804
2805 /*
2806 * On EPT, we can't emulate NX, so we must switch EFER atomically.
2807 * On CPUs that support "load IA32_EFER", always switch EFER
2808 * atomically, since it's faster than switching it manually.
2809 */
2810 if (cpu_has_load_ia32_efer ||
2811 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
2812 if (!(guest_efer & EFER_LMA))
2813 guest_efer &= ~EFER_LME;
2814 if (guest_efer != host_efer)
2815 add_atomic_switch_msr(vmx, MSR_EFER,
2816 guest_efer, host_efer, false);
2817 return false;
2818 } else {
2819 guest_efer &= ~ignore_bits;
2820 guest_efer |= host_efer & ignore_bits;
2821
2822 vmx->guest_msrs[efer_offset].data = guest_efer;
2823 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
2824
2825 return true;
2826 }
2827}
2828
2829#ifdef CONFIG_X86_32
2830/*
2831 * On 32-bit kernels, VM exits still load the FS and GS bases from the
2832 * VMCS rather than the segment table. KVM uses this helper to figure
2833 * out the current bases to poke them into the VMCS before entry.
2834 */
2835static unsigned long segment_base(u16 selector)
2836{
2837 struct desc_struct *table;
2838 unsigned long v;
2839
2840 if (!(selector & ~SEGMENT_RPL_MASK))
2841 return 0;
2842
2843 table = get_current_gdt_ro();
2844
2845 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2846 u16 ldt_selector = kvm_read_ldt();
2847
2848 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
2849 return 0;
2850
2851 table = (struct desc_struct *)segment_base(ldt_selector);
2852 }
2853 v = get_desc_base(&table[selector >> 3]);
2854 return v;
2855}
2856#endif
2857
2858static void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
2859{
2860 struct vcpu_vmx *vmx = to_vmx(vcpu);
2861 struct vmcs_host_state *host_state;
2862#ifdef CONFIG_X86_64
2863 int cpu = raw_smp_processor_id();
2864#endif
2865 unsigned long fs_base, gs_base;
2866 u16 fs_sel, gs_sel;
2867 int i;
2868
2869 vmx->req_immediate_exit = false;
2870
2871 /*
2872 * Note that guest MSRs to be saved/restored can also be changed
2873 * when guest state is loaded. This happens when guest transitions
2874 * to/from long-mode by setting MSR_EFER.LMA.
2875 */
2876 if (!vmx->loaded_cpu_state || vmx->guest_msrs_dirty) {
2877 vmx->guest_msrs_dirty = false;
2878 for (i = 0; i < vmx->save_nmsrs; ++i)
2879 kvm_set_shared_msr(vmx->guest_msrs[i].index,
2880 vmx->guest_msrs[i].data,
2881 vmx->guest_msrs[i].mask);
2882
2883 }
2884
2885 if (vmx->loaded_cpu_state)
2886 return;
2887
2888 vmx->loaded_cpu_state = vmx->loaded_vmcs;
2889 host_state = &vmx->loaded_cpu_state->host_state;
2890
2891 /*
2892 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
2893 * allow segment selectors with cpl > 0 or ti == 1.
2894 */
2895 host_state->ldt_sel = kvm_read_ldt();
2896
2897#ifdef CONFIG_X86_64
2898 savesegment(ds, host_state->ds_sel);
2899 savesegment(es, host_state->es_sel);
2900
2901 gs_base = cpu_kernelmode_gs_base(cpu);
2902 if (likely(is_64bit_mm(current->mm))) {
2903 save_fsgs_for_kvm();
2904 fs_sel = current->thread.fsindex;
2905 gs_sel = current->thread.gsindex;
2906 fs_base = current->thread.fsbase;
2907 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
2908 } else {
2909 savesegment(fs, fs_sel);
2910 savesegment(gs, gs_sel);
2911 fs_base = read_msr(MSR_FS_BASE);
2912 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
2913 }
2914
2915 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2916#else
2917 savesegment(fs, fs_sel);
2918 savesegment(gs, gs_sel);
2919 fs_base = segment_base(fs_sel);
2920 gs_base = segment_base(gs_sel);
2921#endif
2922
2923 if (unlikely(fs_sel != host_state->fs_sel)) {
2924 if (!(fs_sel & 7))
2925 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
2926 else
2927 vmcs_write16(HOST_FS_SELECTOR, 0);
2928 host_state->fs_sel = fs_sel;
2929 }
2930 if (unlikely(gs_sel != host_state->gs_sel)) {
2931 if (!(gs_sel & 7))
2932 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
2933 else
2934 vmcs_write16(HOST_GS_SELECTOR, 0);
2935 host_state->gs_sel = gs_sel;
2936 }
2937 if (unlikely(fs_base != host_state->fs_base)) {
2938 vmcs_writel(HOST_FS_BASE, fs_base);
2939 host_state->fs_base = fs_base;
2940 }
2941 if (unlikely(gs_base != host_state->gs_base)) {
2942 vmcs_writel(HOST_GS_BASE, gs_base);
2943 host_state->gs_base = gs_base;
2944 }
2945}
2946
2947static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
2948{
2949 struct vmcs_host_state *host_state;
2950
2951 if (!vmx->loaded_cpu_state)
2952 return;
2953
2954 WARN_ON_ONCE(vmx->loaded_cpu_state != vmx->loaded_vmcs);
2955 host_state = &vmx->loaded_cpu_state->host_state;
2956
2957 ++vmx->vcpu.stat.host_state_reload;
2958 vmx->loaded_cpu_state = NULL;
2959
2960#ifdef CONFIG_X86_64
2961 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2962#endif
2963 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
2964 kvm_load_ldt(host_state->ldt_sel);
2965#ifdef CONFIG_X86_64
2966 load_gs_index(host_state->gs_sel);
2967#else
2968 loadsegment(gs, host_state->gs_sel);
2969#endif
2970 }
2971 if (host_state->fs_sel & 7)
2972 loadsegment(fs, host_state->fs_sel);
2973#ifdef CONFIG_X86_64
2974 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
2975 loadsegment(ds, host_state->ds_sel);
2976 loadsegment(es, host_state->es_sel);
2977 }
2978#endif
2979 invalidate_tss_limit();
2980#ifdef CONFIG_X86_64
2981 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2982#endif
2983 load_fixmap_gdt(raw_smp_processor_id());
2984}
2985
2986#ifdef CONFIG_X86_64
2987static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
2988{
2989 preempt_disable();
2990 if (vmx->loaded_cpu_state)
2991 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2992 preempt_enable();
2993 return vmx->msr_guest_kernel_gs_base;
2994}
2995
2996static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
2997{
2998 preempt_disable();
2999 if (vmx->loaded_cpu_state)
3000 wrmsrl(MSR_KERNEL_GS_BASE, data);
3001 preempt_enable();
3002 vmx->msr_guest_kernel_gs_base = data;
3003}
3004#endif
3005
3006static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
3007{
3008 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
3009 struct pi_desc old, new;
3010 unsigned int dest;
3011
3012 /*
3013 * In case of hot-plug or hot-unplug, we may have to undo
3014 * vmx_vcpu_pi_put even if there is no assigned device. And we
3015 * always keep PI.NDST up to date for simplicity: it makes the
3016 * code easier, and CPU migration is not a fast path.
3017 */
3018 if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
3019 return;
3020
3021 /*
3022 * First handle the simple case where no cmpxchg is necessary; just
3023 * allow posting non-urgent interrupts.
3024 *
3025 * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
3026 * PI.NDST: pi_post_block will do it for us and the wakeup_handler
3027 * expects the VCPU to be on the blocked_vcpu_list that matches
3028 * PI.NDST.
3029 */
3030 if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
3031 vcpu->cpu == cpu) {
3032 pi_clear_sn(pi_desc);
3033 return;
3034 }
3035
3036 /* The full case. */
3037 do {
3038 old.control = new.control = pi_desc->control;
3039
3040 dest = cpu_physical_id(cpu);
3041
3042 if (x2apic_enabled())
3043 new.ndst = dest;
3044 else
3045 new.ndst = (dest << 8) & 0xFF00;
3046
3047 new.sn = 0;
3048 } while (cmpxchg64(&pi_desc->control, old.control,
3049 new.control) != old.control);
3050}
3051
3052static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
3053{
3054 vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
3055 vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
3056}
3057
3058/*
3059 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
3060 * vcpu mutex is already taken.
3061 */
3062static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3063{
3064 struct vcpu_vmx *vmx = to_vmx(vcpu);
3065 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
3066
3067 if (!already_loaded) {
3068 loaded_vmcs_clear(vmx->loaded_vmcs);
3069 local_irq_disable();
3070 crash_disable_local_vmclear(cpu);
3071
3072 /*
3073 * Read loaded_vmcs->cpu should be before fetching
3074 * loaded_vmcs->loaded_vmcss_on_cpu_link.
3075 * See the comments in __loaded_vmcs_clear().
3076 */
3077 smp_rmb();
3078
3079 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
3080 &per_cpu(loaded_vmcss_on_cpu, cpu));
3081 crash_enable_local_vmclear(cpu);
3082 local_irq_enable();
3083 }
3084
3085 if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
3086 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
3087 vmcs_load(vmx->loaded_vmcs->vmcs);
3088 indirect_branch_prediction_barrier();
3089 }
3090
3091 if (!already_loaded) {
3092 void *gdt = get_current_gdt_ro();
3093 unsigned long sysenter_esp;
3094
3095 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3096
3097 /*
3098 * Linux uses per-cpu TSS and GDT, so set these when switching
3099 * processors. See 22.2.4.
3100 */
3101 vmcs_writel(HOST_TR_BASE,
3102 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
3103 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
3104
3105 /*
3106 * VM exits change the host TR limit to 0x67 after a VM
3107 * exit. This is okay, since 0x67 covers everything except
3108 * the IO bitmap and have have code to handle the IO bitmap
3109 * being lost after a VM exit.
3110 */
3111 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
3112
3113 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
3114 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
3115
3116 vmx->loaded_vmcs->cpu = cpu;
3117 }
3118
3119 /* Setup TSC multiplier */
3120 if (kvm_has_tsc_control &&
3121 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
3122 decache_tsc_multiplier(vmx);
3123
3124 vmx_vcpu_pi_load(vcpu, cpu);
3125 vmx->host_pkru = read_pkru();
3126 vmx->host_debugctlmsr = get_debugctlmsr();
3127}
3128
3129static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
3130{
3131 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
3132
3133 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
3134 !irq_remapping_cap(IRQ_POSTING_CAP) ||
3135 !kvm_vcpu_apicv_active(vcpu))
3136 return;
3137
3138 /* Set SN when the vCPU is preempted */
3139 if (vcpu->preempted)
3140 pi_set_sn(pi_desc);
3141}
3142
3143static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
3144{
3145 vmx_vcpu_pi_put(vcpu);
3146
3147 vmx_prepare_switch_to_host(to_vmx(vcpu));
3148}
3149
3150static bool emulation_required(struct kvm_vcpu *vcpu)
3151{
3152 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
3153}
3154
3155static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
3156
3157/*
3158 * Return the cr0 value that a nested guest would read. This is a combination
3159 * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
3160 * its hypervisor (cr0_read_shadow).
3161 */
3162static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
3163{
3164 return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
3165 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
3166}
3167static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
3168{
3169 return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
3170 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
3171}
3172
3173static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
3174{
3175 unsigned long rflags, save_rflags;
3176
3177 if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
3178 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
3179 rflags = vmcs_readl(GUEST_RFLAGS);
3180 if (to_vmx(vcpu)->rmode.vm86_active) {
3181 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
3182 save_rflags = to_vmx(vcpu)->rmode.save_rflags;
3183 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
3184 }
3185 to_vmx(vcpu)->rflags = rflags;
3186 }
3187 return to_vmx(vcpu)->rflags;
3188}
3189
3190static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
3191{
3192 unsigned long old_rflags = vmx_get_rflags(vcpu);
3193
3194 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
3195 to_vmx(vcpu)->rflags = rflags;
3196 if (to_vmx(vcpu)->rmode.vm86_active) {
3197 to_vmx(vcpu)->rmode.save_rflags = rflags;
3198 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
3199 }
3200 vmcs_writel(GUEST_RFLAGS, rflags);
3201
3202 if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
3203 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
3204}
3205
3206static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
3207{
3208 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
3209 int ret = 0;
3210
3211 if (interruptibility & GUEST_INTR_STATE_STI)
3212 ret |= KVM_X86_SHADOW_INT_STI;
3213 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
3214 ret |= KVM_X86_SHADOW_INT_MOV_SS;
3215
3216 return ret;
3217}
3218
3219static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
3220{
3221 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
3222 u32 interruptibility = interruptibility_old;
3223
3224 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
3225
3226 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
3227 interruptibility |= GUEST_INTR_STATE_MOV_SS;
3228 else if (mask & KVM_X86_SHADOW_INT_STI)
3229 interruptibility |= GUEST_INTR_STATE_STI;
3230
3231 if ((interruptibility != interruptibility_old))
3232 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
3233}
3234
3235static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
3236{
3237 unsigned long rip;
3238
3239 rip = kvm_rip_read(vcpu);
3240 rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
3241 kvm_rip_write(vcpu, rip);
3242
3243 /* skipping an emulated instruction also counts */
3244 vmx_set_interrupt_shadow(vcpu, 0);
3245}
3246
3247static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
3248 unsigned long exit_qual)
3249{
3250 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3251 unsigned int nr = vcpu->arch.exception.nr;
3252 u32 intr_info = nr | INTR_INFO_VALID_MASK;
3253
3254 if (vcpu->arch.exception.has_error_code) {
3255 vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code;
3256 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
3257 }
3258
3259 if (kvm_exception_is_soft(nr))
3260 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
3261 else
3262 intr_info |= INTR_TYPE_HARD_EXCEPTION;
3263
3264 if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
3265 vmx_get_nmi_mask(vcpu))
3266 intr_info |= INTR_INFO_UNBLOCK_NMI;
3267
3268 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
3269}
3270
3271/*
3272 * KVM wants to inject page-faults which it got to the guest. This function
3273 * checks whether in a nested guest, we need to inject them to L1 or L2.
3274 */
3275static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned long *exit_qual)
3276{
3277 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3278 unsigned int nr = vcpu->arch.exception.nr;
3279
3280 if (nr == PF_VECTOR) {
3281 if (vcpu->arch.exception.nested_apf) {
3282 *exit_qual = vcpu->arch.apf.nested_apf_token;
3283 return 1;
3284 }
3285 /*
3286 * FIXME: we must not write CR2 when L1 intercepts an L2 #PF exception.
3287 * The fix is to add the ancillary datum (CR2 or DR6) to structs
3288 * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6
3289 * can be written only when inject_pending_event runs. This should be
3290 * conditional on a new capability---if the capability is disabled,
3291 * kvm_multiple_exception would write the ancillary information to
3292 * CR2 or DR6, for backwards ABI-compatibility.
3293 */
3294 if (nested_vmx_is_page_fault_vmexit(vmcs12,
3295 vcpu->arch.exception.error_code)) {
3296 *exit_qual = vcpu->arch.cr2;
3297 return 1;
3298 }
3299 } else {
3300 if (vmcs12->exception_bitmap & (1u << nr)) {
3301 if (nr == DB_VECTOR) {
3302 *exit_qual = vcpu->arch.dr6;
3303 *exit_qual &= ~(DR6_FIXED_1 | DR6_BT);
3304 *exit_qual ^= DR6_RTM;
3305 } else {
3306 *exit_qual = 0;
3307 }
3308 return 1;
3309 }
3310 }
3311
3312 return 0;
3313}
3314
3315static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
3316{
3317 /*
3318 * Ensure that we clear the HLT state in the VMCS. We don't need to
3319 * explicitly skip the instruction because if the HLT state is set,
3320 * then the instruction is already executing and RIP has already been
3321 * advanced.
3322 */
3323 if (kvm_hlt_in_guest(vcpu->kvm) &&
3324 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
3325 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
3326}
3327
3328static void vmx_queue_exception(struct kvm_vcpu *vcpu)
3329{
3330 struct vcpu_vmx *vmx = to_vmx(vcpu);
3331 unsigned nr = vcpu->arch.exception.nr;
3332 bool has_error_code = vcpu->arch.exception.has_error_code;
3333 u32 error_code = vcpu->arch.exception.error_code;
3334 u32 intr_info = nr | INTR_INFO_VALID_MASK;
3335
3336 if (has_error_code) {
3337 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
3338 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
3339 }
3340
3341 if (vmx->rmode.vm86_active) {
3342 int inc_eip = 0;
3343 if (kvm_exception_is_soft(nr))
3344 inc_eip = vcpu->arch.event_exit_inst_len;
3345 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
3346 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3347 return;
3348 }
3349
3350 WARN_ON_ONCE(vmx->emulation_required);
3351
3352 if (kvm_exception_is_soft(nr)) {
3353 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
3354 vmx->vcpu.arch.event_exit_inst_len);
3355 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
3356 } else
3357 intr_info |= INTR_TYPE_HARD_EXCEPTION;
3358
3359 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
3360
3361 vmx_clear_hlt(vcpu);
3362}
3363
3364static bool vmx_rdtscp_supported(void)
3365{
3366 return cpu_has_vmx_rdtscp();
3367}
3368
3369static bool vmx_invpcid_supported(void)
3370{
3371 return cpu_has_vmx_invpcid();
3372}
3373
3374/*
3375 * Swap MSR entry in host/guest MSR entry array.
3376 */
3377static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
3378{
3379 struct shared_msr_entry tmp;
3380
3381 tmp = vmx->guest_msrs[to];
3382 vmx->guest_msrs[to] = vmx->guest_msrs[from];
3383 vmx->guest_msrs[from] = tmp;
3384}
3385
3386/*
3387 * Set up the vmcs to automatically save and restore system
3388 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
3389 * mode, as fiddling with msrs is very expensive.
3390 */
3391static void setup_msrs(struct vcpu_vmx *vmx)
3392{
3393 int save_nmsrs, index;
3394
3395 save_nmsrs = 0;
3396#ifdef CONFIG_X86_64
3397 if (is_long_mode(&vmx->vcpu)) {
3398 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
3399 if (index >= 0)
3400 move_msr_up(vmx, index, save_nmsrs++);
3401 index = __find_msr_index(vmx, MSR_LSTAR);
3402 if (index >= 0)
3403 move_msr_up(vmx, index, save_nmsrs++);
3404 index = __find_msr_index(vmx, MSR_CSTAR);
3405 if (index >= 0)
3406 move_msr_up(vmx, index, save_nmsrs++);
3407 /*
3408 * MSR_STAR is only needed on long mode guests, and only
3409 * if efer.sce is enabled.
3410 */
3411 index = __find_msr_index(vmx, MSR_STAR);
3412 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
3413 move_msr_up(vmx, index, save_nmsrs++);
3414 }
3415#endif
3416 index = __find_msr_index(vmx, MSR_EFER);
3417 if (index >= 0 && update_transition_efer(vmx, index))
3418 move_msr_up(vmx, index, save_nmsrs++);
3419 index = __find_msr_index(vmx, MSR_TSC_AUX);
3420 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
3421 move_msr_up(vmx, index, save_nmsrs++);
3422
3423 vmx->save_nmsrs = save_nmsrs;
3424 vmx->guest_msrs_dirty = true;
3425
3426 if (cpu_has_vmx_msr_bitmap())
3427 vmx_update_msr_bitmap(&vmx->vcpu);
3428}
3429
3430static u64 vmx_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
3431{
3432 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3433
3434 if (is_guest_mode(vcpu) &&
3435 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
3436 return vcpu->arch.tsc_offset - vmcs12->tsc_offset;
3437
3438 return vcpu->arch.tsc_offset;
3439}
3440
3441static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
3442{
3443 u64 active_offset = offset;
3444 if (is_guest_mode(vcpu)) {
3445 /*
3446 * We're here if L1 chose not to trap WRMSR to TSC. According
3447 * to the spec, this should set L1's TSC; The offset that L1
3448 * set for L2 remains unchanged, and still needs to be added
3449 * to the newly set TSC to get L2's TSC.
3450 */
3451 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3452 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING))
3453 active_offset += vmcs12->tsc_offset;
3454 } else {
3455 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
3456 vmcs_read64(TSC_OFFSET), offset);
3457 }
3458
3459 vmcs_write64(TSC_OFFSET, active_offset);
3460 return active_offset;
3461}
3462
3463/*
3464 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
3465 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
3466 * all guests if the "nested" module option is off, and can also be disabled
3467 * for a single guest by disabling its VMX cpuid bit.
3468 */
3469static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
3470{
3471 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
3472}
3473
3474/*
3475 * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
3476 * returned for the various VMX controls MSRs when nested VMX is enabled.
3477 * The same values should also be used to verify that vmcs12 control fields are
3478 * valid during nested entry from L1 to L2.
3479 * Each of these control msrs has a low and high 32-bit half: A low bit is on
3480 * if the corresponding bit in the (32-bit) control field *must* be on, and a
3481 * bit in the high half is on if the corresponding bit in the control field
3482 * may be on. See also vmx_control_verify().
3483 */
3484static void nested_vmx_setup_ctls_msrs(struct nested_vmx_msrs *msrs, bool apicv)
3485{
3486 if (!nested) {
3487 memset(msrs, 0, sizeof(*msrs));
3488 return;
3489 }
3490
3491 /*
3492 * Note that as a general rule, the high half of the MSRs (bits in
3493 * the control fields which may be 1) should be initialized by the
3494 * intersection of the underlying hardware's MSR (i.e., features which
3495 * can be supported) and the list of features we want to expose -
3496 * because they are known to be properly supported in our code.
3497 * Also, usually, the low half of the MSRs (bits which must be 1) can
3498 * be set to 0, meaning that L1 may turn off any of these bits. The
3499 * reason is that if one of these bits is necessary, it will appear
3500 * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
3501 * fields of vmcs01 and vmcs02, will turn these bits off - and
3502 * nested_vmx_exit_reflected() will not pass related exits to L1.
3503 * These rules have exceptions below.
3504 */
3505
3506 /* pin-based controls */
3507 rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
3508 msrs->pinbased_ctls_low,
3509 msrs->pinbased_ctls_high);
3510 msrs->pinbased_ctls_low |=
3511 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3512 msrs->pinbased_ctls_high &=
3513 PIN_BASED_EXT_INTR_MASK |
3514 PIN_BASED_NMI_EXITING |
3515 PIN_BASED_VIRTUAL_NMIS |
3516 (apicv ? PIN_BASED_POSTED_INTR : 0);
3517 msrs->pinbased_ctls_high |=
3518 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
3519 PIN_BASED_VMX_PREEMPTION_TIMER;
3520
3521 /* exit controls */
3522 rdmsr(MSR_IA32_VMX_EXIT_CTLS,
3523 msrs->exit_ctls_low,
3524 msrs->exit_ctls_high);
3525 msrs->exit_ctls_low =
3526 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
3527
3528 msrs->exit_ctls_high &=
3529#ifdef CONFIG_X86_64
3530 VM_EXIT_HOST_ADDR_SPACE_SIZE |
3531#endif
3532 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
3533 msrs->exit_ctls_high |=
3534 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
3535 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
3536 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
3537
3538 /* We support free control of debug control saving. */
3539 msrs->exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
3540
3541 /* entry controls */
3542 rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
3543 msrs->entry_ctls_low,
3544 msrs->entry_ctls_high);
3545 msrs->entry_ctls_low =
3546 VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
3547 msrs->entry_ctls_high &=
3548#ifdef CONFIG_X86_64
3549 VM_ENTRY_IA32E_MODE |
3550#endif
3551 VM_ENTRY_LOAD_IA32_PAT;
3552 msrs->entry_ctls_high |=
3553 (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
3554
3555 /* We support free control of debug control loading. */
3556 msrs->entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
3557
3558 /* cpu-based controls */
3559 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
3560 msrs->procbased_ctls_low,
3561 msrs->procbased_ctls_high);
3562 msrs->procbased_ctls_low =
3563 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3564 msrs->procbased_ctls_high &=
3565 CPU_BASED_VIRTUAL_INTR_PENDING |
3566 CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
3567 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
3568 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
3569 CPU_BASED_CR3_STORE_EXITING |
3570#ifdef CONFIG_X86_64
3571 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
3572#endif
3573 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
3574 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
3575 CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
3576 CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
3577 CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
3578 /*
3579 * We can allow some features even when not supported by the
3580 * hardware. For example, L1 can specify an MSR bitmap - and we
3581 * can use it to avoid exits to L1 - even when L0 runs L2
3582 * without MSR bitmaps.
3583 */
3584 msrs->procbased_ctls_high |=
3585 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
3586 CPU_BASED_USE_MSR_BITMAPS;
3587
3588 /* We support free control of CR3 access interception. */
3589 msrs->procbased_ctls_low &=
3590 ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
3591
3592 /*
3593 * secondary cpu-based controls. Do not include those that
3594 * depend on CPUID bits, they are added later by vmx_cpuid_update.
3595 */
3596 if (msrs->procbased_ctls_high & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)
3597 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
3598 msrs->secondary_ctls_low,
3599 msrs->secondary_ctls_high);
3600
3601 msrs->secondary_ctls_low = 0;
3602 msrs->secondary_ctls_high &=
3603 SECONDARY_EXEC_DESC |
3604 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3605 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3606 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
3607 SECONDARY_EXEC_WBINVD_EXITING;
3608
3609 /*
3610 * We can emulate "VMCS shadowing," even if the hardware
3611 * doesn't support it.
3612 */
3613 msrs->secondary_ctls_high |=
3614 SECONDARY_EXEC_SHADOW_VMCS;
3615
3616 if (enable_ept) {
3617 /* nested EPT: emulate EPT also to L1 */
3618 msrs->secondary_ctls_high |=
3619 SECONDARY_EXEC_ENABLE_EPT;
3620 msrs->ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
3621 VMX_EPTP_WB_BIT | VMX_EPT_INVEPT_BIT;
3622 if (cpu_has_vmx_ept_execute_only())
3623 msrs->ept_caps |=
3624 VMX_EPT_EXECUTE_ONLY_BIT;
3625 msrs->ept_caps &= vmx_capability.ept;
3626 msrs->ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
3627 VMX_EPT_EXTENT_CONTEXT_BIT | VMX_EPT_2MB_PAGE_BIT |
3628 VMX_EPT_1GB_PAGE_BIT;
3629 if (enable_ept_ad_bits) {
3630 msrs->secondary_ctls_high |=
3631 SECONDARY_EXEC_ENABLE_PML;
3632 msrs->ept_caps |= VMX_EPT_AD_BIT;
3633 }
3634 }
3635
3636 if (cpu_has_vmx_vmfunc()) {
3637 msrs->secondary_ctls_high |=
3638 SECONDARY_EXEC_ENABLE_VMFUNC;
3639 /*
3640 * Advertise EPTP switching unconditionally
3641 * since we emulate it
3642 */
3643 if (enable_ept)
3644 msrs->vmfunc_controls =
3645 VMX_VMFUNC_EPTP_SWITCHING;
3646 }
3647
3648 /*
3649 * Old versions of KVM use the single-context version without
3650 * checking for support, so declare that it is supported even
3651 * though it is treated as global context. The alternative is
3652 * not failing the single-context invvpid, and it is worse.
3653 */
3654 if (enable_vpid) {
3655 msrs->secondary_ctls_high |=
3656 SECONDARY_EXEC_ENABLE_VPID;
3657 msrs->vpid_caps = VMX_VPID_INVVPID_BIT |
3658 VMX_VPID_EXTENT_SUPPORTED_MASK;
3659 }
3660
3661 if (enable_unrestricted_guest)
3662 msrs->secondary_ctls_high |=
3663 SECONDARY_EXEC_UNRESTRICTED_GUEST;
3664
3665 if (flexpriority_enabled)
3666 msrs->secondary_ctls_high |=
3667 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
3668
3669 /* miscellaneous data */
3670 rdmsr(MSR_IA32_VMX_MISC,
3671 msrs->misc_low,
3672 msrs->misc_high);
3673 msrs->misc_low &= VMX_MISC_SAVE_EFER_LMA;
3674 msrs->misc_low |=
3675 MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS |
3676 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
3677 VMX_MISC_ACTIVITY_HLT;
3678 msrs->misc_high = 0;
3679
3680 /*
3681 * This MSR reports some information about VMX support. We
3682 * should return information about the VMX we emulate for the
3683 * guest, and the VMCS structure we give it - not about the
3684 * VMX support of the underlying hardware.
3685 */
3686 msrs->basic =
3687 VMCS12_REVISION |
3688 VMX_BASIC_TRUE_CTLS |
3689 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
3690 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
3691
3692 if (cpu_has_vmx_basic_inout())
3693 msrs->basic |= VMX_BASIC_INOUT;
3694
3695 /*
3696 * These MSRs specify bits which the guest must keep fixed on
3697 * while L1 is in VMXON mode (in L1's root mode, or running an L2).
3698 * We picked the standard core2 setting.
3699 */
3700#define VMXON_CR0_ALWAYSON (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
3701#define VMXON_CR4_ALWAYSON X86_CR4_VMXE
3702 msrs->cr0_fixed0 = VMXON_CR0_ALWAYSON;
3703 msrs->cr4_fixed0 = VMXON_CR4_ALWAYSON;
3704
3705 /* These MSRs specify bits which the guest must keep fixed off. */
3706 rdmsrl(MSR_IA32_VMX_CR0_FIXED1, msrs->cr0_fixed1);
3707 rdmsrl(MSR_IA32_VMX_CR4_FIXED1, msrs->cr4_fixed1);
3708
3709 /* highest index: VMX_PREEMPTION_TIMER_VALUE */
3710 msrs->vmcs_enum = VMCS12_MAX_FIELD_INDEX << 1;
3711}
3712
3713/*
3714 * if fixed0[i] == 1: val[i] must be 1
3715 * if fixed1[i] == 0: val[i] must be 0
3716 */
3717static inline bool fixed_bits_valid(u64 val, u64 fixed0, u64 fixed1)
3718{
3719 return ((val & fixed1) | fixed0) == val;
3720}
3721
3722static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
3723{
3724 return fixed_bits_valid(control, low, high);
3725}
3726
3727static inline u64 vmx_control_msr(u32 low, u32 high)
3728{
3729 return low | ((u64)high << 32);
3730}
3731
3732static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
3733{
3734 superset &= mask;
3735 subset &= mask;
3736
3737 return (superset | subset) == superset;
3738}
3739
3740static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
3741{
3742 const u64 feature_and_reserved =
3743 /* feature (except bit 48; see below) */
3744 BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
3745 /* reserved */
3746 BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
3747 u64 vmx_basic = vmx->nested.msrs.basic;
3748
3749 if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
3750 return -EINVAL;
3751
3752 /*
3753 * KVM does not emulate a version of VMX that constrains physical
3754 * addresses of VMX structures (e.g. VMCS) to 32-bits.
3755 */
3756 if (data & BIT_ULL(48))
3757 return -EINVAL;
3758
3759 if (vmx_basic_vmcs_revision_id(vmx_basic) !=
3760 vmx_basic_vmcs_revision_id(data))
3761 return -EINVAL;
3762
3763 if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
3764 return -EINVAL;
3765
3766 vmx->nested.msrs.basic = data;
3767 return 0;
3768}
3769
3770static int
3771vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3772{
3773 u64 supported;
3774 u32 *lowp, *highp;
3775
3776 switch (msr_index) {
3777 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3778 lowp = &vmx->nested.msrs.pinbased_ctls_low;
3779 highp = &vmx->nested.msrs.pinbased_ctls_high;
3780 break;
3781 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3782 lowp = &vmx->nested.msrs.procbased_ctls_low;
3783 highp = &vmx->nested.msrs.procbased_ctls_high;
3784 break;
3785 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3786 lowp = &vmx->nested.msrs.exit_ctls_low;
3787 highp = &vmx->nested.msrs.exit_ctls_high;
3788 break;
3789 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3790 lowp = &vmx->nested.msrs.entry_ctls_low;
3791 highp = &vmx->nested.msrs.entry_ctls_high;
3792 break;
3793 case MSR_IA32_VMX_PROCBASED_CTLS2:
3794 lowp = &vmx->nested.msrs.secondary_ctls_low;
3795 highp = &vmx->nested.msrs.secondary_ctls_high;
3796 break;
3797 default:
3798 BUG();
3799 }
3800
3801 supported = vmx_control_msr(*lowp, *highp);
3802
3803 /* Check must-be-1 bits are still 1. */
3804 if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
3805 return -EINVAL;
3806
3807 /* Check must-be-0 bits are still 0. */
3808 if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
3809 return -EINVAL;
3810
3811 *lowp = data;
3812 *highp = data >> 32;
3813 return 0;
3814}
3815
3816static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
3817{
3818 const u64 feature_and_reserved_bits =
3819 /* feature */
3820 BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
3821 BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
3822 /* reserved */
3823 GENMASK_ULL(13, 9) | BIT_ULL(31);
3824 u64 vmx_misc;
3825
3826 vmx_misc = vmx_control_msr(vmx->nested.msrs.misc_low,
3827 vmx->nested.msrs.misc_high);
3828
3829 if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
3830 return -EINVAL;
3831
3832 if ((vmx->nested.msrs.pinbased_ctls_high &
3833 PIN_BASED_VMX_PREEMPTION_TIMER) &&
3834 vmx_misc_preemption_timer_rate(data) !=
3835 vmx_misc_preemption_timer_rate(vmx_misc))
3836 return -EINVAL;
3837
3838 if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
3839 return -EINVAL;
3840
3841 if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
3842 return -EINVAL;
3843
3844 if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
3845 return -EINVAL;
3846
3847 vmx->nested.msrs.misc_low = data;
3848 vmx->nested.msrs.misc_high = data >> 32;
3849
3850 /*
3851 * If L1 has read-only VM-exit information fields, use the
3852 * less permissive vmx_vmwrite_bitmap to specify write
3853 * permissions for the shadow VMCS.
3854 */
3855 if (enable_shadow_vmcs && !nested_cpu_has_vmwrite_any_field(&vmx->vcpu))
3856 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
3857
3858 return 0;
3859}
3860
3861static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
3862{
3863 u64 vmx_ept_vpid_cap;
3864
3865 vmx_ept_vpid_cap = vmx_control_msr(vmx->nested.msrs.ept_caps,
3866 vmx->nested.msrs.vpid_caps);
3867
3868 /* Every bit is either reserved or a feature bit. */
3869 if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
3870 return -EINVAL;
3871
3872 vmx->nested.msrs.ept_caps = data;
3873 vmx->nested.msrs.vpid_caps = data >> 32;
3874 return 0;
3875}
3876
3877static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3878{
3879 u64 *msr;
3880
3881 switch (msr_index) {
3882 case MSR_IA32_VMX_CR0_FIXED0:
3883 msr = &vmx->nested.msrs.cr0_fixed0;
3884 break;
3885 case MSR_IA32_VMX_CR4_FIXED0:
3886 msr = &vmx->nested.msrs.cr4_fixed0;
3887 break;
3888 default:
3889 BUG();
3890 }
3891
3892 /*
3893 * 1 bits (which indicates bits which "must-be-1" during VMX operation)
3894 * must be 1 in the restored value.
3895 */
3896 if (!is_bitwise_subset(data, *msr, -1ULL))
3897 return -EINVAL;
3898
3899 *msr = data;
3900 return 0;
3901}
3902
3903/*
3904 * Called when userspace is restoring VMX MSRs.
3905 *
3906 * Returns 0 on success, non-0 otherwise.
3907 */
3908static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
3909{
3910 struct vcpu_vmx *vmx = to_vmx(vcpu);
3911
3912 /*
3913 * Don't allow changes to the VMX capability MSRs while the vCPU
3914 * is in VMX operation.
3915 */
3916 if (vmx->nested.vmxon)
3917 return -EBUSY;
3918
3919 switch (msr_index) {
3920 case MSR_IA32_VMX_BASIC:
3921 return vmx_restore_vmx_basic(vmx, data);
3922 case MSR_IA32_VMX_PINBASED_CTLS:
3923 case MSR_IA32_VMX_PROCBASED_CTLS:
3924 case MSR_IA32_VMX_EXIT_CTLS:
3925 case MSR_IA32_VMX_ENTRY_CTLS:
3926 /*
3927 * The "non-true" VMX capability MSRs are generated from the
3928 * "true" MSRs, so we do not support restoring them directly.
3929 *
3930 * If userspace wants to emulate VMX_BASIC[55]=0, userspace
3931 * should restore the "true" MSRs with the must-be-1 bits
3932 * set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
3933 * DEFAULT SETTINGS".
3934 */
3935 return -EINVAL;
3936 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3937 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3938 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3939 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3940 case MSR_IA32_VMX_PROCBASED_CTLS2:
3941 return vmx_restore_control_msr(vmx, msr_index, data);
3942 case MSR_IA32_VMX_MISC:
3943 return vmx_restore_vmx_misc(vmx, data);
3944 case MSR_IA32_VMX_CR0_FIXED0:
3945 case MSR_IA32_VMX_CR4_FIXED0:
3946 return vmx_restore_fixed0_msr(vmx, msr_index, data);
3947 case MSR_IA32_VMX_CR0_FIXED1:
3948 case MSR_IA32_VMX_CR4_FIXED1:
3949 /*
3950 * These MSRs are generated based on the vCPU's CPUID, so we
3951 * do not support restoring them directly.
3952 */
3953 return -EINVAL;
3954 case MSR_IA32_VMX_EPT_VPID_CAP:
3955 return vmx_restore_vmx_ept_vpid_cap(vmx, data);
3956 case MSR_IA32_VMX_VMCS_ENUM:
3957 vmx->nested.msrs.vmcs_enum = data;
3958 return 0;
3959 default:
3960 /*
3961 * The rest of the VMX capability MSRs do not support restore.
3962 */
3963 return -EINVAL;
3964 }
3965}
3966
3967/* Returns 0 on success, non-0 otherwise. */
3968static int vmx_get_vmx_msr(struct nested_vmx_msrs *msrs, u32 msr_index, u64 *pdata)
3969{
3970 switch (msr_index) {
3971 case MSR_IA32_VMX_BASIC:
3972 *pdata = msrs->basic;
3973 break;
3974 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3975 case MSR_IA32_VMX_PINBASED_CTLS:
3976 *pdata = vmx_control_msr(
3977 msrs->pinbased_ctls_low,
3978 msrs->pinbased_ctls_high);
3979 if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
3980 *pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3981 break;
3982 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3983 case MSR_IA32_VMX_PROCBASED_CTLS:
3984 *pdata = vmx_control_msr(
3985 msrs->procbased_ctls_low,
3986 msrs->procbased_ctls_high);
3987 if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
3988 *pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3989 break;
3990 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3991 case MSR_IA32_VMX_EXIT_CTLS:
3992 *pdata = vmx_control_msr(
3993 msrs->exit_ctls_low,
3994 msrs->exit_ctls_high);
3995 if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
3996 *pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
3997 break;
3998 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3999 case MSR_IA32_VMX_ENTRY_CTLS:
4000 *pdata = vmx_control_msr(
4001 msrs->entry_ctls_low,
4002 msrs->entry_ctls_high);
4003 if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
4004 *pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
4005 break;
4006 case MSR_IA32_VMX_MISC:
4007 *pdata = vmx_control_msr(
4008 msrs->misc_low,
4009 msrs->misc_high);
4010 break;
4011 case MSR_IA32_VMX_CR0_FIXED0:
4012 *pdata = msrs->cr0_fixed0;
4013 break;
4014 case MSR_IA32_VMX_CR0_FIXED1:
4015 *pdata = msrs->cr0_fixed1;
4016 break;
4017 case MSR_IA32_VMX_CR4_FIXED0:
4018 *pdata = msrs->cr4_fixed0;
4019 break;
4020 case MSR_IA32_VMX_CR4_FIXED1:
4021 *pdata = msrs->cr4_fixed1;
4022 break;
4023 case MSR_IA32_VMX_VMCS_ENUM:
4024 *pdata = msrs->vmcs_enum;
4025 break;
4026 case MSR_IA32_VMX_PROCBASED_CTLS2:
4027 *pdata = vmx_control_msr(
4028 msrs->secondary_ctls_low,
4029 msrs->secondary_ctls_high);
4030 break;
4031 case MSR_IA32_VMX_EPT_VPID_CAP:
4032 *pdata = msrs->ept_caps |
4033 ((u64)msrs->vpid_caps << 32);
4034 break;
4035 case MSR_IA32_VMX_VMFUNC:
4036 *pdata = msrs->vmfunc_controls;
4037 break;
4038 default:
4039 return 1;
4040 }
4041
4042 return 0;
4043}
4044
4045static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
4046 uint64_t val)
4047{
4048 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
4049
4050 return !(val & ~valid_bits);
4051}
4052
4053static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
4054{
4055 switch (msr->index) {
4056 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4057 if (!nested)
4058 return 1;
4059 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
4060 default:
4061 return 1;
4062 }
4063
4064 return 0;
4065}
4066
4067/*
4068 * Reads an msr value (of 'msr_index') into 'pdata'.
4069 * Returns 0 on success, non-0 otherwise.
4070 * Assumes vcpu_load() was already called.
4071 */
4072static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4073{
4074 struct vcpu_vmx *vmx = to_vmx(vcpu);
4075 struct shared_msr_entry *msr;
4076
4077 switch (msr_info->index) {
4078#ifdef CONFIG_X86_64
4079 case MSR_FS_BASE:
4080 msr_info->data = vmcs_readl(GUEST_FS_BASE);
4081 break;
4082 case MSR_GS_BASE:
4083 msr_info->data = vmcs_readl(GUEST_GS_BASE);
4084 break;
4085 case MSR_KERNEL_GS_BASE:
4086 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
4087 break;
4088#endif
4089 case MSR_EFER:
4090 return kvm_get_msr_common(vcpu, msr_info);
4091 case MSR_IA32_SPEC_CTRL:
4092 if (!msr_info->host_initiated &&
4093 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
4094 return 1;
4095
4096 msr_info->data = to_vmx(vcpu)->spec_ctrl;
4097 break;
4098 case MSR_IA32_SYSENTER_CS:
4099 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
4100 break;
4101 case MSR_IA32_SYSENTER_EIP:
4102 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
4103 break;
4104 case MSR_IA32_SYSENTER_ESP:
4105 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
4106 break;
4107 case MSR_IA32_BNDCFGS:
4108 if (!kvm_mpx_supported() ||
4109 (!msr_info->host_initiated &&
4110 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
4111 return 1;
4112 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
4113 break;
4114 case MSR_IA32_MCG_EXT_CTL:
4115 if (!msr_info->host_initiated &&
4116 !(vmx->msr_ia32_feature_control &
4117 FEATURE_CONTROL_LMCE))
4118 return 1;
4119 msr_info->data = vcpu->arch.mcg_ext_ctl;
4120 break;
4121 case MSR_IA32_FEATURE_CONTROL:
4122 msr_info->data = vmx->msr_ia32_feature_control;
4123 break;
4124 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4125 if (!nested_vmx_allowed(vcpu))
4126 return 1;
4127 return vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
4128 &msr_info->data);
4129 case MSR_IA32_XSS:
4130 if (!vmx_xsaves_supported() ||
4131 (!msr_info->host_initiated &&
4132 !(guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4133 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))))
4134 return 1;
4135 msr_info->data = vcpu->arch.ia32_xss;
4136 break;
4137 case MSR_TSC_AUX:
4138 if (!msr_info->host_initiated &&
4139 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
4140 return 1;
4141 /* Otherwise falls through */
4142 default:
4143 msr = find_msr_entry(vmx, msr_info->index);
4144 if (msr) {
4145 msr_info->data = msr->data;
4146 break;
4147 }
4148 return kvm_get_msr_common(vcpu, msr_info);
4149 }
4150
4151 return 0;
4152}
4153
4154static void vmx_leave_nested(struct kvm_vcpu *vcpu);
4155
4156/*
4157 * Writes msr value into into the appropriate "register".
4158 * Returns 0 on success, non-0 otherwise.
4159 * Assumes vcpu_load() was already called.
4160 */
4161static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4162{
4163 struct vcpu_vmx *vmx = to_vmx(vcpu);
4164 struct shared_msr_entry *msr;
4165 int ret = 0;
4166 u32 msr_index = msr_info->index;
4167 u64 data = msr_info->data;
4168
4169 switch (msr_index) {
4170 case MSR_EFER:
4171 ret = kvm_set_msr_common(vcpu, msr_info);
4172 break;
4173#ifdef CONFIG_X86_64
4174 case MSR_FS_BASE:
4175 vmx_segment_cache_clear(vmx);
4176 vmcs_writel(GUEST_FS_BASE, data);
4177 break;
4178 case MSR_GS_BASE:
4179 vmx_segment_cache_clear(vmx);
4180 vmcs_writel(GUEST_GS_BASE, data);
4181 break;
4182 case MSR_KERNEL_GS_BASE:
4183 vmx_write_guest_kernel_gs_base(vmx, data);
4184 break;
4185#endif
4186 case MSR_IA32_SYSENTER_CS:
4187 vmcs_write32(GUEST_SYSENTER_CS, data);
4188 break;
4189 case MSR_IA32_SYSENTER_EIP:
4190 vmcs_writel(GUEST_SYSENTER_EIP, data);
4191 break;
4192 case MSR_IA32_SYSENTER_ESP:
4193 vmcs_writel(GUEST_SYSENTER_ESP, data);
4194 break;
4195 case MSR_IA32_BNDCFGS:
4196 if (!kvm_mpx_supported() ||
4197 (!msr_info->host_initiated &&
4198 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
4199 return 1;
4200 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
4201 (data & MSR_IA32_BNDCFGS_RSVD))
4202 return 1;
4203 vmcs_write64(GUEST_BNDCFGS, data);
4204 break;
4205 case MSR_IA32_SPEC_CTRL:
4206 if (!msr_info->host_initiated &&
4207 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
4208 return 1;
4209
4210 /* The STIBP bit doesn't fault even if it's not advertised */
4211 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
4212 return 1;
4213
4214 vmx->spec_ctrl = data;
4215
4216 if (!data)
4217 break;
4218
4219 /*
4220 * For non-nested:
4221 * When it's written (to non-zero) for the first time, pass
4222 * it through.
4223 *
4224 * For nested:
4225 * The handling of the MSR bitmap for L2 guests is done in
4226 * nested_vmx_merge_msr_bitmap. We should not touch the
4227 * vmcs02.msr_bitmap here since it gets completely overwritten
4228 * in the merging. We update the vmcs01 here for L1 as well
4229 * since it will end up touching the MSR anyway now.
4230 */
4231 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
4232 MSR_IA32_SPEC_CTRL,
4233 MSR_TYPE_RW);
4234 break;
4235 case MSR_IA32_PRED_CMD:
4236 if (!msr_info->host_initiated &&
4237 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
4238 return 1;
4239
4240 if (data & ~PRED_CMD_IBPB)
4241 return 1;
4242
4243 if (!data)
4244 break;
4245
4246 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
4247
4248 /*
4249 * For non-nested:
4250 * When it's written (to non-zero) for the first time, pass
4251 * it through.
4252 *
4253 * For nested:
4254 * The handling of the MSR bitmap for L2 guests is done in
4255 * nested_vmx_merge_msr_bitmap. We should not touch the
4256 * vmcs02.msr_bitmap here since it gets completely overwritten
4257 * in the merging.
4258 */
4259 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
4260 MSR_TYPE_W);
4261 break;
4262 case MSR_IA32_CR_PAT:
4263 if (!kvm_pat_valid(data))
4264 return 1;
4265
4266 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
4267 vmcs_write64(GUEST_IA32_PAT, data);
4268 vcpu->arch.pat = data;
4269 break;
4270 }
4271 ret = kvm_set_msr_common(vcpu, msr_info);
4272 break;
4273 case MSR_IA32_TSC_ADJUST:
4274 ret = kvm_set_msr_common(vcpu, msr_info);
4275 break;
4276 case MSR_IA32_MCG_EXT_CTL:
4277 if ((!msr_info->host_initiated &&
4278 !(to_vmx(vcpu)->msr_ia32_feature_control &
4279 FEATURE_CONTROL_LMCE)) ||
4280 (data & ~MCG_EXT_CTL_LMCE_EN))
4281 return 1;
4282 vcpu->arch.mcg_ext_ctl = data;
4283 break;
4284 case MSR_IA32_FEATURE_CONTROL:
4285 if (!vmx_feature_control_msr_valid(vcpu, data) ||
4286 (to_vmx(vcpu)->msr_ia32_feature_control &
4287 FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
4288 return 1;
4289 vmx->msr_ia32_feature_control = data;
4290 if (msr_info->host_initiated && data == 0)
4291 vmx_leave_nested(vcpu);
4292 break;
4293 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4294 if (!msr_info->host_initiated)
4295 return 1; /* they are read-only */
4296 if (!nested_vmx_allowed(vcpu))
4297 return 1;
4298 return vmx_set_vmx_msr(vcpu, msr_index, data);
4299 case MSR_IA32_XSS:
4300 if (!vmx_xsaves_supported() ||
4301 (!msr_info->host_initiated &&
4302 !(guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4303 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))))
4304 return 1;
4305 /*
4306 * The only supported bit as of Skylake is bit 8, but
4307 * it is not supported on KVM.
4308 */
4309 if (data != 0)
4310 return 1;
4311 vcpu->arch.ia32_xss = data;
4312 if (vcpu->arch.ia32_xss != host_xss)
4313 add_atomic_switch_msr(vmx, MSR_IA32_XSS,
4314 vcpu->arch.ia32_xss, host_xss, false);
4315 else
4316 clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
4317 break;
4318 case MSR_TSC_AUX:
4319 if (!msr_info->host_initiated &&
4320 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
4321 return 1;
4322 /* Check reserved bit, higher 32 bits should be zero */
4323 if ((data >> 32) != 0)
4324 return 1;
4325 /* Otherwise falls through */
4326 default:
4327 msr = find_msr_entry(vmx, msr_index);
4328 if (msr) {
4329 u64 old_msr_data = msr->data;
4330 msr->data = data;
4331 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
4332 preempt_disable();
4333 ret = kvm_set_shared_msr(msr->index, msr->data,
4334 msr->mask);
4335 preempt_enable();
4336 if (ret)
4337 msr->data = old_msr_data;
4338 }
4339 break;
4340 }
4341 ret = kvm_set_msr_common(vcpu, msr_info);
4342 }
4343
4344 return ret;
4345}
4346
4347static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
4348{
4349 __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
4350 switch (reg) {
4351 case VCPU_REGS_RSP:
4352 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
4353 break;
4354 case VCPU_REGS_RIP:
4355 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
4356 break;
4357 case VCPU_EXREG_PDPTR:
4358 if (enable_ept)
4359 ept_save_pdptrs(vcpu);
4360 break;
4361 default:
4362 break;
4363 }
4364}
4365
4366static __init int cpu_has_kvm_support(void)
4367{
4368 return cpu_has_vmx();
4369}
4370
4371static __init int vmx_disabled_by_bios(void)
4372{
4373 u64 msr;
4374
4375 rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
4376 if (msr & FEATURE_CONTROL_LOCKED) {
4377 /* launched w/ TXT and VMX disabled */
4378 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
4379 && tboot_enabled())
4380 return 1;
4381 /* launched w/o TXT and VMX only enabled w/ TXT */
4382 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
4383 && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
4384 && !tboot_enabled()) {
4385 printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
4386 "activate TXT before enabling KVM\n");
4387 return 1;
4388 }
4389 /* launched w/o TXT and VMX disabled */
4390 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
4391 && !tboot_enabled())
4392 return 1;
4393 }
4394
4395 return 0;
4396}
4397
4398static void kvm_cpu_vmxon(u64 addr)
4399{
4400 cr4_set_bits(X86_CR4_VMXE);
4401 intel_pt_handle_vmx(1);
4402
4403 asm volatile (ASM_VMX_VMXON_RAX
4404 : : "a"(&addr), "m"(addr)
4405 : "memory", "cc");
4406}
4407
4408static int hardware_enable(void)
4409{
4410 int cpu = raw_smp_processor_id();
4411 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
4412 u64 old, test_bits;
4413
4414 if (cr4_read_shadow() & X86_CR4_VMXE)
4415 return -EBUSY;
4416
4417 /*
4418 * This can happen if we hot-added a CPU but failed to allocate
4419 * VP assist page for it.
4420 */
4421 if (static_branch_unlikely(&enable_evmcs) &&
4422 !hv_get_vp_assist_page(cpu))
4423 return -EFAULT;
4424
4425 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
4426 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
4427 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
4428
4429 /*
4430 * Now we can enable the vmclear operation in kdump
4431 * since the loaded_vmcss_on_cpu list on this cpu
4432 * has been initialized.
4433 *
4434 * Though the cpu is not in VMX operation now, there
4435 * is no problem to enable the vmclear operation
4436 * for the loaded_vmcss_on_cpu list is empty!
4437 */
4438 crash_enable_local_vmclear(cpu);
4439
4440 rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
4441
4442 test_bits = FEATURE_CONTROL_LOCKED;
4443 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
4444 if (tboot_enabled())
4445 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
4446
4447 if ((old & test_bits) != test_bits) {
4448 /* enable and lock */
4449 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
4450 }
4451 kvm_cpu_vmxon(phys_addr);
4452 if (enable_ept)
4453 ept_sync_global();
4454
4455 return 0;
4456}
4457
4458static void vmclear_local_loaded_vmcss(void)
4459{
4460 int cpu = raw_smp_processor_id();
4461 struct loaded_vmcs *v, *n;
4462
4463 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
4464 loaded_vmcss_on_cpu_link)
4465 __loaded_vmcs_clear(v);
4466}
4467
4468
4469/* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
4470 * tricks.
4471 */
4472static void kvm_cpu_vmxoff(void)
4473{
4474 asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
4475
4476 intel_pt_handle_vmx(0);
4477 cr4_clear_bits(X86_CR4_VMXE);
4478}
4479
4480static void hardware_disable(void)
4481{
4482 vmclear_local_loaded_vmcss();
4483 kvm_cpu_vmxoff();
4484}
4485
4486static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
4487 u32 msr, u32 *result)
4488{
4489 u32 vmx_msr_low, vmx_msr_high;
4490 u32 ctl = ctl_min | ctl_opt;
4491
4492 rdmsr(msr, vmx_msr_low, vmx_msr_high);
4493
4494 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
4495 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
4496
4497 /* Ensure minimum (required) set of control bits are supported. */
4498 if (ctl_min & ~ctl)
4499 return -EIO;
4500
4501 *result = ctl;
4502 return 0;
4503}
4504
4505static __init bool allow_1_setting(u32 msr, u32 ctl)
4506{
4507 u32 vmx_msr_low, vmx_msr_high;
4508
4509 rdmsr(msr, vmx_msr_low, vmx_msr_high);
4510 return vmx_msr_high & ctl;
4511}
4512
4513static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
4514{
4515 u32 vmx_msr_low, vmx_msr_high;
4516 u32 min, opt, min2, opt2;
4517 u32 _pin_based_exec_control = 0;
4518 u32 _cpu_based_exec_control = 0;
4519 u32 _cpu_based_2nd_exec_control = 0;
4520 u32 _vmexit_control = 0;
4521 u32 _vmentry_control = 0;
4522
4523 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
4524 min = CPU_BASED_HLT_EXITING |
4525#ifdef CONFIG_X86_64
4526 CPU_BASED_CR8_LOAD_EXITING |
4527 CPU_BASED_CR8_STORE_EXITING |
4528#endif
4529 CPU_BASED_CR3_LOAD_EXITING |
4530 CPU_BASED_CR3_STORE_EXITING |
4531 CPU_BASED_UNCOND_IO_EXITING |
4532 CPU_BASED_MOV_DR_EXITING |
4533 CPU_BASED_USE_TSC_OFFSETING |
4534 CPU_BASED_MWAIT_EXITING |
4535 CPU_BASED_MONITOR_EXITING |
4536 CPU_BASED_INVLPG_EXITING |
4537 CPU_BASED_RDPMC_EXITING;
4538
4539 opt = CPU_BASED_TPR_SHADOW |
4540 CPU_BASED_USE_MSR_BITMAPS |
4541 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
4542 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
4543 &_cpu_based_exec_control) < 0)
4544 return -EIO;
4545#ifdef CONFIG_X86_64
4546 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
4547 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
4548 ~CPU_BASED_CR8_STORE_EXITING;
4549#endif
4550 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
4551 min2 = 0;
4552 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
4553 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
4554 SECONDARY_EXEC_WBINVD_EXITING |
4555 SECONDARY_EXEC_ENABLE_VPID |
4556 SECONDARY_EXEC_ENABLE_EPT |
4557 SECONDARY_EXEC_UNRESTRICTED_GUEST |
4558 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
4559 SECONDARY_EXEC_DESC |
4560 SECONDARY_EXEC_RDTSCP |
4561 SECONDARY_EXEC_ENABLE_INVPCID |
4562 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4563 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
4564 SECONDARY_EXEC_SHADOW_VMCS |
4565 SECONDARY_EXEC_XSAVES |
4566 SECONDARY_EXEC_RDSEED_EXITING |
4567 SECONDARY_EXEC_RDRAND_EXITING |
4568 SECONDARY_EXEC_ENABLE_PML |
4569 SECONDARY_EXEC_TSC_SCALING |
4570 SECONDARY_EXEC_ENABLE_VMFUNC |
4571 SECONDARY_EXEC_ENCLS_EXITING;
4572 if (adjust_vmx_controls(min2, opt2,
4573 MSR_IA32_VMX_PROCBASED_CTLS2,
4574 &_cpu_based_2nd_exec_control) < 0)
4575 return -EIO;
4576 }
4577#ifndef CONFIG_X86_64
4578 if (!(_cpu_based_2nd_exec_control &
4579 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
4580 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
4581#endif
4582
4583 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
4584 _cpu_based_2nd_exec_control &= ~(
4585 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4586 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
4587 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4588
4589 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
4590 &vmx_capability.ept, &vmx_capability.vpid);
4591
4592 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
4593 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
4594 enabled */
4595 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
4596 CPU_BASED_CR3_STORE_EXITING |
4597 CPU_BASED_INVLPG_EXITING);
4598 } else if (vmx_capability.ept) {
4599 vmx_capability.ept = 0;
4600 pr_warn_once("EPT CAP should not exist if not support "
4601 "1-setting enable EPT VM-execution control\n");
4602 }
4603 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
4604 vmx_capability.vpid) {
4605 vmx_capability.vpid = 0;
4606 pr_warn_once("VPID CAP should not exist if not support "
4607 "1-setting enable VPID VM-execution control\n");
4608 }
4609
4610 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
4611#ifdef CONFIG_X86_64
4612 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
4613#endif
4614 opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
4615 VM_EXIT_CLEAR_BNDCFGS;
4616 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
4617 &_vmexit_control) < 0)
4618 return -EIO;
4619
4620 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
4621 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
4622 PIN_BASED_VMX_PREEMPTION_TIMER;
4623 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
4624 &_pin_based_exec_control) < 0)
4625 return -EIO;
4626
4627 if (cpu_has_broken_vmx_preemption_timer())
4628 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4629 if (!(_cpu_based_2nd_exec_control &
4630 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
4631 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
4632
4633 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
4634 opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
4635 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
4636 &_vmentry_control) < 0)
4637 return -EIO;
4638
4639 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
4640
4641 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
4642 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
4643 return -EIO;
4644
4645#ifdef CONFIG_X86_64
4646 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
4647 if (vmx_msr_high & (1u<<16))
4648 return -EIO;
4649#endif
4650
4651 /* Require Write-Back (WB) memory type for VMCS accesses. */
4652 if (((vmx_msr_high >> 18) & 15) != 6)
4653 return -EIO;
4654
4655 vmcs_conf->size = vmx_msr_high & 0x1fff;
4656 vmcs_conf->order = get_order(vmcs_conf->size);
4657 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
4658
4659 vmcs_conf->revision_id = vmx_msr_low;
4660
4661 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
4662 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
4663 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
4664 vmcs_conf->vmexit_ctrl = _vmexit_control;
4665 vmcs_conf->vmentry_ctrl = _vmentry_control;
4666
4667 if (static_branch_unlikely(&enable_evmcs))
4668 evmcs_sanitize_exec_ctrls(vmcs_conf);
4669
4670 cpu_has_load_ia32_efer =
4671 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
4672 VM_ENTRY_LOAD_IA32_EFER)
4673 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
4674 VM_EXIT_LOAD_IA32_EFER);
4675
4676 cpu_has_load_perf_global_ctrl =
4677 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
4678 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
4679 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
4680 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
4681
4682 /*
4683 * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
4684 * but due to errata below it can't be used. Workaround is to use
4685 * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
4686 *
4687 * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
4688 *
4689 * AAK155 (model 26)
4690 * AAP115 (model 30)
4691 * AAT100 (model 37)
4692 * BC86,AAY89,BD102 (model 44)
4693 * BA97 (model 46)
4694 *
4695 */
4696 if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
4697 switch (boot_cpu_data.x86_model) {
4698 case 26:
4699 case 30:
4700 case 37:
4701 case 44:
4702 case 46:
4703 cpu_has_load_perf_global_ctrl = false;
4704 printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
4705 "does not work properly. Using workaround\n");
4706 break;
4707 default:
4708 break;
4709 }
4710 }
4711
4712 if (boot_cpu_has(X86_FEATURE_XSAVES))
4713 rdmsrl(MSR_IA32_XSS, host_xss);
4714
4715 return 0;
4716}
4717
4718static struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu)
4719{
4720 int node = cpu_to_node(cpu);
4721 struct page *pages;
4722 struct vmcs *vmcs;
4723
4724 pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
4725 if (!pages)
4726 return NULL;
4727 vmcs = page_address(pages);
4728 memset(vmcs, 0, vmcs_config.size);
4729
4730 /* KVM supports Enlightened VMCS v1 only */
4731 if (static_branch_unlikely(&enable_evmcs))
4732 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
4733 else
4734 vmcs->hdr.revision_id = vmcs_config.revision_id;
4735
4736 if (shadow)
4737 vmcs->hdr.shadow_vmcs = 1;
4738 return vmcs;
4739}
4740
4741static void free_vmcs(struct vmcs *vmcs)
4742{
4743 free_pages((unsigned long)vmcs, vmcs_config.order);
4744}
4745
4746/*
4747 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
4748 */
4749static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
4750{
4751 if (!loaded_vmcs->vmcs)
4752 return;
4753 loaded_vmcs_clear(loaded_vmcs);
4754 free_vmcs(loaded_vmcs->vmcs);
4755 loaded_vmcs->vmcs = NULL;
4756 if (loaded_vmcs->msr_bitmap)
4757 free_page((unsigned long)loaded_vmcs->msr_bitmap);
4758 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
4759}
4760
4761static struct vmcs *alloc_vmcs(bool shadow)
4762{
4763 return alloc_vmcs_cpu(shadow, raw_smp_processor_id());
4764}
4765
4766static int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
4767{
4768 loaded_vmcs->vmcs = alloc_vmcs(false);
4769 if (!loaded_vmcs->vmcs)
4770 return -ENOMEM;
4771
4772 loaded_vmcs->shadow_vmcs = NULL;
4773 loaded_vmcs_init(loaded_vmcs);
4774
4775 if (cpu_has_vmx_msr_bitmap()) {
4776 loaded_vmcs->msr_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
4777 if (!loaded_vmcs->msr_bitmap)
4778 goto out_vmcs;
4779 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
4780
4781 if (IS_ENABLED(CONFIG_HYPERV) &&
4782 static_branch_unlikely(&enable_evmcs) &&
4783 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
4784 struct hv_enlightened_vmcs *evmcs =
4785 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
4786
4787 evmcs->hv_enlightenments_control.msr_bitmap = 1;
4788 }
4789 }
4790
4791 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
4792
4793 return 0;
4794
4795out_vmcs:
4796 free_loaded_vmcs(loaded_vmcs);
4797 return -ENOMEM;
4798}
4799
4800static void free_kvm_area(void)
4801{
4802 int cpu;
4803
4804 for_each_possible_cpu(cpu) {
4805 free_vmcs(per_cpu(vmxarea, cpu));
4806 per_cpu(vmxarea, cpu) = NULL;
4807 }
4808}
4809
4810enum vmcs_field_width {
4811 VMCS_FIELD_WIDTH_U16 = 0,
4812 VMCS_FIELD_WIDTH_U64 = 1,
4813 VMCS_FIELD_WIDTH_U32 = 2,
4814 VMCS_FIELD_WIDTH_NATURAL_WIDTH = 3
4815};
4816
4817static inline int vmcs_field_width(unsigned long field)
4818{
4819 if (0x1 & field) /* the *_HIGH fields are all 32 bit */
4820 return VMCS_FIELD_WIDTH_U32;
4821 return (field >> 13) & 0x3 ;
4822}
4823
4824static inline int vmcs_field_readonly(unsigned long field)
4825{
4826 return (((field >> 10) & 0x3) == 1);
4827}
4828
4829static void init_vmcs_shadow_fields(void)
4830{
4831 int i, j;
4832
4833 for (i = j = 0; i < max_shadow_read_only_fields; i++) {
4834 u16 field = shadow_read_only_fields[i];
4835 if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
4836 (i + 1 == max_shadow_read_only_fields ||
4837 shadow_read_only_fields[i + 1] != field + 1))
4838 pr_err("Missing field from shadow_read_only_field %x\n",
4839 field + 1);
4840
4841 clear_bit(field, vmx_vmread_bitmap);
4842#ifdef CONFIG_X86_64
4843 if (field & 1)
4844 continue;
4845#endif
4846 if (j < i)
4847 shadow_read_only_fields[j] = field;
4848 j++;
4849 }
4850 max_shadow_read_only_fields = j;
4851
4852 for (i = j = 0; i < max_shadow_read_write_fields; i++) {
4853 u16 field = shadow_read_write_fields[i];
4854 if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
4855 (i + 1 == max_shadow_read_write_fields ||
4856 shadow_read_write_fields[i + 1] != field + 1))
4857 pr_err("Missing field from shadow_read_write_field %x\n",
4858 field + 1);
4859
4860 /*
4861 * PML and the preemption timer can be emulated, but the
4862 * processor cannot vmwrite to fields that don't exist
4863 * on bare metal.
4864 */
4865 switch (field) {
4866 case GUEST_PML_INDEX:
4867 if (!cpu_has_vmx_pml())
4868 continue;
4869 break;
4870 case VMX_PREEMPTION_TIMER_VALUE:
4871 if (!cpu_has_vmx_preemption_timer())
4872 continue;
4873 break;
4874 case GUEST_INTR_STATUS:
4875 if (!cpu_has_vmx_apicv())
4876 continue;
4877 break;
4878 default:
4879 break;
4880 }
4881
4882 clear_bit(field, vmx_vmwrite_bitmap);
4883 clear_bit(field, vmx_vmread_bitmap);
4884#ifdef CONFIG_X86_64
4885 if (field & 1)
4886 continue;
4887#endif
4888 if (j < i)
4889 shadow_read_write_fields[j] = field;
4890 j++;
4891 }
4892 max_shadow_read_write_fields = j;
4893}
4894
4895static __init int alloc_kvm_area(void)
4896{
4897 int cpu;
4898
4899 for_each_possible_cpu(cpu) {
4900 struct vmcs *vmcs;
4901
4902 vmcs = alloc_vmcs_cpu(false, cpu);
4903 if (!vmcs) {
4904 free_kvm_area();
4905 return -ENOMEM;
4906 }
4907
4908 /*
4909 * When eVMCS is enabled, alloc_vmcs_cpu() sets
4910 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
4911 * revision_id reported by MSR_IA32_VMX_BASIC.
4912 *
4913 * However, even though not explictly documented by
4914 * TLFS, VMXArea passed as VMXON argument should
4915 * still be marked with revision_id reported by
4916 * physical CPU.
4917 */
4918 if (static_branch_unlikely(&enable_evmcs))
4919 vmcs->hdr.revision_id = vmcs_config.revision_id;
4920
4921 per_cpu(vmxarea, cpu) = vmcs;
4922 }
4923 return 0;
4924}
4925
4926static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
4927 struct kvm_segment *save)
4928{
4929 if (!emulate_invalid_guest_state) {
4930 /*
4931 * CS and SS RPL should be equal during guest entry according
4932 * to VMX spec, but in reality it is not always so. Since vcpu
4933 * is in the middle of the transition from real mode to
4934 * protected mode it is safe to assume that RPL 0 is a good
4935 * default value.
4936 */
4937 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
4938 save->selector &= ~SEGMENT_RPL_MASK;
4939 save->dpl = save->selector & SEGMENT_RPL_MASK;
4940 save->s = 1;
4941 }
4942 vmx_set_segment(vcpu, save, seg);
4943}
4944
4945static void enter_pmode(struct kvm_vcpu *vcpu)
4946{
4947 unsigned long flags;
4948 struct vcpu_vmx *vmx = to_vmx(vcpu);
4949
4950 /*
4951 * Update real mode segment cache. It may be not up-to-date if sement
4952 * register was written while vcpu was in a guest mode.
4953 */
4954 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4955 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4956 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4957 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4958 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4959 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4960
4961 vmx->rmode.vm86_active = 0;
4962
4963 vmx_segment_cache_clear(vmx);
4964
4965 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4966
4967 flags = vmcs_readl(GUEST_RFLAGS);
4968 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
4969 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
4970 vmcs_writel(GUEST_RFLAGS, flags);
4971
4972 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
4973 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
4974
4975 update_exception_bitmap(vcpu);
4976
4977 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4978 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4979 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4980 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4981 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4982 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4983}
4984
4985static void fix_rmode_seg(int seg, struct kvm_segment *save)
4986{
4987 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4988 struct kvm_segment var = *save;
4989
4990 var.dpl = 0x3;
4991 if (seg == VCPU_SREG_CS)
4992 var.type = 0x3;
4993
4994 if (!emulate_invalid_guest_state) {
4995 var.selector = var.base >> 4;
4996 var.base = var.base & 0xffff0;
4997 var.limit = 0xffff;
4998 var.g = 0;
4999 var.db = 0;
5000 var.present = 1;
5001 var.s = 1;
5002 var.l = 0;
5003 var.unusable = 0;
5004 var.type = 0x3;
5005 var.avl = 0;
5006 if (save->base & 0xf)
5007 printk_once(KERN_WARNING "kvm: segment base is not "
5008 "paragraph aligned when entering "
5009 "protected mode (seg=%d)", seg);
5010 }
5011
5012 vmcs_write16(sf->selector, var.selector);
5013 vmcs_writel(sf->base, var.base);
5014 vmcs_write32(sf->limit, var.limit);
5015 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
5016}
5017
5018static void enter_rmode(struct kvm_vcpu *vcpu)
5019{
5020 unsigned long flags;
5021 struct vcpu_vmx *vmx = to_vmx(vcpu);
5022 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
5023
5024 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
5025 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
5026 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
5027 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
5028 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
5029 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
5030 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
5031
5032 vmx->rmode.vm86_active = 1;
5033
5034 /*
5035 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
5036 * vcpu. Warn the user that an update is overdue.
5037 */
5038 if (!kvm_vmx->tss_addr)
5039 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
5040 "called before entering vcpu\n");
5041
5042 vmx_segment_cache_clear(vmx);
5043
5044 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
5045 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
5046 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
5047
5048 flags = vmcs_readl(GUEST_RFLAGS);
5049 vmx->rmode.save_rflags = flags;
5050
5051 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
5052
5053 vmcs_writel(GUEST_RFLAGS, flags);
5054 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
5055 update_exception_bitmap(vcpu);
5056
5057 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
5058 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
5059 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
5060 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
5061 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
5062 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
5063
5064 kvm_mmu_reset_context(vcpu);
5065}
5066
5067static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
5068{
5069 struct vcpu_vmx *vmx = to_vmx(vcpu);
5070 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
5071
5072 if (!msr)
5073 return;
5074
5075 vcpu->arch.efer = efer;
5076 if (efer & EFER_LMA) {
5077 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
5078 msr->data = efer;
5079 } else {
5080 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
5081
5082 msr->data = efer & ~EFER_LME;
5083 }
5084 setup_msrs(vmx);
5085}
5086
5087#ifdef CONFIG_X86_64
5088
5089static void enter_lmode(struct kvm_vcpu *vcpu)
5090{
5091 u32 guest_tr_ar;
5092
5093 vmx_segment_cache_clear(to_vmx(vcpu));
5094
5095 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
5096 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
5097 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
5098 __func__);
5099 vmcs_write32(GUEST_TR_AR_BYTES,
5100 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
5101 | VMX_AR_TYPE_BUSY_64_TSS);
5102 }
5103 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
5104}
5105
5106static void exit_lmode(struct kvm_vcpu *vcpu)
5107{
5108 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
5109 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
5110}
5111
5112#endif
5113
5114static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid,
5115 bool invalidate_gpa)
5116{
5117 if (enable_ept && (invalidate_gpa || !enable_vpid)) {
5118 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
5119 return;
5120 ept_sync_context(construct_eptp(vcpu, vcpu->arch.mmu.root_hpa));
5121 } else {
5122 vpid_sync_context(vpid);
5123 }
5124}
5125
5126static void vmx_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
5127{
5128 __vmx_flush_tlb(vcpu, to_vmx(vcpu)->vpid, invalidate_gpa);
5129}
5130
5131static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
5132{
5133 int vpid = to_vmx(vcpu)->vpid;
5134
5135 if (!vpid_sync_vcpu_addr(vpid, addr))
5136 vpid_sync_context(vpid);
5137
5138 /*
5139 * If VPIDs are not supported or enabled, then the above is a no-op.
5140 * But we don't really need a TLB flush in that case anyway, because
5141 * each VM entry/exit includes an implicit flush when VPID is 0.
5142 */
5143}
5144
5145static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
5146{
5147 ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
5148
5149 vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
5150 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
5151}
5152
5153static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
5154{
5155 if (enable_unrestricted_guest || (enable_ept && is_paging(vcpu)))
5156 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
5157 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
5158}
5159
5160static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
5161{
5162 ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
5163
5164 vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
5165 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
5166}
5167
5168static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
5169{
5170 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
5171
5172 if (!test_bit(VCPU_EXREG_PDPTR,
5173 (unsigned long *)&vcpu->arch.regs_dirty))
5174 return;
5175
5176 if (is_pae_paging(vcpu)) {
5177 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
5178 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
5179 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
5180 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
5181 }
5182}
5183
5184static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
5185{
5186 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
5187
5188 if (is_pae_paging(vcpu)) {
5189 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
5190 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
5191 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
5192 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
5193 }
5194
5195 __set_bit(VCPU_EXREG_PDPTR,
5196 (unsigned long *)&vcpu->arch.regs_avail);
5197 __set_bit(VCPU_EXREG_PDPTR,
5198 (unsigned long *)&vcpu->arch.regs_dirty);
5199}
5200
5201static bool nested_guest_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
5202{
5203 u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr0_fixed0;
5204 u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr0_fixed1;
5205 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5206
5207 if (to_vmx(vcpu)->nested.msrs.secondary_ctls_high &
5208 SECONDARY_EXEC_UNRESTRICTED_GUEST &&
5209 nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
5210 fixed0 &= ~(X86_CR0_PE | X86_CR0_PG);
5211
5212 return fixed_bits_valid(val, fixed0, fixed1);
5213}
5214
5215static bool nested_host_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
5216{
5217 u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr0_fixed0;
5218 u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr0_fixed1;
5219
5220 return fixed_bits_valid(val, fixed0, fixed1);
5221}
5222
5223static bool nested_cr4_valid(struct kvm_vcpu *vcpu, unsigned long val)
5224{
5225 u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr4_fixed0;
5226 u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr4_fixed1;
5227
5228 return fixed_bits_valid(val, fixed0, fixed1);
5229}
5230
5231/* No difference in the restrictions on guest and host CR4 in VMX operation. */
5232#define nested_guest_cr4_valid nested_cr4_valid
5233#define nested_host_cr4_valid nested_cr4_valid
5234
5235static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
5236
5237static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
5238 unsigned long cr0,
5239 struct kvm_vcpu *vcpu)
5240{
5241 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
5242 vmx_decache_cr3(vcpu);
5243 if (!(cr0 & X86_CR0_PG)) {
5244 /* From paging/starting to nonpaging */
5245 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
5246 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
5247 (CPU_BASED_CR3_LOAD_EXITING |
5248 CPU_BASED_CR3_STORE_EXITING));
5249 vcpu->arch.cr0 = cr0;
5250 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
5251 } else if (!is_paging(vcpu)) {
5252 /* From nonpaging to paging */
5253 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
5254 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
5255 ~(CPU_BASED_CR3_LOAD_EXITING |
5256 CPU_BASED_CR3_STORE_EXITING));
5257 vcpu->arch.cr0 = cr0;
5258 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
5259 }
5260
5261 if (!(cr0 & X86_CR0_WP))
5262 *hw_cr0 &= ~X86_CR0_WP;
5263}
5264
5265static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
5266{
5267 struct vcpu_vmx *vmx = to_vmx(vcpu);
5268 unsigned long hw_cr0;
5269
5270 hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
5271 if (enable_unrestricted_guest)
5272 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
5273 else {
5274 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
5275
5276 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
5277 enter_pmode(vcpu);
5278
5279 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
5280 enter_rmode(vcpu);
5281 }
5282
5283#ifdef CONFIG_X86_64
5284 if (vcpu->arch.efer & EFER_LME) {
5285 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
5286 enter_lmode(vcpu);
5287 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
5288 exit_lmode(vcpu);
5289 }
5290#endif
5291
5292 if (enable_ept && !enable_unrestricted_guest)
5293 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
5294
5295 vmcs_writel(CR0_READ_SHADOW, cr0);
5296 vmcs_writel(GUEST_CR0, hw_cr0);
5297 vcpu->arch.cr0 = cr0;
5298
5299 /* depends on vcpu->arch.cr0 to be set to a new value */
5300 vmx->emulation_required = emulation_required(vcpu);
5301}
5302
5303static int get_ept_level(struct kvm_vcpu *vcpu)
5304{
5305 if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
5306 return 5;
5307 return 4;
5308}
5309
5310static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
5311{
5312 u64 eptp = VMX_EPTP_MT_WB;
5313
5314 eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
5315
5316 if (enable_ept_ad_bits &&
5317 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
5318 eptp |= VMX_EPTP_AD_ENABLE_BIT;
5319 eptp |= (root_hpa & PAGE_MASK);
5320
5321 return eptp;
5322}
5323
5324static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
5325{
5326 struct kvm *kvm = vcpu->kvm;
5327 unsigned long guest_cr3;
5328 u64 eptp;
5329
5330 guest_cr3 = cr3;
5331 if (enable_ept) {
5332 eptp = construct_eptp(vcpu, cr3);
5333 vmcs_write64(EPT_POINTER, eptp);
5334
5335 if (kvm_x86_ops->tlb_remote_flush) {
5336 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
5337 to_vmx(vcpu)->ept_pointer = eptp;
5338 to_kvm_vmx(kvm)->ept_pointers_match
5339 = EPT_POINTERS_CHECK;
5340 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
5341 }
5342
5343 if (enable_unrestricted_guest || is_paging(vcpu) ||
5344 is_guest_mode(vcpu))
5345 guest_cr3 = kvm_read_cr3(vcpu);
5346 else
5347 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
5348 ept_load_pdptrs(vcpu);
5349 }
5350
5351 vmcs_writel(GUEST_CR3, guest_cr3);
5352}
5353
5354static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
5355{
5356 /*
5357 * Pass through host's Machine Check Enable value to hw_cr4, which
5358 * is in force while we are in guest mode. Do not let guests control
5359 * this bit, even if host CR4.MCE == 0.
5360 */
5361 unsigned long hw_cr4;
5362
5363 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
5364 if (enable_unrestricted_guest)
5365 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
5366 else if (to_vmx(vcpu)->rmode.vm86_active)
5367 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
5368 else
5369 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
5370
5371 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
5372 if (cr4 & X86_CR4_UMIP) {
5373 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
5374 SECONDARY_EXEC_DESC);
5375 hw_cr4 &= ~X86_CR4_UMIP;
5376 } else if (!is_guest_mode(vcpu) ||
5377 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC))
5378 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
5379 SECONDARY_EXEC_DESC);
5380 }
5381
5382 if (cr4 & X86_CR4_VMXE) {
5383 /*
5384 * To use VMXON (and later other VMX instructions), a guest
5385 * must first be able to turn on cr4.VMXE (see handle_vmon()).
5386 * So basically the check on whether to allow nested VMX
5387 * is here. We operate under the default treatment of SMM,
5388 * so VMX cannot be enabled under SMM.
5389 */
5390 if (!nested_vmx_allowed(vcpu) || is_smm(vcpu))
5391 return 1;
5392 }
5393
5394 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
5395 return 1;
5396
5397 vcpu->arch.cr4 = cr4;
5398
5399 if (!enable_unrestricted_guest) {
5400 if (enable_ept) {
5401 if (!is_paging(vcpu)) {
5402 hw_cr4 &= ~X86_CR4_PAE;
5403 hw_cr4 |= X86_CR4_PSE;
5404 } else if (!(cr4 & X86_CR4_PAE)) {
5405 hw_cr4 &= ~X86_CR4_PAE;
5406 }
5407 }
5408
5409 /*
5410 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
5411 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
5412 * to be manually disabled when guest switches to non-paging
5413 * mode.
5414 *
5415 * If !enable_unrestricted_guest, the CPU is always running
5416 * with CR0.PG=1 and CR4 needs to be modified.
5417 * If enable_unrestricted_guest, the CPU automatically
5418 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
5419 */
5420 if (!is_paging(vcpu))
5421 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
5422 }
5423
5424 vmcs_writel(CR4_READ_SHADOW, cr4);
5425 vmcs_writel(GUEST_CR4, hw_cr4);
5426 return 0;
5427}
5428
5429static void vmx_get_segment(struct kvm_vcpu *vcpu,
5430 struct kvm_segment *var, int seg)
5431{
5432 struct vcpu_vmx *vmx = to_vmx(vcpu);
5433 u32 ar;
5434
5435 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
5436 *var = vmx->rmode.segs[seg];
5437 if (seg == VCPU_SREG_TR
5438 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
5439 return;
5440 var->base = vmx_read_guest_seg_base(vmx, seg);
5441 var->selector = vmx_read_guest_seg_selector(vmx, seg);
5442 return;
5443 }
5444 var->base = vmx_read_guest_seg_base(vmx, seg);
5445 var->limit = vmx_read_guest_seg_limit(vmx, seg);
5446 var->selector = vmx_read_guest_seg_selector(vmx, seg);
5447 ar = vmx_read_guest_seg_ar(vmx, seg);
5448 var->unusable = (ar >> 16) & 1;
5449 var->type = ar & 15;
5450 var->s = (ar >> 4) & 1;
5451 var->dpl = (ar >> 5) & 3;
5452 /*
5453 * Some userspaces do not preserve unusable property. Since usable
5454 * segment has to be present according to VMX spec we can use present
5455 * property to amend userspace bug by making unusable segment always
5456 * nonpresent. vmx_segment_access_rights() already marks nonpresent
5457 * segment as unusable.
5458 */
5459 var->present = !var->unusable;
5460 var->avl = (ar >> 12) & 1;
5461 var->l = (ar >> 13) & 1;
5462 var->db = (ar >> 14) & 1;
5463 var->g = (ar >> 15) & 1;
5464}
5465
5466static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
5467{
5468 struct kvm_segment s;
5469
5470 if (to_vmx(vcpu)->rmode.vm86_active) {
5471 vmx_get_segment(vcpu, &s, seg);
5472 return s.base;
5473 }
5474 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
5475}
5476
5477static int vmx_get_cpl(struct kvm_vcpu *vcpu)
5478{
5479 struct vcpu_vmx *vmx = to_vmx(vcpu);
5480
5481 if (unlikely(vmx->rmode.vm86_active))
5482 return 0;
5483 else {
5484 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
5485 return VMX_AR_DPL(ar);
5486 }
5487}
5488
5489static u32 vmx_segment_access_rights(struct kvm_segment *var)
5490{
5491 u32 ar;
5492
5493 if (var->unusable || !var->present)
5494 ar = 1 << 16;
5495 else {
5496 ar = var->type & 15;
5497 ar |= (var->s & 1) << 4;
5498 ar |= (var->dpl & 3) << 5;
5499 ar |= (var->present & 1) << 7;
5500 ar |= (var->avl & 1) << 12;
5501 ar |= (var->l & 1) << 13;
5502 ar |= (var->db & 1) << 14;
5503 ar |= (var->g & 1) << 15;
5504 }
5505
5506 return ar;
5507}
5508
5509static void vmx_set_segment(struct kvm_vcpu *vcpu,
5510 struct kvm_segment *var, int seg)
5511{
5512 struct vcpu_vmx *vmx = to_vmx(vcpu);
5513 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
5514
5515 vmx_segment_cache_clear(vmx);
5516
5517 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
5518 vmx->rmode.segs[seg] = *var;
5519 if (seg == VCPU_SREG_TR)
5520 vmcs_write16(sf->selector, var->selector);
5521 else if (var->s)
5522 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
5523 goto out;
5524 }
5525
5526 vmcs_writel(sf->base, var->base);
5527 vmcs_write32(sf->limit, var->limit);
5528 vmcs_write16(sf->selector, var->selector);
5529
5530 /*
5531 * Fix the "Accessed" bit in AR field of segment registers for older
5532 * qemu binaries.
5533 * IA32 arch specifies that at the time of processor reset the
5534 * "Accessed" bit in the AR field of segment registers is 1. And qemu
5535 * is setting it to 0 in the userland code. This causes invalid guest
5536 * state vmexit when "unrestricted guest" mode is turned on.
5537 * Fix for this setup issue in cpu_reset is being pushed in the qemu
5538 * tree. Newer qemu binaries with that qemu fix would not need this
5539 * kvm hack.
5540 */
5541 if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
5542 var->type |= 0x1; /* Accessed */
5543
5544 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
5545
5546out:
5547 vmx->emulation_required = emulation_required(vcpu);
5548}
5549
5550static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
5551{
5552 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
5553
5554 *db = (ar >> 14) & 1;
5555 *l = (ar >> 13) & 1;
5556}
5557
5558static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5559{
5560 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
5561 dt->address = vmcs_readl(GUEST_IDTR_BASE);
5562}
5563
5564static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5565{
5566 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
5567 vmcs_writel(GUEST_IDTR_BASE, dt->address);
5568}
5569
5570static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5571{
5572 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
5573 dt->address = vmcs_readl(GUEST_GDTR_BASE);
5574}
5575
5576static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5577{
5578 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
5579 vmcs_writel(GUEST_GDTR_BASE, dt->address);
5580}
5581
5582static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
5583{
5584 struct kvm_segment var;
5585 u32 ar;
5586
5587 vmx_get_segment(vcpu, &var, seg);
5588 var.dpl = 0x3;
5589 if (seg == VCPU_SREG_CS)
5590 var.type = 0x3;
5591 ar = vmx_segment_access_rights(&var);
5592
5593 if (var.base != (var.selector << 4))
5594 return false;
5595 if (var.limit != 0xffff)
5596 return false;
5597 if (ar != 0xf3)
5598 return false;
5599
5600 return true;
5601}
5602
5603static bool code_segment_valid(struct kvm_vcpu *vcpu)
5604{
5605 struct kvm_segment cs;
5606 unsigned int cs_rpl;
5607
5608 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5609 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
5610
5611 if (cs.unusable)
5612 return false;
5613 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
5614 return false;
5615 if (!cs.s)
5616 return false;
5617 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
5618 if (cs.dpl > cs_rpl)
5619 return false;
5620 } else {
5621 if (cs.dpl != cs_rpl)
5622 return false;
5623 }
5624 if (!cs.present)
5625 return false;
5626
5627 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
5628 return true;
5629}
5630
5631static bool stack_segment_valid(struct kvm_vcpu *vcpu)
5632{
5633 struct kvm_segment ss;
5634 unsigned int ss_rpl;
5635
5636 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
5637 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
5638
5639 if (ss.unusable)
5640 return true;
5641 if (ss.type != 3 && ss.type != 7)
5642 return false;
5643 if (!ss.s)
5644 return false;
5645 if (ss.dpl != ss_rpl) /* DPL != RPL */
5646 return false;
5647 if (!ss.present)
5648 return false;
5649
5650 return true;
5651}
5652
5653static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
5654{
5655 struct kvm_segment var;
5656 unsigned int rpl;
5657
5658 vmx_get_segment(vcpu, &var, seg);
5659 rpl = var.selector & SEGMENT_RPL_MASK;
5660
5661 if (var.unusable)
5662 return true;
5663 if (!var.s)
5664 return false;
5665 if (!var.present)
5666 return false;
5667 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
5668 if (var.dpl < rpl) /* DPL < RPL */
5669 return false;
5670 }
5671
5672 /* TODO: Add other members to kvm_segment_field to allow checking for other access
5673 * rights flags
5674 */
5675 return true;
5676}
5677
5678static bool tr_valid(struct kvm_vcpu *vcpu)
5679{
5680 struct kvm_segment tr;
5681
5682 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
5683
5684 if (tr.unusable)
5685 return false;
5686 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
5687 return false;
5688 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
5689 return false;
5690 if (!tr.present)
5691 return false;
5692
5693 return true;
5694}
5695
5696static bool ldtr_valid(struct kvm_vcpu *vcpu)
5697{
5698 struct kvm_segment ldtr;
5699
5700 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
5701
5702 if (ldtr.unusable)
5703 return true;
5704 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
5705 return false;
5706 if (ldtr.type != 2)
5707 return false;
5708 if (!ldtr.present)
5709 return false;
5710
5711 return true;
5712}
5713
5714static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
5715{
5716 struct kvm_segment cs, ss;
5717
5718 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5719 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
5720
5721 return ((cs.selector & SEGMENT_RPL_MASK) ==
5722 (ss.selector & SEGMENT_RPL_MASK));
5723}
5724
5725/*
5726 * Check if guest state is valid. Returns true if valid, false if
5727 * not.
5728 * We assume that registers are always usable
5729 */
5730static bool guest_state_valid(struct kvm_vcpu *vcpu)
5731{
5732 if (enable_unrestricted_guest)
5733 return true;
5734
5735 /* real mode guest state checks */
5736 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
5737 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
5738 return false;
5739 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
5740 return false;
5741 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
5742 return false;
5743 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
5744 return false;
5745 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
5746 return false;
5747 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
5748 return false;
5749 } else {
5750 /* protected mode guest state checks */
5751 if (!cs_ss_rpl_check(vcpu))
5752 return false;
5753 if (!code_segment_valid(vcpu))
5754 return false;
5755 if (!stack_segment_valid(vcpu))
5756 return false;
5757 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
5758 return false;
5759 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
5760 return false;
5761 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
5762 return false;
5763 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
5764 return false;
5765 if (!tr_valid(vcpu))
5766 return false;
5767 if (!ldtr_valid(vcpu))
5768 return false;
5769 }
5770 /* TODO:
5771 * - Add checks on RIP
5772 * - Add checks on RFLAGS
5773 */
5774
5775 return true;
5776}
5777
5778static bool page_address_valid(struct kvm_vcpu *vcpu, gpa_t gpa)
5779{
5780 return PAGE_ALIGNED(gpa) && !(gpa >> cpuid_maxphyaddr(vcpu));
5781}
5782
5783static int init_rmode_tss(struct kvm *kvm)
5784{
5785 gfn_t fn;
5786 u16 data = 0;
5787 int idx, r;
5788
5789 idx = srcu_read_lock(&kvm->srcu);
5790 fn = to_kvm_vmx(kvm)->tss_addr >> PAGE_SHIFT;
5791 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
5792 if (r < 0)
5793 goto out;
5794 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
5795 r = kvm_write_guest_page(kvm, fn++, &data,
5796 TSS_IOPB_BASE_OFFSET, sizeof(u16));
5797 if (r < 0)
5798 goto out;
5799 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
5800 if (r < 0)
5801 goto out;
5802 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
5803 if (r < 0)
5804 goto out;
5805 data = ~0;
5806 r = kvm_write_guest_page(kvm, fn, &data,
5807 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
5808 sizeof(u8));
5809out:
5810 srcu_read_unlock(&kvm->srcu, idx);
5811 return r;
5812}
5813
5814static int init_rmode_identity_map(struct kvm *kvm)
5815{
5816 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
5817 int i, idx, r = 0;
5818 kvm_pfn_t identity_map_pfn;
5819 u32 tmp;
5820
5821 /* Protect kvm_vmx->ept_identity_pagetable_done. */
5822 mutex_lock(&kvm->slots_lock);
5823
5824 if (likely(kvm_vmx->ept_identity_pagetable_done))
5825 goto out2;
5826
5827 if (!kvm_vmx->ept_identity_map_addr)
5828 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
5829 identity_map_pfn = kvm_vmx->ept_identity_map_addr >> PAGE_SHIFT;
5830
5831 r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
5832 kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
5833 if (r < 0)
5834 goto out2;
5835
5836 idx = srcu_read_lock(&kvm->srcu);
5837 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
5838 if (r < 0)
5839 goto out;
5840 /* Set up identity-mapping pagetable for EPT in real mode */
5841 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
5842 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
5843 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
5844 r = kvm_write_guest_page(kvm, identity_map_pfn,
5845 &tmp, i * sizeof(tmp), sizeof(tmp));
5846 if (r < 0)
5847 goto out;
5848 }
5849 kvm_vmx->ept_identity_pagetable_done = true;
5850
5851out:
5852 srcu_read_unlock(&kvm->srcu, idx);
5853
5854out2:
5855 mutex_unlock(&kvm->slots_lock);
5856 return r;
5857}
5858
5859static void seg_setup(int seg)
5860{
5861 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
5862 unsigned int ar;
5863
5864 vmcs_write16(sf->selector, 0);
5865 vmcs_writel(sf->base, 0);
5866 vmcs_write32(sf->limit, 0xffff);
5867 ar = 0x93;
5868 if (seg == VCPU_SREG_CS)
5869 ar |= 0x08; /* code segment */
5870
5871 vmcs_write32(sf->ar_bytes, ar);
5872}
5873
5874static int alloc_apic_access_page(struct kvm *kvm)
5875{
5876 struct page *page;
5877 int r = 0;
5878
5879 mutex_lock(&kvm->slots_lock);
5880 if (kvm->arch.apic_access_page_done)
5881 goto out;
5882 r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
5883 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
5884 if (r)
5885 goto out;
5886
5887 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
5888 if (is_error_page(page)) {
5889 r = -EFAULT;
5890 goto out;
5891 }
5892
5893 /*
5894 * Do not pin the page in memory, so that memory hot-unplug
5895 * is able to migrate it.
5896 */
5897 put_page(page);
5898 kvm->arch.apic_access_page_done = true;
5899out:
5900 mutex_unlock(&kvm->slots_lock);
5901 return r;
5902}
5903
5904static int allocate_vpid(void)
5905{
5906 int vpid;
5907
5908 if (!enable_vpid)
5909 return 0;
5910 spin_lock(&vmx_vpid_lock);
5911 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
5912 if (vpid < VMX_NR_VPIDS)
5913 __set_bit(vpid, vmx_vpid_bitmap);
5914 else
5915 vpid = 0;
5916 spin_unlock(&vmx_vpid_lock);
5917 return vpid;
5918}
5919
5920static void free_vpid(int vpid)
5921{
5922 if (!enable_vpid || vpid == 0)
5923 return;
5924 spin_lock(&vmx_vpid_lock);
5925 __clear_bit(vpid, vmx_vpid_bitmap);
5926 spin_unlock(&vmx_vpid_lock);
5927}
5928
5929static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
5930 u32 msr, int type)
5931{
5932 int f = sizeof(unsigned long);
5933
5934 if (!cpu_has_vmx_msr_bitmap())
5935 return;
5936
5937 if (static_branch_unlikely(&enable_evmcs))
5938 evmcs_touch_msr_bitmap();
5939
5940 /*
5941 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5942 * have the write-low and read-high bitmap offsets the wrong way round.
5943 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5944 */
5945 if (msr <= 0x1fff) {
5946 if (type & MSR_TYPE_R)
5947 /* read-low */
5948 __clear_bit(msr, msr_bitmap + 0x000 / f);
5949
5950 if (type & MSR_TYPE_W)
5951 /* write-low */
5952 __clear_bit(msr, msr_bitmap + 0x800 / f);
5953
5954 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5955 msr &= 0x1fff;
5956 if (type & MSR_TYPE_R)
5957 /* read-high */
5958 __clear_bit(msr, msr_bitmap + 0x400 / f);
5959
5960 if (type & MSR_TYPE_W)
5961 /* write-high */
5962 __clear_bit(msr, msr_bitmap + 0xc00 / f);
5963
5964 }
5965}
5966
5967static __always_inline void vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
5968 u32 msr, int type)
5969{
5970 int f = sizeof(unsigned long);
5971
5972 if (!cpu_has_vmx_msr_bitmap())
5973 return;
5974
5975 if (static_branch_unlikely(&enable_evmcs))
5976 evmcs_touch_msr_bitmap();
5977
5978 /*
5979 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5980 * have the write-low and read-high bitmap offsets the wrong way round.
5981 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5982 */
5983 if (msr <= 0x1fff) {
5984 if (type & MSR_TYPE_R)
5985 /* read-low */
5986 __set_bit(msr, msr_bitmap + 0x000 / f);
5987
5988 if (type & MSR_TYPE_W)
5989 /* write-low */
5990 __set_bit(msr, msr_bitmap + 0x800 / f);
5991
5992 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5993 msr &= 0x1fff;
5994 if (type & MSR_TYPE_R)
5995 /* read-high */
5996 __set_bit(msr, msr_bitmap + 0x400 / f);
5997
5998 if (type & MSR_TYPE_W)
5999 /* write-high */
6000 __set_bit(msr, msr_bitmap + 0xc00 / f);
6001
6002 }
6003}
6004
6005static __always_inline void vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
6006 u32 msr, int type, bool value)
6007{
6008 if (value)
6009 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
6010 else
6011 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
6012}
6013
6014/*
6015 * If a msr is allowed by L0, we should check whether it is allowed by L1.
6016 * The corresponding bit will be cleared unless both of L0 and L1 allow it.
6017 */
6018static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
6019 unsigned long *msr_bitmap_nested,
6020 u32 msr, int type)
6021{
6022 int f = sizeof(unsigned long);
6023
6024 /*
6025 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
6026 * have the write-low and read-high bitmap offsets the wrong way round.
6027 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
6028 */
6029 if (msr <= 0x1fff) {
6030 if (type & MSR_TYPE_R &&
6031 !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
6032 /* read-low */
6033 __clear_bit(msr, msr_bitmap_nested + 0x000 / f);
6034
6035 if (type & MSR_TYPE_W &&
6036 !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
6037 /* write-low */
6038 __clear_bit(msr, msr_bitmap_nested + 0x800 / f);
6039
6040 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
6041 msr &= 0x1fff;
6042 if (type & MSR_TYPE_R &&
6043 !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
6044 /* read-high */
6045 __clear_bit(msr, msr_bitmap_nested + 0x400 / f);
6046
6047 if (type & MSR_TYPE_W &&
6048 !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
6049 /* write-high */
6050 __clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
6051
6052 }
6053}
6054
6055static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
6056{
6057 u8 mode = 0;
6058
6059 if (cpu_has_secondary_exec_ctrls() &&
6060 (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
6061 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
6062 mode |= MSR_BITMAP_MODE_X2APIC;
6063 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
6064 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
6065 }
6066
6067 return mode;
6068}
6069
6070#define X2APIC_MSR(r) (APIC_BASE_MSR + ((r) >> 4))
6071
6072static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
6073 u8 mode)
6074{
6075 int msr;
6076
6077 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
6078 unsigned word = msr / BITS_PER_LONG;
6079 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
6080 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
6081 }
6082
6083 if (mode & MSR_BITMAP_MODE_X2APIC) {
6084 /*
6085 * TPR reads and writes can be virtualized even if virtual interrupt
6086 * delivery is not in use.
6087 */
6088 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
6089 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
6090 vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
6091 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
6092 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
6093 }
6094 }
6095}
6096
6097static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
6098{
6099 struct vcpu_vmx *vmx = to_vmx(vcpu);
6100 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
6101 u8 mode = vmx_msr_bitmap_mode(vcpu);
6102 u8 changed = mode ^ vmx->msr_bitmap_mode;
6103
6104 if (!changed)
6105 return;
6106
6107 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
6108 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
6109
6110 vmx->msr_bitmap_mode = mode;
6111}
6112
6113static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
6114{
6115 return enable_apicv;
6116}
6117
6118static void nested_mark_vmcs12_pages_dirty(struct kvm_vcpu *vcpu)
6119{
6120 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6121 gfn_t gfn;
6122
6123 /*
6124 * Don't need to mark the APIC access page dirty; it is never
6125 * written to by the CPU during APIC virtualization.
6126 */
6127
6128 if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
6129 gfn = vmcs12->virtual_apic_page_addr >> PAGE_SHIFT;
6130 kvm_vcpu_mark_page_dirty(vcpu, gfn);
6131 }
6132
6133 if (nested_cpu_has_posted_intr(vmcs12)) {
6134 gfn = vmcs12->posted_intr_desc_addr >> PAGE_SHIFT;
6135 kvm_vcpu_mark_page_dirty(vcpu, gfn);
6136 }
6137}
6138
6139
6140static void vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
6141{
6142 struct vcpu_vmx *vmx = to_vmx(vcpu);
6143 int max_irr;
6144 void *vapic_page;
6145 u16 status;
6146
6147 if (!vmx->nested.pi_desc || !vmx->nested.pi_pending)
6148 return;
6149
6150 vmx->nested.pi_pending = false;
6151 if (!pi_test_and_clear_on(vmx->nested.pi_desc))
6152 return;
6153
6154 max_irr = find_last_bit((unsigned long *)vmx->nested.pi_desc->pir, 256);
6155 if (max_irr != 256) {
6156 vapic_page = kmap(vmx->nested.virtual_apic_page);
6157 __kvm_apic_update_irr(vmx->nested.pi_desc->pir,
6158 vapic_page, &max_irr);
6159 kunmap(vmx->nested.virtual_apic_page);
6160
6161 status = vmcs_read16(GUEST_INTR_STATUS);
6162 if ((u8)max_irr > ((u8)status & 0xff)) {
6163 status &= ~0xff;
6164 status |= (u8)max_irr;
6165 vmcs_write16(GUEST_INTR_STATUS, status);
6166 }
6167 }
6168
6169 nested_mark_vmcs12_pages_dirty(vcpu);
6170}
6171
6172static u8 vmx_get_rvi(void)
6173{
6174 return vmcs_read16(GUEST_INTR_STATUS) & 0xff;
6175}
6176
6177static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
6178{
6179 struct vcpu_vmx *vmx = to_vmx(vcpu);
6180 void *vapic_page;
6181 u32 vppr;
6182 int rvi;
6183
6184 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
6185 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
6186 WARN_ON_ONCE(!vmx->nested.virtual_apic_page))
6187 return false;
6188
6189 rvi = vmx_get_rvi();
6190
6191 vapic_page = kmap(vmx->nested.virtual_apic_page);
6192 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
6193 kunmap(vmx->nested.virtual_apic_page);
6194
6195 return ((rvi & 0xf0) > (vppr & 0xf0));
6196}
6197
6198static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
6199 bool nested)
6200{
6201#ifdef CONFIG_SMP
6202 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
6203
6204 if (vcpu->mode == IN_GUEST_MODE) {
6205 /*
6206 * The vector of interrupt to be delivered to vcpu had
6207 * been set in PIR before this function.
6208 *
6209 * Following cases will be reached in this block, and
6210 * we always send a notification event in all cases as
6211 * explained below.
6212 *
6213 * Case 1: vcpu keeps in non-root mode. Sending a
6214 * notification event posts the interrupt to vcpu.
6215 *
6216 * Case 2: vcpu exits to root mode and is still
6217 * runnable. PIR will be synced to vIRR before the
6218 * next vcpu entry. Sending a notification event in
6219 * this case has no effect, as vcpu is not in root
6220 * mode.
6221 *
6222 * Case 3: vcpu exits to root mode and is blocked.
6223 * vcpu_block() has already synced PIR to vIRR and
6224 * never blocks vcpu if vIRR is not cleared. Therefore,
6225 * a blocked vcpu here does not wait for any requested
6226 * interrupts in PIR, and sending a notification event
6227 * which has no effect is safe here.
6228 */
6229
6230 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
6231 return true;
6232 }
6233#endif
6234 return false;
6235}
6236
6237static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
6238 int vector)
6239{
6240 struct vcpu_vmx *vmx = to_vmx(vcpu);
6241
6242 if (is_guest_mode(vcpu) &&
6243 vector == vmx->nested.posted_intr_nv) {
6244 /*
6245 * If a posted intr is not recognized by hardware,
6246 * we will accomplish it in the next vmentry.
6247 */
6248 vmx->nested.pi_pending = true;
6249 kvm_make_request(KVM_REQ_EVENT, vcpu);
6250 /* the PIR and ON have been set by L1. */
6251 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
6252 kvm_vcpu_kick(vcpu);
6253 return 0;
6254 }
6255 return -1;
6256}
6257/*
6258 * Send interrupt to vcpu via posted interrupt way.
6259 * 1. If target vcpu is running(non-root mode), send posted interrupt
6260 * notification to vcpu and hardware will sync PIR to vIRR atomically.
6261 * 2. If target vcpu isn't running(root mode), kick it to pick up the
6262 * interrupt from PIR in next vmentry.
6263 */
6264static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
6265{
6266 struct vcpu_vmx *vmx = to_vmx(vcpu);
6267 int r;
6268
6269 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
6270 if (!r)
6271 return;
6272
6273 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
6274 return;
6275
6276 /* If a previous notification has sent the IPI, nothing to do. */
6277 if (pi_test_and_set_on(&vmx->pi_desc))
6278 return;
6279
6280 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
6281 kvm_vcpu_kick(vcpu);
6282}
6283
6284/*
6285 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
6286 * will not change in the lifetime of the guest.
6287 * Note that host-state that does change is set elsewhere. E.g., host-state
6288 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
6289 */
6290static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
6291{
6292 u32 low32, high32;
6293 unsigned long tmpl;
6294 struct desc_ptr dt;
6295 unsigned long cr0, cr3, cr4;
6296
6297 cr0 = read_cr0();
6298 WARN_ON(cr0 & X86_CR0_TS);
6299 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
6300
6301 /*
6302 * Save the most likely value for this task's CR3 in the VMCS.
6303 * We can't use __get_current_cr3_fast() because we're not atomic.
6304 */
6305 cr3 = __read_cr3();
6306 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
6307 vmx->loaded_vmcs->host_state.cr3 = cr3;
6308
6309 /* Save the most likely value for this task's CR4 in the VMCS. */
6310 cr4 = cr4_read_shadow();
6311 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
6312 vmx->loaded_vmcs->host_state.cr4 = cr4;
6313
6314 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
6315#ifdef CONFIG_X86_64
6316 /*
6317 * Load null selectors, so we can avoid reloading them in
6318 * vmx_prepare_switch_to_host(), in case userspace uses
6319 * the null selectors too (the expected case).
6320 */
6321 vmcs_write16(HOST_DS_SELECTOR, 0);
6322 vmcs_write16(HOST_ES_SELECTOR, 0);
6323#else
6324 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
6325 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
6326#endif
6327 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
6328 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
6329
6330 store_idt(&dt);
6331 vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
6332 vmx->host_idt_base = dt.address;
6333
6334 vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
6335
6336 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
6337 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
6338 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
6339 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
6340
6341 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
6342 rdmsr(MSR_IA32_CR_PAT, low32, high32);
6343 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
6344 }
6345}
6346
6347static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
6348{
6349 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
6350 if (enable_ept)
6351 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
6352 if (is_guest_mode(&vmx->vcpu))
6353 vmx->vcpu.arch.cr4_guest_owned_bits &=
6354 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
6355 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
6356}
6357
6358static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
6359{
6360 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
6361
6362 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
6363 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
6364
6365 if (!enable_vnmi)
6366 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
6367
6368 /* Enable the preemption timer dynamically */
6369 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
6370 return pin_based_exec_ctrl;
6371}
6372
6373static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
6374{
6375 struct vcpu_vmx *vmx = to_vmx(vcpu);
6376
6377 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
6378 if (cpu_has_secondary_exec_ctrls()) {
6379 if (kvm_vcpu_apicv_active(vcpu))
6380 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
6381 SECONDARY_EXEC_APIC_REGISTER_VIRT |
6382 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6383 else
6384 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
6385 SECONDARY_EXEC_APIC_REGISTER_VIRT |
6386 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6387 }
6388
6389 if (cpu_has_vmx_msr_bitmap())
6390 vmx_update_msr_bitmap(vcpu);
6391}
6392
6393static u32 vmx_exec_control(struct vcpu_vmx *vmx)
6394{
6395 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
6396
6397 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
6398 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
6399
6400 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
6401 exec_control &= ~CPU_BASED_TPR_SHADOW;
6402#ifdef CONFIG_X86_64
6403 exec_control |= CPU_BASED_CR8_STORE_EXITING |
6404 CPU_BASED_CR8_LOAD_EXITING;
6405#endif
6406 }
6407 if (!enable_ept)
6408 exec_control |= CPU_BASED_CR3_STORE_EXITING |
6409 CPU_BASED_CR3_LOAD_EXITING |
6410 CPU_BASED_INVLPG_EXITING;
6411 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
6412 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
6413 CPU_BASED_MONITOR_EXITING);
6414 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
6415 exec_control &= ~CPU_BASED_HLT_EXITING;
6416 return exec_control;
6417}
6418
6419static bool vmx_rdrand_supported(void)
6420{
6421 return vmcs_config.cpu_based_2nd_exec_ctrl &
6422 SECONDARY_EXEC_RDRAND_EXITING;
6423}
6424
6425static bool vmx_rdseed_supported(void)
6426{
6427 return vmcs_config.cpu_based_2nd_exec_ctrl &
6428 SECONDARY_EXEC_RDSEED_EXITING;
6429}
6430
6431static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
6432{
6433 struct kvm_vcpu *vcpu = &vmx->vcpu;
6434
6435 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
6436
6437 if (!cpu_need_virtualize_apic_accesses(vcpu))
6438 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6439 if (vmx->vpid == 0)
6440 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
6441 if (!enable_ept) {
6442 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
6443 enable_unrestricted_guest = 0;
6444 }
6445 if (!enable_unrestricted_guest)
6446 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
6447 if (kvm_pause_in_guest(vmx->vcpu.kvm))
6448 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
6449 if (!kvm_vcpu_apicv_active(vcpu))
6450 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
6451 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6452 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6453
6454 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
6455 * in vmx_set_cr4. */
6456 exec_control &= ~SECONDARY_EXEC_DESC;
6457
6458 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
6459 (handle_vmptrld).
6460 We can NOT enable shadow_vmcs here because we don't have yet
6461 a current VMCS12
6462 */
6463 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
6464
6465 if (!enable_pml)
6466 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
6467
6468 if (vmx_xsaves_supported()) {
6469 /* Exposing XSAVES only when XSAVE is exposed */
6470 bool xsaves_enabled =
6471 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
6472 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
6473
6474 if (!xsaves_enabled)
6475 exec_control &= ~SECONDARY_EXEC_XSAVES;
6476
6477 if (nested) {
6478 if (xsaves_enabled)
6479 vmx->nested.msrs.secondary_ctls_high |=
6480 SECONDARY_EXEC_XSAVES;
6481 else
6482 vmx->nested.msrs.secondary_ctls_high &=
6483 ~SECONDARY_EXEC_XSAVES;
6484 }
6485 }
6486
6487 if (vmx_rdtscp_supported()) {
6488 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
6489 if (!rdtscp_enabled)
6490 exec_control &= ~SECONDARY_EXEC_RDTSCP;
6491
6492 if (nested) {
6493 if (rdtscp_enabled)
6494 vmx->nested.msrs.secondary_ctls_high |=
6495 SECONDARY_EXEC_RDTSCP;
6496 else
6497 vmx->nested.msrs.secondary_ctls_high &=
6498 ~SECONDARY_EXEC_RDTSCP;
6499 }
6500 }
6501
6502 if (vmx_invpcid_supported()) {
6503 /* Exposing INVPCID only when PCID is exposed */
6504 bool invpcid_enabled =
6505 guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
6506 guest_cpuid_has(vcpu, X86_FEATURE_PCID);
6507
6508 if (!invpcid_enabled) {
6509 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
6510 guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
6511 }
6512
6513 if (nested) {
6514 if (invpcid_enabled)
6515 vmx->nested.msrs.secondary_ctls_high |=
6516 SECONDARY_EXEC_ENABLE_INVPCID;
6517 else
6518 vmx->nested.msrs.secondary_ctls_high &=
6519 ~SECONDARY_EXEC_ENABLE_INVPCID;
6520 }
6521 }
6522
6523 if (vmx_rdrand_supported()) {
6524 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
6525 if (rdrand_enabled)
6526 exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
6527
6528 if (nested) {
6529 if (rdrand_enabled)
6530 vmx->nested.msrs.secondary_ctls_high |=
6531 SECONDARY_EXEC_RDRAND_EXITING;
6532 else
6533 vmx->nested.msrs.secondary_ctls_high &=
6534 ~SECONDARY_EXEC_RDRAND_EXITING;
6535 }
6536 }
6537
6538 if (vmx_rdseed_supported()) {
6539 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
6540 if (rdseed_enabled)
6541 exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
6542
6543 if (nested) {
6544 if (rdseed_enabled)
6545 vmx->nested.msrs.secondary_ctls_high |=
6546 SECONDARY_EXEC_RDSEED_EXITING;
6547 else
6548 vmx->nested.msrs.secondary_ctls_high &=
6549 ~SECONDARY_EXEC_RDSEED_EXITING;
6550 }
6551 }
6552
6553 vmx->secondary_exec_control = exec_control;
6554}
6555
6556static void ept_set_mmio_spte_mask(void)
6557{
6558 /*
6559 * EPT Misconfigurations can be generated if the value of bits 2:0
6560 * of an EPT paging-structure entry is 110b (write/execute).
6561 */
6562 kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
6563 VMX_EPT_MISCONFIG_WX_VALUE);
6564}
6565
6566#define VMX_XSS_EXIT_BITMAP 0
6567/*
6568 * Sets up the vmcs for emulated real mode.
6569 */
6570static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
6571{
6572 int i;
6573
6574 if (enable_shadow_vmcs) {
6575 /*
6576 * At vCPU creation, "VMWRITE to any supported field
6577 * in the VMCS" is supported, so use the more
6578 * permissive vmx_vmread_bitmap to specify both read
6579 * and write permissions for the shadow VMCS.
6580 */
6581 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
6582 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmread_bitmap));
6583 }
6584 if (cpu_has_vmx_msr_bitmap())
6585 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
6586
6587 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
6588
6589 /* Control */
6590 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
6591 vmx->hv_deadline_tsc = -1;
6592
6593 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
6594
6595 if (cpu_has_secondary_exec_ctrls()) {
6596 vmx_compute_secondary_exec_control(vmx);
6597 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
6598 vmx->secondary_exec_control);
6599 }
6600
6601 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
6602 vmcs_write64(EOI_EXIT_BITMAP0, 0);
6603 vmcs_write64(EOI_EXIT_BITMAP1, 0);
6604 vmcs_write64(EOI_EXIT_BITMAP2, 0);
6605 vmcs_write64(EOI_EXIT_BITMAP3, 0);
6606
6607 vmcs_write16(GUEST_INTR_STATUS, 0);
6608
6609 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
6610 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
6611 }
6612
6613 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
6614 vmcs_write32(PLE_GAP, ple_gap);
6615 vmx->ple_window = ple_window;
6616 vmx->ple_window_dirty = true;
6617 }
6618
6619 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
6620 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
6621 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
6622
6623 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
6624 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
6625 vmx_set_constant_host_state(vmx);
6626 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
6627 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
6628
6629 if (cpu_has_vmx_vmfunc())
6630 vmcs_write64(VM_FUNCTION_CONTROL, 0);
6631
6632 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
6633 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
6634 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
6635 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
6636 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
6637
6638 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
6639 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
6640
6641 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
6642 u32 index = vmx_msr_index[i];
6643 u32 data_low, data_high;
6644 int j = vmx->nmsrs;
6645
6646 if (rdmsr_safe(index, &data_low, &data_high) < 0)
6647 continue;
6648 if (wrmsr_safe(index, data_low, data_high) < 0)
6649 continue;
6650 vmx->guest_msrs[j].index = i;
6651 vmx->guest_msrs[j].data = 0;
6652 vmx->guest_msrs[j].mask = -1ull;
6653 ++vmx->nmsrs;
6654 }
6655
6656 vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
6657
6658 /* 22.2.1, 20.8.1 */
6659 vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
6660
6661 vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
6662 vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
6663
6664 set_cr4_guest_host_mask(vmx);
6665
6666 if (vmx_xsaves_supported())
6667 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
6668
6669 if (enable_pml) {
6670 ASSERT(vmx->pml_pg);
6671 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
6672 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
6673 }
6674
6675 if (cpu_has_vmx_encls_vmexit())
6676 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
6677}
6678
6679static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
6680{
6681 struct vcpu_vmx *vmx = to_vmx(vcpu);
6682 struct msr_data apic_base_msr;
6683 u64 cr0;
6684
6685 vmx->rmode.vm86_active = 0;
6686 vmx->spec_ctrl = 0;
6687
6688 vcpu->arch.microcode_version = 0x100000000ULL;
6689 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
6690 kvm_set_cr8(vcpu, 0);
6691
6692 if (!init_event) {
6693 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
6694 MSR_IA32_APICBASE_ENABLE;
6695 if (kvm_vcpu_is_reset_bsp(vcpu))
6696 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
6697 apic_base_msr.host_initiated = true;
6698 kvm_set_apic_base(vcpu, &apic_base_msr);
6699 }
6700
6701 vmx_segment_cache_clear(vmx);
6702
6703 seg_setup(VCPU_SREG_CS);
6704 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
6705 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
6706
6707 seg_setup(VCPU_SREG_DS);
6708 seg_setup(VCPU_SREG_ES);
6709 seg_setup(VCPU_SREG_FS);
6710 seg_setup(VCPU_SREG_GS);
6711 seg_setup(VCPU_SREG_SS);
6712
6713 vmcs_write16(GUEST_TR_SELECTOR, 0);
6714 vmcs_writel(GUEST_TR_BASE, 0);
6715 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
6716 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
6717
6718 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
6719 vmcs_writel(GUEST_LDTR_BASE, 0);
6720 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
6721 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
6722
6723 if (!init_event) {
6724 vmcs_write32(GUEST_SYSENTER_CS, 0);
6725 vmcs_writel(GUEST_SYSENTER_ESP, 0);
6726 vmcs_writel(GUEST_SYSENTER_EIP, 0);
6727 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
6728 }
6729
6730 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6731 kvm_rip_write(vcpu, 0xfff0);
6732
6733 vmcs_writel(GUEST_GDTR_BASE, 0);
6734 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
6735
6736 vmcs_writel(GUEST_IDTR_BASE, 0);
6737 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
6738
6739 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
6740 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
6741 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
6742 if (kvm_mpx_supported())
6743 vmcs_write64(GUEST_BNDCFGS, 0);
6744
6745 setup_msrs(vmx);
6746
6747 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
6748
6749 if (cpu_has_vmx_tpr_shadow() && !init_event) {
6750 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
6751 if (cpu_need_tpr_shadow(vcpu))
6752 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
6753 __pa(vcpu->arch.apic->regs));
6754 vmcs_write32(TPR_THRESHOLD, 0);
6755 }
6756
6757 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6758
6759 if (vmx->vpid != 0)
6760 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
6761
6762 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
6763 vmx->vcpu.arch.cr0 = cr0;
6764 vmx_set_cr0(vcpu, cr0); /* enter rmode */
6765 vmx_set_cr4(vcpu, 0);
6766 vmx_set_efer(vcpu, 0);
6767
6768 update_exception_bitmap(vcpu);
6769
6770 vpid_sync_context(vmx->vpid);
6771 if (init_event)
6772 vmx_clear_hlt(vcpu);
6773}
6774
6775/*
6776 * In nested virtualization, check if L1 asked to exit on external interrupts.
6777 * For most existing hypervisors, this will always return true.
6778 */
6779static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
6780{
6781 return get_vmcs12(vcpu)->pin_based_vm_exec_control &
6782 PIN_BASED_EXT_INTR_MASK;
6783}
6784
6785/*
6786 * In nested virtualization, check if L1 has set
6787 * VM_EXIT_ACK_INTR_ON_EXIT
6788 */
6789static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
6790{
6791 return get_vmcs12(vcpu)->vm_exit_controls &
6792 VM_EXIT_ACK_INTR_ON_EXIT;
6793}
6794
6795static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
6796{
6797 return nested_cpu_has_nmi_exiting(get_vmcs12(vcpu));
6798}
6799
6800static void enable_irq_window(struct kvm_vcpu *vcpu)
6801{
6802 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
6803 CPU_BASED_VIRTUAL_INTR_PENDING);
6804}
6805
6806static void enable_nmi_window(struct kvm_vcpu *vcpu)
6807{
6808 if (!enable_vnmi ||
6809 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
6810 enable_irq_window(vcpu);
6811 return;
6812 }
6813
6814 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
6815 CPU_BASED_VIRTUAL_NMI_PENDING);
6816}
6817
6818static void vmx_inject_irq(struct kvm_vcpu *vcpu)
6819{
6820 struct vcpu_vmx *vmx = to_vmx(vcpu);
6821 uint32_t intr;
6822 int irq = vcpu->arch.interrupt.nr;
6823
6824 trace_kvm_inj_virq(irq);
6825
6826 ++vcpu->stat.irq_injections;
6827 if (vmx->rmode.vm86_active) {
6828 int inc_eip = 0;
6829 if (vcpu->arch.interrupt.soft)
6830 inc_eip = vcpu->arch.event_exit_inst_len;
6831 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
6832 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6833 return;
6834 }
6835 intr = irq | INTR_INFO_VALID_MASK;
6836 if (vcpu->arch.interrupt.soft) {
6837 intr |= INTR_TYPE_SOFT_INTR;
6838 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
6839 vmx->vcpu.arch.event_exit_inst_len);
6840 } else
6841 intr |= INTR_TYPE_EXT_INTR;
6842 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
6843
6844 vmx_clear_hlt(vcpu);
6845}
6846
6847static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
6848{
6849 struct vcpu_vmx *vmx = to_vmx(vcpu);
6850
6851 if (!enable_vnmi) {
6852 /*
6853 * Tracking the NMI-blocked state in software is built upon
6854 * finding the next open IRQ window. This, in turn, depends on
6855 * well-behaving guests: They have to keep IRQs disabled at
6856 * least as long as the NMI handler runs. Otherwise we may
6857 * cause NMI nesting, maybe breaking the guest. But as this is
6858 * highly unlikely, we can live with the residual risk.
6859 */
6860 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
6861 vmx->loaded_vmcs->vnmi_blocked_time = 0;
6862 }
6863
6864 ++vcpu->stat.nmi_injections;
6865 vmx->loaded_vmcs->nmi_known_unmasked = false;
6866
6867 if (vmx->rmode.vm86_active) {
6868 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
6869 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6870 return;
6871 }
6872
6873 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
6874 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
6875
6876 vmx_clear_hlt(vcpu);
6877}
6878
6879static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
6880{
6881 struct vcpu_vmx *vmx = to_vmx(vcpu);
6882 bool masked;
6883
6884 if (!enable_vnmi)
6885 return vmx->loaded_vmcs->soft_vnmi_blocked;
6886 if (vmx->loaded_vmcs->nmi_known_unmasked)
6887 return false;
6888 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
6889 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
6890 return masked;
6891}
6892
6893static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
6894{
6895 struct vcpu_vmx *vmx = to_vmx(vcpu);
6896
6897 if (!enable_vnmi) {
6898 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
6899 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
6900 vmx->loaded_vmcs->vnmi_blocked_time = 0;
6901 }
6902 } else {
6903 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
6904 if (masked)
6905 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6906 GUEST_INTR_STATE_NMI);
6907 else
6908 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
6909 GUEST_INTR_STATE_NMI);
6910 }
6911}
6912
6913static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
6914{
6915 if (to_vmx(vcpu)->nested.nested_run_pending)
6916 return 0;
6917
6918 if (!enable_vnmi &&
6919 to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
6920 return 0;
6921
6922 return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6923 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
6924 | GUEST_INTR_STATE_NMI));
6925}
6926
6927static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
6928{
6929 return (!to_vmx(vcpu)->nested.nested_run_pending &&
6930 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
6931 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6932 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
6933}
6934
6935static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
6936{
6937 int ret;
6938
6939 if (enable_unrestricted_guest)
6940 return 0;
6941
6942 ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
6943 PAGE_SIZE * 3);
6944 if (ret)
6945 return ret;
6946 to_kvm_vmx(kvm)->tss_addr = addr;
6947 return init_rmode_tss(kvm);
6948}
6949
6950static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
6951{
6952 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
6953 return 0;
6954}
6955
6956static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
6957{
6958 switch (vec) {
6959 case BP_VECTOR:
6960 /*
6961 * Update instruction length as we may reinject the exception
6962 * from user space while in guest debugging mode.
6963 */
6964 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
6965 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6966 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
6967 return false;
6968 /* fall through */
6969 case DB_VECTOR:
6970 if (vcpu->guest_debug &
6971 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
6972 return false;
6973 /* fall through */
6974 case DE_VECTOR:
6975 case OF_VECTOR:
6976 case BR_VECTOR:
6977 case UD_VECTOR:
6978 case DF_VECTOR:
6979 case SS_VECTOR:
6980 case GP_VECTOR:
6981 case MF_VECTOR:
6982 return true;
6983 break;
6984 }
6985 return false;
6986}
6987
6988static int handle_rmode_exception(struct kvm_vcpu *vcpu,
6989 int vec, u32 err_code)
6990{
6991 /*
6992 * Instruction with address size override prefix opcode 0x67
6993 * Cause the #SS fault with 0 error code in VM86 mode.
6994 */
6995 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
6996 if (kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE) {
6997 if (vcpu->arch.halt_request) {
6998 vcpu->arch.halt_request = 0;
6999 return kvm_vcpu_halt(vcpu);
7000 }
7001 return 1;
7002 }
7003 return 0;
7004 }
7005
7006 /*
7007 * Forward all other exceptions that are valid in real mode.
7008 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
7009 * the required debugging infrastructure rework.
7010 */
7011 kvm_queue_exception(vcpu, vec);
7012 return 1;
7013}
7014
7015/*
7016 * Trigger machine check on the host. We assume all the MSRs are already set up
7017 * by the CPU and that we still run on the same CPU as the MCE occurred on.
7018 * We pass a fake environment to the machine check handler because we want
7019 * the guest to be always treated like user space, no matter what context
7020 * it used internally.
7021 */
7022static void kvm_machine_check(void)
7023{
7024#if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
7025 struct pt_regs regs = {
7026 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
7027 .flags = X86_EFLAGS_IF,
7028 };
7029
7030 do_machine_check(&regs, 0);
7031#endif
7032}
7033
7034static int handle_machine_check(struct kvm_vcpu *vcpu)
7035{
7036 /* already handled by vcpu_run */
7037 return 1;
7038}
7039
7040static int handle_exception(struct kvm_vcpu *vcpu)
7041{
7042 struct vcpu_vmx *vmx = to_vmx(vcpu);
7043 struct kvm_run *kvm_run = vcpu->run;
7044 u32 intr_info, ex_no, error_code;
7045 unsigned long cr2, rip, dr6;
7046 u32 vect_info;
7047 enum emulation_result er;
7048
7049 vect_info = vmx->idt_vectoring_info;
7050 intr_info = vmx->exit_intr_info;
7051
7052 if (is_machine_check(intr_info))
7053 return handle_machine_check(vcpu);
7054
7055 if (is_nmi(intr_info))
7056 return 1; /* already handled by vmx_vcpu_run() */
7057
7058 if (is_invalid_opcode(intr_info))
7059 return handle_ud(vcpu);
7060
7061 error_code = 0;
7062 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
7063 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
7064
7065 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
7066 WARN_ON_ONCE(!enable_vmware_backdoor);
7067 er = kvm_emulate_instruction(vcpu,
7068 EMULTYPE_VMWARE | EMULTYPE_NO_UD_ON_FAIL);
7069 if (er == EMULATE_USER_EXIT)
7070 return 0;
7071 else if (er != EMULATE_DONE)
7072 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
7073 return 1;
7074 }
7075
7076 /*
7077 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
7078 * MMIO, it is better to report an internal error.
7079 * See the comments in vmx_handle_exit.
7080 */
7081 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
7082 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
7083 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7084 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
7085 vcpu->run->internal.ndata = 3;
7086 vcpu->run->internal.data[0] = vect_info;
7087 vcpu->run->internal.data[1] = intr_info;
7088 vcpu->run->internal.data[2] = error_code;
7089 return 0;
7090 }
7091
7092 if (is_page_fault(intr_info)) {
7093 cr2 = vmcs_readl(EXIT_QUALIFICATION);
7094 /* EPT won't cause page fault directly */
7095 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
7096 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
7097 }
7098
7099 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
7100
7101 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
7102 return handle_rmode_exception(vcpu, ex_no, error_code);
7103
7104 switch (ex_no) {
7105 case AC_VECTOR:
7106 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
7107 return 1;
7108 case DB_VECTOR:
7109 dr6 = vmcs_readl(EXIT_QUALIFICATION);
7110 if (!(vcpu->guest_debug &
7111 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
7112 vcpu->arch.dr6 &= ~15;
7113 vcpu->arch.dr6 |= dr6 | DR6_RTM;
7114 if (is_icebp(intr_info))
7115 skip_emulated_instruction(vcpu);
7116
7117 kvm_queue_exception(vcpu, DB_VECTOR);
7118 return 1;
7119 }
7120 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
7121 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
7122 /* fall through */
7123 case BP_VECTOR:
7124 /*
7125 * Update instruction length as we may reinject #BP from
7126 * user space while in guest debugging mode. Reading it for
7127 * #DB as well causes no harm, it is not used in that case.
7128 */
7129 vmx->vcpu.arch.event_exit_inst_len =
7130 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
7131 kvm_run->exit_reason = KVM_EXIT_DEBUG;
7132 rip = kvm_rip_read(vcpu);
7133 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
7134 kvm_run->debug.arch.exception = ex_no;
7135 break;
7136 default:
7137 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
7138 kvm_run->ex.exception = ex_no;
7139 kvm_run->ex.error_code = error_code;
7140 break;
7141 }
7142 return 0;
7143}
7144
7145static int handle_external_interrupt(struct kvm_vcpu *vcpu)
7146{
7147 ++vcpu->stat.irq_exits;
7148 return 1;
7149}
7150
7151static int handle_triple_fault(struct kvm_vcpu *vcpu)
7152{
7153 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
7154 vcpu->mmio_needed = 0;
7155 return 0;
7156}
7157
7158static int handle_io(struct kvm_vcpu *vcpu)
7159{
7160 unsigned long exit_qualification;
7161 int size, in, string;
7162 unsigned port;
7163
7164 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7165 string = (exit_qualification & 16) != 0;
7166
7167 ++vcpu->stat.io_exits;
7168
7169 if (string)
7170 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7171
7172 port = exit_qualification >> 16;
7173 size = (exit_qualification & 7) + 1;
7174 in = (exit_qualification & 8) != 0;
7175
7176 return kvm_fast_pio(vcpu, size, port, in);
7177}
7178
7179static void
7180vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
7181{
7182 /*
7183 * Patch in the VMCALL instruction:
7184 */
7185 hypercall[0] = 0x0f;
7186 hypercall[1] = 0x01;
7187 hypercall[2] = 0xc1;
7188}
7189
7190/* called to set cr0 as appropriate for a mov-to-cr0 exit. */
7191static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
7192{
7193 if (is_guest_mode(vcpu)) {
7194 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7195 unsigned long orig_val = val;
7196
7197 /*
7198 * We get here when L2 changed cr0 in a way that did not change
7199 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
7200 * but did change L0 shadowed bits. So we first calculate the
7201 * effective cr0 value that L1 would like to write into the
7202 * hardware. It consists of the L2-owned bits from the new
7203 * value combined with the L1-owned bits from L1's guest_cr0.
7204 */
7205 val = (val & ~vmcs12->cr0_guest_host_mask) |
7206 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
7207
7208 if (!nested_guest_cr0_valid(vcpu, val))
7209 return 1;
7210
7211 if (kvm_set_cr0(vcpu, val))
7212 return 1;
7213 vmcs_writel(CR0_READ_SHADOW, orig_val);
7214 return 0;
7215 } else {
7216 if (to_vmx(vcpu)->nested.vmxon &&
7217 !nested_host_cr0_valid(vcpu, val))
7218 return 1;
7219
7220 return kvm_set_cr0(vcpu, val);
7221 }
7222}
7223
7224static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
7225{
7226 if (is_guest_mode(vcpu)) {
7227 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7228 unsigned long orig_val = val;
7229
7230 /* analogously to handle_set_cr0 */
7231 val = (val & ~vmcs12->cr4_guest_host_mask) |
7232 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
7233 if (kvm_set_cr4(vcpu, val))
7234 return 1;
7235 vmcs_writel(CR4_READ_SHADOW, orig_val);
7236 return 0;
7237 } else
7238 return kvm_set_cr4(vcpu, val);
7239}
7240
7241static int handle_desc(struct kvm_vcpu *vcpu)
7242{
7243 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
7244 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7245}
7246
7247static int handle_cr(struct kvm_vcpu *vcpu)
7248{
7249 unsigned long exit_qualification, val;
7250 int cr;
7251 int reg;
7252 int err;
7253 int ret;
7254
7255 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7256 cr = exit_qualification & 15;
7257 reg = (exit_qualification >> 8) & 15;
7258 switch ((exit_qualification >> 4) & 3) {
7259 case 0: /* mov to cr */
7260 val = kvm_register_readl(vcpu, reg);
7261 trace_kvm_cr_write(cr, val);
7262 switch (cr) {
7263 case 0:
7264 err = handle_set_cr0(vcpu, val);
7265 return kvm_complete_insn_gp(vcpu, err);
7266 case 3:
7267 WARN_ON_ONCE(enable_unrestricted_guest);
7268 err = kvm_set_cr3(vcpu, val);
7269 return kvm_complete_insn_gp(vcpu, err);
7270 case 4:
7271 err = handle_set_cr4(vcpu, val);
7272 return kvm_complete_insn_gp(vcpu, err);
7273 case 8: {
7274 u8 cr8_prev = kvm_get_cr8(vcpu);
7275 u8 cr8 = (u8)val;
7276 err = kvm_set_cr8(vcpu, cr8);
7277 ret = kvm_complete_insn_gp(vcpu, err);
7278 if (lapic_in_kernel(vcpu))
7279 return ret;
7280 if (cr8_prev <= cr8)
7281 return ret;
7282 /*
7283 * TODO: we might be squashing a
7284 * KVM_GUESTDBG_SINGLESTEP-triggered
7285 * KVM_EXIT_DEBUG here.
7286 */
7287 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
7288 return 0;
7289 }
7290 }
7291 break;
7292 case 2: /* clts */
7293 WARN_ONCE(1, "Guest should always own CR0.TS");
7294 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
7295 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
7296 return kvm_skip_emulated_instruction(vcpu);
7297 case 1: /*mov from cr*/
7298 switch (cr) {
7299 case 3:
7300 WARN_ON_ONCE(enable_unrestricted_guest);
7301 val = kvm_read_cr3(vcpu);
7302 kvm_register_write(vcpu, reg, val);
7303 trace_kvm_cr_read(cr, val);
7304 return kvm_skip_emulated_instruction(vcpu);
7305 case 8:
7306 val = kvm_get_cr8(vcpu);
7307 kvm_register_write(vcpu, reg, val);
7308 trace_kvm_cr_read(cr, val);
7309 return kvm_skip_emulated_instruction(vcpu);
7310 }
7311 break;
7312 case 3: /* lmsw */
7313 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
7314 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
7315 kvm_lmsw(vcpu, val);
7316
7317 return kvm_skip_emulated_instruction(vcpu);
7318 default:
7319 break;
7320 }
7321 vcpu->run->exit_reason = 0;
7322 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
7323 (int)(exit_qualification >> 4) & 3, cr);
7324 return 0;
7325}
7326
7327static int handle_dr(struct kvm_vcpu *vcpu)
7328{
7329 unsigned long exit_qualification;
7330 int dr, dr7, reg;
7331
7332 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7333 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
7334
7335 /* First, if DR does not exist, trigger UD */
7336 if (!kvm_require_dr(vcpu, dr))
7337 return 1;
7338
7339 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
7340 if (!kvm_require_cpl(vcpu, 0))
7341 return 1;
7342 dr7 = vmcs_readl(GUEST_DR7);
7343 if (dr7 & DR7_GD) {
7344 /*
7345 * As the vm-exit takes precedence over the debug trap, we
7346 * need to emulate the latter, either for the host or the
7347 * guest debugging itself.
7348 */
7349 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7350 vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
7351 vcpu->run->debug.arch.dr7 = dr7;
7352 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
7353 vcpu->run->debug.arch.exception = DB_VECTOR;
7354 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
7355 return 0;
7356 } else {
7357 vcpu->arch.dr6 &= ~15;
7358 vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
7359 kvm_queue_exception(vcpu, DB_VECTOR);
7360 return 1;
7361 }
7362 }
7363
7364 if (vcpu->guest_debug == 0) {
7365 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7366 CPU_BASED_MOV_DR_EXITING);
7367
7368 /*
7369 * No more DR vmexits; force a reload of the debug registers
7370 * and reenter on this instruction. The next vmexit will
7371 * retrieve the full state of the debug registers.
7372 */
7373 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
7374 return 1;
7375 }
7376
7377 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
7378 if (exit_qualification & TYPE_MOV_FROM_DR) {
7379 unsigned long val;
7380
7381 if (kvm_get_dr(vcpu, dr, &val))
7382 return 1;
7383 kvm_register_write(vcpu, reg, val);
7384 } else
7385 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
7386 return 1;
7387
7388 return kvm_skip_emulated_instruction(vcpu);
7389}
7390
7391static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
7392{
7393 return vcpu->arch.dr6;
7394}
7395
7396static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
7397{
7398}
7399
7400static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
7401{
7402 get_debugreg(vcpu->arch.db[0], 0);
7403 get_debugreg(vcpu->arch.db[1], 1);
7404 get_debugreg(vcpu->arch.db[2], 2);
7405 get_debugreg(vcpu->arch.db[3], 3);
7406 get_debugreg(vcpu->arch.dr6, 6);
7407 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
7408
7409 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
7410 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
7411}
7412
7413static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
7414{
7415 vmcs_writel(GUEST_DR7, val);
7416}
7417
7418static int handle_cpuid(struct kvm_vcpu *vcpu)
7419{
7420 return kvm_emulate_cpuid(vcpu);
7421}
7422
7423static int handle_rdmsr(struct kvm_vcpu *vcpu)
7424{
7425 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
7426 struct msr_data msr_info;
7427
7428 msr_info.index = ecx;
7429 msr_info.host_initiated = false;
7430 if (vmx_get_msr(vcpu, &msr_info)) {
7431 trace_kvm_msr_read_ex(ecx);
7432 kvm_inject_gp(vcpu, 0);
7433 return 1;
7434 }
7435
7436 trace_kvm_msr_read(ecx, msr_info.data);
7437
7438 /* FIXME: handling of bits 32:63 of rax, rdx */
7439 vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
7440 vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
7441 return kvm_skip_emulated_instruction(vcpu);
7442}
7443
7444static int handle_wrmsr(struct kvm_vcpu *vcpu)
7445{
7446 struct msr_data msr;
7447 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
7448 u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
7449 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
7450
7451 msr.data = data;
7452 msr.index = ecx;
7453 msr.host_initiated = false;
7454 if (kvm_set_msr(vcpu, &msr) != 0) {
7455 trace_kvm_msr_write_ex(ecx, data);
7456 kvm_inject_gp(vcpu, 0);
7457 return 1;
7458 }
7459
7460 trace_kvm_msr_write(ecx, data);
7461 return kvm_skip_emulated_instruction(vcpu);
7462}
7463
7464static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
7465{
7466 kvm_apic_update_ppr(vcpu);
7467 return 1;
7468}
7469
7470static int handle_interrupt_window(struct kvm_vcpu *vcpu)
7471{
7472 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7473 CPU_BASED_VIRTUAL_INTR_PENDING);
7474
7475 kvm_make_request(KVM_REQ_EVENT, vcpu);
7476
7477 ++vcpu->stat.irq_window_exits;
7478 return 1;
7479}
7480
7481static int handle_halt(struct kvm_vcpu *vcpu)
7482{
7483 return kvm_emulate_halt(vcpu);
7484}
7485
7486static int handle_vmcall(struct kvm_vcpu *vcpu)
7487{
7488 return kvm_emulate_hypercall(vcpu);
7489}
7490
7491static int handle_invd(struct kvm_vcpu *vcpu)
7492{
7493 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7494}
7495
7496static int handle_invlpg(struct kvm_vcpu *vcpu)
7497{
7498 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7499
7500 kvm_mmu_invlpg(vcpu, exit_qualification);
7501 return kvm_skip_emulated_instruction(vcpu);
7502}
7503
7504static int handle_rdpmc(struct kvm_vcpu *vcpu)
7505{
7506 int err;
7507
7508 err = kvm_rdpmc(vcpu);
7509 return kvm_complete_insn_gp(vcpu, err);
7510}
7511
7512static int handle_wbinvd(struct kvm_vcpu *vcpu)
7513{
7514 return kvm_emulate_wbinvd(vcpu);
7515}
7516
7517static int handle_xsetbv(struct kvm_vcpu *vcpu)
7518{
7519 u64 new_bv = kvm_read_edx_eax(vcpu);
7520 u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
7521
7522 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
7523 return kvm_skip_emulated_instruction(vcpu);
7524 return 1;
7525}
7526
7527static int handle_xsaves(struct kvm_vcpu *vcpu)
7528{
7529 kvm_skip_emulated_instruction(vcpu);
7530 WARN(1, "this should never happen\n");
7531 return 1;
7532}
7533
7534static int handle_xrstors(struct kvm_vcpu *vcpu)
7535{
7536 kvm_skip_emulated_instruction(vcpu);
7537 WARN(1, "this should never happen\n");
7538 return 1;
7539}
7540
7541static int handle_apic_access(struct kvm_vcpu *vcpu)
7542{
7543 if (likely(fasteoi)) {
7544 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7545 int access_type, offset;
7546
7547 access_type = exit_qualification & APIC_ACCESS_TYPE;
7548 offset = exit_qualification & APIC_ACCESS_OFFSET;
7549 /*
7550 * Sane guest uses MOV to write EOI, with written value
7551 * not cared. So make a short-circuit here by avoiding
7552 * heavy instruction emulation.
7553 */
7554 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
7555 (offset == APIC_EOI)) {
7556 kvm_lapic_set_eoi(vcpu);
7557 return kvm_skip_emulated_instruction(vcpu);
7558 }
7559 }
7560 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7561}
7562
7563static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
7564{
7565 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7566 int vector = exit_qualification & 0xff;
7567
7568 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
7569 kvm_apic_set_eoi_accelerated(vcpu, vector);
7570 return 1;
7571}
7572
7573static int handle_apic_write(struct kvm_vcpu *vcpu)
7574{
7575 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7576 u32 offset = exit_qualification & 0xfff;
7577
7578 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
7579 kvm_apic_write_nodecode(vcpu, offset);
7580 return 1;
7581}
7582
7583static int handle_task_switch(struct kvm_vcpu *vcpu)
7584{
7585 struct vcpu_vmx *vmx = to_vmx(vcpu);
7586 unsigned long exit_qualification;
7587 bool has_error_code = false;
7588 u32 error_code = 0;
7589 u16 tss_selector;
7590 int reason, type, idt_v, idt_index;
7591
7592 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
7593 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
7594 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
7595
7596 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7597
7598 reason = (u32)exit_qualification >> 30;
7599 if (reason == TASK_SWITCH_GATE && idt_v) {
7600 switch (type) {
7601 case INTR_TYPE_NMI_INTR:
7602 vcpu->arch.nmi_injected = false;
7603 vmx_set_nmi_mask(vcpu, true);
7604 break;
7605 case INTR_TYPE_EXT_INTR:
7606 case INTR_TYPE_SOFT_INTR:
7607 kvm_clear_interrupt_queue(vcpu);
7608 break;
7609 case INTR_TYPE_HARD_EXCEPTION:
7610 if (vmx->idt_vectoring_info &
7611 VECTORING_INFO_DELIVER_CODE_MASK) {
7612 has_error_code = true;
7613 error_code =
7614 vmcs_read32(IDT_VECTORING_ERROR_CODE);
7615 }
7616 /* fall through */
7617 case INTR_TYPE_SOFT_EXCEPTION:
7618 kvm_clear_exception_queue(vcpu);
7619 break;
7620 default:
7621 break;
7622 }
7623 }
7624 tss_selector = exit_qualification;
7625
7626 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
7627 type != INTR_TYPE_EXT_INTR &&
7628 type != INTR_TYPE_NMI_INTR))
7629 skip_emulated_instruction(vcpu);
7630
7631 if (kvm_task_switch(vcpu, tss_selector,
7632 type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
7633 has_error_code, error_code) == EMULATE_FAIL) {
7634 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7635 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7636 vcpu->run->internal.ndata = 0;
7637 return 0;
7638 }
7639
7640 /*
7641 * TODO: What about debug traps on tss switch?
7642 * Are we supposed to inject them and update dr6?
7643 */
7644
7645 return 1;
7646}
7647
7648static int handle_ept_violation(struct kvm_vcpu *vcpu)
7649{
7650 unsigned long exit_qualification;
7651 gpa_t gpa;
7652 u64 error_code;
7653
7654 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7655
7656 /*
7657 * EPT violation happened while executing iret from NMI,
7658 * "blocked by NMI" bit has to be set before next VM entry.
7659 * There are errata that may cause this bit to not be set:
7660 * AAK134, BY25.
7661 */
7662 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
7663 enable_vnmi &&
7664 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
7665 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
7666
7667 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
7668 trace_kvm_page_fault(gpa, exit_qualification);
7669
7670 /* Is it a read fault? */
7671 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
7672 ? PFERR_USER_MASK : 0;
7673 /* Is it a write fault? */
7674 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
7675 ? PFERR_WRITE_MASK : 0;
7676 /* Is it a fetch fault? */
7677 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
7678 ? PFERR_FETCH_MASK : 0;
7679 /* ept page table entry is present? */
7680 error_code |= (exit_qualification &
7681 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
7682 EPT_VIOLATION_EXECUTABLE))
7683 ? PFERR_PRESENT_MASK : 0;
7684
7685 error_code |= (exit_qualification & 0x100) != 0 ?
7686 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
7687
7688 vcpu->arch.exit_qualification = exit_qualification;
7689 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
7690}
7691
7692static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
7693{
7694 gpa_t gpa;
7695
7696 /*
7697 * A nested guest cannot optimize MMIO vmexits, because we have an
7698 * nGPA here instead of the required GPA.
7699 */
7700 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
7701 if (!is_guest_mode(vcpu) &&
7702 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
7703 trace_kvm_fast_mmio(gpa);
7704 /*
7705 * Doing kvm_skip_emulated_instruction() depends on undefined
7706 * behavior: Intel's manual doesn't mandate
7707 * VM_EXIT_INSTRUCTION_LEN to be set in VMCS when EPT MISCONFIG
7708 * occurs and while on real hardware it was observed to be set,
7709 * other hypervisors (namely Hyper-V) don't set it, we end up
7710 * advancing IP with some random value. Disable fast mmio when
7711 * running nested and keep it for real hardware in hope that
7712 * VM_EXIT_INSTRUCTION_LEN will always be set correctly.
7713 */
7714 if (!static_cpu_has(X86_FEATURE_HYPERVISOR))
7715 return kvm_skip_emulated_instruction(vcpu);
7716 else
7717 return kvm_emulate_instruction(vcpu, EMULTYPE_SKIP) ==
7718 EMULATE_DONE;
7719 }
7720
7721 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
7722}
7723
7724static int handle_nmi_window(struct kvm_vcpu *vcpu)
7725{
7726 WARN_ON_ONCE(!enable_vnmi);
7727 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7728 CPU_BASED_VIRTUAL_NMI_PENDING);
7729 ++vcpu->stat.nmi_window_exits;
7730 kvm_make_request(KVM_REQ_EVENT, vcpu);
7731
7732 return 1;
7733}
7734
7735static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
7736{
7737 struct vcpu_vmx *vmx = to_vmx(vcpu);
7738 enum emulation_result err = EMULATE_DONE;
7739 int ret = 1;
7740 u32 cpu_exec_ctrl;
7741 bool intr_window_requested;
7742 unsigned count = 130;
7743
7744 /*
7745 * We should never reach the point where we are emulating L2
7746 * due to invalid guest state as that means we incorrectly
7747 * allowed a nested VMEntry with an invalid vmcs12.
7748 */
7749 WARN_ON_ONCE(vmx->emulation_required && vmx->nested.nested_run_pending);
7750
7751 cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
7752 intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
7753
7754 while (vmx->emulation_required && count-- != 0) {
7755 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
7756 return handle_interrupt_window(&vmx->vcpu);
7757
7758 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
7759 return 1;
7760
7761 err = kvm_emulate_instruction(vcpu, 0);
7762
7763 if (err == EMULATE_USER_EXIT) {
7764 ++vcpu->stat.mmio_exits;
7765 ret = 0;
7766 goto out;
7767 }
7768
7769 if (err != EMULATE_DONE)
7770 goto emulation_error;
7771
7772 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
7773 vcpu->arch.exception.pending)
7774 goto emulation_error;
7775
7776 if (vcpu->arch.halt_request) {
7777 vcpu->arch.halt_request = 0;
7778 ret = kvm_vcpu_halt(vcpu);
7779 goto out;
7780 }
7781
7782 if (signal_pending(current))
7783 goto out;
7784 if (need_resched())
7785 schedule();
7786 }
7787
7788out:
7789 return ret;
7790
7791emulation_error:
7792 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7793 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7794 vcpu->run->internal.ndata = 0;
7795 return 0;
7796}
7797
7798static void grow_ple_window(struct kvm_vcpu *vcpu)
7799{
7800 struct vcpu_vmx *vmx = to_vmx(vcpu);
7801 int old = vmx->ple_window;
7802
7803 vmx->ple_window = __grow_ple_window(old, ple_window,
7804 ple_window_grow,
7805 ple_window_max);
7806
7807 if (vmx->ple_window != old)
7808 vmx->ple_window_dirty = true;
7809
7810 trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
7811}
7812
7813static void shrink_ple_window(struct kvm_vcpu *vcpu)
7814{
7815 struct vcpu_vmx *vmx = to_vmx(vcpu);
7816 int old = vmx->ple_window;
7817
7818 vmx->ple_window = __shrink_ple_window(old, ple_window,
7819 ple_window_shrink,
7820 ple_window);
7821
7822 if (vmx->ple_window != old)
7823 vmx->ple_window_dirty = true;
7824
7825 trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
7826}
7827
7828/*
7829 * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
7830 */
7831static void wakeup_handler(void)
7832{
7833 struct kvm_vcpu *vcpu;
7834 int cpu = smp_processor_id();
7835
7836 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
7837 list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
7838 blocked_vcpu_list) {
7839 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7840
7841 if (pi_test_on(pi_desc) == 1)
7842 kvm_vcpu_kick(vcpu);
7843 }
7844 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
7845}
7846
7847static void vmx_enable_tdp(void)
7848{
7849 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
7850 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
7851 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
7852 0ull, VMX_EPT_EXECUTABLE_MASK,
7853 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
7854 VMX_EPT_RWX_MASK, 0ull);
7855
7856 ept_set_mmio_spte_mask();
7857 kvm_enable_tdp();
7858}
7859
7860static __init int hardware_setup(void)
7861{
7862 unsigned long host_bndcfgs;
7863 int r = -ENOMEM, i;
7864
7865 rdmsrl_safe(MSR_EFER, &host_efer);
7866
7867 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7868 kvm_define_shared_msr(i, vmx_msr_index[i]);
7869
7870 for (i = 0; i < VMX_BITMAP_NR; i++) {
7871 vmx_bitmap[i] = (unsigned long *)__get_free_page(GFP_KERNEL);
7872 if (!vmx_bitmap[i])
7873 goto out;
7874 }
7875
7876 memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
7877 memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
7878
7879 if (setup_vmcs_config(&vmcs_config) < 0) {
7880 r = -EIO;
7881 goto out;
7882 }
7883
7884 if (boot_cpu_has(X86_FEATURE_NX))
7885 kvm_enable_efer_bits(EFER_NX);
7886
7887 if (boot_cpu_has(X86_FEATURE_MPX)) {
7888 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7889 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7890 }
7891
7892 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7893 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7894 enable_vpid = 0;
7895
7896 if (!cpu_has_vmx_ept() ||
7897 !cpu_has_vmx_ept_4levels() ||
7898 !cpu_has_vmx_ept_mt_wb() ||
7899 !cpu_has_vmx_invept_global())
7900 enable_ept = 0;
7901
7902 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7903 enable_ept_ad_bits = 0;
7904
7905 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7906 enable_unrestricted_guest = 0;
7907
7908 if (!cpu_has_vmx_flexpriority())
7909 flexpriority_enabled = 0;
7910
7911 if (!cpu_has_virtual_nmis())
7912 enable_vnmi = 0;
7913
7914 /*
7915 * set_apic_access_page_addr() is used to reload apic access
7916 * page upon invalidation. No need to do anything if not
7917 * using the APIC_ACCESS_ADDR VMCS field.
7918 */
7919 if (!flexpriority_enabled)
7920 kvm_x86_ops->set_apic_access_page_addr = NULL;
7921
7922 if (!cpu_has_vmx_tpr_shadow())
7923 kvm_x86_ops->update_cr8_intercept = NULL;
7924
7925 if (enable_ept && !cpu_has_vmx_ept_2m_page())
7926 kvm_disable_largepages();
7927
7928#if IS_ENABLED(CONFIG_HYPERV)
7929 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7930 && enable_ept)
7931 kvm_x86_ops->tlb_remote_flush = vmx_hv_remote_flush_tlb;
7932#endif
7933
7934 if (!cpu_has_vmx_ple()) {
7935 ple_gap = 0;
7936 ple_window = 0;
7937 ple_window_grow = 0;
7938 ple_window_max = 0;
7939 ple_window_shrink = 0;
7940 }
7941
7942 if (!cpu_has_vmx_apicv()) {
7943 enable_apicv = 0;
7944 kvm_x86_ops->sync_pir_to_irr = NULL;
7945 }
7946
7947 if (cpu_has_vmx_tsc_scaling()) {
7948 kvm_has_tsc_control = true;
7949 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7950 kvm_tsc_scaling_ratio_frac_bits = 48;
7951 }
7952
7953 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7954
7955 if (enable_ept)
7956 vmx_enable_tdp();
7957 else
7958 kvm_disable_tdp();
7959
7960 if (!nested) {
7961 kvm_x86_ops->get_nested_state = NULL;
7962 kvm_x86_ops->set_nested_state = NULL;
7963 }
7964
7965 /*
7966 * Only enable PML when hardware supports PML feature, and both EPT
7967 * and EPT A/D bit features are enabled -- PML depends on them to work.
7968 */
7969 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7970 enable_pml = 0;
7971
7972 if (!enable_pml) {
7973 kvm_x86_ops->slot_enable_log_dirty = NULL;
7974 kvm_x86_ops->slot_disable_log_dirty = NULL;
7975 kvm_x86_ops->flush_log_dirty = NULL;
7976 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
7977 }
7978
7979 if (!cpu_has_vmx_preemption_timer())
7980 kvm_x86_ops->request_immediate_exit = __kvm_request_immediate_exit;
7981
7982 if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
7983 u64 vmx_msr;
7984
7985 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7986 cpu_preemption_timer_multi =
7987 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7988 } else {
7989 kvm_x86_ops->set_hv_timer = NULL;
7990 kvm_x86_ops->cancel_hv_timer = NULL;
7991 }
7992
7993 if (!cpu_has_vmx_shadow_vmcs())
7994 enable_shadow_vmcs = 0;
7995 if (enable_shadow_vmcs)
7996 init_vmcs_shadow_fields();
7997
7998 kvm_set_posted_intr_wakeup_handler(wakeup_handler);
7999 nested_vmx_setup_ctls_msrs(&vmcs_config.nested, enable_apicv);
8000
8001 kvm_mce_cap_supported |= MCG_LMCE_P;
8002
8003 r = alloc_kvm_area();
8004 if (r)
8005 goto out;
8006 return 0;
8007
8008out:
8009 for (i = 0; i < VMX_BITMAP_NR; i++)
8010 free_page((unsigned long)vmx_bitmap[i]);
8011
8012 return r;
8013}
8014
8015static __exit void hardware_unsetup(void)
8016{
8017 int i;
8018
8019 for (i = 0; i < VMX_BITMAP_NR; i++)
8020 free_page((unsigned long)vmx_bitmap[i]);
8021
8022 free_kvm_area();
8023}
8024
8025/*
8026 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
8027 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
8028 */
8029static int handle_pause(struct kvm_vcpu *vcpu)
8030{
8031 if (!kvm_pause_in_guest(vcpu->kvm))
8032 grow_ple_window(vcpu);
8033
8034 /*
8035 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
8036 * VM-execution control is ignored if CPL > 0. OTOH, KVM
8037 * never set PAUSE_EXITING and just set PLE if supported,
8038 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
8039 */
8040 kvm_vcpu_on_spin(vcpu, true);
8041 return kvm_skip_emulated_instruction(vcpu);
8042}
8043
8044static int handle_nop(struct kvm_vcpu *vcpu)
8045{
8046 return kvm_skip_emulated_instruction(vcpu);
8047}
8048
8049static int handle_mwait(struct kvm_vcpu *vcpu)
8050{
8051 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
8052 return handle_nop(vcpu);
8053}
8054
8055static int handle_invalid_op(struct kvm_vcpu *vcpu)
8056{
8057 kvm_queue_exception(vcpu, UD_VECTOR);
8058 return 1;
8059}
8060
8061static int handle_monitor_trap(struct kvm_vcpu *vcpu)
8062{
8063 return 1;
8064}
8065
8066static int handle_monitor(struct kvm_vcpu *vcpu)
8067{
8068 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
8069 return handle_nop(vcpu);
8070}
8071
8072/*
8073 * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
8074 * set the success or error code of an emulated VMX instruction, as specified
8075 * by Vol 2B, VMX Instruction Reference, "Conventions".
8076 */
8077static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
8078{
8079 vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
8080 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
8081 X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
8082}
8083
8084static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
8085{
8086 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
8087 & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
8088 X86_EFLAGS_SF | X86_EFLAGS_OF))
8089 | X86_EFLAGS_CF);
8090}
8091
8092static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
8093 u32 vm_instruction_error)
8094{
8095 if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
8096 /*
8097 * failValid writes the error number to the current VMCS, which
8098 * can't be done there isn't a current VMCS.
8099 */
8100 nested_vmx_failInvalid(vcpu);
8101 return;
8102 }
8103 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
8104 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
8105 X86_EFLAGS_SF | X86_EFLAGS_OF))
8106 | X86_EFLAGS_ZF);
8107 get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
8108 /*
8109 * We don't need to force a shadow sync because
8110 * VM_INSTRUCTION_ERROR is not shadowed
8111 */
8112}
8113
8114static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
8115{
8116 /* TODO: not to reset guest simply here. */
8117 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8118 pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
8119}
8120
8121static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
8122{
8123 struct vcpu_vmx *vmx =
8124 container_of(timer, struct vcpu_vmx, nested.preemption_timer);
8125
8126 vmx->nested.preemption_timer_expired = true;
8127 kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
8128 kvm_vcpu_kick(&vmx->vcpu);
8129
8130 return HRTIMER_NORESTART;
8131}
8132
8133/*
8134 * Decode the memory-address operand of a vmx instruction, as recorded on an
8135 * exit caused by such an instruction (run by a guest hypervisor).
8136 * On success, returns 0. When the operand is invalid, returns 1 and throws
8137 * #UD or #GP.
8138 */
8139static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
8140 unsigned long exit_qualification,
8141 u32 vmx_instruction_info, bool wr, gva_t *ret)
8142{
8143 gva_t off;
8144 bool exn;
8145 struct kvm_segment s;
8146
8147 /*
8148 * According to Vol. 3B, "Information for VM Exits Due to Instruction
8149 * Execution", on an exit, vmx_instruction_info holds most of the
8150 * addressing components of the operand. Only the displacement part
8151 * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
8152 * For how an actual address is calculated from all these components,
8153 * refer to Vol. 1, "Operand Addressing".
8154 */
8155 int scaling = vmx_instruction_info & 3;
8156 int addr_size = (vmx_instruction_info >> 7) & 7;
8157 bool is_reg = vmx_instruction_info & (1u << 10);
8158 int seg_reg = (vmx_instruction_info >> 15) & 7;
8159 int index_reg = (vmx_instruction_info >> 18) & 0xf;
8160 bool index_is_valid = !(vmx_instruction_info & (1u << 22));
8161 int base_reg = (vmx_instruction_info >> 23) & 0xf;
8162 bool base_is_valid = !(vmx_instruction_info & (1u << 27));
8163
8164 if (is_reg) {
8165 kvm_queue_exception(vcpu, UD_VECTOR);
8166 return 1;
8167 }
8168
8169 /* Addr = segment_base + offset */
8170 /* offset = base + [index * scale] + displacement */
8171 off = exit_qualification; /* holds the displacement */
8172 if (addr_size == 1)
8173 off = (gva_t)sign_extend64(off, 31);
8174 else if (addr_size == 0)
8175 off = (gva_t)sign_extend64(off, 15);
8176 if (base_is_valid)
8177 off += kvm_register_read(vcpu, base_reg);
8178 if (index_is_valid)
8179 off += kvm_register_read(vcpu, index_reg)<<scaling;
8180 vmx_get_segment(vcpu, &s, seg_reg);
8181
8182 /*
8183 * The effective address, i.e. @off, of a memory operand is truncated
8184 * based on the address size of the instruction. Note that this is
8185 * the *effective address*, i.e. the address prior to accounting for
8186 * the segment's base.
8187 */
8188 if (addr_size == 1) /* 32 bit */
8189 off &= 0xffffffff;
8190 else if (addr_size == 0) /* 16 bit */
8191 off &= 0xffff;
8192
8193 /* Checks for #GP/#SS exceptions. */
8194 exn = false;
8195 if (is_long_mode(vcpu)) {
8196 /*
8197 * The virtual/linear address is never truncated in 64-bit
8198 * mode, e.g. a 32-bit address size can yield a 64-bit virtual
8199 * address when using FS/GS with a non-zero base.
8200 */
8201 *ret = s.base + off;
8202
8203 /* Long mode: #GP(0)/#SS(0) if the memory address is in a
8204 * non-canonical form. This is the only check on the memory
8205 * destination for long mode!
8206 */
8207 exn = is_noncanonical_address(*ret, vcpu);
8208 } else if (is_protmode(vcpu)) {
8209 /*
8210 * When not in long mode, the virtual/linear address is
8211 * unconditionally truncated to 32 bits regardless of the
8212 * address size.
8213 */
8214 *ret = (s.base + off) & 0xffffffff;
8215
8216 /* Protected mode: apply checks for segment validity in the
8217 * following order:
8218 * - segment type check (#GP(0) may be thrown)
8219 * - usability check (#GP(0)/#SS(0))
8220 * - limit check (#GP(0)/#SS(0))
8221 */
8222 if (wr)
8223 /* #GP(0) if the destination operand is located in a
8224 * read-only data segment or any code segment.
8225 */
8226 exn = ((s.type & 0xa) == 0 || (s.type & 8));
8227 else
8228 /* #GP(0) if the source operand is located in an
8229 * execute-only code segment
8230 */
8231 exn = ((s.type & 0xa) == 8);
8232 if (exn) {
8233 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
8234 return 1;
8235 }
8236 /* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
8237 */
8238 exn = (s.unusable != 0);
8239
8240 /*
8241 * Protected mode: #GP(0)/#SS(0) if the memory operand is
8242 * outside the segment limit. All CPUs that support VMX ignore
8243 * limit checks for flat segments, i.e. segments with base==0,
8244 * limit==0xffffffff and of type expand-up data or code.
8245 */
8246 if (!(s.base == 0 && s.limit == 0xffffffff &&
8247 ((s.type & 8) || !(s.type & 4))))
8248 exn = exn || (off + sizeof(u64) > s.limit);
8249 }
8250 if (exn) {
8251 kvm_queue_exception_e(vcpu,
8252 seg_reg == VCPU_SREG_SS ?
8253 SS_VECTOR : GP_VECTOR,
8254 0);
8255 return 1;
8256 }
8257
8258 return 0;
8259}
8260
8261static int nested_vmx_get_vmptr(struct kvm_vcpu *vcpu, gpa_t *vmpointer)
8262{
8263 gva_t gva;
8264 struct x86_exception e;
8265
8266 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
8267 vmcs_read32(VMX_INSTRUCTION_INFO), false, &gva))
8268 return 1;
8269
8270 if (kvm_read_guest_virt(vcpu, gva, vmpointer, sizeof(*vmpointer), &e)) {
8271 kvm_inject_page_fault(vcpu, &e);
8272 return 1;
8273 }
8274
8275 return 0;
8276}
8277
8278/*
8279 * Allocate a shadow VMCS and associate it with the currently loaded
8280 * VMCS, unless such a shadow VMCS already exists. The newly allocated
8281 * VMCS is also VMCLEARed, so that it is ready for use.
8282 */
8283static struct vmcs *alloc_shadow_vmcs(struct kvm_vcpu *vcpu)
8284{
8285 struct vcpu_vmx *vmx = to_vmx(vcpu);
8286 struct loaded_vmcs *loaded_vmcs = vmx->loaded_vmcs;
8287
8288 /*
8289 * We should allocate a shadow vmcs for vmcs01 only when L1
8290 * executes VMXON and free it when L1 executes VMXOFF.
8291 * As it is invalid to execute VMXON twice, we shouldn't reach
8292 * here when vmcs01 already have an allocated shadow vmcs.
8293 */
8294 WARN_ON(loaded_vmcs == &vmx->vmcs01 && loaded_vmcs->shadow_vmcs);
8295
8296 if (!loaded_vmcs->shadow_vmcs) {
8297 loaded_vmcs->shadow_vmcs = alloc_vmcs(true);
8298 if (loaded_vmcs->shadow_vmcs)
8299 vmcs_clear(loaded_vmcs->shadow_vmcs);
8300 }
8301 return loaded_vmcs->shadow_vmcs;
8302}
8303
8304static int enter_vmx_operation(struct kvm_vcpu *vcpu)
8305{
8306 struct vcpu_vmx *vmx = to_vmx(vcpu);
8307 int r;
8308
8309 r = alloc_loaded_vmcs(&vmx->nested.vmcs02);
8310 if (r < 0)
8311 goto out_vmcs02;
8312
8313 vmx->nested.cached_vmcs12 = kzalloc(VMCS12_SIZE, GFP_KERNEL);
8314 if (!vmx->nested.cached_vmcs12)
8315 goto out_cached_vmcs12;
8316
8317 vmx->nested.cached_shadow_vmcs12 = kzalloc(VMCS12_SIZE, GFP_KERNEL);
8318 if (!vmx->nested.cached_shadow_vmcs12)
8319 goto out_cached_shadow_vmcs12;
8320
8321 if (enable_shadow_vmcs && !alloc_shadow_vmcs(vcpu))
8322 goto out_shadow_vmcs;
8323
8324 hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
8325 HRTIMER_MODE_REL_PINNED);
8326 vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
8327
8328 vmx->nested.vpid02 = allocate_vpid();
8329
8330 vmx->nested.vmxon = true;
8331 return 0;
8332
8333out_shadow_vmcs:
8334 kfree(vmx->nested.cached_shadow_vmcs12);
8335
8336out_cached_shadow_vmcs12:
8337 kfree(vmx->nested.cached_vmcs12);
8338
8339out_cached_vmcs12:
8340 free_loaded_vmcs(&vmx->nested.vmcs02);
8341
8342out_vmcs02:
8343 return -ENOMEM;
8344}
8345
8346/*
8347 * Emulate the VMXON instruction.
8348 * Currently, we just remember that VMX is active, and do not save or even
8349 * inspect the argument to VMXON (the so-called "VMXON pointer") because we
8350 * do not currently need to store anything in that guest-allocated memory
8351 * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
8352 * argument is different from the VMXON pointer (which the spec says they do).
8353 */
8354static int handle_vmon(struct kvm_vcpu *vcpu)
8355{
8356 int ret;
8357 gpa_t vmptr;
8358 struct page *page;
8359 struct vcpu_vmx *vmx = to_vmx(vcpu);
8360 const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
8361 | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
8362
8363 /*
8364 * The Intel VMX Instruction Reference lists a bunch of bits that are
8365 * prerequisite to running VMXON, most notably cr4.VMXE must be set to
8366 * 1 (see vmx_set_cr4() for when we allow the guest to set this).
8367 * Otherwise, we should fail with #UD. But most faulting conditions
8368 * have already been checked by hardware, prior to the VM-exit for
8369 * VMXON. We do test guest cr4.VMXE because processor CR4 always has
8370 * that bit set to 1 in non-root mode.
8371 */
8372 if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) {
8373 kvm_queue_exception(vcpu, UD_VECTOR);
8374 return 1;
8375 }
8376
8377 /* CPL=0 must be checked manually. */
8378 if (vmx_get_cpl(vcpu)) {
8379 kvm_inject_gp(vcpu, 0);
8380 return 1;
8381 }
8382
8383 if (vmx->nested.vmxon) {
8384 nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
8385 return kvm_skip_emulated_instruction(vcpu);
8386 }
8387
8388 if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
8389 != VMXON_NEEDED_FEATURES) {
8390 kvm_inject_gp(vcpu, 0);
8391 return 1;
8392 }
8393
8394 if (nested_vmx_get_vmptr(vcpu, &vmptr))
8395 return 1;
8396
8397 /*
8398 * SDM 3: 24.11.5
8399 * The first 4 bytes of VMXON region contain the supported
8400 * VMCS revision identifier
8401 *
8402 * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
8403 * which replaces physical address width with 32
8404 */
8405 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
8406 nested_vmx_failInvalid(vcpu);
8407 return kvm_skip_emulated_instruction(vcpu);
8408 }
8409
8410 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
8411 if (is_error_page(page)) {
8412 nested_vmx_failInvalid(vcpu);
8413 return kvm_skip_emulated_instruction(vcpu);
8414 }
8415 if (*(u32 *)kmap(page) != VMCS12_REVISION) {
8416 kunmap(page);
8417 kvm_release_page_clean(page);
8418 nested_vmx_failInvalid(vcpu);
8419 return kvm_skip_emulated_instruction(vcpu);
8420 }
8421 kunmap(page);
8422 kvm_release_page_clean(page);
8423
8424 vmx->nested.vmxon_ptr = vmptr;
8425 ret = enter_vmx_operation(vcpu);
8426 if (ret)
8427 return ret;
8428
8429 nested_vmx_succeed(vcpu);
8430 return kvm_skip_emulated_instruction(vcpu);
8431}
8432
8433/*
8434 * Intel's VMX Instruction Reference specifies a common set of prerequisites
8435 * for running VMX instructions (except VMXON, whose prerequisites are
8436 * slightly different). It also specifies what exception to inject otherwise.
8437 * Note that many of these exceptions have priority over VM exits, so they
8438 * don't have to be checked again here.
8439 */
8440static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
8441{
8442 if (!to_vmx(vcpu)->nested.vmxon) {
8443 kvm_queue_exception(vcpu, UD_VECTOR);
8444 return 0;
8445 }
8446
8447 if (vmx_get_cpl(vcpu)) {
8448 kvm_inject_gp(vcpu, 0);
8449 return 0;
8450 }
8451
8452 return 1;
8453}
8454
8455static void vmx_disable_shadow_vmcs(struct vcpu_vmx *vmx)
8456{
8457 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL, SECONDARY_EXEC_SHADOW_VMCS);
8458 vmcs_write64(VMCS_LINK_POINTER, -1ull);
8459 vmx->nested.sync_shadow_vmcs = false;
8460}
8461
8462static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
8463{
8464 if (vmx->nested.current_vmptr == -1ull)
8465 return;
8466
8467 if (enable_shadow_vmcs) {
8468 /* copy to memory all shadowed fields in case
8469 they were modified */
8470 copy_shadow_to_vmcs12(vmx);
8471 vmx_disable_shadow_vmcs(vmx);
8472 }
8473 vmx->nested.posted_intr_nv = -1;
8474
8475 /* Flush VMCS12 to guest memory */
8476 kvm_vcpu_write_guest_page(&vmx->vcpu,
8477 vmx->nested.current_vmptr >> PAGE_SHIFT,
8478 vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
8479
8480 vmx->nested.current_vmptr = -1ull;
8481}
8482
8483/*
8484 * Free whatever needs to be freed from vmx->nested when L1 goes down, or
8485 * just stops using VMX.
8486 */
8487static void free_nested(struct vcpu_vmx *vmx)
8488{
8489 if (!vmx->nested.vmxon && !vmx->nested.smm.vmxon)
8490 return;
8491
8492 kvm_clear_request(KVM_REQ_GET_VMCS12_PAGES, &vmx->vcpu);
8493
8494 hrtimer_cancel(&vmx->nested.preemption_timer);
8495 vmx->nested.vmxon = false;
8496 vmx->nested.smm.vmxon = false;
8497 free_vpid(vmx->nested.vpid02);
8498 vmx->nested.posted_intr_nv = -1;
8499 vmx->nested.current_vmptr = -1ull;
8500 if (enable_shadow_vmcs) {
8501 vmx_disable_shadow_vmcs(vmx);
8502 vmcs_clear(vmx->vmcs01.shadow_vmcs);
8503 free_vmcs(vmx->vmcs01.shadow_vmcs);
8504 vmx->vmcs01.shadow_vmcs = NULL;
8505 }
8506 kfree(vmx->nested.cached_vmcs12);
8507 kfree(vmx->nested.cached_shadow_vmcs12);
8508 /* Unpin physical memory we referred to in the vmcs02 */
8509 if (vmx->nested.apic_access_page) {
8510 kvm_release_page_dirty(vmx->nested.apic_access_page);
8511 vmx->nested.apic_access_page = NULL;
8512 }
8513 if (vmx->nested.virtual_apic_page) {
8514 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
8515 vmx->nested.virtual_apic_page = NULL;
8516 }
8517 if (vmx->nested.pi_desc_page) {
8518 kunmap(vmx->nested.pi_desc_page);
8519 kvm_release_page_dirty(vmx->nested.pi_desc_page);
8520 vmx->nested.pi_desc_page = NULL;
8521 vmx->nested.pi_desc = NULL;
8522 }
8523
8524 free_loaded_vmcs(&vmx->nested.vmcs02);
8525}
8526
8527/* Emulate the VMXOFF instruction */
8528static int handle_vmoff(struct kvm_vcpu *vcpu)
8529{
8530 if (!nested_vmx_check_permission(vcpu))
8531 return 1;
8532 free_nested(to_vmx(vcpu));
8533 nested_vmx_succeed(vcpu);
8534 return kvm_skip_emulated_instruction(vcpu);
8535}
8536
8537/* Emulate the VMCLEAR instruction */
8538static int handle_vmclear(struct kvm_vcpu *vcpu)
8539{
8540 struct vcpu_vmx *vmx = to_vmx(vcpu);
8541 u32 zero = 0;
8542 gpa_t vmptr;
8543
8544 if (!nested_vmx_check_permission(vcpu))
8545 return 1;
8546
8547 if (nested_vmx_get_vmptr(vcpu, &vmptr))
8548 return 1;
8549
8550 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
8551 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
8552 return kvm_skip_emulated_instruction(vcpu);
8553 }
8554
8555 if (vmptr == vmx->nested.vmxon_ptr) {
8556 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_VMXON_POINTER);
8557 return kvm_skip_emulated_instruction(vcpu);
8558 }
8559
8560 if (vmptr == vmx->nested.current_vmptr)
8561 nested_release_vmcs12(vmx);
8562
8563 kvm_vcpu_write_guest(vcpu,
8564 vmptr + offsetof(struct vmcs12, launch_state),
8565 &zero, sizeof(zero));
8566
8567 nested_vmx_succeed(vcpu);
8568 return kvm_skip_emulated_instruction(vcpu);
8569}
8570
8571static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
8572
8573/* Emulate the VMLAUNCH instruction */
8574static int handle_vmlaunch(struct kvm_vcpu *vcpu)
8575{
8576 return nested_vmx_run(vcpu, true);
8577}
8578
8579/* Emulate the VMRESUME instruction */
8580static int handle_vmresume(struct kvm_vcpu *vcpu)
8581{
8582
8583 return nested_vmx_run(vcpu, false);
8584}
8585
8586/*
8587 * Read a vmcs12 field. Since these can have varying lengths and we return
8588 * one type, we chose the biggest type (u64) and zero-extend the return value
8589 * to that size. Note that the caller, handle_vmread, might need to use only
8590 * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
8591 * 64-bit fields are to be returned).
8592 */
8593static inline int vmcs12_read_any(struct vmcs12 *vmcs12,
8594 unsigned long field, u64 *ret)
8595{
8596 short offset = vmcs_field_to_offset(field);
8597 char *p;
8598
8599 if (offset < 0)
8600 return offset;
8601
8602 p = (char *)vmcs12 + offset;
8603
8604 switch (vmcs_field_width(field)) {
8605 case VMCS_FIELD_WIDTH_NATURAL_WIDTH:
8606 *ret = *((natural_width *)p);
8607 return 0;
8608 case VMCS_FIELD_WIDTH_U16:
8609 *ret = *((u16 *)p);
8610 return 0;
8611 case VMCS_FIELD_WIDTH_U32:
8612 *ret = *((u32 *)p);
8613 return 0;
8614 case VMCS_FIELD_WIDTH_U64:
8615 *ret = *((u64 *)p);
8616 return 0;
8617 default:
8618 WARN_ON(1);
8619 return -ENOENT;
8620 }
8621}
8622
8623
8624static inline int vmcs12_write_any(struct vmcs12 *vmcs12,
8625 unsigned long field, u64 field_value){
8626 short offset = vmcs_field_to_offset(field);
8627 char *p = (char *)vmcs12 + offset;
8628 if (offset < 0)
8629 return offset;
8630
8631 switch (vmcs_field_width(field)) {
8632 case VMCS_FIELD_WIDTH_U16:
8633 *(u16 *)p = field_value;
8634 return 0;
8635 case VMCS_FIELD_WIDTH_U32:
8636 *(u32 *)p = field_value;
8637 return 0;
8638 case VMCS_FIELD_WIDTH_U64:
8639 *(u64 *)p = field_value;
8640 return 0;
8641 case VMCS_FIELD_WIDTH_NATURAL_WIDTH:
8642 *(natural_width *)p = field_value;
8643 return 0;
8644 default:
8645 WARN_ON(1);
8646 return -ENOENT;
8647 }
8648
8649}
8650
8651/*
8652 * Copy the writable VMCS shadow fields back to the VMCS12, in case
8653 * they have been modified by the L1 guest. Note that the "read-only"
8654 * VM-exit information fields are actually writable if the vCPU is
8655 * configured to support "VMWRITE to any supported field in the VMCS."
8656 */
8657static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
8658{
8659 const u16 *fields[] = {
8660 shadow_read_write_fields,
8661 shadow_read_only_fields
8662 };
8663 const int max_fields[] = {
8664 max_shadow_read_write_fields,
8665 max_shadow_read_only_fields
8666 };
8667 int i, q;
8668 unsigned long field;
8669 u64 field_value;
8670 struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
8671
8672 if (WARN_ON(!shadow_vmcs))
8673 return;
8674
8675 preempt_disable();
8676
8677 vmcs_load(shadow_vmcs);
8678
8679 for (q = 0; q < ARRAY_SIZE(fields); q++) {
8680 for (i = 0; i < max_fields[q]; i++) {
8681 field = fields[q][i];
8682 field_value = __vmcs_readl(field);
8683 vmcs12_write_any(get_vmcs12(&vmx->vcpu), field, field_value);
8684 }
8685 /*
8686 * Skip the VM-exit information fields if they are read-only.
8687 */
8688 if (!nested_cpu_has_vmwrite_any_field(&vmx->vcpu))
8689 break;
8690 }
8691
8692 vmcs_clear(shadow_vmcs);
8693 vmcs_load(vmx->loaded_vmcs->vmcs);
8694
8695 preempt_enable();
8696}
8697
8698static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
8699{
8700 const u16 *fields[] = {
8701 shadow_read_write_fields,
8702 shadow_read_only_fields
8703 };
8704 const int max_fields[] = {
8705 max_shadow_read_write_fields,
8706 max_shadow_read_only_fields
8707 };
8708 int i, q;
8709 unsigned long field;
8710 u64 field_value = 0;
8711 struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
8712
8713 if (WARN_ON(!shadow_vmcs))
8714 return;
8715
8716 vmcs_load(shadow_vmcs);
8717
8718 for (q = 0; q < ARRAY_SIZE(fields); q++) {
8719 for (i = 0; i < max_fields[q]; i++) {
8720 field = fields[q][i];
8721 vmcs12_read_any(get_vmcs12(&vmx->vcpu), field, &field_value);
8722 __vmcs_writel(field, field_value);
8723 }
8724 }
8725
8726 vmcs_clear(shadow_vmcs);
8727 vmcs_load(vmx->loaded_vmcs->vmcs);
8728}
8729
8730/*
8731 * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
8732 * used before) all generate the same failure when it is missing.
8733 */
8734static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
8735{
8736 struct vcpu_vmx *vmx = to_vmx(vcpu);
8737 if (vmx->nested.current_vmptr == -1ull) {
8738 nested_vmx_failInvalid(vcpu);
8739 return 0;
8740 }
8741 return 1;
8742}
8743
8744static int handle_vmread(struct kvm_vcpu *vcpu)
8745{
8746 unsigned long field;
8747 u64 field_value;
8748 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8749 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8750 gva_t gva = 0;
8751 struct vmcs12 *vmcs12;
8752 struct x86_exception e;
8753
8754 if (!nested_vmx_check_permission(vcpu))
8755 return 1;
8756
8757 if (!nested_vmx_check_vmcs12(vcpu))
8758 return kvm_skip_emulated_instruction(vcpu);
8759
8760 if (!is_guest_mode(vcpu))
8761 vmcs12 = get_vmcs12(vcpu);
8762 else {
8763 /*
8764 * When vmcs->vmcs_link_pointer is -1ull, any VMREAD
8765 * to shadowed-field sets the ALU flags for VMfailInvalid.
8766 */
8767 if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull) {
8768 nested_vmx_failInvalid(vcpu);
8769 return kvm_skip_emulated_instruction(vcpu);
8770 }
8771 vmcs12 = get_shadow_vmcs12(vcpu);
8772 }
8773
8774 /* Decode instruction info and find the field to read */
8775 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
8776 /* Read the field, zero-extended to a u64 field_value */
8777 if (vmcs12_read_any(vmcs12, field, &field_value) < 0) {
8778 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
8779 return kvm_skip_emulated_instruction(vcpu);
8780 }
8781 /*
8782 * Now copy part of this value to register or memory, as requested.
8783 * Note that the number of bits actually copied is 32 or 64 depending
8784 * on the guest's mode (32 or 64 bit), not on the given field's length.
8785 */
8786 if (vmx_instruction_info & (1u << 10)) {
8787 kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
8788 field_value);
8789 } else {
8790 if (get_vmx_mem_address(vcpu, exit_qualification,
8791 vmx_instruction_info, true, &gva))
8792 return 1;
8793 /* _system ok, nested_vmx_check_permission has verified cpl=0 */
8794 if (kvm_write_guest_virt_system(vcpu, gva, &field_value,
8795 (is_long_mode(vcpu) ? 8 : 4),
8796 &e))
8797 kvm_inject_page_fault(vcpu, &e);
8798 }
8799
8800 nested_vmx_succeed(vcpu);
8801 return kvm_skip_emulated_instruction(vcpu);
8802}
8803
8804
8805static int handle_vmwrite(struct kvm_vcpu *vcpu)
8806{
8807 unsigned long field;
8808 gva_t gva;
8809 struct vcpu_vmx *vmx = to_vmx(vcpu);
8810 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8811 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8812
8813 /* The value to write might be 32 or 64 bits, depending on L1's long
8814 * mode, and eventually we need to write that into a field of several
8815 * possible lengths. The code below first zero-extends the value to 64
8816 * bit (field_value), and then copies only the appropriate number of
8817 * bits into the vmcs12 field.
8818 */
8819 u64 field_value = 0;
8820 struct x86_exception e;
8821 struct vmcs12 *vmcs12;
8822
8823 if (!nested_vmx_check_permission(vcpu))
8824 return 1;
8825
8826 if (!nested_vmx_check_vmcs12(vcpu))
8827 return kvm_skip_emulated_instruction(vcpu);
8828
8829 if (vmx_instruction_info & (1u << 10))
8830 field_value = kvm_register_readl(vcpu,
8831 (((vmx_instruction_info) >> 3) & 0xf));
8832 else {
8833 if (get_vmx_mem_address(vcpu, exit_qualification,
8834 vmx_instruction_info, false, &gva))
8835 return 1;
8836 if (kvm_read_guest_virt(vcpu, gva, &field_value,
8837 (is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
8838 kvm_inject_page_fault(vcpu, &e);
8839 return 1;
8840 }
8841 }
8842
8843
8844 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
8845 /*
8846 * If the vCPU supports "VMWRITE to any supported field in the
8847 * VMCS," then the "read-only" fields are actually read/write.
8848 */
8849 if (vmcs_field_readonly(field) &&
8850 !nested_cpu_has_vmwrite_any_field(vcpu)) {
8851 nested_vmx_failValid(vcpu,
8852 VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
8853 return kvm_skip_emulated_instruction(vcpu);
8854 }
8855
8856 if (!is_guest_mode(vcpu))
8857 vmcs12 = get_vmcs12(vcpu);
8858 else {
8859 /*
8860 * When vmcs->vmcs_link_pointer is -1ull, any VMWRITE
8861 * to shadowed-field sets the ALU flags for VMfailInvalid.
8862 */
8863 if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull) {
8864 nested_vmx_failInvalid(vcpu);
8865 return kvm_skip_emulated_instruction(vcpu);
8866 }
8867 vmcs12 = get_shadow_vmcs12(vcpu);
8868
8869 }
8870
8871 if (vmcs12_write_any(vmcs12, field, field_value) < 0) {
8872 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
8873 return kvm_skip_emulated_instruction(vcpu);
8874 }
8875
8876 /*
8877 * Do not track vmcs12 dirty-state if in guest-mode
8878 * as we actually dirty shadow vmcs12 instead of vmcs12.
8879 */
8880 if (!is_guest_mode(vcpu)) {
8881 switch (field) {
8882#define SHADOW_FIELD_RW(x) case x:
8883#include "vmx_shadow_fields.h"
8884 /*
8885 * The fields that can be updated by L1 without a vmexit are
8886 * always updated in the vmcs02, the others go down the slow
8887 * path of prepare_vmcs02.
8888 */
8889 break;
8890 default:
8891 vmx->nested.dirty_vmcs12 = true;
8892 break;
8893 }
8894 }
8895
8896 nested_vmx_succeed(vcpu);
8897 return kvm_skip_emulated_instruction(vcpu);
8898}
8899
8900static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
8901{
8902 vmx->nested.current_vmptr = vmptr;
8903 if (enable_shadow_vmcs) {
8904 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
8905 SECONDARY_EXEC_SHADOW_VMCS);
8906 vmcs_write64(VMCS_LINK_POINTER,
8907 __pa(vmx->vmcs01.shadow_vmcs));
8908 vmx->nested.sync_shadow_vmcs = true;
8909 }
8910 vmx->nested.dirty_vmcs12 = true;
8911}
8912
8913/* Emulate the VMPTRLD instruction */
8914static int handle_vmptrld(struct kvm_vcpu *vcpu)
8915{
8916 struct vcpu_vmx *vmx = to_vmx(vcpu);
8917 gpa_t vmptr;
8918
8919 if (!nested_vmx_check_permission(vcpu))
8920 return 1;
8921
8922 if (nested_vmx_get_vmptr(vcpu, &vmptr))
8923 return 1;
8924
8925 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
8926 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS);
8927 return kvm_skip_emulated_instruction(vcpu);
8928 }
8929
8930 if (vmptr == vmx->nested.vmxon_ptr) {
8931 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_VMXON_POINTER);
8932 return kvm_skip_emulated_instruction(vcpu);
8933 }
8934
8935 if (vmx->nested.current_vmptr != vmptr) {
8936 struct vmcs12 *new_vmcs12;
8937 struct page *page;
8938 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
8939 if (is_error_page(page)) {
8940 nested_vmx_failInvalid(vcpu);
8941 return kvm_skip_emulated_instruction(vcpu);
8942 }
8943 new_vmcs12 = kmap(page);
8944 if (new_vmcs12->hdr.revision_id != VMCS12_REVISION ||
8945 (new_vmcs12->hdr.shadow_vmcs &&
8946 !nested_cpu_has_vmx_shadow_vmcs(vcpu))) {
8947 kunmap(page);
8948 kvm_release_page_clean(page);
8949 nested_vmx_failValid(vcpu,
8950 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
8951 return kvm_skip_emulated_instruction(vcpu);
8952 }
8953
8954 nested_release_vmcs12(vmx);
8955 /*
8956 * Load VMCS12 from guest memory since it is not already
8957 * cached.
8958 */
8959 memcpy(vmx->nested.cached_vmcs12, new_vmcs12, VMCS12_SIZE);
8960 kunmap(page);
8961 kvm_release_page_clean(page);
8962
8963 set_current_vmptr(vmx, vmptr);
8964 }
8965
8966 nested_vmx_succeed(vcpu);
8967 return kvm_skip_emulated_instruction(vcpu);
8968}
8969
8970/* Emulate the VMPTRST instruction */
8971static int handle_vmptrst(struct kvm_vcpu *vcpu)
8972{
8973 unsigned long exit_qual = vmcs_readl(EXIT_QUALIFICATION);
8974 u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8975 gpa_t current_vmptr = to_vmx(vcpu)->nested.current_vmptr;
8976 struct x86_exception e;
8977 gva_t gva;
8978
8979 if (!nested_vmx_check_permission(vcpu))
8980 return 1;
8981
8982 if (get_vmx_mem_address(vcpu, exit_qual, instr_info, true, &gva))
8983 return 1;
8984 /* *_system ok, nested_vmx_check_permission has verified cpl=0 */
8985 if (kvm_write_guest_virt_system(vcpu, gva, (void *)&current_vmptr,
8986 sizeof(gpa_t), &e)) {
8987 kvm_inject_page_fault(vcpu, &e);
8988 return 1;
8989 }
8990 nested_vmx_succeed(vcpu);
8991 return kvm_skip_emulated_instruction(vcpu);
8992}
8993
8994/* Emulate the INVEPT instruction */
8995static int handle_invept(struct kvm_vcpu *vcpu)
8996{
8997 struct vcpu_vmx *vmx = to_vmx(vcpu);
8998 u32 vmx_instruction_info, types;
8999 unsigned long type;
9000 gva_t gva;
9001 struct x86_exception e;
9002 struct {
9003 u64 eptp, gpa;
9004 } operand;
9005
9006 if (!(vmx->nested.msrs.secondary_ctls_high &
9007 SECONDARY_EXEC_ENABLE_EPT) ||
9008 !(vmx->nested.msrs.ept_caps & VMX_EPT_INVEPT_BIT)) {
9009 kvm_queue_exception(vcpu, UD_VECTOR);
9010 return 1;
9011 }
9012
9013 if (!nested_vmx_check_permission(vcpu))
9014 return 1;
9015
9016 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9017 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9018
9019 types = (vmx->nested.msrs.ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
9020
9021 if (type >= 32 || !(types & (1 << type))) {
9022 nested_vmx_failValid(vcpu,
9023 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9024 return kvm_skip_emulated_instruction(vcpu);
9025 }
9026
9027 /* According to the Intel VMX instruction reference, the memory
9028 * operand is read even if it isn't needed (e.g., for type==global)
9029 */
9030 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9031 vmx_instruction_info, false, &gva))
9032 return 1;
9033 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9034 kvm_inject_page_fault(vcpu, &e);
9035 return 1;
9036 }
9037
9038 switch (type) {
9039 case VMX_EPT_EXTENT_GLOBAL:
9040 /*
9041 * TODO: track mappings and invalidate
9042 * single context requests appropriately
9043 */
9044 case VMX_EPT_EXTENT_CONTEXT:
9045 kvm_mmu_sync_roots(vcpu);
9046 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
9047 nested_vmx_succeed(vcpu);
9048 break;
9049 default:
9050 BUG_ON(1);
9051 break;
9052 }
9053
9054 return kvm_skip_emulated_instruction(vcpu);
9055}
9056
9057static int handle_invvpid(struct kvm_vcpu *vcpu)
9058{
9059 struct vcpu_vmx *vmx = to_vmx(vcpu);
9060 u32 vmx_instruction_info;
9061 unsigned long type, types;
9062 gva_t gva;
9063 struct x86_exception e;
9064 struct {
9065 u64 vpid;
9066 u64 gla;
9067 } operand;
9068
9069 if (!(vmx->nested.msrs.secondary_ctls_high &
9070 SECONDARY_EXEC_ENABLE_VPID) ||
9071 !(vmx->nested.msrs.vpid_caps & VMX_VPID_INVVPID_BIT)) {
9072 kvm_queue_exception(vcpu, UD_VECTOR);
9073 return 1;
9074 }
9075
9076 if (!nested_vmx_check_permission(vcpu))
9077 return 1;
9078
9079 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9080 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9081
9082 types = (vmx->nested.msrs.vpid_caps &
9083 VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
9084
9085 if (type >= 32 || !(types & (1 << type))) {
9086 nested_vmx_failValid(vcpu,
9087 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9088 return kvm_skip_emulated_instruction(vcpu);
9089 }
9090
9091 /* according to the intel vmx instruction reference, the memory
9092 * operand is read even if it isn't needed (e.g., for type==global)
9093 */
9094 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9095 vmx_instruction_info, false, &gva))
9096 return 1;
9097 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9098 kvm_inject_page_fault(vcpu, &e);
9099 return 1;
9100 }
9101 if (operand.vpid >> 16) {
9102 nested_vmx_failValid(vcpu,
9103 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9104 return kvm_skip_emulated_instruction(vcpu);
9105 }
9106
9107 switch (type) {
9108 case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
9109 if (!operand.vpid ||
9110 is_noncanonical_address(operand.gla, vcpu)) {
9111 nested_vmx_failValid(vcpu,
9112 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9113 return kvm_skip_emulated_instruction(vcpu);
9114 }
9115 if (cpu_has_vmx_invvpid_individual_addr() &&
9116 vmx->nested.vpid02) {
9117 __invvpid(VMX_VPID_EXTENT_INDIVIDUAL_ADDR,
9118 vmx->nested.vpid02, operand.gla);
9119 } else
9120 __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
9121 break;
9122 case VMX_VPID_EXTENT_SINGLE_CONTEXT:
9123 case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
9124 if (!operand.vpid) {
9125 nested_vmx_failValid(vcpu,
9126 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9127 return kvm_skip_emulated_instruction(vcpu);
9128 }
9129 __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
9130 break;
9131 case VMX_VPID_EXTENT_ALL_CONTEXT:
9132 __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
9133 break;
9134 default:
9135 WARN_ON_ONCE(1);
9136 return kvm_skip_emulated_instruction(vcpu);
9137 }
9138
9139 nested_vmx_succeed(vcpu);
9140
9141 return kvm_skip_emulated_instruction(vcpu);
9142}
9143
9144static int handle_invpcid(struct kvm_vcpu *vcpu)
9145{
9146 u32 vmx_instruction_info;
9147 unsigned long type;
9148 bool pcid_enabled;
9149 gva_t gva;
9150 struct x86_exception e;
9151 unsigned i;
9152 unsigned long roots_to_free = 0;
9153 struct {
9154 u64 pcid;
9155 u64 gla;
9156 } operand;
9157
9158 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
9159 kvm_queue_exception(vcpu, UD_VECTOR);
9160 return 1;
9161 }
9162
9163 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9164 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9165
9166 if (type > 3) {
9167 kvm_inject_gp(vcpu, 0);
9168 return 1;
9169 }
9170
9171 /* According to the Intel instruction reference, the memory operand
9172 * is read even if it isn't needed (e.g., for type==all)
9173 */
9174 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9175 vmx_instruction_info, false, &gva))
9176 return 1;
9177
9178 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9179 kvm_inject_page_fault(vcpu, &e);
9180 return 1;
9181 }
9182
9183 if (operand.pcid >> 12 != 0) {
9184 kvm_inject_gp(vcpu, 0);
9185 return 1;
9186 }
9187
9188 pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
9189
9190 switch (type) {
9191 case INVPCID_TYPE_INDIV_ADDR:
9192 if ((!pcid_enabled && (operand.pcid != 0)) ||
9193 is_noncanonical_address(operand.gla, vcpu)) {
9194 kvm_inject_gp(vcpu, 0);
9195 return 1;
9196 }
9197 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
9198 return kvm_skip_emulated_instruction(vcpu);
9199
9200 case INVPCID_TYPE_SINGLE_CTXT:
9201 if (!pcid_enabled && (operand.pcid != 0)) {
9202 kvm_inject_gp(vcpu, 0);
9203 return 1;
9204 }
9205
9206 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
9207 kvm_mmu_sync_roots(vcpu);
9208 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
9209 }
9210
9211 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
9212 if (kvm_get_pcid(vcpu, vcpu->arch.mmu.prev_roots[i].cr3)
9213 == operand.pcid)
9214 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
9215
9216 kvm_mmu_free_roots(vcpu, roots_to_free);
9217 /*
9218 * If neither the current cr3 nor any of the prev_roots use the
9219 * given PCID, then nothing needs to be done here because a
9220 * resync will happen anyway before switching to any other CR3.
9221 */
9222
9223 return kvm_skip_emulated_instruction(vcpu);
9224
9225 case INVPCID_TYPE_ALL_NON_GLOBAL:
9226 /*
9227 * Currently, KVM doesn't mark global entries in the shadow
9228 * page tables, so a non-global flush just degenerates to a
9229 * global flush. If needed, we could optimize this later by
9230 * keeping track of global entries in shadow page tables.
9231 */
9232
9233 /* fall-through */
9234 case INVPCID_TYPE_ALL_INCL_GLOBAL:
9235 kvm_mmu_unload(vcpu);
9236 return kvm_skip_emulated_instruction(vcpu);
9237
9238 default:
9239 BUG(); /* We have already checked above that type <= 3 */
9240 }
9241}
9242
9243static int handle_pml_full(struct kvm_vcpu *vcpu)
9244{
9245 unsigned long exit_qualification;
9246
9247 trace_kvm_pml_full(vcpu->vcpu_id);
9248
9249 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9250
9251 /*
9252 * PML buffer FULL happened while executing iret from NMI,
9253 * "blocked by NMI" bit has to be set before next VM entry.
9254 */
9255 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
9256 enable_vnmi &&
9257 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
9258 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
9259 GUEST_INTR_STATE_NMI);
9260
9261 /*
9262 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
9263 * here.., and there's no userspace involvement needed for PML.
9264 */
9265 return 1;
9266}
9267
9268static int handle_preemption_timer(struct kvm_vcpu *vcpu)
9269{
9270 if (!to_vmx(vcpu)->req_immediate_exit)
9271 kvm_lapic_expired_hv_timer(vcpu);
9272 return 1;
9273}
9274
9275static bool valid_ept_address(struct kvm_vcpu *vcpu, u64 address)
9276{
9277 struct vcpu_vmx *vmx = to_vmx(vcpu);
9278 int maxphyaddr = cpuid_maxphyaddr(vcpu);
9279
9280 /* Check for memory type validity */
9281 switch (address & VMX_EPTP_MT_MASK) {
9282 case VMX_EPTP_MT_UC:
9283 if (!(vmx->nested.msrs.ept_caps & VMX_EPTP_UC_BIT))
9284 return false;
9285 break;
9286 case VMX_EPTP_MT_WB:
9287 if (!(vmx->nested.msrs.ept_caps & VMX_EPTP_WB_BIT))
9288 return false;
9289 break;
9290 default:
9291 return false;
9292 }
9293
9294 /* only 4 levels page-walk length are valid */
9295 if ((address & VMX_EPTP_PWL_MASK) != VMX_EPTP_PWL_4)
9296 return false;
9297
9298 /* Reserved bits should not be set */
9299 if (address >> maxphyaddr || ((address >> 7) & 0x1f))
9300 return false;
9301
9302 /* AD, if set, should be supported */
9303 if (address & VMX_EPTP_AD_ENABLE_BIT) {
9304 if (!(vmx->nested.msrs.ept_caps & VMX_EPT_AD_BIT))
9305 return false;
9306 }
9307
9308 return true;
9309}
9310
9311static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
9312 struct vmcs12 *vmcs12)
9313{
9314 u32 index = vcpu->arch.regs[VCPU_REGS_RCX];
9315 u64 address;
9316 bool accessed_dirty;
9317 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
9318
9319 if (!nested_cpu_has_eptp_switching(vmcs12) ||
9320 !nested_cpu_has_ept(vmcs12))
9321 return 1;
9322
9323 if (index >= VMFUNC_EPTP_ENTRIES)
9324 return 1;
9325
9326
9327 if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
9328 &address, index * 8, 8))
9329 return 1;
9330
9331 accessed_dirty = !!(address & VMX_EPTP_AD_ENABLE_BIT);
9332
9333 /*
9334 * If the (L2) guest does a vmfunc to the currently
9335 * active ept pointer, we don't have to do anything else
9336 */
9337 if (vmcs12->ept_pointer != address) {
9338 if (!valid_ept_address(vcpu, address))
9339 return 1;
9340
9341 kvm_mmu_unload(vcpu);
9342 mmu->ept_ad = accessed_dirty;
9343 mmu->base_role.ad_disabled = !accessed_dirty;
9344 vmcs12->ept_pointer = address;
9345 /*
9346 * TODO: Check what's the correct approach in case
9347 * mmu reload fails. Currently, we just let the next
9348 * reload potentially fail
9349 */
9350 kvm_mmu_reload(vcpu);
9351 }
9352
9353 return 0;
9354}
9355
9356static int handle_vmfunc(struct kvm_vcpu *vcpu)
9357{
9358 struct vcpu_vmx *vmx = to_vmx(vcpu);
9359 struct vmcs12 *vmcs12;
9360 u32 function = vcpu->arch.regs[VCPU_REGS_RAX];
9361
9362 /*
9363 * VMFUNC is only supported for nested guests, but we always enable the
9364 * secondary control for simplicity; for non-nested mode, fake that we
9365 * didn't by injecting #UD.
9366 */
9367 if (!is_guest_mode(vcpu)) {
9368 kvm_queue_exception(vcpu, UD_VECTOR);
9369 return 1;
9370 }
9371
9372 vmcs12 = get_vmcs12(vcpu);
9373 if ((vmcs12->vm_function_control & (1 << function)) == 0)
9374 goto fail;
9375
9376 switch (function) {
9377 case 0:
9378 if (nested_vmx_eptp_switching(vcpu, vmcs12))
9379 goto fail;
9380 break;
9381 default:
9382 goto fail;
9383 }
9384 return kvm_skip_emulated_instruction(vcpu);
9385
9386fail:
9387 nested_vmx_vmexit(vcpu, vmx->exit_reason,
9388 vmcs_read32(VM_EXIT_INTR_INFO),
9389 vmcs_readl(EXIT_QUALIFICATION));
9390 return 1;
9391}
9392
9393static int handle_encls(struct kvm_vcpu *vcpu)
9394{
9395 /*
9396 * SGX virtualization is not yet supported. There is no software
9397 * enable bit for SGX, so we have to trap ENCLS and inject a #UD
9398 * to prevent the guest from executing ENCLS.
9399 */
9400 kvm_queue_exception(vcpu, UD_VECTOR);
9401 return 1;
9402}
9403
9404/*
9405 * The exit handlers return 1 if the exit was handled fully and guest execution
9406 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
9407 * to be done to userspace and return 0.
9408 */
9409static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
9410 [EXIT_REASON_EXCEPTION_NMI] = handle_exception,
9411 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
9412 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
9413 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
9414 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
9415 [EXIT_REASON_CR_ACCESS] = handle_cr,
9416 [EXIT_REASON_DR_ACCESS] = handle_dr,
9417 [EXIT_REASON_CPUID] = handle_cpuid,
9418 [EXIT_REASON_MSR_READ] = handle_rdmsr,
9419 [EXIT_REASON_MSR_WRITE] = handle_wrmsr,
9420 [EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window,
9421 [EXIT_REASON_HLT] = handle_halt,
9422 [EXIT_REASON_INVD] = handle_invd,
9423 [EXIT_REASON_INVLPG] = handle_invlpg,
9424 [EXIT_REASON_RDPMC] = handle_rdpmc,
9425 [EXIT_REASON_VMCALL] = handle_vmcall,
9426 [EXIT_REASON_VMCLEAR] = handle_vmclear,
9427 [EXIT_REASON_VMLAUNCH] = handle_vmlaunch,
9428 [EXIT_REASON_VMPTRLD] = handle_vmptrld,
9429 [EXIT_REASON_VMPTRST] = handle_vmptrst,
9430 [EXIT_REASON_VMREAD] = handle_vmread,
9431 [EXIT_REASON_VMRESUME] = handle_vmresume,
9432 [EXIT_REASON_VMWRITE] = handle_vmwrite,
9433 [EXIT_REASON_VMOFF] = handle_vmoff,
9434 [EXIT_REASON_VMON] = handle_vmon,
9435 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
9436 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
9437 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
9438 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
9439 [EXIT_REASON_WBINVD] = handle_wbinvd,
9440 [EXIT_REASON_XSETBV] = handle_xsetbv,
9441 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
9442 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
9443 [EXIT_REASON_GDTR_IDTR] = handle_desc,
9444 [EXIT_REASON_LDTR_TR] = handle_desc,
9445 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
9446 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
9447 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
9448 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
9449 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
9450 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
9451 [EXIT_REASON_INVEPT] = handle_invept,
9452 [EXIT_REASON_INVVPID] = handle_invvpid,
9453 [EXIT_REASON_RDRAND] = handle_invalid_op,
9454 [EXIT_REASON_RDSEED] = handle_invalid_op,
9455 [EXIT_REASON_XSAVES] = handle_xsaves,
9456 [EXIT_REASON_XRSTORS] = handle_xrstors,
9457 [EXIT_REASON_PML_FULL] = handle_pml_full,
9458 [EXIT_REASON_INVPCID] = handle_invpcid,
9459 [EXIT_REASON_VMFUNC] = handle_vmfunc,
9460 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
9461 [EXIT_REASON_ENCLS] = handle_encls,
9462};
9463
9464static const int kvm_vmx_max_exit_handlers =
9465 ARRAY_SIZE(kvm_vmx_exit_handlers);
9466
9467static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
9468 struct vmcs12 *vmcs12)
9469{
9470 unsigned long exit_qualification;
9471 gpa_t bitmap, last_bitmap;
9472 unsigned int port;
9473 int size;
9474 u8 b;
9475
9476 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
9477 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
9478
9479 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9480
9481 port = exit_qualification >> 16;
9482 size = (exit_qualification & 7) + 1;
9483
9484 last_bitmap = (gpa_t)-1;
9485 b = -1;
9486
9487 while (size > 0) {
9488 if (port < 0x8000)
9489 bitmap = vmcs12->io_bitmap_a;
9490 else if (port < 0x10000)
9491 bitmap = vmcs12->io_bitmap_b;
9492 else
9493 return true;
9494 bitmap += (port & 0x7fff) / 8;
9495
9496 if (last_bitmap != bitmap)
9497 if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
9498 return true;
9499 if (b & (1 << (port & 7)))
9500 return true;
9501
9502 port++;
9503 size--;
9504 last_bitmap = bitmap;
9505 }
9506
9507 return false;
9508}
9509
9510/*
9511 * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
9512 * rather than handle it ourselves in L0. I.e., check whether L1 expressed
9513 * disinterest in the current event (read or write a specific MSR) by using an
9514 * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
9515 */
9516static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
9517 struct vmcs12 *vmcs12, u32 exit_reason)
9518{
9519 u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
9520 gpa_t bitmap;
9521
9522 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
9523 return true;
9524
9525 /*
9526 * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
9527 * for the four combinations of read/write and low/high MSR numbers.
9528 * First we need to figure out which of the four to use:
9529 */
9530 bitmap = vmcs12->msr_bitmap;
9531 if (exit_reason == EXIT_REASON_MSR_WRITE)
9532 bitmap += 2048;
9533 if (msr_index >= 0xc0000000) {
9534 msr_index -= 0xc0000000;
9535 bitmap += 1024;
9536 }
9537
9538 /* Then read the msr_index'th bit from this bitmap: */
9539 if (msr_index < 1024*8) {
9540 unsigned char b;
9541 if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
9542 return true;
9543 return 1 & (b >> (msr_index & 7));
9544 } else
9545 return true; /* let L1 handle the wrong parameter */
9546}
9547
9548/*
9549 * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
9550 * rather than handle it ourselves in L0. I.e., check if L1 wanted to
9551 * intercept (via guest_host_mask etc.) the current event.
9552 */
9553static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
9554 struct vmcs12 *vmcs12)
9555{
9556 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9557 int cr = exit_qualification & 15;
9558 int reg;
9559 unsigned long val;
9560
9561 switch ((exit_qualification >> 4) & 3) {
9562 case 0: /* mov to cr */
9563 reg = (exit_qualification >> 8) & 15;
9564 val = kvm_register_readl(vcpu, reg);
9565 switch (cr) {
9566 case 0:
9567 if (vmcs12->cr0_guest_host_mask &
9568 (val ^ vmcs12->cr0_read_shadow))
9569 return true;
9570 break;
9571 case 3:
9572 if ((vmcs12->cr3_target_count >= 1 &&
9573 vmcs12->cr3_target_value0 == val) ||
9574 (vmcs12->cr3_target_count >= 2 &&
9575 vmcs12->cr3_target_value1 == val) ||
9576 (vmcs12->cr3_target_count >= 3 &&
9577 vmcs12->cr3_target_value2 == val) ||
9578 (vmcs12->cr3_target_count >= 4 &&
9579 vmcs12->cr3_target_value3 == val))
9580 return false;
9581 if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
9582 return true;
9583 break;
9584 case 4:
9585 if (vmcs12->cr4_guest_host_mask &
9586 (vmcs12->cr4_read_shadow ^ val))
9587 return true;
9588 break;
9589 case 8:
9590 if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
9591 return true;
9592 break;
9593 }
9594 break;
9595 case 2: /* clts */
9596 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
9597 (vmcs12->cr0_read_shadow & X86_CR0_TS))
9598 return true;
9599 break;
9600 case 1: /* mov from cr */
9601 switch (cr) {
9602 case 3:
9603 if (vmcs12->cpu_based_vm_exec_control &
9604 CPU_BASED_CR3_STORE_EXITING)
9605 return true;
9606 break;
9607 case 8:
9608 if (vmcs12->cpu_based_vm_exec_control &
9609 CPU_BASED_CR8_STORE_EXITING)
9610 return true;
9611 break;
9612 }
9613 break;
9614 case 3: /* lmsw */
9615 /*
9616 * lmsw can change bits 1..3 of cr0, and only set bit 0 of
9617 * cr0. Other attempted changes are ignored, with no exit.
9618 */
9619 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
9620 if (vmcs12->cr0_guest_host_mask & 0xe &
9621 (val ^ vmcs12->cr0_read_shadow))
9622 return true;
9623 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
9624 !(vmcs12->cr0_read_shadow & 0x1) &&
9625 (val & 0x1))
9626 return true;
9627 break;
9628 }
9629 return false;
9630}
9631
9632static bool nested_vmx_exit_handled_vmcs_access(struct kvm_vcpu *vcpu,
9633 struct vmcs12 *vmcs12, gpa_t bitmap)
9634{
9635 u32 vmx_instruction_info;
9636 unsigned long field;
9637 u8 b;
9638
9639 if (!nested_cpu_has_shadow_vmcs(vmcs12))
9640 return true;
9641
9642 /* Decode instruction info and find the field to access */
9643 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9644 field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
9645
9646 /* Out-of-range fields always cause a VM exit from L2 to L1 */
9647 if (field >> 15)
9648 return true;
9649
9650 if (kvm_vcpu_read_guest(vcpu, bitmap + field/8, &b, 1))
9651 return true;
9652
9653 return 1 & (b >> (field & 7));
9654}
9655
9656/*
9657 * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
9658 * should handle it ourselves in L0 (and then continue L2). Only call this
9659 * when in is_guest_mode (L2).
9660 */
9661static bool nested_vmx_exit_reflected(struct kvm_vcpu *vcpu, u32 exit_reason)
9662{
9663 u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9664 struct vcpu_vmx *vmx = to_vmx(vcpu);
9665 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9666
9667 if (vmx->nested.nested_run_pending)
9668 return false;
9669
9670 if (unlikely(vmx->fail)) {
9671 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
9672 vmcs_read32(VM_INSTRUCTION_ERROR));
9673 return true;
9674 }
9675
9676 /*
9677 * The host physical addresses of some pages of guest memory
9678 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
9679 * Page). The CPU may write to these pages via their host
9680 * physical address while L2 is running, bypassing any
9681 * address-translation-based dirty tracking (e.g. EPT write
9682 * protection).
9683 *
9684 * Mark them dirty on every exit from L2 to prevent them from
9685 * getting out of sync with dirty tracking.
9686 */
9687 nested_mark_vmcs12_pages_dirty(vcpu);
9688
9689 trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
9690 vmcs_readl(EXIT_QUALIFICATION),
9691 vmx->idt_vectoring_info,
9692 intr_info,
9693 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
9694 KVM_ISA_VMX);
9695
9696 switch (exit_reason) {
9697 case EXIT_REASON_EXCEPTION_NMI:
9698 if (is_nmi(intr_info))
9699 return false;
9700 else if (is_page_fault(intr_info))
9701 return !vmx->vcpu.arch.apf.host_apf_reason && enable_ept;
9702 else if (is_no_device(intr_info) &&
9703 !(vmcs12->guest_cr0 & X86_CR0_TS))
9704 return false;
9705 else if (is_debug(intr_info) &&
9706 vcpu->guest_debug &
9707 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
9708 return false;
9709 else if (is_breakpoint(intr_info) &&
9710 vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
9711 return false;
9712 return vmcs12->exception_bitmap &
9713 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
9714 case EXIT_REASON_EXTERNAL_INTERRUPT:
9715 return false;
9716 case EXIT_REASON_TRIPLE_FAULT:
9717 return true;
9718 case EXIT_REASON_PENDING_INTERRUPT:
9719 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
9720 case EXIT_REASON_NMI_WINDOW:
9721 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
9722 case EXIT_REASON_TASK_SWITCH:
9723 return true;
9724 case EXIT_REASON_CPUID:
9725 return true;
9726 case EXIT_REASON_HLT:
9727 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
9728 case EXIT_REASON_INVD:
9729 return true;
9730 case EXIT_REASON_INVLPG:
9731 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
9732 case EXIT_REASON_RDPMC:
9733 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
9734 case EXIT_REASON_RDRAND:
9735 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND_EXITING);
9736 case EXIT_REASON_RDSEED:
9737 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED_EXITING);
9738 case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
9739 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
9740 case EXIT_REASON_VMREAD:
9741 return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
9742 vmcs12->vmread_bitmap);
9743 case EXIT_REASON_VMWRITE:
9744 return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
9745 vmcs12->vmwrite_bitmap);
9746 case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
9747 case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
9748 case EXIT_REASON_VMPTRST: case EXIT_REASON_VMRESUME:
9749 case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
9750 case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
9751 /*
9752 * VMX instructions trap unconditionally. This allows L1 to
9753 * emulate them for its L2 guest, i.e., allows 3-level nesting!
9754 */
9755 return true;
9756 case EXIT_REASON_CR_ACCESS:
9757 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
9758 case EXIT_REASON_DR_ACCESS:
9759 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
9760 case EXIT_REASON_IO_INSTRUCTION:
9761 return nested_vmx_exit_handled_io(vcpu, vmcs12);
9762 case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
9763 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
9764 case EXIT_REASON_MSR_READ:
9765 case EXIT_REASON_MSR_WRITE:
9766 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
9767 case EXIT_REASON_INVALID_STATE:
9768 return true;
9769 case EXIT_REASON_MWAIT_INSTRUCTION:
9770 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
9771 case EXIT_REASON_MONITOR_TRAP_FLAG:
9772 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG);
9773 case EXIT_REASON_MONITOR_INSTRUCTION:
9774 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
9775 case EXIT_REASON_PAUSE_INSTRUCTION:
9776 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
9777 nested_cpu_has2(vmcs12,
9778 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
9779 case EXIT_REASON_MCE_DURING_VMENTRY:
9780 return false;
9781 case EXIT_REASON_TPR_BELOW_THRESHOLD:
9782 return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
9783 case EXIT_REASON_APIC_ACCESS:
9784 case EXIT_REASON_APIC_WRITE:
9785 case EXIT_REASON_EOI_INDUCED:
9786 /*
9787 * The controls for "virtualize APIC accesses," "APIC-
9788 * register virtualization," and "virtual-interrupt
9789 * delivery" only come from vmcs12.
9790 */
9791 return true;
9792 case EXIT_REASON_EPT_VIOLATION:
9793 /*
9794 * L0 always deals with the EPT violation. If nested EPT is
9795 * used, and the nested mmu code discovers that the address is
9796 * missing in the guest EPT table (EPT12), the EPT violation
9797 * will be injected with nested_ept_inject_page_fault()
9798 */
9799 return false;
9800 case EXIT_REASON_EPT_MISCONFIG:
9801 /*
9802 * L2 never uses directly L1's EPT, but rather L0's own EPT
9803 * table (shadow on EPT) or a merged EPT table that L0 built
9804 * (EPT on EPT). So any problems with the structure of the
9805 * table is L0's fault.
9806 */
9807 return false;
9808 case EXIT_REASON_INVPCID:
9809 return
9810 nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
9811 nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
9812 case EXIT_REASON_WBINVD:
9813 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
9814 case EXIT_REASON_XSETBV:
9815 return true;
9816 case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
9817 /*
9818 * This should never happen, since it is not possible to
9819 * set XSS to a non-zero value---neither in L1 nor in L2.
9820 * If if it were, XSS would have to be checked against
9821 * the XSS exit bitmap in vmcs12.
9822 */
9823 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
9824 case EXIT_REASON_PREEMPTION_TIMER:
9825 return false;
9826 case EXIT_REASON_PML_FULL:
9827 /* We emulate PML support to L1. */
9828 return false;
9829 case EXIT_REASON_VMFUNC:
9830 /* VM functions are emulated through L2->L0 vmexits. */
9831 return false;
9832 case EXIT_REASON_ENCLS:
9833 /* SGX is never exposed to L1 */
9834 return false;
9835 default:
9836 return true;
9837 }
9838}
9839
9840static int nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason)
9841{
9842 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9843
9844 /*
9845 * At this point, the exit interruption info in exit_intr_info
9846 * is only valid for EXCEPTION_NMI exits. For EXTERNAL_INTERRUPT
9847 * we need to query the in-kernel LAPIC.
9848 */
9849 WARN_ON(exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT);
9850 if ((exit_intr_info &
9851 (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
9852 (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) {
9853 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9854 vmcs12->vm_exit_intr_error_code =
9855 vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
9856 }
9857
9858 nested_vmx_vmexit(vcpu, exit_reason, exit_intr_info,
9859 vmcs_readl(EXIT_QUALIFICATION));
9860 return 1;
9861}
9862
9863static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
9864{
9865 *info1 = vmcs_readl(EXIT_QUALIFICATION);
9866 *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
9867}
9868
9869static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
9870{
9871 if (vmx->pml_pg) {
9872 __free_page(vmx->pml_pg);
9873 vmx->pml_pg = NULL;
9874 }
9875}
9876
9877static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
9878{
9879 struct vcpu_vmx *vmx = to_vmx(vcpu);
9880 u64 *pml_buf;
9881 u16 pml_idx;
9882
9883 pml_idx = vmcs_read16(GUEST_PML_INDEX);
9884
9885 /* Do nothing if PML buffer is empty */
9886 if (pml_idx == (PML_ENTITY_NUM - 1))
9887 return;
9888
9889 /* PML index always points to next available PML buffer entity */
9890 if (pml_idx >= PML_ENTITY_NUM)
9891 pml_idx = 0;
9892 else
9893 pml_idx++;
9894
9895 pml_buf = page_address(vmx->pml_pg);
9896 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
9897 u64 gpa;
9898
9899 gpa = pml_buf[pml_idx];
9900 WARN_ON(gpa & (PAGE_SIZE - 1));
9901 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
9902 }
9903
9904 /* reset PML index */
9905 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
9906}
9907
9908/*
9909 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
9910 * Called before reporting dirty_bitmap to userspace.
9911 */
9912static void kvm_flush_pml_buffers(struct kvm *kvm)
9913{
9914 int i;
9915 struct kvm_vcpu *vcpu;
9916 /*
9917 * We only need to kick vcpu out of guest mode here, as PML buffer
9918 * is flushed at beginning of all VMEXITs, and it's obvious that only
9919 * vcpus running in guest are possible to have unflushed GPAs in PML
9920 * buffer.
9921 */
9922 kvm_for_each_vcpu(i, vcpu, kvm)
9923 kvm_vcpu_kick(vcpu);
9924}
9925
9926static void vmx_dump_sel(char *name, uint32_t sel)
9927{
9928 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
9929 name, vmcs_read16(sel),
9930 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
9931 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
9932 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
9933}
9934
9935static void vmx_dump_dtsel(char *name, uint32_t limit)
9936{
9937 pr_err("%s limit=0x%08x, base=0x%016lx\n",
9938 name, vmcs_read32(limit),
9939 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
9940}
9941
9942static void dump_vmcs(void)
9943{
9944 u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
9945 u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
9946 u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
9947 u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
9948 u32 secondary_exec_control = 0;
9949 unsigned long cr4 = vmcs_readl(GUEST_CR4);
9950 u64 efer = vmcs_read64(GUEST_IA32_EFER);
9951 int i, n;
9952
9953 if (cpu_has_secondary_exec_ctrls())
9954 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
9955
9956 pr_err("*** Guest State ***\n");
9957 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
9958 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
9959 vmcs_readl(CR0_GUEST_HOST_MASK));
9960 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
9961 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
9962 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
9963 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
9964 (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
9965 {
9966 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
9967 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
9968 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
9969 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
9970 }
9971 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
9972 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
9973 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
9974 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
9975 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
9976 vmcs_readl(GUEST_SYSENTER_ESP),
9977 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
9978 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
9979 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
9980 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
9981 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
9982 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
9983 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
9984 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
9985 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
9986 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
9987 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
9988 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
9989 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
9990 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
9991 efer, vmcs_read64(GUEST_IA32_PAT));
9992 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
9993 vmcs_read64(GUEST_IA32_DEBUGCTL),
9994 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
9995 if (cpu_has_load_perf_global_ctrl &&
9996 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
9997 pr_err("PerfGlobCtl = 0x%016llx\n",
9998 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
9999 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
10000 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
10001 pr_err("Interruptibility = %08x ActivityState = %08x\n",
10002 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
10003 vmcs_read32(GUEST_ACTIVITY_STATE));
10004 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
10005 pr_err("InterruptStatus = %04x\n",
10006 vmcs_read16(GUEST_INTR_STATUS));
10007
10008 pr_err("*** Host State ***\n");
10009 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
10010 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
10011 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
10012 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
10013 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
10014 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
10015 vmcs_read16(HOST_TR_SELECTOR));
10016 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
10017 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
10018 vmcs_readl(HOST_TR_BASE));
10019 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
10020 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
10021 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
10022 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
10023 vmcs_readl(HOST_CR4));
10024 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
10025 vmcs_readl(HOST_IA32_SYSENTER_ESP),
10026 vmcs_read32(HOST_IA32_SYSENTER_CS),
10027 vmcs_readl(HOST_IA32_SYSENTER_EIP));
10028 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
10029 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
10030 vmcs_read64(HOST_IA32_EFER),
10031 vmcs_read64(HOST_IA32_PAT));
10032 if (cpu_has_load_perf_global_ctrl &&
10033 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
10034 pr_err("PerfGlobCtl = 0x%016llx\n",
10035 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
10036
10037 pr_err("*** Control State ***\n");
10038 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
10039 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
10040 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
10041 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
10042 vmcs_read32(EXCEPTION_BITMAP),
10043 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
10044 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
10045 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
10046 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
10047 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
10048 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
10049 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
10050 vmcs_read32(VM_EXIT_INTR_INFO),
10051 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
10052 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
10053 pr_err(" reason=%08x qualification=%016lx\n",
10054 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
10055 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
10056 vmcs_read32(IDT_VECTORING_INFO_FIELD),
10057 vmcs_read32(IDT_VECTORING_ERROR_CODE));
10058 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
10059 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
10060 pr_err("TSC Multiplier = 0x%016llx\n",
10061 vmcs_read64(TSC_MULTIPLIER));
10062 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
10063 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
10064 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
10065 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
10066 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
10067 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
10068 n = vmcs_read32(CR3_TARGET_COUNT);
10069 for (i = 0; i + 1 < n; i += 4)
10070 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
10071 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
10072 i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
10073 if (i < n)
10074 pr_err("CR3 target%u=%016lx\n",
10075 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
10076 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
10077 pr_err("PLE Gap=%08x Window=%08x\n",
10078 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
10079 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
10080 pr_err("Virtual processor ID = 0x%04x\n",
10081 vmcs_read16(VIRTUAL_PROCESSOR_ID));
10082}
10083
10084/*
10085 * The guest has exited. See if we can fix it or if we need userspace
10086 * assistance.
10087 */
10088static int vmx_handle_exit(struct kvm_vcpu *vcpu)
10089{
10090 struct vcpu_vmx *vmx = to_vmx(vcpu);
10091 u32 exit_reason = vmx->exit_reason;
10092 u32 vectoring_info = vmx->idt_vectoring_info;
10093
10094 trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
10095
10096 /*
10097 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
10098 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
10099 * querying dirty_bitmap, we only need to kick all vcpus out of guest
10100 * mode as if vcpus is in root mode, the PML buffer must has been
10101 * flushed already.
10102 */
10103 if (enable_pml)
10104 vmx_flush_pml_buffer(vcpu);
10105
10106 /* If guest state is invalid, start emulating */
10107 if (vmx->emulation_required)
10108 return handle_invalid_guest_state(vcpu);
10109
10110 if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
10111 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
10112
10113 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
10114 dump_vmcs();
10115 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
10116 vcpu->run->fail_entry.hardware_entry_failure_reason
10117 = exit_reason;
10118 return 0;
10119 }
10120
10121 if (unlikely(vmx->fail)) {
10122 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
10123 vcpu->run->fail_entry.hardware_entry_failure_reason
10124 = vmcs_read32(VM_INSTRUCTION_ERROR);
10125 return 0;
10126 }
10127
10128 /*
10129 * Note:
10130 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
10131 * delivery event since it indicates guest is accessing MMIO.
10132 * The vm-exit can be triggered again after return to guest that
10133 * will cause infinite loop.
10134 */
10135 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
10136 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
10137 exit_reason != EXIT_REASON_EPT_VIOLATION &&
10138 exit_reason != EXIT_REASON_PML_FULL &&
10139 exit_reason != EXIT_REASON_TASK_SWITCH)) {
10140 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
10141 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
10142 vcpu->run->internal.ndata = 3;
10143 vcpu->run->internal.data[0] = vectoring_info;
10144 vcpu->run->internal.data[1] = exit_reason;
10145 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
10146 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
10147 vcpu->run->internal.ndata++;
10148 vcpu->run->internal.data[3] =
10149 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
10150 }
10151 return 0;
10152 }
10153
10154 if (unlikely(!enable_vnmi &&
10155 vmx->loaded_vmcs->soft_vnmi_blocked)) {
10156 if (vmx_interrupt_allowed(vcpu)) {
10157 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
10158 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
10159 vcpu->arch.nmi_pending) {
10160 /*
10161 * This CPU don't support us in finding the end of an
10162 * NMI-blocked window if the guest runs with IRQs
10163 * disabled. So we pull the trigger after 1 s of
10164 * futile waiting, but inform the user about this.
10165 */
10166 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
10167 "state on VCPU %d after 1 s timeout\n",
10168 __func__, vcpu->vcpu_id);
10169 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
10170 }
10171 }
10172
10173 if (exit_reason < kvm_vmx_max_exit_handlers
10174 && kvm_vmx_exit_handlers[exit_reason])
10175 return kvm_vmx_exit_handlers[exit_reason](vcpu);
10176 else {
10177 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
10178 exit_reason);
10179 kvm_queue_exception(vcpu, UD_VECTOR);
10180 return 1;
10181 }
10182}
10183
10184/*
10185 * Software based L1D cache flush which is used when microcode providing
10186 * the cache control MSR is not loaded.
10187 *
10188 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
10189 * flush it is required to read in 64 KiB because the replacement algorithm
10190 * is not exactly LRU. This could be sized at runtime via topology
10191 * information but as all relevant affected CPUs have 32KiB L1D cache size
10192 * there is no point in doing so.
10193 */
10194static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
10195{
10196 int size = PAGE_SIZE << L1D_CACHE_ORDER;
10197
10198 /*
10199 * This code is only executed when the the flush mode is 'cond' or
10200 * 'always'
10201 */
10202 if (static_branch_likely(&vmx_l1d_flush_cond)) {
10203 bool flush_l1d;
10204
10205 /*
10206 * Clear the per-vcpu flush bit, it gets set again
10207 * either from vcpu_run() or from one of the unsafe
10208 * VMEXIT handlers.
10209 */
10210 flush_l1d = vcpu->arch.l1tf_flush_l1d;
10211 vcpu->arch.l1tf_flush_l1d = false;
10212
10213 /*
10214 * Clear the per-cpu flush bit, it gets set again from
10215 * the interrupt handlers.
10216 */
10217 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
10218 kvm_clear_cpu_l1tf_flush_l1d();
10219
10220 if (!flush_l1d)
10221 return;
10222 }
10223
10224 vcpu->stat.l1d_flush++;
10225
10226 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
10227 wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
10228 return;
10229 }
10230
10231 asm volatile(
10232 /* First ensure the pages are in the TLB */
10233 "xorl %%eax, %%eax\n"
10234 ".Lpopulate_tlb:\n\t"
10235 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
10236 "addl $4096, %%eax\n\t"
10237 "cmpl %%eax, %[size]\n\t"
10238 "jne .Lpopulate_tlb\n\t"
10239 "xorl %%eax, %%eax\n\t"
10240 "cpuid\n\t"
10241 /* Now fill the cache */
10242 "xorl %%eax, %%eax\n"
10243 ".Lfill_cache:\n"
10244 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
10245 "addl $64, %%eax\n\t"
10246 "cmpl %%eax, %[size]\n\t"
10247 "jne .Lfill_cache\n\t"
10248 "lfence\n"
10249 :: [flush_pages] "r" (vmx_l1d_flush_pages),
10250 [size] "r" (size)
10251 : "eax", "ebx", "ecx", "edx");
10252}
10253
10254static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
10255{
10256 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10257
10258 if (is_guest_mode(vcpu) &&
10259 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10260 return;
10261
10262 if (irr == -1 || tpr < irr) {
10263 vmcs_write32(TPR_THRESHOLD, 0);
10264 return;
10265 }
10266
10267 vmcs_write32(TPR_THRESHOLD, irr);
10268}
10269
10270static void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
10271{
10272 u32 sec_exec_control;
10273
10274 if (!lapic_in_kernel(vcpu))
10275 return;
10276
10277 if (!flexpriority_enabled &&
10278 !cpu_has_vmx_virtualize_x2apic_mode())
10279 return;
10280
10281 /* Postpone execution until vmcs01 is the current VMCS. */
10282 if (is_guest_mode(vcpu)) {
10283 to_vmx(vcpu)->nested.change_vmcs01_virtual_apic_mode = true;
10284 return;
10285 }
10286
10287 sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
10288 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
10289 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
10290
10291 switch (kvm_get_apic_mode(vcpu)) {
10292 case LAPIC_MODE_INVALID:
10293 WARN_ONCE(true, "Invalid local APIC state");
10294 case LAPIC_MODE_DISABLED:
10295 break;
10296 case LAPIC_MODE_XAPIC:
10297 if (flexpriority_enabled) {
10298 sec_exec_control |=
10299 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
10300 vmx_flush_tlb(vcpu, true);
10301 }
10302 break;
10303 case LAPIC_MODE_X2APIC:
10304 if (cpu_has_vmx_virtualize_x2apic_mode())
10305 sec_exec_control |=
10306 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
10307 break;
10308 }
10309 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
10310
10311 vmx_update_msr_bitmap(vcpu);
10312}
10313
10314static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
10315{
10316 if (!is_guest_mode(vcpu)) {
10317 vmcs_write64(APIC_ACCESS_ADDR, hpa);
10318 vmx_flush_tlb(vcpu, true);
10319 }
10320}
10321
10322static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
10323{
10324 u16 status;
10325 u8 old;
10326
10327 if (max_isr == -1)
10328 max_isr = 0;
10329
10330 status = vmcs_read16(GUEST_INTR_STATUS);
10331 old = status >> 8;
10332 if (max_isr != old) {
10333 status &= 0xff;
10334 status |= max_isr << 8;
10335 vmcs_write16(GUEST_INTR_STATUS, status);
10336 }
10337}
10338
10339static void vmx_set_rvi(int vector)
10340{
10341 u16 status;
10342 u8 old;
10343
10344 if (vector == -1)
10345 vector = 0;
10346
10347 status = vmcs_read16(GUEST_INTR_STATUS);
10348 old = (u8)status & 0xff;
10349 if ((u8)vector != old) {
10350 status &= ~0xff;
10351 status |= (u8)vector;
10352 vmcs_write16(GUEST_INTR_STATUS, status);
10353 }
10354}
10355
10356static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
10357{
10358 /*
10359 * When running L2, updating RVI is only relevant when
10360 * vmcs12 virtual-interrupt-delivery enabled.
10361 * However, it can be enabled only when L1 also
10362 * intercepts external-interrupts and in that case
10363 * we should not update vmcs02 RVI but instead intercept
10364 * interrupt. Therefore, do nothing when running L2.
10365 */
10366 if (!is_guest_mode(vcpu))
10367 vmx_set_rvi(max_irr);
10368}
10369
10370static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
10371{
10372 struct vcpu_vmx *vmx = to_vmx(vcpu);
10373 int max_irr;
10374 bool max_irr_updated;
10375
10376 WARN_ON(!vcpu->arch.apicv_active);
10377 if (pi_test_on(&vmx->pi_desc)) {
10378 pi_clear_on(&vmx->pi_desc);
10379 /*
10380 * IOMMU can write to PIR.ON, so the barrier matters even on UP.
10381 * But on x86 this is just a compiler barrier anyway.
10382 */
10383 smp_mb__after_atomic();
10384 max_irr_updated =
10385 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
10386
10387 /*
10388 * If we are running L2 and L1 has a new pending interrupt
10389 * which can be injected, we should re-evaluate
10390 * what should be done with this new L1 interrupt.
10391 * If L1 intercepts external-interrupts, we should
10392 * exit from L2 to L1. Otherwise, interrupt should be
10393 * delivered directly to L2.
10394 */
10395 if (is_guest_mode(vcpu) && max_irr_updated) {
10396 if (nested_exit_on_intr(vcpu))
10397 kvm_vcpu_exiting_guest_mode(vcpu);
10398 else
10399 kvm_make_request(KVM_REQ_EVENT, vcpu);
10400 }
10401 } else {
10402 max_irr = kvm_lapic_find_highest_irr(vcpu);
10403 }
10404 vmx_hwapic_irr_update(vcpu, max_irr);
10405 return max_irr;
10406}
10407
10408static u8 vmx_has_apicv_interrupt(struct kvm_vcpu *vcpu)
10409{
10410 u8 rvi = vmx_get_rvi();
10411 u8 vppr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_PROCPRI);
10412
10413 return ((rvi & 0xf0) > (vppr & 0xf0));
10414}
10415
10416static bool vmx_dy_apicv_has_pending_interrupt(struct kvm_vcpu *vcpu)
10417{
10418 return pi_test_on(vcpu_to_pi_desc(vcpu));
10419}
10420
10421static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
10422{
10423 if (!kvm_vcpu_apicv_active(vcpu))
10424 return;
10425
10426 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
10427 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
10428 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
10429 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
10430}
10431
10432static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
10433{
10434 struct vcpu_vmx *vmx = to_vmx(vcpu);
10435
10436 pi_clear_on(&vmx->pi_desc);
10437 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
10438}
10439
10440static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
10441{
10442 if (vmx->exit_reason != EXIT_REASON_EXCEPTION_NMI)
10443 return;
10444
10445 vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10446
10447 /* if exit due to PF check for async PF */
10448 if (is_page_fault(vmx->exit_intr_info))
10449 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
10450
10451 /* Handle machine checks before interrupts are enabled */
10452 if (is_machine_check(vmx->exit_intr_info))
10453 kvm_machine_check();
10454
10455 /* We need to handle NMIs before interrupts are enabled */
10456 if (is_nmi(vmx->exit_intr_info)) {
10457 kvm_before_interrupt(&vmx->vcpu);
10458 asm("int $2");
10459 kvm_after_interrupt(&vmx->vcpu);
10460 }
10461}
10462
10463static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
10464{
10465 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10466
10467 if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
10468 == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
10469 unsigned int vector;
10470 unsigned long entry;
10471 gate_desc *desc;
10472 struct vcpu_vmx *vmx = to_vmx(vcpu);
10473#ifdef CONFIG_X86_64
10474 unsigned long tmp;
10475#endif
10476
10477 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
10478 desc = (gate_desc *)vmx->host_idt_base + vector;
10479 entry = gate_offset(desc);
10480 asm volatile(
10481#ifdef CONFIG_X86_64
10482 "mov %%" _ASM_SP ", %[sp]\n\t"
10483 "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
10484 "push $%c[ss]\n\t"
10485 "push %[sp]\n\t"
10486#endif
10487 "pushf\n\t"
10488 __ASM_SIZE(push) " $%c[cs]\n\t"
10489 CALL_NOSPEC
10490 :
10491#ifdef CONFIG_X86_64
10492 [sp]"=&r"(tmp),
10493#endif
10494 ASM_CALL_CONSTRAINT
10495 :
10496 THUNK_TARGET(entry),
10497 [ss]"i"(__KERNEL_DS),
10498 [cs]"i"(__KERNEL_CS)
10499 );
10500 }
10501}
10502STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
10503
10504static bool vmx_has_emulated_msr(int index)
10505{
10506 switch (index) {
10507 case MSR_IA32_SMBASE:
10508 /*
10509 * We cannot do SMM unless we can run the guest in big
10510 * real mode.
10511 */
10512 return enable_unrestricted_guest || emulate_invalid_guest_state;
10513 case MSR_AMD64_VIRT_SPEC_CTRL:
10514 /* This is AMD only. */
10515 return false;
10516 default:
10517 return true;
10518 }
10519}
10520
10521static bool vmx_mpx_supported(void)
10522{
10523 return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
10524 (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
10525}
10526
10527static bool vmx_xsaves_supported(void)
10528{
10529 return vmcs_config.cpu_based_2nd_exec_ctrl &
10530 SECONDARY_EXEC_XSAVES;
10531}
10532
10533static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
10534{
10535 u32 exit_intr_info;
10536 bool unblock_nmi;
10537 u8 vector;
10538 bool idtv_info_valid;
10539
10540 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
10541
10542 if (enable_vnmi) {
10543 if (vmx->loaded_vmcs->nmi_known_unmasked)
10544 return;
10545 /*
10546 * Can't use vmx->exit_intr_info since we're not sure what
10547 * the exit reason is.
10548 */
10549 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10550 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
10551 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
10552 /*
10553 * SDM 3: 27.7.1.2 (September 2008)
10554 * Re-set bit "block by NMI" before VM entry if vmexit caused by
10555 * a guest IRET fault.
10556 * SDM 3: 23.2.2 (September 2008)
10557 * Bit 12 is undefined in any of the following cases:
10558 * If the VM exit sets the valid bit in the IDT-vectoring
10559 * information field.
10560 * If the VM exit is due to a double fault.
10561 */
10562 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
10563 vector != DF_VECTOR && !idtv_info_valid)
10564 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
10565 GUEST_INTR_STATE_NMI);
10566 else
10567 vmx->loaded_vmcs->nmi_known_unmasked =
10568 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
10569 & GUEST_INTR_STATE_NMI);
10570 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
10571 vmx->loaded_vmcs->vnmi_blocked_time +=
10572 ktime_to_ns(ktime_sub(ktime_get(),
10573 vmx->loaded_vmcs->entry_time));
10574}
10575
10576static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
10577 u32 idt_vectoring_info,
10578 int instr_len_field,
10579 int error_code_field)
10580{
10581 u8 vector;
10582 int type;
10583 bool idtv_info_valid;
10584
10585 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
10586
10587 vcpu->arch.nmi_injected = false;
10588 kvm_clear_exception_queue(vcpu);
10589 kvm_clear_interrupt_queue(vcpu);
10590
10591 if (!idtv_info_valid)
10592 return;
10593
10594 kvm_make_request(KVM_REQ_EVENT, vcpu);
10595
10596 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
10597 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
10598
10599 switch (type) {
10600 case INTR_TYPE_NMI_INTR:
10601 vcpu->arch.nmi_injected = true;
10602 /*
10603 * SDM 3: 27.7.1.2 (September 2008)
10604 * Clear bit "block by NMI" before VM entry if a NMI
10605 * delivery faulted.
10606 */
10607 vmx_set_nmi_mask(vcpu, false);
10608 break;
10609 case INTR_TYPE_SOFT_EXCEPTION:
10610 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
10611 /* fall through */
10612 case INTR_TYPE_HARD_EXCEPTION:
10613 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
10614 u32 err = vmcs_read32(error_code_field);
10615 kvm_requeue_exception_e(vcpu, vector, err);
10616 } else
10617 kvm_requeue_exception(vcpu, vector);
10618 break;
10619 case INTR_TYPE_SOFT_INTR:
10620 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
10621 /* fall through */
10622 case INTR_TYPE_EXT_INTR:
10623 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
10624 break;
10625 default:
10626 break;
10627 }
10628}
10629
10630static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
10631{
10632 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
10633 VM_EXIT_INSTRUCTION_LEN,
10634 IDT_VECTORING_ERROR_CODE);
10635}
10636
10637static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
10638{
10639 __vmx_complete_interrupts(vcpu,
10640 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
10641 VM_ENTRY_INSTRUCTION_LEN,
10642 VM_ENTRY_EXCEPTION_ERROR_CODE);
10643
10644 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
10645}
10646
10647static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
10648{
10649 int i, nr_msrs;
10650 struct perf_guest_switch_msr *msrs;
10651
10652 msrs = perf_guest_get_msrs(&nr_msrs);
10653
10654 if (!msrs)
10655 return;
10656
10657 for (i = 0; i < nr_msrs; i++)
10658 if (msrs[i].host == msrs[i].guest)
10659 clear_atomic_switch_msr(vmx, msrs[i].msr);
10660 else
10661 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
10662 msrs[i].host, false);
10663}
10664
10665static void vmx_arm_hv_timer(struct vcpu_vmx *vmx, u32 val)
10666{
10667 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, val);
10668 if (!vmx->loaded_vmcs->hv_timer_armed)
10669 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
10670 PIN_BASED_VMX_PREEMPTION_TIMER);
10671 vmx->loaded_vmcs->hv_timer_armed = true;
10672}
10673
10674static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
10675{
10676 struct vcpu_vmx *vmx = to_vmx(vcpu);
10677 u64 tscl;
10678 u32 delta_tsc;
10679
10680 if (vmx->req_immediate_exit) {
10681 vmx_arm_hv_timer(vmx, 0);
10682 return;
10683 }
10684
10685 if (vmx->hv_deadline_tsc != -1) {
10686 tscl = rdtsc();
10687 if (vmx->hv_deadline_tsc > tscl)
10688 /* set_hv_timer ensures the delta fits in 32-bits */
10689 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
10690 cpu_preemption_timer_multi);
10691 else
10692 delta_tsc = 0;
10693
10694 vmx_arm_hv_timer(vmx, delta_tsc);
10695 return;
10696 }
10697
10698 if (vmx->loaded_vmcs->hv_timer_armed)
10699 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
10700 PIN_BASED_VMX_PREEMPTION_TIMER);
10701 vmx->loaded_vmcs->hv_timer_armed = false;
10702}
10703
10704static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
10705{
10706 struct vcpu_vmx *vmx = to_vmx(vcpu);
10707 unsigned long cr3, cr4, evmcs_rsp;
10708
10709 /* Record the guest's net vcpu time for enforced NMI injections. */
10710 if (unlikely(!enable_vnmi &&
10711 vmx->loaded_vmcs->soft_vnmi_blocked))
10712 vmx->loaded_vmcs->entry_time = ktime_get();
10713
10714 /* Don't enter VMX if guest state is invalid, let the exit handler
10715 start emulation until we arrive back to a valid state */
10716 if (vmx->emulation_required)
10717 return;
10718
10719 if (vmx->ple_window_dirty) {
10720 vmx->ple_window_dirty = false;
10721 vmcs_write32(PLE_WINDOW, vmx->ple_window);
10722 }
10723
10724 if (vmx->nested.sync_shadow_vmcs) {
10725 copy_vmcs12_to_shadow(vmx);
10726 vmx->nested.sync_shadow_vmcs = false;
10727 }
10728
10729 if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
10730 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
10731 if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
10732 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
10733
10734 cr3 = __get_current_cr3_fast();
10735 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
10736 vmcs_writel(HOST_CR3, cr3);
10737 vmx->loaded_vmcs->host_state.cr3 = cr3;
10738 }
10739
10740 cr4 = cr4_read_shadow();
10741 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
10742 vmcs_writel(HOST_CR4, cr4);
10743 vmx->loaded_vmcs->host_state.cr4 = cr4;
10744 }
10745
10746 /* When single-stepping over STI and MOV SS, we must clear the
10747 * corresponding interruptibility bits in the guest state. Otherwise
10748 * vmentry fails as it then expects bit 14 (BS) in pending debug
10749 * exceptions being set, but that's not correct for the guest debugging
10750 * case. */
10751 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
10752 vmx_set_interrupt_shadow(vcpu, 0);
10753
10754 kvm_load_guest_xcr0(vcpu);
10755
10756 if (static_cpu_has(X86_FEATURE_PKU) &&
10757 kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
10758 vcpu->arch.pkru != vmx->host_pkru)
10759 __write_pkru(vcpu->arch.pkru);
10760
10761 atomic_switch_perf_msrs(vmx);
10762
10763 vmx_update_hv_timer(vcpu);
10764
10765 /*
10766 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
10767 * it's non-zero. Since vmentry is serialising on affected CPUs, there
10768 * is no need to worry about the conditional branch over the wrmsr
10769 * being speculatively taken.
10770 */
10771 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
10772
10773 vmx->__launched = vmx->loaded_vmcs->launched;
10774
10775 evmcs_rsp = static_branch_unlikely(&enable_evmcs) ?
10776 (unsigned long)&current_evmcs->host_rsp : 0;
10777
10778 /* L1D Flush includes CPU buffer clear to mitigate MDS */
10779 if (static_branch_unlikely(&vmx_l1d_should_flush))
10780 vmx_l1d_flush(vcpu);
10781 else if (static_branch_unlikely(&mds_user_clear))
10782 mds_clear_cpu_buffers();
10783
10784 asm(
10785 /* Store host registers */
10786 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
10787 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
10788 "push %%" _ASM_CX " \n\t"
10789 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
10790 "je 1f \n\t"
10791 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
10792 /* Avoid VMWRITE when Enlightened VMCS is in use */
10793 "test %%" _ASM_SI ", %%" _ASM_SI " \n\t"
10794 "jz 2f \n\t"
10795 "mov %%" _ASM_SP ", (%%" _ASM_SI ") \n\t"
10796 "jmp 1f \n\t"
10797 "2: \n\t"
10798 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
10799 "1: \n\t"
10800 /* Reload cr2 if changed */
10801 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
10802 "mov %%cr2, %%" _ASM_DX " \n\t"
10803 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
10804 "je 3f \n\t"
10805 "mov %%" _ASM_AX", %%cr2 \n\t"
10806 "3: \n\t"
10807 /* Check if vmlaunch of vmresume is needed */
10808 "cmpb $0, %c[launched](%0) \n\t"
10809 /* Load guest registers. Don't clobber flags. */
10810 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
10811 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
10812 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
10813 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
10814 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
10815 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
10816#ifdef CONFIG_X86_64
10817 "mov %c[r8](%0), %%r8 \n\t"
10818 "mov %c[r9](%0), %%r9 \n\t"
10819 "mov %c[r10](%0), %%r10 \n\t"
10820 "mov %c[r11](%0), %%r11 \n\t"
10821 "mov %c[r12](%0), %%r12 \n\t"
10822 "mov %c[r13](%0), %%r13 \n\t"
10823 "mov %c[r14](%0), %%r14 \n\t"
10824 "mov %c[r15](%0), %%r15 \n\t"
10825#endif
10826 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
10827
10828 /* Enter guest mode */
10829 "jne 1f \n\t"
10830 __ex(ASM_VMX_VMLAUNCH) "\n\t"
10831 "jmp 2f \n\t"
10832 "1: " __ex(ASM_VMX_VMRESUME) "\n\t"
10833 "2: "
10834 /* Save guest registers, load host registers, keep flags */
10835 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
10836 "pop %0 \n\t"
10837 "setbe %c[fail](%0)\n\t"
10838 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
10839 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
10840 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
10841 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
10842 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
10843 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
10844 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
10845#ifdef CONFIG_X86_64
10846 "mov %%r8, %c[r8](%0) \n\t"
10847 "mov %%r9, %c[r9](%0) \n\t"
10848 "mov %%r10, %c[r10](%0) \n\t"
10849 "mov %%r11, %c[r11](%0) \n\t"
10850 "mov %%r12, %c[r12](%0) \n\t"
10851 "mov %%r13, %c[r13](%0) \n\t"
10852 "mov %%r14, %c[r14](%0) \n\t"
10853 "mov %%r15, %c[r15](%0) \n\t"
10854 "xor %%r8d, %%r8d \n\t"
10855 "xor %%r9d, %%r9d \n\t"
10856 "xor %%r10d, %%r10d \n\t"
10857 "xor %%r11d, %%r11d \n\t"
10858 "xor %%r12d, %%r12d \n\t"
10859 "xor %%r13d, %%r13d \n\t"
10860 "xor %%r14d, %%r14d \n\t"
10861 "xor %%r15d, %%r15d \n\t"
10862#endif
10863 "mov %%cr2, %%" _ASM_AX " \n\t"
10864 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
10865
10866 "xor %%eax, %%eax \n\t"
10867 "xor %%ebx, %%ebx \n\t"
10868 "xor %%esi, %%esi \n\t"
10869 "xor %%edi, %%edi \n\t"
10870 "pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t"
10871 ".pushsection .rodata \n\t"
10872 ".global vmx_return \n\t"
10873 "vmx_return: " _ASM_PTR " 2b \n\t"
10874 ".popsection"
10875 : : "c"(vmx), "d"((unsigned long)HOST_RSP), "S"(evmcs_rsp),
10876 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
10877 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
10878 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
10879 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
10880 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
10881 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
10882 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
10883 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
10884 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
10885 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
10886#ifdef CONFIG_X86_64
10887 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
10888 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
10889 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
10890 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
10891 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
10892 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
10893 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
10894 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
10895#endif
10896 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
10897 [wordsize]"i"(sizeof(ulong))
10898 : "cc", "memory"
10899#ifdef CONFIG_X86_64
10900 , "rax", "rbx", "rdi"
10901 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
10902#else
10903 , "eax", "ebx", "edi"
10904#endif
10905 );
10906
10907 /*
10908 * We do not use IBRS in the kernel. If this vCPU has used the
10909 * SPEC_CTRL MSR it may have left it on; save the value and
10910 * turn it off. This is much more efficient than blindly adding
10911 * it to the atomic save/restore list. Especially as the former
10912 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
10913 *
10914 * For non-nested case:
10915 * If the L01 MSR bitmap does not intercept the MSR, then we need to
10916 * save it.
10917 *
10918 * For nested case:
10919 * If the L02 MSR bitmap does not intercept the MSR, then we need to
10920 * save it.
10921 */
10922 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
10923 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
10924
10925 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
10926
10927 /* Eliminate branch target predictions from guest mode */
10928 vmexit_fill_RSB();
10929
10930 /* All fields are clean at this point */
10931 if (static_branch_unlikely(&enable_evmcs))
10932 current_evmcs->hv_clean_fields |=
10933 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
10934
10935 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
10936 if (vmx->host_debugctlmsr)
10937 update_debugctlmsr(vmx->host_debugctlmsr);
10938
10939#ifndef CONFIG_X86_64
10940 /*
10941 * The sysexit path does not restore ds/es, so we must set them to
10942 * a reasonable value ourselves.
10943 *
10944 * We can't defer this to vmx_prepare_switch_to_host() since that
10945 * function may be executed in interrupt context, which saves and
10946 * restore segments around it, nullifying its effect.
10947 */
10948 loadsegment(ds, __USER_DS);
10949 loadsegment(es, __USER_DS);
10950#endif
10951
10952 vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
10953 | (1 << VCPU_EXREG_RFLAGS)
10954 | (1 << VCPU_EXREG_PDPTR)
10955 | (1 << VCPU_EXREG_SEGMENTS)
10956 | (1 << VCPU_EXREG_CR3));
10957 vcpu->arch.regs_dirty = 0;
10958
10959 /*
10960 * eager fpu is enabled if PKEY is supported and CR4 is switched
10961 * back on host, so it is safe to read guest PKRU from current
10962 * XSAVE.
10963 */
10964 if (static_cpu_has(X86_FEATURE_PKU) &&
10965 kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
10966 vcpu->arch.pkru = __read_pkru();
10967 if (vcpu->arch.pkru != vmx->host_pkru)
10968 __write_pkru(vmx->host_pkru);
10969 }
10970
10971 kvm_put_guest_xcr0(vcpu);
10972
10973 vmx->nested.nested_run_pending = 0;
10974 vmx->idt_vectoring_info = 0;
10975
10976 vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
10977 if ((u16)vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY)
10978 kvm_machine_check();
10979
10980 if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
10981 return;
10982
10983 vmx->loaded_vmcs->launched = 1;
10984 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
10985
10986 vmx_complete_atomic_exit(vmx);
10987 vmx_recover_nmi_blocking(vmx);
10988 vmx_complete_interrupts(vmx);
10989}
10990STACK_FRAME_NON_STANDARD(vmx_vcpu_run);
10991
10992static struct kvm *vmx_vm_alloc(void)
10993{
10994 struct kvm_vmx *kvm_vmx = vzalloc(sizeof(struct kvm_vmx));
10995 return &kvm_vmx->kvm;
10996}
10997
10998static void vmx_vm_free(struct kvm *kvm)
10999{
11000 vfree(to_kvm_vmx(kvm));
11001}
11002
11003static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
11004{
11005 struct vcpu_vmx *vmx = to_vmx(vcpu);
11006 int cpu;
11007
11008 if (vmx->loaded_vmcs == vmcs)
11009 return;
11010
11011 cpu = get_cpu();
11012 vmx_vcpu_put(vcpu);
11013 vmx->loaded_vmcs = vmcs;
11014 vmx_vcpu_load(vcpu, cpu);
11015 put_cpu();
11016}
11017
11018/*
11019 * Ensure that the current vmcs of the logical processor is the
11020 * vmcs01 of the vcpu before calling free_nested().
11021 */
11022static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
11023{
11024 struct vcpu_vmx *vmx = to_vmx(vcpu);
11025
11026 vcpu_load(vcpu);
11027 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
11028 free_nested(vmx);
11029 vcpu_put(vcpu);
11030}
11031
11032static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
11033{
11034 struct vcpu_vmx *vmx = to_vmx(vcpu);
11035
11036 if (enable_pml)
11037 vmx_destroy_pml_buffer(vmx);
11038 free_vpid(vmx->vpid);
11039 leave_guest_mode(vcpu);
11040 vmx_free_vcpu_nested(vcpu);
11041 free_loaded_vmcs(vmx->loaded_vmcs);
11042 kfree(vmx->guest_msrs);
11043 kvm_vcpu_uninit(vcpu);
11044 kmem_cache_free(kvm_vcpu_cache, vmx);
11045}
11046
11047static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
11048{
11049 int err;
11050 struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
11051 unsigned long *msr_bitmap;
11052 int cpu;
11053
11054 if (!vmx)
11055 return ERR_PTR(-ENOMEM);
11056
11057 vmx->vpid = allocate_vpid();
11058
11059 err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
11060 if (err)
11061 goto free_vcpu;
11062
11063 err = -ENOMEM;
11064
11065 /*
11066 * If PML is turned on, failure on enabling PML just results in failure
11067 * of creating the vcpu, therefore we can simplify PML logic (by
11068 * avoiding dealing with cases, such as enabling PML partially on vcpus
11069 * for the guest, etc.
11070 */
11071 if (enable_pml) {
11072 vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
11073 if (!vmx->pml_pg)
11074 goto uninit_vcpu;
11075 }
11076
11077 vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
11078 BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
11079 > PAGE_SIZE);
11080
11081 if (!vmx->guest_msrs)
11082 goto free_pml;
11083
11084 err = alloc_loaded_vmcs(&vmx->vmcs01);
11085 if (err < 0)
11086 goto free_msrs;
11087
11088 msr_bitmap = vmx->vmcs01.msr_bitmap;
11089 vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
11090 vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
11091 vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
11092 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
11093 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
11094 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
11095 vmx->msr_bitmap_mode = 0;
11096
11097 vmx->loaded_vmcs = &vmx->vmcs01;
11098 cpu = get_cpu();
11099 vmx_vcpu_load(&vmx->vcpu, cpu);
11100 vmx->vcpu.cpu = cpu;
11101 vmx_vcpu_setup(vmx);
11102 vmx_vcpu_put(&vmx->vcpu);
11103 put_cpu();
11104 if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
11105 err = alloc_apic_access_page(kvm);
11106 if (err)
11107 goto free_vmcs;
11108 }
11109
11110 if (enable_ept && !enable_unrestricted_guest) {
11111 err = init_rmode_identity_map(kvm);
11112 if (err)
11113 goto free_vmcs;
11114 }
11115
11116 if (nested)
11117 nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
11118 kvm_vcpu_apicv_active(&vmx->vcpu));
11119
11120 vmx->nested.posted_intr_nv = -1;
11121 vmx->nested.current_vmptr = -1ull;
11122
11123 vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
11124
11125 /*
11126 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
11127 * or POSTED_INTR_WAKEUP_VECTOR.
11128 */
11129 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
11130 vmx->pi_desc.sn = 1;
11131
11132 return &vmx->vcpu;
11133
11134free_vmcs:
11135 free_loaded_vmcs(vmx->loaded_vmcs);
11136free_msrs:
11137 kfree(vmx->guest_msrs);
11138free_pml:
11139 vmx_destroy_pml_buffer(vmx);
11140uninit_vcpu:
11141 kvm_vcpu_uninit(&vmx->vcpu);
11142free_vcpu:
11143 free_vpid(vmx->vpid);
11144 kmem_cache_free(kvm_vcpu_cache, vmx);
11145 return ERR_PTR(err);
11146}
11147
11148#define L1TF_MSG_SMT "L1TF CPU bug present and SMT on, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
11149#define L1TF_MSG_L1D "L1TF CPU bug present and virtualization mitigation disabled, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
11150
11151static int vmx_vm_init(struct kvm *kvm)
11152{
11153 spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
11154
11155 if (!ple_gap)
11156 kvm->arch.pause_in_guest = true;
11157
11158 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
11159 switch (l1tf_mitigation) {
11160 case L1TF_MITIGATION_OFF:
11161 case L1TF_MITIGATION_FLUSH_NOWARN:
11162 /* 'I explicitly don't care' is set */
11163 break;
11164 case L1TF_MITIGATION_FLUSH:
11165 case L1TF_MITIGATION_FLUSH_NOSMT:
11166 case L1TF_MITIGATION_FULL:
11167 /*
11168 * Warn upon starting the first VM in a potentially
11169 * insecure environment.
11170 */
11171 if (sched_smt_active())
11172 pr_warn_once(L1TF_MSG_SMT);
11173 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
11174 pr_warn_once(L1TF_MSG_L1D);
11175 break;
11176 case L1TF_MITIGATION_FULL_FORCE:
11177 /* Flush is enforced */
11178 break;
11179 }
11180 }
11181 return 0;
11182}
11183
11184static void __init vmx_check_processor_compat(void *rtn)
11185{
11186 struct vmcs_config vmcs_conf;
11187
11188 *(int *)rtn = 0;
11189 if (setup_vmcs_config(&vmcs_conf) < 0)
11190 *(int *)rtn = -EIO;
11191 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, enable_apicv);
11192 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
11193 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
11194 smp_processor_id());
11195 *(int *)rtn = -EIO;
11196 }
11197}
11198
11199static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
11200{
11201 u8 cache;
11202 u64 ipat = 0;
11203
11204 /* For VT-d and EPT combination
11205 * 1. MMIO: always map as UC
11206 * 2. EPT with VT-d:
11207 * a. VT-d without snooping control feature: can't guarantee the
11208 * result, try to trust guest.
11209 * b. VT-d with snooping control feature: snooping control feature of
11210 * VT-d engine can guarantee the cache correctness. Just set it
11211 * to WB to keep consistent with host. So the same as item 3.
11212 * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
11213 * consistent with host MTRR
11214 */
11215 if (is_mmio) {
11216 cache = MTRR_TYPE_UNCACHABLE;
11217 goto exit;
11218 }
11219
11220 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
11221 ipat = VMX_EPT_IPAT_BIT;
11222 cache = MTRR_TYPE_WRBACK;
11223 goto exit;
11224 }
11225
11226 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
11227 ipat = VMX_EPT_IPAT_BIT;
11228 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
11229 cache = MTRR_TYPE_WRBACK;
11230 else
11231 cache = MTRR_TYPE_UNCACHABLE;
11232 goto exit;
11233 }
11234
11235 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
11236
11237exit:
11238 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
11239}
11240
11241static int vmx_get_lpage_level(void)
11242{
11243 if (enable_ept && !cpu_has_vmx_ept_1g_page())
11244 return PT_DIRECTORY_LEVEL;
11245 else
11246 /* For shadow and EPT supported 1GB page */
11247 return PT_PDPE_LEVEL;
11248}
11249
11250static void vmcs_set_secondary_exec_control(u32 new_ctl)
11251{
11252 /*
11253 * These bits in the secondary execution controls field
11254 * are dynamic, the others are mostly based on the hypervisor
11255 * architecture and the guest's CPUID. Do not touch the
11256 * dynamic bits.
11257 */
11258 u32 mask =
11259 SECONDARY_EXEC_SHADOW_VMCS |
11260 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
11261 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
11262 SECONDARY_EXEC_DESC;
11263
11264 u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
11265
11266 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
11267 (new_ctl & ~mask) | (cur_ctl & mask));
11268}
11269
11270/*
11271 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
11272 * (indicating "allowed-1") if they are supported in the guest's CPUID.
11273 */
11274static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
11275{
11276 struct vcpu_vmx *vmx = to_vmx(vcpu);
11277 struct kvm_cpuid_entry2 *entry;
11278
11279 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
11280 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
11281
11282#define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
11283 if (entry && (entry->_reg & (_cpuid_mask))) \
11284 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
11285} while (0)
11286
11287 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
11288 cr4_fixed1_update(X86_CR4_VME, edx, bit(X86_FEATURE_VME));
11289 cr4_fixed1_update(X86_CR4_PVI, edx, bit(X86_FEATURE_VME));
11290 cr4_fixed1_update(X86_CR4_TSD, edx, bit(X86_FEATURE_TSC));
11291 cr4_fixed1_update(X86_CR4_DE, edx, bit(X86_FEATURE_DE));
11292 cr4_fixed1_update(X86_CR4_PSE, edx, bit(X86_FEATURE_PSE));
11293 cr4_fixed1_update(X86_CR4_PAE, edx, bit(X86_FEATURE_PAE));
11294 cr4_fixed1_update(X86_CR4_MCE, edx, bit(X86_FEATURE_MCE));
11295 cr4_fixed1_update(X86_CR4_PGE, edx, bit(X86_FEATURE_PGE));
11296 cr4_fixed1_update(X86_CR4_OSFXSR, edx, bit(X86_FEATURE_FXSR));
11297 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
11298 cr4_fixed1_update(X86_CR4_VMXE, ecx, bit(X86_FEATURE_VMX));
11299 cr4_fixed1_update(X86_CR4_SMXE, ecx, bit(X86_FEATURE_SMX));
11300 cr4_fixed1_update(X86_CR4_PCIDE, ecx, bit(X86_FEATURE_PCID));
11301 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, bit(X86_FEATURE_XSAVE));
11302
11303 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
11304 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, bit(X86_FEATURE_FSGSBASE));
11305 cr4_fixed1_update(X86_CR4_SMEP, ebx, bit(X86_FEATURE_SMEP));
11306 cr4_fixed1_update(X86_CR4_SMAP, ebx, bit(X86_FEATURE_SMAP));
11307 cr4_fixed1_update(X86_CR4_PKE, ecx, bit(X86_FEATURE_PKU));
11308 cr4_fixed1_update(X86_CR4_UMIP, ecx, bit(X86_FEATURE_UMIP));
11309
11310#undef cr4_fixed1_update
11311}
11312
11313static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
11314{
11315 struct vcpu_vmx *vmx = to_vmx(vcpu);
11316
11317 if (kvm_mpx_supported()) {
11318 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
11319
11320 if (mpx_enabled) {
11321 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
11322 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
11323 } else {
11324 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
11325 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
11326 }
11327 }
11328}
11329
11330static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
11331{
11332 struct vcpu_vmx *vmx = to_vmx(vcpu);
11333
11334 if (cpu_has_secondary_exec_ctrls()) {
11335 vmx_compute_secondary_exec_control(vmx);
11336 vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
11337 }
11338
11339 if (nested_vmx_allowed(vcpu))
11340 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
11341 FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
11342 else
11343 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
11344 ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
11345
11346 if (nested_vmx_allowed(vcpu)) {
11347 nested_vmx_cr_fixed1_bits_update(vcpu);
11348 nested_vmx_entry_exit_ctls_update(vcpu);
11349 }
11350}
11351
11352static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
11353{
11354 if (func == 1 && nested)
11355 entry->ecx |= bit(X86_FEATURE_VMX);
11356}
11357
11358static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
11359 struct x86_exception *fault)
11360{
11361 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11362 struct vcpu_vmx *vmx = to_vmx(vcpu);
11363 u32 exit_reason;
11364 unsigned long exit_qualification = vcpu->arch.exit_qualification;
11365
11366 if (vmx->nested.pml_full) {
11367 exit_reason = EXIT_REASON_PML_FULL;
11368 vmx->nested.pml_full = false;
11369 exit_qualification &= INTR_INFO_UNBLOCK_NMI;
11370 } else if (fault->error_code & PFERR_RSVD_MASK)
11371 exit_reason = EXIT_REASON_EPT_MISCONFIG;
11372 else
11373 exit_reason = EXIT_REASON_EPT_VIOLATION;
11374
11375 nested_vmx_vmexit(vcpu, exit_reason, 0, exit_qualification);
11376 vmcs12->guest_physical_address = fault->address;
11377}
11378
11379static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu)
11380{
11381 return nested_ept_get_cr3(vcpu) & VMX_EPTP_AD_ENABLE_BIT;
11382}
11383
11384/* Callbacks for nested_ept_init_mmu_context: */
11385
11386static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
11387{
11388 /* return the page table to be shadowed - in our case, EPT12 */
11389 return get_vmcs12(vcpu)->ept_pointer;
11390}
11391
11392static int nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
11393{
11394 WARN_ON(mmu_is_nested(vcpu));
11395 if (!valid_ept_address(vcpu, nested_ept_get_cr3(vcpu)))
11396 return 1;
11397
11398 kvm_init_shadow_ept_mmu(vcpu,
11399 to_vmx(vcpu)->nested.msrs.ept_caps &
11400 VMX_EPT_EXECUTE_ONLY_BIT,
11401 nested_ept_ad_enabled(vcpu),
11402 nested_ept_get_cr3(vcpu));
11403 vcpu->arch.mmu.set_cr3 = vmx_set_cr3;
11404 vcpu->arch.mmu.get_cr3 = nested_ept_get_cr3;
11405 vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
11406
11407 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
11408 return 0;
11409}
11410
11411static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
11412{
11413 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
11414}
11415
11416static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
11417 u16 error_code)
11418{
11419 bool inequality, bit;
11420
11421 bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
11422 inequality =
11423 (error_code & vmcs12->page_fault_error_code_mask) !=
11424 vmcs12->page_fault_error_code_match;
11425 return inequality ^ bit;
11426}
11427
11428static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
11429 struct x86_exception *fault)
11430{
11431 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11432
11433 WARN_ON(!is_guest_mode(vcpu));
11434
11435 if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code) &&
11436 !to_vmx(vcpu)->nested.nested_run_pending) {
11437 vmcs12->vm_exit_intr_error_code = fault->error_code;
11438 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
11439 PF_VECTOR | INTR_TYPE_HARD_EXCEPTION |
11440 INTR_INFO_DELIVER_CODE_MASK | INTR_INFO_VALID_MASK,
11441 fault->address);
11442 } else {
11443 kvm_inject_page_fault(vcpu, fault);
11444 }
11445}
11446
11447static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
11448 struct vmcs12 *vmcs12);
11449
11450static void nested_get_vmcs12_pages(struct kvm_vcpu *vcpu)
11451{
11452 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11453 struct vcpu_vmx *vmx = to_vmx(vcpu);
11454 struct page *page;
11455 u64 hpa;
11456
11457 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
11458 /*
11459 * Translate L1 physical address to host physical
11460 * address for vmcs02. Keep the page pinned, so this
11461 * physical address remains valid. We keep a reference
11462 * to it so we can release it later.
11463 */
11464 if (vmx->nested.apic_access_page) { /* shouldn't happen */
11465 kvm_release_page_dirty(vmx->nested.apic_access_page);
11466 vmx->nested.apic_access_page = NULL;
11467 }
11468 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->apic_access_addr);
11469 /*
11470 * If translation failed, no matter: This feature asks
11471 * to exit when accessing the given address, and if it
11472 * can never be accessed, this feature won't do
11473 * anything anyway.
11474 */
11475 if (!is_error_page(page)) {
11476 vmx->nested.apic_access_page = page;
11477 hpa = page_to_phys(vmx->nested.apic_access_page);
11478 vmcs_write64(APIC_ACCESS_ADDR, hpa);
11479 } else {
11480 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
11481 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
11482 }
11483 }
11484
11485 if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
11486 if (vmx->nested.virtual_apic_page) { /* shouldn't happen */
11487 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
11488 vmx->nested.virtual_apic_page = NULL;
11489 }
11490 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->virtual_apic_page_addr);
11491
11492 /*
11493 * If translation failed, VM entry will fail because
11494 * prepare_vmcs02 set VIRTUAL_APIC_PAGE_ADDR to -1ull.
11495 * Failing the vm entry is _not_ what the processor
11496 * does but it's basically the only possibility we
11497 * have. We could still enter the guest if CR8 load
11498 * exits are enabled, CR8 store exits are enabled, and
11499 * virtualize APIC access is disabled; in this case
11500 * the processor would never use the TPR shadow and we
11501 * could simply clear the bit from the execution
11502 * control. But such a configuration is useless, so
11503 * let's keep the code simple.
11504 */
11505 if (!is_error_page(page)) {
11506 vmx->nested.virtual_apic_page = page;
11507 hpa = page_to_phys(vmx->nested.virtual_apic_page);
11508 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, hpa);
11509 }
11510 }
11511
11512 if (nested_cpu_has_posted_intr(vmcs12)) {
11513 if (vmx->nested.pi_desc_page) { /* shouldn't happen */
11514 kunmap(vmx->nested.pi_desc_page);
11515 kvm_release_page_dirty(vmx->nested.pi_desc_page);
11516 vmx->nested.pi_desc_page = NULL;
11517 vmx->nested.pi_desc = NULL;
11518 vmcs_write64(POSTED_INTR_DESC_ADDR, -1ull);
11519 }
11520 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->posted_intr_desc_addr);
11521 if (is_error_page(page))
11522 return;
11523 vmx->nested.pi_desc_page = page;
11524 vmx->nested.pi_desc = kmap(vmx->nested.pi_desc_page);
11525 vmx->nested.pi_desc =
11526 (struct pi_desc *)((void *)vmx->nested.pi_desc +
11527 (unsigned long)(vmcs12->posted_intr_desc_addr &
11528 (PAGE_SIZE - 1)));
11529 vmcs_write64(POSTED_INTR_DESC_ADDR,
11530 page_to_phys(vmx->nested.pi_desc_page) +
11531 (unsigned long)(vmcs12->posted_intr_desc_addr &
11532 (PAGE_SIZE - 1)));
11533 }
11534 if (nested_vmx_prepare_msr_bitmap(vcpu, vmcs12))
11535 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
11536 CPU_BASED_USE_MSR_BITMAPS);
11537 else
11538 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
11539 CPU_BASED_USE_MSR_BITMAPS);
11540}
11541
11542static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
11543{
11544 u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
11545 struct vcpu_vmx *vmx = to_vmx(vcpu);
11546
11547 /*
11548 * A timer value of zero is architecturally guaranteed to cause
11549 * a VMExit prior to executing any instructions in the guest.
11550 */
11551 if (preemption_timeout == 0) {
11552 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
11553 return;
11554 }
11555
11556 if (vcpu->arch.virtual_tsc_khz == 0)
11557 return;
11558
11559 preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
11560 preemption_timeout *= 1000000;
11561 do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
11562 hrtimer_start(&vmx->nested.preemption_timer,
11563 ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
11564}
11565
11566static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
11567 struct vmcs12 *vmcs12)
11568{
11569 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
11570 return 0;
11571
11572 if (!page_address_valid(vcpu, vmcs12->io_bitmap_a) ||
11573 !page_address_valid(vcpu, vmcs12->io_bitmap_b))
11574 return -EINVAL;
11575
11576 return 0;
11577}
11578
11579static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
11580 struct vmcs12 *vmcs12)
11581{
11582 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
11583 return 0;
11584
11585 if (!page_address_valid(vcpu, vmcs12->msr_bitmap))
11586 return -EINVAL;
11587
11588 return 0;
11589}
11590
11591static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
11592 struct vmcs12 *vmcs12)
11593{
11594 if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
11595 return 0;
11596
11597 if (!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr))
11598 return -EINVAL;
11599
11600 return 0;
11601}
11602
11603static inline void enable_x2apic_msr_intercepts(unsigned long *msr_bitmap) {
11604 int msr;
11605
11606 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
11607 unsigned word = msr / BITS_PER_LONG;
11608
11609 msr_bitmap[word] = ~0;
11610 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
11611 }
11612}
11613
11614/*
11615 * Merge L0's and L1's MSR bitmap, return false to indicate that
11616 * we do not use the hardware.
11617 */
11618static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
11619 struct vmcs12 *vmcs12)
11620{
11621 int msr;
11622 struct page *page;
11623 unsigned long *msr_bitmap_l1;
11624 unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap;
11625 /*
11626 * pred_cmd & spec_ctrl are trying to verify two things:
11627 *
11628 * 1. L0 gave a permission to L1 to actually passthrough the MSR. This
11629 * ensures that we do not accidentally generate an L02 MSR bitmap
11630 * from the L12 MSR bitmap that is too permissive.
11631 * 2. That L1 or L2s have actually used the MSR. This avoids
11632 * unnecessarily merging of the bitmap if the MSR is unused. This
11633 * works properly because we only update the L01 MSR bitmap lazily.
11634 * So even if L0 should pass L1 these MSRs, the L01 bitmap is only
11635 * updated to reflect this when L1 (or its L2s) actually write to
11636 * the MSR.
11637 */
11638 bool pred_cmd = !msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD);
11639 bool spec_ctrl = !msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL);
11640
11641 /* Nothing to do if the MSR bitmap is not in use. */
11642 if (!cpu_has_vmx_msr_bitmap() ||
11643 !nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
11644 return false;
11645
11646 if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
11647 !pred_cmd && !spec_ctrl)
11648 return false;
11649
11650 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->msr_bitmap);
11651 if (is_error_page(page))
11652 return false;
11653
11654 msr_bitmap_l1 = (unsigned long *)kmap(page);
11655
11656 /*
11657 * To keep the control flow simple, pay eight 8-byte writes (sixteen
11658 * 4-byte writes on 32-bit systems) up front to enable intercepts for
11659 * the x2APIC MSR range and selectively disable them below.
11660 */
11661 enable_x2apic_msr_intercepts(msr_bitmap_l0);
11662
11663 if (nested_cpu_has_virt_x2apic_mode(vmcs12)) {
11664 if (nested_cpu_has_apic_reg_virt(vmcs12)) {
11665 /*
11666 * L0 need not intercept reads for MSRs between 0x800
11667 * and 0x8ff, it just lets the processor take the value
11668 * from the virtual-APIC page; take those 256 bits
11669 * directly from the L1 bitmap.
11670 */
11671 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
11672 unsigned word = msr / BITS_PER_LONG;
11673
11674 msr_bitmap_l0[word] = msr_bitmap_l1[word];
11675 }
11676 }
11677
11678 nested_vmx_disable_intercept_for_msr(
11679 msr_bitmap_l1, msr_bitmap_l0,
11680 X2APIC_MSR(APIC_TASKPRI),
11681 MSR_TYPE_R | MSR_TYPE_W);
11682
11683 if (nested_cpu_has_vid(vmcs12)) {
11684 nested_vmx_disable_intercept_for_msr(
11685 msr_bitmap_l1, msr_bitmap_l0,
11686 X2APIC_MSR(APIC_EOI),
11687 MSR_TYPE_W);
11688 nested_vmx_disable_intercept_for_msr(
11689 msr_bitmap_l1, msr_bitmap_l0,
11690 X2APIC_MSR(APIC_SELF_IPI),
11691 MSR_TYPE_W);
11692 }
11693 }
11694
11695 if (spec_ctrl)
11696 nested_vmx_disable_intercept_for_msr(
11697 msr_bitmap_l1, msr_bitmap_l0,
11698 MSR_IA32_SPEC_CTRL,
11699 MSR_TYPE_R | MSR_TYPE_W);
11700
11701 if (pred_cmd)
11702 nested_vmx_disable_intercept_for_msr(
11703 msr_bitmap_l1, msr_bitmap_l0,
11704 MSR_IA32_PRED_CMD,
11705 MSR_TYPE_W);
11706
11707 kunmap(page);
11708 kvm_release_page_clean(page);
11709
11710 return true;
11711}
11712
11713static void nested_cache_shadow_vmcs12(struct kvm_vcpu *vcpu,
11714 struct vmcs12 *vmcs12)
11715{
11716 struct vmcs12 *shadow;
11717 struct page *page;
11718
11719 if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
11720 vmcs12->vmcs_link_pointer == -1ull)
11721 return;
11722
11723 shadow = get_shadow_vmcs12(vcpu);
11724 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->vmcs_link_pointer);
11725
11726 memcpy(shadow, kmap(page), VMCS12_SIZE);
11727
11728 kunmap(page);
11729 kvm_release_page_clean(page);
11730}
11731
11732static void nested_flush_cached_shadow_vmcs12(struct kvm_vcpu *vcpu,
11733 struct vmcs12 *vmcs12)
11734{
11735 struct vcpu_vmx *vmx = to_vmx(vcpu);
11736
11737 if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
11738 vmcs12->vmcs_link_pointer == -1ull)
11739 return;
11740
11741 kvm_write_guest(vmx->vcpu.kvm, vmcs12->vmcs_link_pointer,
11742 get_shadow_vmcs12(vcpu), VMCS12_SIZE);
11743}
11744
11745static int nested_vmx_check_apic_access_controls(struct kvm_vcpu *vcpu,
11746 struct vmcs12 *vmcs12)
11747{
11748 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
11749 !page_address_valid(vcpu, vmcs12->apic_access_addr))
11750 return -EINVAL;
11751 else
11752 return 0;
11753}
11754
11755static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
11756 struct vmcs12 *vmcs12)
11757{
11758 if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
11759 !nested_cpu_has_apic_reg_virt(vmcs12) &&
11760 !nested_cpu_has_vid(vmcs12) &&
11761 !nested_cpu_has_posted_intr(vmcs12))
11762 return 0;
11763
11764 /*
11765 * If virtualize x2apic mode is enabled,
11766 * virtualize apic access must be disabled.
11767 */
11768 if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
11769 nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
11770 return -EINVAL;
11771
11772 /*
11773 * If virtual interrupt delivery is enabled,
11774 * we must exit on external interrupts.
11775 */
11776 if (nested_cpu_has_vid(vmcs12) &&
11777 !nested_exit_on_intr(vcpu))
11778 return -EINVAL;
11779
11780 /*
11781 * bits 15:8 should be zero in posted_intr_nv,
11782 * the descriptor address has been already checked
11783 * in nested_get_vmcs12_pages.
11784 *
11785 * bits 5:0 of posted_intr_desc_addr should be zero.
11786 */
11787 if (nested_cpu_has_posted_intr(vmcs12) &&
11788 (!nested_cpu_has_vid(vmcs12) ||
11789 !nested_exit_intr_ack_set(vcpu) ||
11790 (vmcs12->posted_intr_nv & 0xff00) ||
11791 (vmcs12->posted_intr_desc_addr & 0x3f) ||
11792 (vmcs12->posted_intr_desc_addr >> cpuid_maxphyaddr(vcpu))))
11793 return -EINVAL;
11794
11795 /* tpr shadow is needed by all apicv features. */
11796 if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
11797 return -EINVAL;
11798
11799 return 0;
11800}
11801
11802static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
11803 unsigned long count_field,
11804 unsigned long addr_field)
11805{
11806 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11807 int maxphyaddr;
11808 u64 count, addr;
11809
11810 if (vmcs12_read_any(vmcs12, count_field, &count) ||
11811 vmcs12_read_any(vmcs12, addr_field, &addr)) {
11812 WARN_ON(1);
11813 return -EINVAL;
11814 }
11815 if (count == 0)
11816 return 0;
11817 maxphyaddr = cpuid_maxphyaddr(vcpu);
11818 if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
11819 (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
11820 pr_debug_ratelimited(
11821 "nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
11822 addr_field, maxphyaddr, count, addr);
11823 return -EINVAL;
11824 }
11825 return 0;
11826}
11827
11828static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
11829 struct vmcs12 *vmcs12)
11830{
11831 if (vmcs12->vm_exit_msr_load_count == 0 &&
11832 vmcs12->vm_exit_msr_store_count == 0 &&
11833 vmcs12->vm_entry_msr_load_count == 0)
11834 return 0; /* Fast path */
11835 if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
11836 VM_EXIT_MSR_LOAD_ADDR) ||
11837 nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
11838 VM_EXIT_MSR_STORE_ADDR) ||
11839 nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
11840 VM_ENTRY_MSR_LOAD_ADDR))
11841 return -EINVAL;
11842 return 0;
11843}
11844
11845static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
11846 struct vmcs12 *vmcs12)
11847{
11848 u64 address = vmcs12->pml_address;
11849 int maxphyaddr = cpuid_maxphyaddr(vcpu);
11850
11851 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML)) {
11852 if (!nested_cpu_has_ept(vmcs12) ||
11853 !IS_ALIGNED(address, 4096) ||
11854 address >> maxphyaddr)
11855 return -EINVAL;
11856 }
11857
11858 return 0;
11859}
11860
11861static int nested_vmx_check_shadow_vmcs_controls(struct kvm_vcpu *vcpu,
11862 struct vmcs12 *vmcs12)
11863{
11864 if (!nested_cpu_has_shadow_vmcs(vmcs12))
11865 return 0;
11866
11867 if (!page_address_valid(vcpu, vmcs12->vmread_bitmap) ||
11868 !page_address_valid(vcpu, vmcs12->vmwrite_bitmap))
11869 return -EINVAL;
11870
11871 return 0;
11872}
11873
11874static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
11875 struct vmx_msr_entry *e)
11876{
11877 /* x2APIC MSR accesses are not allowed */
11878 if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
11879 return -EINVAL;
11880 if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
11881 e->index == MSR_IA32_UCODE_REV)
11882 return -EINVAL;
11883 if (e->reserved != 0)
11884 return -EINVAL;
11885 return 0;
11886}
11887
11888static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
11889 struct vmx_msr_entry *e)
11890{
11891 if (e->index == MSR_FS_BASE ||
11892 e->index == MSR_GS_BASE ||
11893 e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
11894 nested_vmx_msr_check_common(vcpu, e))
11895 return -EINVAL;
11896 return 0;
11897}
11898
11899static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
11900 struct vmx_msr_entry *e)
11901{
11902 if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
11903 nested_vmx_msr_check_common(vcpu, e))
11904 return -EINVAL;
11905 return 0;
11906}
11907
11908/*
11909 * Load guest's/host's msr at nested entry/exit.
11910 * return 0 for success, entry index for failure.
11911 */
11912static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
11913{
11914 u32 i;
11915 struct vmx_msr_entry e;
11916 struct msr_data msr;
11917
11918 msr.host_initiated = false;
11919 for (i = 0; i < count; i++) {
11920 if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
11921 &e, sizeof(e))) {
11922 pr_debug_ratelimited(
11923 "%s cannot read MSR entry (%u, 0x%08llx)\n",
11924 __func__, i, gpa + i * sizeof(e));
11925 goto fail;
11926 }
11927 if (nested_vmx_load_msr_check(vcpu, &e)) {
11928 pr_debug_ratelimited(
11929 "%s check failed (%u, 0x%x, 0x%x)\n",
11930 __func__, i, e.index, e.reserved);
11931 goto fail;
11932 }
11933 msr.index = e.index;
11934 msr.data = e.value;
11935 if (kvm_set_msr(vcpu, &msr)) {
11936 pr_debug_ratelimited(
11937 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
11938 __func__, i, e.index, e.value);
11939 goto fail;
11940 }
11941 }
11942 return 0;
11943fail:
11944 return i + 1;
11945}
11946
11947static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
11948{
11949 u32 i;
11950 struct vmx_msr_entry e;
11951
11952 for (i = 0; i < count; i++) {
11953 struct msr_data msr_info;
11954 if (kvm_vcpu_read_guest(vcpu,
11955 gpa + i * sizeof(e),
11956 &e, 2 * sizeof(u32))) {
11957 pr_debug_ratelimited(
11958 "%s cannot read MSR entry (%u, 0x%08llx)\n",
11959 __func__, i, gpa + i * sizeof(e));
11960 return -EINVAL;
11961 }
11962 if (nested_vmx_store_msr_check(vcpu, &e)) {
11963 pr_debug_ratelimited(
11964 "%s check failed (%u, 0x%x, 0x%x)\n",
11965 __func__, i, e.index, e.reserved);
11966 return -EINVAL;
11967 }
11968 msr_info.host_initiated = false;
11969 msr_info.index = e.index;
11970 if (kvm_get_msr(vcpu, &msr_info)) {
11971 pr_debug_ratelimited(
11972 "%s cannot read MSR (%u, 0x%x)\n",
11973 __func__, i, e.index);
11974 return -EINVAL;
11975 }
11976 if (kvm_vcpu_write_guest(vcpu,
11977 gpa + i * sizeof(e) +
11978 offsetof(struct vmx_msr_entry, value),
11979 &msr_info.data, sizeof(msr_info.data))) {
11980 pr_debug_ratelimited(
11981 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
11982 __func__, i, e.index, msr_info.data);
11983 return -EINVAL;
11984 }
11985 }
11986 return 0;
11987}
11988
11989static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
11990{
11991 unsigned long invalid_mask;
11992
11993 invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
11994 return (val & invalid_mask) == 0;
11995}
11996
11997/*
11998 * Load guest's/host's cr3 at nested entry/exit. nested_ept is true if we are
11999 * emulating VM entry into a guest with EPT enabled.
12000 * Returns 0 on success, 1 on failure. Invalid state exit qualification code
12001 * is assigned to entry_failure_code on failure.
12002 */
12003static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
12004 u32 *entry_failure_code)
12005{
12006 if (cr3 != kvm_read_cr3(vcpu) || (!nested_ept && pdptrs_changed(vcpu))) {
12007 if (!nested_cr3_valid(vcpu, cr3)) {
12008 *entry_failure_code = ENTRY_FAIL_DEFAULT;
12009 return 1;
12010 }
12011
12012 /*
12013 * If PAE paging and EPT are both on, CR3 is not used by the CPU and
12014 * must not be dereferenced.
12015 */
12016 if (is_pae_paging(vcpu) && !nested_ept) {
12017 if (!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)) {
12018 *entry_failure_code = ENTRY_FAIL_PDPTE;
12019 return 1;
12020 }
12021 }
12022 }
12023
12024 if (!nested_ept)
12025 kvm_mmu_new_cr3(vcpu, cr3, false);
12026
12027 vcpu->arch.cr3 = cr3;
12028 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
12029
12030 kvm_init_mmu(vcpu, false);
12031
12032 return 0;
12033}
12034
12035static void prepare_vmcs02_full(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12036{
12037 struct vcpu_vmx *vmx = to_vmx(vcpu);
12038
12039 vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
12040 vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
12041 vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
12042 vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
12043 vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
12044 vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
12045 vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
12046 vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
12047 vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
12048 vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
12049 vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
12050 vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
12051 vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
12052 vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
12053 vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
12054 vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
12055 vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
12056 vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
12057 vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
12058 vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
12059 vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
12060 vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
12061 vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
12062 vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
12063 vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
12064 vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
12065 vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
12066 vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
12067 vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
12068 vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
12069 vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
12070
12071 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
12072 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
12073 vmcs12->guest_pending_dbg_exceptions);
12074 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
12075 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
12076
12077 if (nested_cpu_has_xsaves(vmcs12))
12078 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
12079 vmcs_write64(VMCS_LINK_POINTER, -1ull);
12080
12081 if (cpu_has_vmx_posted_intr())
12082 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
12083
12084 /*
12085 * Whether page-faults are trapped is determined by a combination of
12086 * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
12087 * If enable_ept, L0 doesn't care about page faults and we should
12088 * set all of these to L1's desires. However, if !enable_ept, L0 does
12089 * care about (at least some) page faults, and because it is not easy
12090 * (if at all possible?) to merge L0 and L1's desires, we simply ask
12091 * to exit on each and every L2 page fault. This is done by setting
12092 * MASK=MATCH=0 and (see below) EB.PF=1.
12093 * Note that below we don't need special code to set EB.PF beyond the
12094 * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
12095 * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
12096 * !enable_ept, EB.PF is 1, so the "or" will always be 1.
12097 */
12098 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
12099 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
12100 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
12101 enable_ept ? vmcs12->page_fault_error_code_match : 0);
12102
12103 /* All VMFUNCs are currently emulated through L0 vmexits. */
12104 if (cpu_has_vmx_vmfunc())
12105 vmcs_write64(VM_FUNCTION_CONTROL, 0);
12106
12107 if (cpu_has_vmx_apicv()) {
12108 vmcs_write64(EOI_EXIT_BITMAP0, vmcs12->eoi_exit_bitmap0);
12109 vmcs_write64(EOI_EXIT_BITMAP1, vmcs12->eoi_exit_bitmap1);
12110 vmcs_write64(EOI_EXIT_BITMAP2, vmcs12->eoi_exit_bitmap2);
12111 vmcs_write64(EOI_EXIT_BITMAP3, vmcs12->eoi_exit_bitmap3);
12112 }
12113
12114 /*
12115 * Set host-state according to L0's settings (vmcs12 is irrelevant here)
12116 * Some constant fields are set here by vmx_set_constant_host_state().
12117 * Other fields are different per CPU, and will be set later when
12118 * vmx_vcpu_load() is called, and when vmx_prepare_switch_to_guest()
12119 * is called.
12120 */
12121 vmx_set_constant_host_state(vmx);
12122
12123 /*
12124 * Set the MSR load/store lists to match L0's settings.
12125 */
12126 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
12127 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
12128 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
12129 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
12130 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
12131
12132 set_cr4_guest_host_mask(vmx);
12133
12134 if (kvm_mpx_supported()) {
12135 if (vmx->nested.nested_run_pending &&
12136 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
12137 vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
12138 else
12139 vmcs_write64(GUEST_BNDCFGS, vmx->nested.vmcs01_guest_bndcfgs);
12140 }
12141
12142 if (enable_vpid) {
12143 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02)
12144 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
12145 else
12146 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
12147 }
12148
12149 /*
12150 * L1 may access the L2's PDPTR, so save them to construct vmcs12
12151 */
12152 if (enable_ept) {
12153 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
12154 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
12155 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
12156 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
12157 }
12158
12159 if (cpu_has_vmx_msr_bitmap())
12160 vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
12161}
12162
12163/*
12164 * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
12165 * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
12166 * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
12167 * guest in a way that will both be appropriate to L1's requests, and our
12168 * needs. In addition to modifying the active vmcs (which is vmcs02), this
12169 * function also has additional necessary side-effects, like setting various
12170 * vcpu->arch fields.
12171 * Returns 0 on success, 1 on failure. Invalid state exit qualification code
12172 * is assigned to entry_failure_code on failure.
12173 */
12174static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12175 u32 *entry_failure_code)
12176{
12177 struct vcpu_vmx *vmx = to_vmx(vcpu);
12178 u32 exec_control, vmcs12_exec_ctrl;
12179
12180 if (vmx->nested.dirty_vmcs12) {
12181 prepare_vmcs02_full(vcpu, vmcs12);
12182 vmx->nested.dirty_vmcs12 = false;
12183 }
12184
12185 /*
12186 * First, the fields that are shadowed. This must be kept in sync
12187 * with vmx_shadow_fields.h.
12188 */
12189
12190 vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
12191 vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
12192 vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
12193 vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
12194 vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
12195
12196 if (vmx->nested.nested_run_pending &&
12197 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
12198 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
12199 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
12200 } else {
12201 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
12202 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
12203 }
12204 if (vmx->nested.nested_run_pending) {
12205 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
12206 vmcs12->vm_entry_intr_info_field);
12207 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
12208 vmcs12->vm_entry_exception_error_code);
12209 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
12210 vmcs12->vm_entry_instruction_len);
12211 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
12212 vmcs12->guest_interruptibility_info);
12213 vmx->loaded_vmcs->nmi_known_unmasked =
12214 !(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
12215 } else {
12216 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
12217 }
12218 vmx_set_rflags(vcpu, vmcs12->guest_rflags);
12219
12220 exec_control = vmcs12->pin_based_vm_exec_control;
12221
12222 /* Preemption timer setting is computed directly in vmx_vcpu_run. */
12223 exec_control |= vmcs_config.pin_based_exec_ctrl;
12224 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
12225 vmx->loaded_vmcs->hv_timer_armed = false;
12226
12227 /* Posted interrupts setting is only taken from vmcs12. */
12228 if (nested_cpu_has_posted_intr(vmcs12)) {
12229 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
12230 vmx->nested.pi_pending = false;
12231 } else {
12232 exec_control &= ~PIN_BASED_POSTED_INTR;
12233 }
12234
12235 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
12236
12237 vmx->nested.preemption_timer_expired = false;
12238 if (nested_cpu_has_preemption_timer(vmcs12))
12239 vmx_start_preemption_timer(vcpu);
12240
12241 if (cpu_has_secondary_exec_ctrls()) {
12242 exec_control = vmx->secondary_exec_control;
12243
12244 /* Take the following fields only from vmcs12 */
12245 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
12246 SECONDARY_EXEC_ENABLE_INVPCID |
12247 SECONDARY_EXEC_RDTSCP |
12248 SECONDARY_EXEC_XSAVES |
12249 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
12250 SECONDARY_EXEC_APIC_REGISTER_VIRT |
12251 SECONDARY_EXEC_ENABLE_VMFUNC);
12252 if (nested_cpu_has(vmcs12,
12253 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
12254 vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
12255 ~SECONDARY_EXEC_ENABLE_PML;
12256 exec_control |= vmcs12_exec_ctrl;
12257 }
12258
12259 /* VMCS shadowing for L2 is emulated for now */
12260 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
12261
12262 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
12263 vmcs_write16(GUEST_INTR_STATUS,
12264 vmcs12->guest_intr_status);
12265
12266 /*
12267 * Write an illegal value to APIC_ACCESS_ADDR. Later,
12268 * nested_get_vmcs12_pages will either fix it up or
12269 * remove the VM execution control.
12270 */
12271 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
12272 vmcs_write64(APIC_ACCESS_ADDR, -1ull);
12273
12274 if (exec_control & SECONDARY_EXEC_ENCLS_EXITING)
12275 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
12276
12277 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
12278 }
12279
12280 /*
12281 * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
12282 * entry, but only if the current (host) sp changed from the value
12283 * we wrote last (vmx->host_rsp). This cache is no longer relevant
12284 * if we switch vmcs, and rather than hold a separate cache per vmcs,
12285 * here we just force the write to happen on entry.
12286 */
12287 vmx->host_rsp = 0;
12288
12289 exec_control = vmx_exec_control(vmx); /* L0's desires */
12290 exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
12291 exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
12292 exec_control &= ~CPU_BASED_TPR_SHADOW;
12293 exec_control |= vmcs12->cpu_based_vm_exec_control;
12294
12295 /*
12296 * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if
12297 * nested_get_vmcs12_pages can't fix it up, the illegal value
12298 * will result in a VM entry failure.
12299 */
12300 if (exec_control & CPU_BASED_TPR_SHADOW) {
12301 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
12302 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
12303 } else {
12304#ifdef CONFIG_X86_64
12305 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
12306 CPU_BASED_CR8_STORE_EXITING;
12307#endif
12308 }
12309
12310 /*
12311 * A vmexit (to either L1 hypervisor or L0 userspace) is always needed
12312 * for I/O port accesses.
12313 */
12314 exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
12315 exec_control |= CPU_BASED_UNCOND_IO_EXITING;
12316
12317 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
12318
12319 /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
12320 * bitwise-or of what L1 wants to trap for L2, and what we want to
12321 * trap. Note that CR0.TS also needs updating - we do this later.
12322 */
12323 update_exception_bitmap(vcpu);
12324 vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
12325 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
12326
12327 /* L2->L1 exit controls are emulated - the hardware exit is to L0 so
12328 * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
12329 * bits are further modified by vmx_set_efer() below.
12330 */
12331 vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
12332
12333 /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
12334 * emulated by vmx_set_efer(), below.
12335 */
12336 vm_entry_controls_init(vmx,
12337 (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
12338 ~VM_ENTRY_IA32E_MODE) |
12339 (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
12340
12341 if (vmx->nested.nested_run_pending &&
12342 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
12343 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
12344 vcpu->arch.pat = vmcs12->guest_ia32_pat;
12345 } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
12346 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
12347 }
12348
12349 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
12350
12351 if (kvm_has_tsc_control)
12352 decache_tsc_multiplier(vmx);
12353
12354 if (enable_vpid) {
12355 /*
12356 * There is no direct mapping between vpid02 and vpid12, the
12357 * vpid02 is per-vCPU for L0 and reused while the value of
12358 * vpid12 is changed w/ one invvpid during nested vmentry.
12359 * The vpid12 is allocated by L1 for L2, so it will not
12360 * influence global bitmap(for vpid01 and vpid02 allocation)
12361 * even if spawn a lot of nested vCPUs.
12362 */
12363 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) {
12364 if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
12365 vmx->nested.last_vpid = vmcs12->virtual_processor_id;
12366 __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
12367 }
12368 } else {
12369 vmx_flush_tlb(vcpu, true);
12370 }
12371 }
12372
12373 if (enable_pml) {
12374 /*
12375 * Conceptually we want to copy the PML address and index from
12376 * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
12377 * since we always flush the log on each vmexit, this happens
12378 * to be equivalent to simply resetting the fields in vmcs02.
12379 */
12380 ASSERT(vmx->pml_pg);
12381 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
12382 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
12383 }
12384
12385 if (nested_cpu_has_ept(vmcs12)) {
12386 if (nested_ept_init_mmu_context(vcpu)) {
12387 *entry_failure_code = ENTRY_FAIL_DEFAULT;
12388 return 1;
12389 }
12390 } else if (nested_cpu_has2(vmcs12,
12391 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
12392 vmx_flush_tlb(vcpu, true);
12393 }
12394
12395 /*
12396 * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
12397 * bits which we consider mandatory enabled.
12398 * The CR0_READ_SHADOW is what L2 should have expected to read given
12399 * the specifications by L1; It's not enough to take
12400 * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
12401 * have more bits than L1 expected.
12402 */
12403 vmx_set_cr0(vcpu, vmcs12->guest_cr0);
12404 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
12405
12406 vmx_set_cr4(vcpu, vmcs12->guest_cr4);
12407 vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
12408
12409 if (vmx->nested.nested_run_pending &&
12410 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
12411 vcpu->arch.efer = vmcs12->guest_ia32_efer;
12412 else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
12413 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
12414 else
12415 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
12416 /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
12417 vmx_set_efer(vcpu, vcpu->arch.efer);
12418
12419 /*
12420 * Guest state is invalid and unrestricted guest is disabled,
12421 * which means L1 attempted VMEntry to L2 with invalid state.
12422 * Fail the VMEntry.
12423 */
12424 if (vmx->emulation_required) {
12425 *entry_failure_code = ENTRY_FAIL_DEFAULT;
12426 return 1;
12427 }
12428
12429 /* Shadow page tables on either EPT or shadow page tables. */
12430 if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
12431 entry_failure_code))
12432 return 1;
12433
12434 if (!enable_ept)
12435 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
12436
12437 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
12438 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
12439 return 0;
12440}
12441
12442static int nested_vmx_check_nmi_controls(struct vmcs12 *vmcs12)
12443{
12444 if (!nested_cpu_has_nmi_exiting(vmcs12) &&
12445 nested_cpu_has_virtual_nmis(vmcs12))
12446 return -EINVAL;
12447
12448 if (!nested_cpu_has_virtual_nmis(vmcs12) &&
12449 nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING))
12450 return -EINVAL;
12451
12452 return 0;
12453}
12454
12455static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12456{
12457 struct vcpu_vmx *vmx = to_vmx(vcpu);
12458
12459 if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
12460 vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT)
12461 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12462
12463 if (nested_cpu_has_vpid(vmcs12) && !vmcs12->virtual_processor_id)
12464 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12465
12466 if (nested_vmx_check_io_bitmap_controls(vcpu, vmcs12))
12467 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12468
12469 if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12))
12470 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12471
12472 if (nested_vmx_check_apic_access_controls(vcpu, vmcs12))
12473 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12474
12475 if (nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12))
12476 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12477
12478 if (nested_vmx_check_apicv_controls(vcpu, vmcs12))
12479 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12480
12481 if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12))
12482 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12483
12484 if (nested_vmx_check_pml_controls(vcpu, vmcs12))
12485 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12486
12487 if (nested_vmx_check_shadow_vmcs_controls(vcpu, vmcs12))
12488 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12489
12490 if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
12491 vmx->nested.msrs.procbased_ctls_low,
12492 vmx->nested.msrs.procbased_ctls_high) ||
12493 (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
12494 !vmx_control_verify(vmcs12->secondary_vm_exec_control,
12495 vmx->nested.msrs.secondary_ctls_low,
12496 vmx->nested.msrs.secondary_ctls_high)) ||
12497 !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
12498 vmx->nested.msrs.pinbased_ctls_low,
12499 vmx->nested.msrs.pinbased_ctls_high) ||
12500 !vmx_control_verify(vmcs12->vm_exit_controls,
12501 vmx->nested.msrs.exit_ctls_low,
12502 vmx->nested.msrs.exit_ctls_high) ||
12503 !vmx_control_verify(vmcs12->vm_entry_controls,
12504 vmx->nested.msrs.entry_ctls_low,
12505 vmx->nested.msrs.entry_ctls_high))
12506 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12507
12508 if (nested_vmx_check_nmi_controls(vmcs12))
12509 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12510
12511 if (nested_cpu_has_vmfunc(vmcs12)) {
12512 if (vmcs12->vm_function_control &
12513 ~vmx->nested.msrs.vmfunc_controls)
12514 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12515
12516 if (nested_cpu_has_eptp_switching(vmcs12)) {
12517 if (!nested_cpu_has_ept(vmcs12) ||
12518 !page_address_valid(vcpu, vmcs12->eptp_list_address))
12519 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12520 }
12521 }
12522
12523 if (vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu))
12524 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12525
12526 if (!nested_host_cr0_valid(vcpu, vmcs12->host_cr0) ||
12527 !nested_host_cr4_valid(vcpu, vmcs12->host_cr4) ||
12528 !nested_cr3_valid(vcpu, vmcs12->host_cr3))
12529 return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
12530
12531 /*
12532 * From the Intel SDM, volume 3:
12533 * Fields relevant to VM-entry event injection must be set properly.
12534 * These fields are the VM-entry interruption-information field, the
12535 * VM-entry exception error code, and the VM-entry instruction length.
12536 */
12537 if (vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) {
12538 u32 intr_info = vmcs12->vm_entry_intr_info_field;
12539 u8 vector = intr_info & INTR_INFO_VECTOR_MASK;
12540 u32 intr_type = intr_info & INTR_INFO_INTR_TYPE_MASK;
12541 bool has_error_code = intr_info & INTR_INFO_DELIVER_CODE_MASK;
12542 bool should_have_error_code;
12543 bool urg = nested_cpu_has2(vmcs12,
12544 SECONDARY_EXEC_UNRESTRICTED_GUEST);
12545 bool prot_mode = !urg || vmcs12->guest_cr0 & X86_CR0_PE;
12546
12547 /* VM-entry interruption-info field: interruption type */
12548 if (intr_type == INTR_TYPE_RESERVED ||
12549 (intr_type == INTR_TYPE_OTHER_EVENT &&
12550 !nested_cpu_supports_monitor_trap_flag(vcpu)))
12551 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12552
12553 /* VM-entry interruption-info field: vector */
12554 if ((intr_type == INTR_TYPE_NMI_INTR && vector != NMI_VECTOR) ||
12555 (intr_type == INTR_TYPE_HARD_EXCEPTION && vector > 31) ||
12556 (intr_type == INTR_TYPE_OTHER_EVENT && vector != 0))
12557 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12558
12559 /* VM-entry interruption-info field: deliver error code */
12560 should_have_error_code =
12561 intr_type == INTR_TYPE_HARD_EXCEPTION && prot_mode &&
12562 x86_exception_has_error_code(vector);
12563 if (has_error_code != should_have_error_code)
12564 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12565
12566 /* VM-entry exception error code */
12567 if (has_error_code &&
12568 vmcs12->vm_entry_exception_error_code & GENMASK(31, 16))
12569 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12570
12571 /* VM-entry interruption-info field: reserved bits */
12572 if (intr_info & INTR_INFO_RESVD_BITS_MASK)
12573 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12574
12575 /* VM-entry instruction length */
12576 switch (intr_type) {
12577 case INTR_TYPE_SOFT_EXCEPTION:
12578 case INTR_TYPE_SOFT_INTR:
12579 case INTR_TYPE_PRIV_SW_EXCEPTION:
12580 if ((vmcs12->vm_entry_instruction_len > 15) ||
12581 (vmcs12->vm_entry_instruction_len == 0 &&
12582 !nested_cpu_has_zero_length_injection(vcpu)))
12583 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12584 }
12585 }
12586
12587 return 0;
12588}
12589
12590static int nested_vmx_check_vmcs_link_ptr(struct kvm_vcpu *vcpu,
12591 struct vmcs12 *vmcs12)
12592{
12593 int r;
12594 struct page *page;
12595 struct vmcs12 *shadow;
12596
12597 if (vmcs12->vmcs_link_pointer == -1ull)
12598 return 0;
12599
12600 if (!page_address_valid(vcpu, vmcs12->vmcs_link_pointer))
12601 return -EINVAL;
12602
12603 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->vmcs_link_pointer);
12604 if (is_error_page(page))
12605 return -EINVAL;
12606
12607 r = 0;
12608 shadow = kmap(page);
12609 if (shadow->hdr.revision_id != VMCS12_REVISION ||
12610 shadow->hdr.shadow_vmcs != nested_cpu_has_shadow_vmcs(vmcs12))
12611 r = -EINVAL;
12612 kunmap(page);
12613 kvm_release_page_clean(page);
12614 return r;
12615}
12616
12617static int check_vmentry_postreqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12618 u32 *exit_qual)
12619{
12620 bool ia32e;
12621
12622 *exit_qual = ENTRY_FAIL_DEFAULT;
12623
12624 if (!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0) ||
12625 !nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4))
12626 return 1;
12627
12628 if (nested_vmx_check_vmcs_link_ptr(vcpu, vmcs12)) {
12629 *exit_qual = ENTRY_FAIL_VMCS_LINK_PTR;
12630 return 1;
12631 }
12632
12633 /*
12634 * If the load IA32_EFER VM-entry control is 1, the following checks
12635 * are performed on the field for the IA32_EFER MSR:
12636 * - Bits reserved in the IA32_EFER MSR must be 0.
12637 * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
12638 * the IA-32e mode guest VM-exit control. It must also be identical
12639 * to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
12640 * CR0.PG) is 1.
12641 */
12642 if (to_vmx(vcpu)->nested.nested_run_pending &&
12643 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
12644 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
12645 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
12646 ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
12647 ((vmcs12->guest_cr0 & X86_CR0_PG) &&
12648 ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME)))
12649 return 1;
12650 }
12651
12652 /*
12653 * If the load IA32_EFER VM-exit control is 1, bits reserved in the
12654 * IA32_EFER MSR must be 0 in the field for that register. In addition,
12655 * the values of the LMA and LME bits in the field must each be that of
12656 * the host address-space size VM-exit control.
12657 */
12658 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
12659 ia32e = (vmcs12->vm_exit_controls &
12660 VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
12661 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
12662 ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
12663 ia32e != !!(vmcs12->host_ia32_efer & EFER_LME))
12664 return 1;
12665 }
12666
12667 if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS) &&
12668 (is_noncanonical_address(vmcs12->guest_bndcfgs & PAGE_MASK, vcpu) ||
12669 (vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD)))
12670 return 1;
12671
12672 return 0;
12673}
12674
12675/*
12676 * If exit_qual is NULL, this is being called from state restore (either RSM
12677 * or KVM_SET_NESTED_STATE). Otherwise it's called from vmlaunch/vmresume.
12678 */
12679static int enter_vmx_non_root_mode(struct kvm_vcpu *vcpu, u32 *exit_qual)
12680{
12681 struct vcpu_vmx *vmx = to_vmx(vcpu);
12682 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
12683 bool from_vmentry = !!exit_qual;
12684 u32 dummy_exit_qual;
12685 bool evaluate_pending_interrupts;
12686 int r = 0;
12687
12688 evaluate_pending_interrupts = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
12689 (CPU_BASED_VIRTUAL_INTR_PENDING | CPU_BASED_VIRTUAL_NMI_PENDING);
12690 if (likely(!evaluate_pending_interrupts) && kvm_vcpu_apicv_active(vcpu))
12691 evaluate_pending_interrupts |= vmx_has_apicv_interrupt(vcpu);
12692
12693 enter_guest_mode(vcpu);
12694
12695 if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
12696 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
12697 if (kvm_mpx_supported() &&
12698 !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
12699 vmx->nested.vmcs01_guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
12700
12701 vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02);
12702 vmx_segment_cache_clear(vmx);
12703
12704 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
12705 vcpu->arch.tsc_offset += vmcs12->tsc_offset;
12706
12707 r = EXIT_REASON_INVALID_STATE;
12708 if (prepare_vmcs02(vcpu, vmcs12, from_vmentry ? exit_qual : &dummy_exit_qual))
12709 goto fail;
12710
12711 if (from_vmentry) {
12712 nested_get_vmcs12_pages(vcpu);
12713
12714 r = EXIT_REASON_MSR_LOAD_FAIL;
12715 *exit_qual = nested_vmx_load_msr(vcpu,
12716 vmcs12->vm_entry_msr_load_addr,
12717 vmcs12->vm_entry_msr_load_count);
12718 if (*exit_qual)
12719 goto fail;
12720 } else {
12721 /*
12722 * The MMU is not initialized to point at the right entities yet and
12723 * "get pages" would need to read data from the guest (i.e. we will
12724 * need to perform gpa to hpa translation). Request a call
12725 * to nested_get_vmcs12_pages before the next VM-entry. The MSRs
12726 * have already been set at vmentry time and should not be reset.
12727 */
12728 kvm_make_request(KVM_REQ_GET_VMCS12_PAGES, vcpu);
12729 }
12730
12731 /*
12732 * If L1 had a pending IRQ/NMI until it executed
12733 * VMLAUNCH/VMRESUME which wasn't delivered because it was
12734 * disallowed (e.g. interrupts disabled), L0 needs to
12735 * evaluate if this pending event should cause an exit from L2
12736 * to L1 or delivered directly to L2 (e.g. In case L1 don't
12737 * intercept EXTERNAL_INTERRUPT).
12738 *
12739 * Usually this would be handled by the processor noticing an
12740 * IRQ/NMI window request, or checking RVI during evaluation of
12741 * pending virtual interrupts. However, this setting was done
12742 * on VMCS01 and now VMCS02 is active instead. Thus, we force L0
12743 * to perform pending event evaluation by requesting a KVM_REQ_EVENT.
12744 */
12745 if (unlikely(evaluate_pending_interrupts))
12746 kvm_make_request(KVM_REQ_EVENT, vcpu);
12747
12748 /*
12749 * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
12750 * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
12751 * returned as far as L1 is concerned. It will only return (and set
12752 * the success flag) when L2 exits (see nested_vmx_vmexit()).
12753 */
12754 return 0;
12755
12756fail:
12757 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
12758 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
12759 leave_guest_mode(vcpu);
12760 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
12761 return r;
12762}
12763
12764/*
12765 * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
12766 * for running an L2 nested guest.
12767 */
12768static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
12769{
12770 struct vmcs12 *vmcs12;
12771 struct vcpu_vmx *vmx = to_vmx(vcpu);
12772 u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
12773 u32 exit_qual;
12774 int ret;
12775
12776 if (!nested_vmx_check_permission(vcpu))
12777 return 1;
12778
12779 if (!nested_vmx_check_vmcs12(vcpu))
12780 goto out;
12781
12782 vmcs12 = get_vmcs12(vcpu);
12783
12784 /*
12785 * Can't VMLAUNCH or VMRESUME a shadow VMCS. Despite the fact
12786 * that there *is* a valid VMCS pointer, RFLAGS.CF is set
12787 * rather than RFLAGS.ZF, and no error number is stored to the
12788 * VM-instruction error field.
12789 */
12790 if (vmcs12->hdr.shadow_vmcs) {
12791 nested_vmx_failInvalid(vcpu);
12792 goto out;
12793 }
12794
12795 if (enable_shadow_vmcs)
12796 copy_shadow_to_vmcs12(vmx);
12797
12798 /*
12799 * The nested entry process starts with enforcing various prerequisites
12800 * on vmcs12 as required by the Intel SDM, and act appropriately when
12801 * they fail: As the SDM explains, some conditions should cause the
12802 * instruction to fail, while others will cause the instruction to seem
12803 * to succeed, but return an EXIT_REASON_INVALID_STATE.
12804 * To speed up the normal (success) code path, we should avoid checking
12805 * for misconfigurations which will anyway be caught by the processor
12806 * when using the merged vmcs02.
12807 */
12808 if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS) {
12809 nested_vmx_failValid(vcpu,
12810 VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
12811 goto out;
12812 }
12813
12814 if (vmcs12->launch_state == launch) {
12815 nested_vmx_failValid(vcpu,
12816 launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
12817 : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
12818 goto out;
12819 }
12820
12821 ret = check_vmentry_prereqs(vcpu, vmcs12);
12822 if (ret) {
12823 nested_vmx_failValid(vcpu, ret);
12824 goto out;
12825 }
12826
12827 /*
12828 * After this point, the trap flag no longer triggers a singlestep trap
12829 * on the vm entry instructions; don't call kvm_skip_emulated_instruction.
12830 * This is not 100% correct; for performance reasons, we delegate most
12831 * of the checks on host state to the processor. If those fail,
12832 * the singlestep trap is missed.
12833 */
12834 skip_emulated_instruction(vcpu);
12835
12836 ret = check_vmentry_postreqs(vcpu, vmcs12, &exit_qual);
12837 if (ret) {
12838 nested_vmx_entry_failure(vcpu, vmcs12,
12839 EXIT_REASON_INVALID_STATE, exit_qual);
12840 return 1;
12841 }
12842
12843 /*
12844 * We're finally done with prerequisite checking, and can start with
12845 * the nested entry.
12846 */
12847
12848 vmx->nested.nested_run_pending = 1;
12849 ret = enter_vmx_non_root_mode(vcpu, &exit_qual);
12850 if (ret) {
12851 nested_vmx_entry_failure(vcpu, vmcs12, ret, exit_qual);
12852 vmx->nested.nested_run_pending = 0;
12853 return 1;
12854 }
12855
12856 /* Hide L1D cache contents from the nested guest. */
12857 vmx->vcpu.arch.l1tf_flush_l1d = true;
12858
12859 /*
12860 * Must happen outside of enter_vmx_non_root_mode() as it will
12861 * also be used as part of restoring nVMX state for
12862 * snapshot restore (migration).
12863 *
12864 * In this flow, it is assumed that vmcs12 cache was
12865 * trasferred as part of captured nVMX state and should
12866 * therefore not be read from guest memory (which may not
12867 * exist on destination host yet).
12868 */
12869 nested_cache_shadow_vmcs12(vcpu, vmcs12);
12870
12871 /*
12872 * If we're entering a halted L2 vcpu and the L2 vcpu won't be
12873 * awakened by event injection or by an NMI-window VM-exit or
12874 * by an interrupt-window VM-exit, halt the vcpu.
12875 */
12876 if ((vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT) &&
12877 !(vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) &&
12878 !(vmcs12->cpu_based_vm_exec_control & CPU_BASED_VIRTUAL_NMI_PENDING) &&
12879 !((vmcs12->cpu_based_vm_exec_control & CPU_BASED_VIRTUAL_INTR_PENDING) &&
12880 (vmcs12->guest_rflags & X86_EFLAGS_IF))) {
12881 vmx->nested.nested_run_pending = 0;
12882 return kvm_vcpu_halt(vcpu);
12883 }
12884 return 1;
12885
12886out:
12887 return kvm_skip_emulated_instruction(vcpu);
12888}
12889
12890/*
12891 * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
12892 * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
12893 * This function returns the new value we should put in vmcs12.guest_cr0.
12894 * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
12895 * 1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
12896 * available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
12897 * didn't trap the bit, because if L1 did, so would L0).
12898 * 2. Bits that L1 asked to trap (and therefore L0 also did) could not have
12899 * been modified by L2, and L1 knows it. So just leave the old value of
12900 * the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
12901 * isn't relevant, because if L0 traps this bit it can set it to anything.
12902 * 3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
12903 * changed these bits, and therefore they need to be updated, but L0
12904 * didn't necessarily allow them to be changed in GUEST_CR0 - and rather
12905 * put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
12906 */
12907static inline unsigned long
12908vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12909{
12910 return
12911 /*1*/ (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
12912 /*2*/ (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
12913 /*3*/ (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
12914 vcpu->arch.cr0_guest_owned_bits));
12915}
12916
12917static inline unsigned long
12918vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12919{
12920 return
12921 /*1*/ (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
12922 /*2*/ (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
12923 /*3*/ (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
12924 vcpu->arch.cr4_guest_owned_bits));
12925}
12926
12927static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
12928 struct vmcs12 *vmcs12)
12929{
12930 u32 idt_vectoring;
12931 unsigned int nr;
12932
12933 if (vcpu->arch.exception.injected) {
12934 nr = vcpu->arch.exception.nr;
12935 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
12936
12937 if (kvm_exception_is_soft(nr)) {
12938 vmcs12->vm_exit_instruction_len =
12939 vcpu->arch.event_exit_inst_len;
12940 idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
12941 } else
12942 idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
12943
12944 if (vcpu->arch.exception.has_error_code) {
12945 idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
12946 vmcs12->idt_vectoring_error_code =
12947 vcpu->arch.exception.error_code;
12948 }
12949
12950 vmcs12->idt_vectoring_info_field = idt_vectoring;
12951 } else if (vcpu->arch.nmi_injected) {
12952 vmcs12->idt_vectoring_info_field =
12953 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
12954 } else if (vcpu->arch.interrupt.injected) {
12955 nr = vcpu->arch.interrupt.nr;
12956 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
12957
12958 if (vcpu->arch.interrupt.soft) {
12959 idt_vectoring |= INTR_TYPE_SOFT_INTR;
12960 vmcs12->vm_entry_instruction_len =
12961 vcpu->arch.event_exit_inst_len;
12962 } else
12963 idt_vectoring |= INTR_TYPE_EXT_INTR;
12964
12965 vmcs12->idt_vectoring_info_field = idt_vectoring;
12966 }
12967}
12968
12969static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
12970{
12971 struct vcpu_vmx *vmx = to_vmx(vcpu);
12972 unsigned long exit_qual;
12973 bool block_nested_events =
12974 vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu);
12975
12976 if (vcpu->arch.exception.pending &&
12977 nested_vmx_check_exception(vcpu, &exit_qual)) {
12978 if (block_nested_events)
12979 return -EBUSY;
12980 nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
12981 return 0;
12982 }
12983
12984 if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
12985 vmx->nested.preemption_timer_expired) {
12986 if (block_nested_events)
12987 return -EBUSY;
12988 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
12989 return 0;
12990 }
12991
12992 if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
12993 if (block_nested_events)
12994 return -EBUSY;
12995 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
12996 NMI_VECTOR | INTR_TYPE_NMI_INTR |
12997 INTR_INFO_VALID_MASK, 0);
12998 /*
12999 * The NMI-triggered VM exit counts as injection:
13000 * clear this one and block further NMIs.
13001 */
13002 vcpu->arch.nmi_pending = 0;
13003 vmx_set_nmi_mask(vcpu, true);
13004 return 0;
13005 }
13006
13007 if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
13008 nested_exit_on_intr(vcpu)) {
13009 if (block_nested_events)
13010 return -EBUSY;
13011 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
13012 return 0;
13013 }
13014
13015 vmx_complete_nested_posted_interrupt(vcpu);
13016 return 0;
13017}
13018
13019static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
13020{
13021 to_vmx(vcpu)->req_immediate_exit = true;
13022}
13023
13024static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
13025{
13026 ktime_t remaining =
13027 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
13028 u64 value;
13029
13030 if (ktime_to_ns(remaining) <= 0)
13031 return 0;
13032
13033 value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
13034 do_div(value, 1000000);
13035 return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
13036}
13037
13038/*
13039 * Update the guest state fields of vmcs12 to reflect changes that
13040 * occurred while L2 was running. (The "IA-32e mode guest" bit of the
13041 * VM-entry controls is also updated, since this is really a guest
13042 * state bit.)
13043 */
13044static void sync_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
13045{
13046 vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
13047 vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
13048
13049 vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
13050 vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
13051 vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
13052
13053 vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
13054 vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
13055 vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
13056 vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
13057 vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
13058 vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
13059 vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
13060 vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
13061 vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
13062 vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
13063 vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
13064 vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
13065 vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
13066 vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
13067 vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
13068 vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
13069 vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
13070 vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
13071 vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
13072 vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
13073 vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
13074 vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
13075 vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
13076 vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
13077 vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
13078 vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
13079 vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
13080 vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
13081 vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
13082 vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
13083 vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
13084 vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
13085 vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
13086 vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
13087 vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
13088 vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
13089
13090 vmcs12->guest_interruptibility_info =
13091 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
13092 vmcs12->guest_pending_dbg_exceptions =
13093 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
13094 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
13095 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
13096 else
13097 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
13098
13099 if (nested_cpu_has_preemption_timer(vmcs12)) {
13100 if (vmcs12->vm_exit_controls &
13101 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
13102 vmcs12->vmx_preemption_timer_value =
13103 vmx_get_preemption_timer_value(vcpu);
13104 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
13105 }
13106
13107 /*
13108 * In some cases (usually, nested EPT), L2 is allowed to change its
13109 * own CR3 without exiting. If it has changed it, we must keep it.
13110 * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
13111 * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
13112 *
13113 * Additionally, restore L2's PDPTR to vmcs12.
13114 */
13115 if (enable_ept) {
13116 vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
13117 vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
13118 vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
13119 vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
13120 vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
13121 }
13122
13123 vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
13124
13125 if (nested_cpu_has_vid(vmcs12))
13126 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
13127
13128 vmcs12->vm_entry_controls =
13129 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
13130 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
13131
13132 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
13133 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
13134 vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
13135 }
13136
13137 /* TODO: These cannot have changed unless we have MSR bitmaps and
13138 * the relevant bit asks not to trap the change */
13139 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
13140 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
13141 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
13142 vmcs12->guest_ia32_efer = vcpu->arch.efer;
13143 vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
13144 vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
13145 vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
13146 if (kvm_mpx_supported())
13147 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
13148}
13149
13150/*
13151 * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
13152 * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
13153 * and this function updates it to reflect the changes to the guest state while
13154 * L2 was running (and perhaps made some exits which were handled directly by L0
13155 * without going back to L1), and to reflect the exit reason.
13156 * Note that we do not have to copy here all VMCS fields, just those that
13157 * could have changed by the L2 guest or the exit - i.e., the guest-state and
13158 * exit-information fields only. Other fields are modified by L1 with VMWRITE,
13159 * which already writes to vmcs12 directly.
13160 */
13161static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
13162 u32 exit_reason, u32 exit_intr_info,
13163 unsigned long exit_qualification)
13164{
13165 /* update guest state fields: */
13166 sync_vmcs12(vcpu, vmcs12);
13167
13168 /* update exit information fields: */
13169
13170 vmcs12->vm_exit_reason = exit_reason;
13171 vmcs12->exit_qualification = exit_qualification;
13172 vmcs12->vm_exit_intr_info = exit_intr_info;
13173
13174 vmcs12->idt_vectoring_info_field = 0;
13175 vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
13176 vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
13177
13178 if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
13179 vmcs12->launch_state = 1;
13180
13181 /* vm_entry_intr_info_field is cleared on exit. Emulate this
13182 * instead of reading the real value. */
13183 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
13184
13185 /*
13186 * Transfer the event that L0 or L1 may wanted to inject into
13187 * L2 to IDT_VECTORING_INFO_FIELD.
13188 */
13189 vmcs12_save_pending_event(vcpu, vmcs12);
13190 }
13191
13192 /*
13193 * Drop what we picked up for L2 via vmx_complete_interrupts. It is
13194 * preserved above and would only end up incorrectly in L1.
13195 */
13196 vcpu->arch.nmi_injected = false;
13197 kvm_clear_exception_queue(vcpu);
13198 kvm_clear_interrupt_queue(vcpu);
13199}
13200
13201/*
13202 * A part of what we need to when the nested L2 guest exits and we want to
13203 * run its L1 parent, is to reset L1's guest state to the host state specified
13204 * in vmcs12.
13205 * This function is to be called not only on normal nested exit, but also on
13206 * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
13207 * Failures During or After Loading Guest State").
13208 * This function should be called when the active VMCS is L1's (vmcs01).
13209 */
13210static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
13211 struct vmcs12 *vmcs12)
13212{
13213 struct kvm_segment seg;
13214 u32 entry_failure_code;
13215
13216 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
13217 vcpu->arch.efer = vmcs12->host_ia32_efer;
13218 else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
13219 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
13220 else
13221 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
13222 vmx_set_efer(vcpu, vcpu->arch.efer);
13223
13224 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
13225 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
13226 vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
13227 /*
13228 * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
13229 * actually changed, because vmx_set_cr0 refers to efer set above.
13230 *
13231 * CR0_GUEST_HOST_MASK is already set in the original vmcs01
13232 * (KVM doesn't change it);
13233 */
13234 vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
13235 vmx_set_cr0(vcpu, vmcs12->host_cr0);
13236
13237 /* Same as above - no reason to call set_cr4_guest_host_mask(). */
13238 vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
13239 vmx_set_cr4(vcpu, vmcs12->host_cr4);
13240
13241 nested_ept_uninit_mmu_context(vcpu);
13242
13243 /*
13244 * Only PDPTE load can fail as the value of cr3 was checked on entry and
13245 * couldn't have changed.
13246 */
13247 if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
13248 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
13249
13250 if (!enable_ept)
13251 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
13252
13253 /*
13254 * If vmcs01 don't use VPID, CPU flushes TLB on every
13255 * VMEntry/VMExit. Thus, no need to flush TLB.
13256 *
13257 * If vmcs12 uses VPID, TLB entries populated by L2 are
13258 * tagged with vmx->nested.vpid02 while L1 entries are tagged
13259 * with vmx->vpid. Thus, no need to flush TLB.
13260 *
13261 * Therefore, flush TLB only in case vmcs01 uses VPID and
13262 * vmcs12 don't use VPID as in this case L1 & L2 TLB entries
13263 * are both tagged with vmx->vpid.
13264 */
13265 if (enable_vpid &&
13266 !(nested_cpu_has_vpid(vmcs12) && to_vmx(vcpu)->nested.vpid02)) {
13267 vmx_flush_tlb(vcpu, true);
13268 }
13269
13270 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
13271 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
13272 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
13273 vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
13274 vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
13275 vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
13276 vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
13277
13278 /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1. */
13279 if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
13280 vmcs_write64(GUEST_BNDCFGS, 0);
13281
13282 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
13283 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
13284 vcpu->arch.pat = vmcs12->host_ia32_pat;
13285 }
13286 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
13287 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
13288 vmcs12->host_ia32_perf_global_ctrl);
13289
13290 /* Set L1 segment info according to Intel SDM
13291 27.5.2 Loading Host Segment and Descriptor-Table Registers */
13292 seg = (struct kvm_segment) {
13293 .base = 0,
13294 .limit = 0xFFFFFFFF,
13295 .selector = vmcs12->host_cs_selector,
13296 .type = 11,
13297 .present = 1,
13298 .s = 1,
13299 .g = 1
13300 };
13301 if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
13302 seg.l = 1;
13303 else
13304 seg.db = 1;
13305 vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
13306 seg = (struct kvm_segment) {
13307 .base = 0,
13308 .limit = 0xFFFFFFFF,
13309 .type = 3,
13310 .present = 1,
13311 .s = 1,
13312 .db = 1,
13313 .g = 1
13314 };
13315 seg.selector = vmcs12->host_ds_selector;
13316 vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
13317 seg.selector = vmcs12->host_es_selector;
13318 vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
13319 seg.selector = vmcs12->host_ss_selector;
13320 vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
13321 seg.selector = vmcs12->host_fs_selector;
13322 seg.base = vmcs12->host_fs_base;
13323 vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
13324 seg.selector = vmcs12->host_gs_selector;
13325 seg.base = vmcs12->host_gs_base;
13326 vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
13327 seg = (struct kvm_segment) {
13328 .base = vmcs12->host_tr_base,
13329 .limit = 0x67,
13330 .selector = vmcs12->host_tr_selector,
13331 .type = 11,
13332 .present = 1
13333 };
13334 vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
13335
13336 kvm_set_dr(vcpu, 7, 0x400);
13337 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
13338
13339 if (cpu_has_vmx_msr_bitmap())
13340 vmx_update_msr_bitmap(vcpu);
13341
13342 if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
13343 vmcs12->vm_exit_msr_load_count))
13344 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
13345}
13346
13347static inline u64 nested_vmx_get_vmcs01_guest_efer(struct vcpu_vmx *vmx)
13348{
13349 struct shared_msr_entry *efer_msr;
13350 unsigned int i;
13351
13352 if (vm_entry_controls_get(vmx) & VM_ENTRY_LOAD_IA32_EFER)
13353 return vmcs_read64(GUEST_IA32_EFER);
13354
13355 if (cpu_has_load_ia32_efer)
13356 return host_efer;
13357
13358 for (i = 0; i < vmx->msr_autoload.guest.nr; ++i) {
13359 if (vmx->msr_autoload.guest.val[i].index == MSR_EFER)
13360 return vmx->msr_autoload.guest.val[i].value;
13361 }
13362
13363 efer_msr = find_msr_entry(vmx, MSR_EFER);
13364 if (efer_msr)
13365 return efer_msr->data;
13366
13367 return host_efer;
13368}
13369
13370static void nested_vmx_restore_host_state(struct kvm_vcpu *vcpu)
13371{
13372 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
13373 struct vcpu_vmx *vmx = to_vmx(vcpu);
13374 struct vmx_msr_entry g, h;
13375 struct msr_data msr;
13376 gpa_t gpa;
13377 u32 i, j;
13378
13379 vcpu->arch.pat = vmcs_read64(GUEST_IA32_PAT);
13380
13381 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
13382 /*
13383 * L1's host DR7 is lost if KVM_GUESTDBG_USE_HW_BP is set
13384 * as vmcs01.GUEST_DR7 contains a userspace defined value
13385 * and vcpu->arch.dr7 is not squirreled away before the
13386 * nested VMENTER (not worth adding a variable in nested_vmx).
13387 */
13388 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
13389 kvm_set_dr(vcpu, 7, DR7_FIXED_1);
13390 else
13391 WARN_ON(kvm_set_dr(vcpu, 7, vmcs_readl(GUEST_DR7)));
13392 }
13393
13394 /*
13395 * Note that calling vmx_set_{efer,cr0,cr4} is important as they
13396 * handle a variety of side effects to KVM's software model.
13397 */
13398 vmx_set_efer(vcpu, nested_vmx_get_vmcs01_guest_efer(vmx));
13399
13400 vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
13401 vmx_set_cr0(vcpu, vmcs_readl(CR0_READ_SHADOW));
13402
13403 vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
13404 vmx_set_cr4(vcpu, vmcs_readl(CR4_READ_SHADOW));
13405
13406 nested_ept_uninit_mmu_context(vcpu);
13407 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
13408 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
13409
13410 /*
13411 * Use ept_save_pdptrs(vcpu) to load the MMU's cached PDPTRs
13412 * from vmcs01 (if necessary). The PDPTRs are not loaded on
13413 * VMFail, like everything else we just need to ensure our
13414 * software model is up-to-date.
13415 */
13416 ept_save_pdptrs(vcpu);
13417
13418 kvm_mmu_reset_context(vcpu);
13419
13420 if (cpu_has_vmx_msr_bitmap())
13421 vmx_update_msr_bitmap(vcpu);
13422
13423 /*
13424 * This nasty bit of open coding is a compromise between blindly
13425 * loading L1's MSRs using the exit load lists (incorrect emulation
13426 * of VMFail), leaving the nested VM's MSRs in the software model
13427 * (incorrect behavior) and snapshotting the modified MSRs (too
13428 * expensive since the lists are unbound by hardware). For each
13429 * MSR that was (prematurely) loaded from the nested VMEntry load
13430 * list, reload it from the exit load list if it exists and differs
13431 * from the guest value. The intent is to stuff host state as
13432 * silently as possible, not to fully process the exit load list.
13433 */
13434 msr.host_initiated = false;
13435 for (i = 0; i < vmcs12->vm_entry_msr_load_count; i++) {
13436 gpa = vmcs12->vm_entry_msr_load_addr + (i * sizeof(g));
13437 if (kvm_vcpu_read_guest(vcpu, gpa, &g, sizeof(g))) {
13438 pr_debug_ratelimited(
13439 "%s read MSR index failed (%u, 0x%08llx)\n",
13440 __func__, i, gpa);
13441 goto vmabort;
13442 }
13443
13444 for (j = 0; j < vmcs12->vm_exit_msr_load_count; j++) {
13445 gpa = vmcs12->vm_exit_msr_load_addr + (j * sizeof(h));
13446 if (kvm_vcpu_read_guest(vcpu, gpa, &h, sizeof(h))) {
13447 pr_debug_ratelimited(
13448 "%s read MSR failed (%u, 0x%08llx)\n",
13449 __func__, j, gpa);
13450 goto vmabort;
13451 }
13452 if (h.index != g.index)
13453 continue;
13454 if (h.value == g.value)
13455 break;
13456
13457 if (nested_vmx_load_msr_check(vcpu, &h)) {
13458 pr_debug_ratelimited(
13459 "%s check failed (%u, 0x%x, 0x%x)\n",
13460 __func__, j, h.index, h.reserved);
13461 goto vmabort;
13462 }
13463
13464 msr.index = h.index;
13465 msr.data = h.value;
13466 if (kvm_set_msr(vcpu, &msr)) {
13467 pr_debug_ratelimited(
13468 "%s WRMSR failed (%u, 0x%x, 0x%llx)\n",
13469 __func__, j, h.index, h.value);
13470 goto vmabort;
13471 }
13472 }
13473 }
13474
13475 return;
13476
13477vmabort:
13478 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
13479}
13480
13481/*
13482 * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
13483 * and modify vmcs12 to make it see what it would expect to see there if
13484 * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
13485 */
13486static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
13487 u32 exit_intr_info,
13488 unsigned long exit_qualification)
13489{
13490 struct vcpu_vmx *vmx = to_vmx(vcpu);
13491 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
13492
13493 /* trying to cancel vmlaunch/vmresume is a bug */
13494 WARN_ON_ONCE(vmx->nested.nested_run_pending);
13495
13496 /*
13497 * The only expected VM-instruction error is "VM entry with
13498 * invalid control field(s)." Anything else indicates a
13499 * problem with L0.
13500 */
13501 WARN_ON_ONCE(vmx->fail && (vmcs_read32(VM_INSTRUCTION_ERROR) !=
13502 VMXERR_ENTRY_INVALID_CONTROL_FIELD));
13503
13504 leave_guest_mode(vcpu);
13505
13506 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
13507 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
13508
13509 if (likely(!vmx->fail)) {
13510 if (exit_reason == -1)
13511 sync_vmcs12(vcpu, vmcs12);
13512 else
13513 prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
13514 exit_qualification);
13515
13516 /*
13517 * Must happen outside of sync_vmcs12() as it will
13518 * also be used to capture vmcs12 cache as part of
13519 * capturing nVMX state for snapshot (migration).
13520 *
13521 * Otherwise, this flush will dirty guest memory at a
13522 * point it is already assumed by user-space to be
13523 * immutable.
13524 */
13525 nested_flush_cached_shadow_vmcs12(vcpu, vmcs12);
13526
13527 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
13528 vmcs12->vm_exit_msr_store_count))
13529 nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
13530 }
13531
13532 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
13533 vm_entry_controls_reset_shadow(vmx);
13534 vm_exit_controls_reset_shadow(vmx);
13535 vmx_segment_cache_clear(vmx);
13536
13537 /* Update any VMCS fields that might have changed while L2 ran */
13538 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
13539 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
13540 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
13541
13542 if (kvm_has_tsc_control)
13543 decache_tsc_multiplier(vmx);
13544
13545 if (vmx->nested.change_vmcs01_virtual_apic_mode) {
13546 vmx->nested.change_vmcs01_virtual_apic_mode = false;
13547 vmx_set_virtual_apic_mode(vcpu);
13548 } else if (!nested_cpu_has_ept(vmcs12) &&
13549 nested_cpu_has2(vmcs12,
13550 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
13551 vmx_flush_tlb(vcpu, true);
13552 }
13553
13554 /* This is needed for same reason as it was needed in prepare_vmcs02 */
13555 vmx->host_rsp = 0;
13556
13557 /* Unpin physical memory we referred to in vmcs02 */
13558 if (vmx->nested.apic_access_page) {
13559 kvm_release_page_dirty(vmx->nested.apic_access_page);
13560 vmx->nested.apic_access_page = NULL;
13561 }
13562 if (vmx->nested.virtual_apic_page) {
13563 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
13564 vmx->nested.virtual_apic_page = NULL;
13565 }
13566 if (vmx->nested.pi_desc_page) {
13567 kunmap(vmx->nested.pi_desc_page);
13568 kvm_release_page_dirty(vmx->nested.pi_desc_page);
13569 vmx->nested.pi_desc_page = NULL;
13570 vmx->nested.pi_desc = NULL;
13571 }
13572
13573 /*
13574 * We are now running in L2, mmu_notifier will force to reload the
13575 * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
13576 */
13577 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
13578
13579 if (enable_shadow_vmcs && exit_reason != -1)
13580 vmx->nested.sync_shadow_vmcs = true;
13581
13582 /* in case we halted in L2 */
13583 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
13584
13585 if (likely(!vmx->fail)) {
13586 /*
13587 * TODO: SDM says that with acknowledge interrupt on
13588 * exit, bit 31 of the VM-exit interrupt information
13589 * (valid interrupt) is always set to 1 on
13590 * EXIT_REASON_EXTERNAL_INTERRUPT, so we shouldn't
13591 * need kvm_cpu_has_interrupt(). See the commit
13592 * message for details.
13593 */
13594 if (nested_exit_intr_ack_set(vcpu) &&
13595 exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT &&
13596 kvm_cpu_has_interrupt(vcpu)) {
13597 int irq = kvm_cpu_get_interrupt(vcpu);
13598 WARN_ON(irq < 0);
13599 vmcs12->vm_exit_intr_info = irq |
13600 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
13601 }
13602
13603 if (exit_reason != -1)
13604 trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
13605 vmcs12->exit_qualification,
13606 vmcs12->idt_vectoring_info_field,
13607 vmcs12->vm_exit_intr_info,
13608 vmcs12->vm_exit_intr_error_code,
13609 KVM_ISA_VMX);
13610
13611 load_vmcs12_host_state(vcpu, vmcs12);
13612
13613 return;
13614 }
13615
13616 /*
13617 * After an early L2 VM-entry failure, we're now back
13618 * in L1 which thinks it just finished a VMLAUNCH or
13619 * VMRESUME instruction, so we need to set the failure
13620 * flag and the VM-instruction error field of the VMCS
13621 * accordingly.
13622 */
13623 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
13624
13625 /*
13626 * Restore L1's host state to KVM's software model. We're here
13627 * because a consistency check was caught by hardware, which
13628 * means some amount of guest state has been propagated to KVM's
13629 * model and needs to be unwound to the host's state.
13630 */
13631 nested_vmx_restore_host_state(vcpu);
13632
13633 /*
13634 * The emulated instruction was already skipped in
13635 * nested_vmx_run, but the updated RIP was never
13636 * written back to the vmcs01.
13637 */
13638 skip_emulated_instruction(vcpu);
13639 vmx->fail = 0;
13640}
13641
13642/*
13643 * Forcibly leave nested mode in order to be able to reset the VCPU later on.
13644 */
13645static void vmx_leave_nested(struct kvm_vcpu *vcpu)
13646{
13647 if (is_guest_mode(vcpu)) {
13648 to_vmx(vcpu)->nested.nested_run_pending = 0;
13649 nested_vmx_vmexit(vcpu, -1, 0, 0);
13650 }
13651 free_nested(to_vmx(vcpu));
13652}
13653
13654/*
13655 * L1's failure to enter L2 is a subset of a normal exit, as explained in
13656 * 23.7 "VM-entry failures during or after loading guest state" (this also
13657 * lists the acceptable exit-reason and exit-qualification parameters).
13658 * It should only be called before L2 actually succeeded to run, and when
13659 * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
13660 */
13661static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
13662 struct vmcs12 *vmcs12,
13663 u32 reason, unsigned long qualification)
13664{
13665 load_vmcs12_host_state(vcpu, vmcs12);
13666 vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
13667 vmcs12->exit_qualification = qualification;
13668 nested_vmx_succeed(vcpu);
13669 if (enable_shadow_vmcs)
13670 to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
13671}
13672
13673static int vmx_check_intercept(struct kvm_vcpu *vcpu,
13674 struct x86_instruction_info *info,
13675 enum x86_intercept_stage stage)
13676{
13677 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
13678 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
13679
13680 /*
13681 * RDPID causes #UD if disabled through secondary execution controls.
13682 * Because it is marked as EmulateOnUD, we need to intercept it here.
13683 */
13684 if (info->intercept == x86_intercept_rdtscp &&
13685 !nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
13686 ctxt->exception.vector = UD_VECTOR;
13687 ctxt->exception.error_code_valid = false;
13688 return X86EMUL_PROPAGATE_FAULT;
13689 }
13690
13691 /* TODO: check more intercepts... */
13692 return X86EMUL_CONTINUE;
13693}
13694
13695#ifdef CONFIG_X86_64
13696/* (a << shift) / divisor, return 1 if overflow otherwise 0 */
13697static inline int u64_shl_div_u64(u64 a, unsigned int shift,
13698 u64 divisor, u64 *result)
13699{
13700 u64 low = a << shift, high = a >> (64 - shift);
13701
13702 /* To avoid the overflow on divq */
13703 if (high >= divisor)
13704 return 1;
13705
13706 /* Low hold the result, high hold rem which is discarded */
13707 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
13708 "rm" (divisor), "0" (low), "1" (high));
13709 *result = low;
13710
13711 return 0;
13712}
13713
13714static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
13715{
13716 struct vcpu_vmx *vmx;
13717 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
13718
13719 if (kvm_mwait_in_guest(vcpu->kvm))
13720 return -EOPNOTSUPP;
13721
13722 vmx = to_vmx(vcpu);
13723 tscl = rdtsc();
13724 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
13725 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
13726 lapic_timer_advance_cycles = nsec_to_cycles(vcpu, lapic_timer_advance_ns);
13727
13728 if (delta_tsc > lapic_timer_advance_cycles)
13729 delta_tsc -= lapic_timer_advance_cycles;
13730 else
13731 delta_tsc = 0;
13732
13733 /* Convert to host delta tsc if tsc scaling is enabled */
13734 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
13735 u64_shl_div_u64(delta_tsc,
13736 kvm_tsc_scaling_ratio_frac_bits,
13737 vcpu->arch.tsc_scaling_ratio,
13738 &delta_tsc))
13739 return -ERANGE;
13740
13741 /*
13742 * If the delta tsc can't fit in the 32 bit after the multi shift,
13743 * we can't use the preemption timer.
13744 * It's possible that it fits on later vmentries, but checking
13745 * on every vmentry is costly so we just use an hrtimer.
13746 */
13747 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
13748 return -ERANGE;
13749
13750 vmx->hv_deadline_tsc = tscl + delta_tsc;
13751 return delta_tsc == 0;
13752}
13753
13754static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
13755{
13756 to_vmx(vcpu)->hv_deadline_tsc = -1;
13757}
13758#endif
13759
13760static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
13761{
13762 if (!kvm_pause_in_guest(vcpu->kvm))
13763 shrink_ple_window(vcpu);
13764}
13765
13766static void vmx_slot_enable_log_dirty(struct kvm *kvm,
13767 struct kvm_memory_slot *slot)
13768{
13769 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
13770 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
13771}
13772
13773static void vmx_slot_disable_log_dirty(struct kvm *kvm,
13774 struct kvm_memory_slot *slot)
13775{
13776 kvm_mmu_slot_set_dirty(kvm, slot);
13777}
13778
13779static void vmx_flush_log_dirty(struct kvm *kvm)
13780{
13781 kvm_flush_pml_buffers(kvm);
13782}
13783
13784static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
13785{
13786 struct vmcs12 *vmcs12;
13787 struct vcpu_vmx *vmx = to_vmx(vcpu);
13788 gpa_t gpa;
13789 struct page *page = NULL;
13790 u64 *pml_address;
13791
13792 if (is_guest_mode(vcpu)) {
13793 WARN_ON_ONCE(vmx->nested.pml_full);
13794
13795 /*
13796 * Check if PML is enabled for the nested guest.
13797 * Whether eptp bit 6 is set is already checked
13798 * as part of A/D emulation.
13799 */
13800 vmcs12 = get_vmcs12(vcpu);
13801 if (!nested_cpu_has_pml(vmcs12))
13802 return 0;
13803
13804 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
13805 vmx->nested.pml_full = true;
13806 return 1;
13807 }
13808
13809 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
13810
13811 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->pml_address);
13812 if (is_error_page(page))
13813 return 0;
13814
13815 pml_address = kmap(page);
13816 pml_address[vmcs12->guest_pml_index--] = gpa;
13817 kunmap(page);
13818 kvm_release_page_clean(page);
13819 }
13820
13821 return 0;
13822}
13823
13824static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
13825 struct kvm_memory_slot *memslot,
13826 gfn_t offset, unsigned long mask)
13827{
13828 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
13829}
13830
13831static void __pi_post_block(struct kvm_vcpu *vcpu)
13832{
13833 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
13834 struct pi_desc old, new;
13835 unsigned int dest;
13836
13837 do {
13838 old.control = new.control = pi_desc->control;
13839 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
13840 "Wakeup handler not enabled while the VCPU is blocked\n");
13841
13842 dest = cpu_physical_id(vcpu->cpu);
13843
13844 if (x2apic_enabled())
13845 new.ndst = dest;
13846 else
13847 new.ndst = (dest << 8) & 0xFF00;
13848
13849 /* set 'NV' to 'notification vector' */
13850 new.nv = POSTED_INTR_VECTOR;
13851 } while (cmpxchg64(&pi_desc->control, old.control,
13852 new.control) != old.control);
13853
13854 if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
13855 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
13856 list_del(&vcpu->blocked_vcpu_list);
13857 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
13858 vcpu->pre_pcpu = -1;
13859 }
13860}
13861
13862/*
13863 * This routine does the following things for vCPU which is going
13864 * to be blocked if VT-d PI is enabled.
13865 * - Store the vCPU to the wakeup list, so when interrupts happen
13866 * we can find the right vCPU to wake up.
13867 * - Change the Posted-interrupt descriptor as below:
13868 * 'NDST' <-- vcpu->pre_pcpu
13869 * 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
13870 * - If 'ON' is set during this process, which means at least one
13871 * interrupt is posted for this vCPU, we cannot block it, in
13872 * this case, return 1, otherwise, return 0.
13873 *
13874 */
13875static int pi_pre_block(struct kvm_vcpu *vcpu)
13876{
13877 unsigned int dest;
13878 struct pi_desc old, new;
13879 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
13880
13881 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
13882 !irq_remapping_cap(IRQ_POSTING_CAP) ||
13883 !kvm_vcpu_apicv_active(vcpu))
13884 return 0;
13885
13886 WARN_ON(irqs_disabled());
13887 local_irq_disable();
13888 if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
13889 vcpu->pre_pcpu = vcpu->cpu;
13890 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
13891 list_add_tail(&vcpu->blocked_vcpu_list,
13892 &per_cpu(blocked_vcpu_on_cpu,
13893 vcpu->pre_pcpu));
13894 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
13895 }
13896
13897 do {
13898 old.control = new.control = pi_desc->control;
13899
13900 WARN((pi_desc->sn == 1),
13901 "Warning: SN field of posted-interrupts "
13902 "is set before blocking\n");
13903
13904 /*
13905 * Since vCPU can be preempted during this process,
13906 * vcpu->cpu could be different with pre_pcpu, we
13907 * need to set pre_pcpu as the destination of wakeup
13908 * notification event, then we can find the right vCPU
13909 * to wakeup in wakeup handler if interrupts happen
13910 * when the vCPU is in blocked state.
13911 */
13912 dest = cpu_physical_id(vcpu->pre_pcpu);
13913
13914 if (x2apic_enabled())
13915 new.ndst = dest;
13916 else
13917 new.ndst = (dest << 8) & 0xFF00;
13918
13919 /* set 'NV' to 'wakeup vector' */
13920 new.nv = POSTED_INTR_WAKEUP_VECTOR;
13921 } while (cmpxchg64(&pi_desc->control, old.control,
13922 new.control) != old.control);
13923
13924 /* We should not block the vCPU if an interrupt is posted for it. */
13925 if (pi_test_on(pi_desc) == 1)
13926 __pi_post_block(vcpu);
13927
13928 local_irq_enable();
13929 return (vcpu->pre_pcpu == -1);
13930}
13931
13932static int vmx_pre_block(struct kvm_vcpu *vcpu)
13933{
13934 if (pi_pre_block(vcpu))
13935 return 1;
13936
13937 if (kvm_lapic_hv_timer_in_use(vcpu))
13938 kvm_lapic_switch_to_sw_timer(vcpu);
13939
13940 return 0;
13941}
13942
13943static void pi_post_block(struct kvm_vcpu *vcpu)
13944{
13945 if (vcpu->pre_pcpu == -1)
13946 return;
13947
13948 WARN_ON(irqs_disabled());
13949 local_irq_disable();
13950 __pi_post_block(vcpu);
13951 local_irq_enable();
13952}
13953
13954static void vmx_post_block(struct kvm_vcpu *vcpu)
13955{
13956 if (kvm_x86_ops->set_hv_timer)
13957 kvm_lapic_switch_to_hv_timer(vcpu);
13958
13959 pi_post_block(vcpu);
13960}
13961
13962/*
13963 * vmx_update_pi_irte - set IRTE for Posted-Interrupts
13964 *
13965 * @kvm: kvm
13966 * @host_irq: host irq of the interrupt
13967 * @guest_irq: gsi of the interrupt
13968 * @set: set or unset PI
13969 * returns 0 on success, < 0 on failure
13970 */
13971static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
13972 uint32_t guest_irq, bool set)
13973{
13974 struct kvm_kernel_irq_routing_entry *e;
13975 struct kvm_irq_routing_table *irq_rt;
13976 struct kvm_lapic_irq irq;
13977 struct kvm_vcpu *vcpu;
13978 struct vcpu_data vcpu_info;
13979 int idx, ret = 0;
13980
13981 if (!kvm_arch_has_assigned_device(kvm) ||
13982 !irq_remapping_cap(IRQ_POSTING_CAP) ||
13983 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
13984 return 0;
13985
13986 idx = srcu_read_lock(&kvm->irq_srcu);
13987 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
13988 if (guest_irq >= irq_rt->nr_rt_entries ||
13989 hlist_empty(&irq_rt->map[guest_irq])) {
13990 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
13991 guest_irq, irq_rt->nr_rt_entries);
13992 goto out;
13993 }
13994
13995 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
13996 if (e->type != KVM_IRQ_ROUTING_MSI)
13997 continue;
13998 /*
13999 * VT-d PI cannot support posting multicast/broadcast
14000 * interrupts to a vCPU, we still use interrupt remapping
14001 * for these kind of interrupts.
14002 *
14003 * For lowest-priority interrupts, we only support
14004 * those with single CPU as the destination, e.g. user
14005 * configures the interrupts via /proc/irq or uses
14006 * irqbalance to make the interrupts single-CPU.
14007 *
14008 * We will support full lowest-priority interrupt later.
14009 */
14010
14011 kvm_set_msi_irq(kvm, e, &irq);
14012 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
14013 /*
14014 * Make sure the IRTE is in remapped mode if
14015 * we don't handle it in posted mode.
14016 */
14017 ret = irq_set_vcpu_affinity(host_irq, NULL);
14018 if (ret < 0) {
14019 printk(KERN_INFO
14020 "failed to back to remapped mode, irq: %u\n",
14021 host_irq);
14022 goto out;
14023 }
14024
14025 continue;
14026 }
14027
14028 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
14029 vcpu_info.vector = irq.vector;
14030
14031 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
14032 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
14033
14034 if (set)
14035 ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
14036 else
14037 ret = irq_set_vcpu_affinity(host_irq, NULL);
14038
14039 if (ret < 0) {
14040 printk(KERN_INFO "%s: failed to update PI IRTE\n",
14041 __func__);
14042 goto out;
14043 }
14044 }
14045
14046 ret = 0;
14047out:
14048 srcu_read_unlock(&kvm->irq_srcu, idx);
14049 return ret;
14050}
14051
14052static void vmx_setup_mce(struct kvm_vcpu *vcpu)
14053{
14054 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
14055 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
14056 FEATURE_CONTROL_LMCE;
14057 else
14058 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
14059 ~FEATURE_CONTROL_LMCE;
14060}
14061
14062static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
14063{
14064 /* we need a nested vmexit to enter SMM, postpone if run is pending */
14065 if (to_vmx(vcpu)->nested.nested_run_pending)
14066 return 0;
14067 return 1;
14068}
14069
14070static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
14071{
14072 struct vcpu_vmx *vmx = to_vmx(vcpu);
14073
14074 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
14075 if (vmx->nested.smm.guest_mode)
14076 nested_vmx_vmexit(vcpu, -1, 0, 0);
14077
14078 vmx->nested.smm.vmxon = vmx->nested.vmxon;
14079 vmx->nested.vmxon = false;
14080 vmx_clear_hlt(vcpu);
14081 return 0;
14082}
14083
14084static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
14085{
14086 struct vcpu_vmx *vmx = to_vmx(vcpu);
14087 int ret;
14088
14089 if (vmx->nested.smm.vmxon) {
14090 vmx->nested.vmxon = true;
14091 vmx->nested.smm.vmxon = false;
14092 }
14093
14094 if (vmx->nested.smm.guest_mode) {
14095 vcpu->arch.hflags &= ~HF_SMM_MASK;
14096 ret = enter_vmx_non_root_mode(vcpu, NULL);
14097 vcpu->arch.hflags |= HF_SMM_MASK;
14098 if (ret)
14099 return ret;
14100
14101 vmx->nested.smm.guest_mode = false;
14102 }
14103 return 0;
14104}
14105
14106static int enable_smi_window(struct kvm_vcpu *vcpu)
14107{
14108 return 0;
14109}
14110
14111static int vmx_get_nested_state(struct kvm_vcpu *vcpu,
14112 struct kvm_nested_state __user *user_kvm_nested_state,
14113 u32 user_data_size)
14114{
14115 struct vcpu_vmx *vmx;
14116 struct vmcs12 *vmcs12;
14117 struct kvm_nested_state kvm_state = {
14118 .flags = 0,
14119 .format = 0,
14120 .size = sizeof(kvm_state),
14121 .vmx.vmxon_pa = -1ull,
14122 .vmx.vmcs_pa = -1ull,
14123 };
14124
14125 if (!vcpu)
14126 return kvm_state.size + 2 * VMCS12_SIZE;
14127
14128 vmx = to_vmx(vcpu);
14129 vmcs12 = get_vmcs12(vcpu);
14130 if (nested_vmx_allowed(vcpu) &&
14131 (vmx->nested.vmxon || vmx->nested.smm.vmxon)) {
14132 kvm_state.vmx.vmxon_pa = vmx->nested.vmxon_ptr;
14133 kvm_state.vmx.vmcs_pa = vmx->nested.current_vmptr;
14134
14135 if (vmx->nested.current_vmptr != -1ull) {
14136 kvm_state.size += VMCS12_SIZE;
14137
14138 if (is_guest_mode(vcpu) &&
14139 nested_cpu_has_shadow_vmcs(vmcs12) &&
14140 vmcs12->vmcs_link_pointer != -1ull)
14141 kvm_state.size += VMCS12_SIZE;
14142 }
14143
14144 if (vmx->nested.smm.vmxon)
14145 kvm_state.vmx.smm.flags |= KVM_STATE_NESTED_SMM_VMXON;
14146
14147 if (vmx->nested.smm.guest_mode)
14148 kvm_state.vmx.smm.flags |= KVM_STATE_NESTED_SMM_GUEST_MODE;
14149
14150 if (is_guest_mode(vcpu)) {
14151 kvm_state.flags |= KVM_STATE_NESTED_GUEST_MODE;
14152
14153 if (vmx->nested.nested_run_pending)
14154 kvm_state.flags |= KVM_STATE_NESTED_RUN_PENDING;
14155 }
14156 }
14157
14158 if (user_data_size < kvm_state.size)
14159 goto out;
14160
14161 if (copy_to_user(user_kvm_nested_state, &kvm_state, sizeof(kvm_state)))
14162 return -EFAULT;
14163
14164 if (vmx->nested.current_vmptr == -1ull)
14165 goto out;
14166
14167 /*
14168 * When running L2, the authoritative vmcs12 state is in the
14169 * vmcs02. When running L1, the authoritative vmcs12 state is
14170 * in the shadow vmcs linked to vmcs01, unless
14171 * sync_shadow_vmcs is set, in which case, the authoritative
14172 * vmcs12 state is in the vmcs12 already.
14173 */
14174 if (is_guest_mode(vcpu))
14175 sync_vmcs12(vcpu, vmcs12);
14176 else if (enable_shadow_vmcs && !vmx->nested.sync_shadow_vmcs)
14177 copy_shadow_to_vmcs12(vmx);
14178
14179 /*
14180 * Copy over the full allocated size of vmcs12 rather than just the size
14181 * of the struct.
14182 */
14183 if (copy_to_user(user_kvm_nested_state->data, vmcs12, VMCS12_SIZE))
14184 return -EFAULT;
14185
14186 if (nested_cpu_has_shadow_vmcs(vmcs12) &&
14187 vmcs12->vmcs_link_pointer != -1ull) {
14188 if (copy_to_user(user_kvm_nested_state->data + VMCS12_SIZE,
14189 get_shadow_vmcs12(vcpu), VMCS12_SIZE))
14190 return -EFAULT;
14191 }
14192
14193out:
14194 return kvm_state.size;
14195}
14196
14197static int vmx_set_nested_state(struct kvm_vcpu *vcpu,
14198 struct kvm_nested_state __user *user_kvm_nested_state,
14199 struct kvm_nested_state *kvm_state)
14200{
14201 struct vcpu_vmx *vmx = to_vmx(vcpu);
14202 struct vmcs12 *vmcs12;
14203 u32 exit_qual;
14204 int ret;
14205
14206 if (kvm_state->format != 0)
14207 return -EINVAL;
14208
14209 if (!nested_vmx_allowed(vcpu))
14210 return kvm_state->vmx.vmxon_pa == -1ull ? 0 : -EINVAL;
14211
14212 if (kvm_state->vmx.vmxon_pa == -1ull) {
14213 if (kvm_state->vmx.smm.flags)
14214 return -EINVAL;
14215
14216 if (kvm_state->vmx.vmcs_pa != -1ull)
14217 return -EINVAL;
14218
14219 vmx_leave_nested(vcpu);
14220 return 0;
14221 }
14222
14223 if (!page_address_valid(vcpu, kvm_state->vmx.vmxon_pa))
14224 return -EINVAL;
14225
14226 if ((kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
14227 (kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
14228 return -EINVAL;
14229
14230 if (kvm_state->vmx.smm.flags &
14231 ~(KVM_STATE_NESTED_SMM_GUEST_MODE | KVM_STATE_NESTED_SMM_VMXON))
14232 return -EINVAL;
14233
14234 /*
14235 * SMM temporarily disables VMX, so we cannot be in guest mode,
14236 * nor can VMLAUNCH/VMRESUME be pending. Outside SMM, SMM flags
14237 * must be zero.
14238 */
14239 if (is_smm(vcpu) ? kvm_state->flags : kvm_state->vmx.smm.flags)
14240 return -EINVAL;
14241
14242 if ((kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
14243 !(kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON))
14244 return -EINVAL;
14245
14246 vmx_leave_nested(vcpu);
14247 if (kvm_state->vmx.vmxon_pa == -1ull)
14248 return 0;
14249
14250 vmx->nested.vmxon_ptr = kvm_state->vmx.vmxon_pa;
14251 ret = enter_vmx_operation(vcpu);
14252 if (ret)
14253 return ret;
14254
14255 /* Empty 'VMXON' state is permitted */
14256 if (kvm_state->size < sizeof(*kvm_state) + sizeof(*vmcs12))
14257 return 0;
14258
14259 if (kvm_state->vmx.vmcs_pa == kvm_state->vmx.vmxon_pa ||
14260 !page_address_valid(vcpu, kvm_state->vmx.vmcs_pa))
14261 return -EINVAL;
14262
14263 set_current_vmptr(vmx, kvm_state->vmx.vmcs_pa);
14264
14265 if (kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON) {
14266 vmx->nested.smm.vmxon = true;
14267 vmx->nested.vmxon = false;
14268
14269 if (kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE)
14270 vmx->nested.smm.guest_mode = true;
14271 }
14272
14273 vmcs12 = get_vmcs12(vcpu);
14274 if (copy_from_user(vmcs12, user_kvm_nested_state->data, sizeof(*vmcs12)))
14275 return -EFAULT;
14276
14277 if (vmcs12->hdr.revision_id != VMCS12_REVISION)
14278 return -EINVAL;
14279
14280 if (!(kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
14281 return 0;
14282
14283 vmx->nested.nested_run_pending =
14284 !!(kvm_state->flags & KVM_STATE_NESTED_RUN_PENDING);
14285
14286 if (nested_cpu_has_shadow_vmcs(vmcs12) &&
14287 vmcs12->vmcs_link_pointer != -1ull) {
14288 struct vmcs12 *shadow_vmcs12 = get_shadow_vmcs12(vcpu);
14289 if (kvm_state->size < sizeof(*kvm_state) + 2 * sizeof(*vmcs12))
14290 return -EINVAL;
14291
14292 if (copy_from_user(shadow_vmcs12,
14293 user_kvm_nested_state->data + VMCS12_SIZE,
14294 sizeof(*vmcs12)))
14295 return -EFAULT;
14296
14297 if (shadow_vmcs12->hdr.revision_id != VMCS12_REVISION ||
14298 !shadow_vmcs12->hdr.shadow_vmcs)
14299 return -EINVAL;
14300 }
14301
14302 if (check_vmentry_prereqs(vcpu, vmcs12) ||
14303 check_vmentry_postreqs(vcpu, vmcs12, &exit_qual))
14304 return -EINVAL;
14305
14306 vmx->nested.dirty_vmcs12 = true;
14307 ret = enter_vmx_non_root_mode(vcpu, NULL);
14308 if (ret)
14309 return -EINVAL;
14310
14311 return 0;
14312}
14313
14314static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
14315 .cpu_has_kvm_support = cpu_has_kvm_support,
14316 .disabled_by_bios = vmx_disabled_by_bios,
14317 .hardware_setup = hardware_setup,
14318 .hardware_unsetup = hardware_unsetup,
14319 .check_processor_compatibility = vmx_check_processor_compat,
14320 .hardware_enable = hardware_enable,
14321 .hardware_disable = hardware_disable,
14322 .cpu_has_accelerated_tpr = report_flexpriority,
14323 .has_emulated_msr = vmx_has_emulated_msr,
14324
14325 .vm_init = vmx_vm_init,
14326 .vm_alloc = vmx_vm_alloc,
14327 .vm_free = vmx_vm_free,
14328
14329 .vcpu_create = vmx_create_vcpu,
14330 .vcpu_free = vmx_free_vcpu,
14331 .vcpu_reset = vmx_vcpu_reset,
14332
14333 .prepare_guest_switch = vmx_prepare_switch_to_guest,
14334 .vcpu_load = vmx_vcpu_load,
14335 .vcpu_put = vmx_vcpu_put,
14336
14337 .update_bp_intercept = update_exception_bitmap,
14338 .get_msr_feature = vmx_get_msr_feature,
14339 .get_msr = vmx_get_msr,
14340 .set_msr = vmx_set_msr,
14341 .get_segment_base = vmx_get_segment_base,
14342 .get_segment = vmx_get_segment,
14343 .set_segment = vmx_set_segment,
14344 .get_cpl = vmx_get_cpl,
14345 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
14346 .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
14347 .decache_cr3 = vmx_decache_cr3,
14348 .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
14349 .set_cr0 = vmx_set_cr0,
14350 .set_cr3 = vmx_set_cr3,
14351 .set_cr4 = vmx_set_cr4,
14352 .set_efer = vmx_set_efer,
14353 .get_idt = vmx_get_idt,
14354 .set_idt = vmx_set_idt,
14355 .get_gdt = vmx_get_gdt,
14356 .set_gdt = vmx_set_gdt,
14357 .get_dr6 = vmx_get_dr6,
14358 .set_dr6 = vmx_set_dr6,
14359 .set_dr7 = vmx_set_dr7,
14360 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
14361 .cache_reg = vmx_cache_reg,
14362 .get_rflags = vmx_get_rflags,
14363 .set_rflags = vmx_set_rflags,
14364
14365 .tlb_flush = vmx_flush_tlb,
14366 .tlb_flush_gva = vmx_flush_tlb_gva,
14367
14368 .run = vmx_vcpu_run,
14369 .handle_exit = vmx_handle_exit,
14370 .skip_emulated_instruction = skip_emulated_instruction,
14371 .set_interrupt_shadow = vmx_set_interrupt_shadow,
14372 .get_interrupt_shadow = vmx_get_interrupt_shadow,
14373 .patch_hypercall = vmx_patch_hypercall,
14374 .set_irq = vmx_inject_irq,
14375 .set_nmi = vmx_inject_nmi,
14376 .queue_exception = vmx_queue_exception,
14377 .cancel_injection = vmx_cancel_injection,
14378 .interrupt_allowed = vmx_interrupt_allowed,
14379 .nmi_allowed = vmx_nmi_allowed,
14380 .get_nmi_mask = vmx_get_nmi_mask,
14381 .set_nmi_mask = vmx_set_nmi_mask,
14382 .enable_nmi_window = enable_nmi_window,
14383 .enable_irq_window = enable_irq_window,
14384 .update_cr8_intercept = update_cr8_intercept,
14385 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
14386 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
14387 .get_enable_apicv = vmx_get_enable_apicv,
14388 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
14389 .load_eoi_exitmap = vmx_load_eoi_exitmap,
14390 .apicv_post_state_restore = vmx_apicv_post_state_restore,
14391 .hwapic_irr_update = vmx_hwapic_irr_update,
14392 .hwapic_isr_update = vmx_hwapic_isr_update,
14393 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
14394 .sync_pir_to_irr = vmx_sync_pir_to_irr,
14395 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
14396 .dy_apicv_has_pending_interrupt = vmx_dy_apicv_has_pending_interrupt,
14397
14398 .set_tss_addr = vmx_set_tss_addr,
14399 .set_identity_map_addr = vmx_set_identity_map_addr,
14400 .get_tdp_level = get_ept_level,
14401 .get_mt_mask = vmx_get_mt_mask,
14402
14403 .get_exit_info = vmx_get_exit_info,
14404
14405 .get_lpage_level = vmx_get_lpage_level,
14406
14407 .cpuid_update = vmx_cpuid_update,
14408
14409 .rdtscp_supported = vmx_rdtscp_supported,
14410 .invpcid_supported = vmx_invpcid_supported,
14411
14412 .set_supported_cpuid = vmx_set_supported_cpuid,
14413
14414 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
14415
14416 .read_l1_tsc_offset = vmx_read_l1_tsc_offset,
14417 .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
14418
14419 .set_tdp_cr3 = vmx_set_cr3,
14420
14421 .check_intercept = vmx_check_intercept,
14422 .handle_external_intr = vmx_handle_external_intr,
14423 .mpx_supported = vmx_mpx_supported,
14424 .xsaves_supported = vmx_xsaves_supported,
14425 .umip_emulated = vmx_umip_emulated,
14426
14427 .check_nested_events = vmx_check_nested_events,
14428 .request_immediate_exit = vmx_request_immediate_exit,
14429
14430 .sched_in = vmx_sched_in,
14431
14432 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
14433 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
14434 .flush_log_dirty = vmx_flush_log_dirty,
14435 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
14436 .write_log_dirty = vmx_write_pml_buffer,
14437
14438 .pre_block = vmx_pre_block,
14439 .post_block = vmx_post_block,
14440
14441 .pmu_ops = &intel_pmu_ops,
14442
14443 .update_pi_irte = vmx_update_pi_irte,
14444
14445#ifdef CONFIG_X86_64
14446 .set_hv_timer = vmx_set_hv_timer,
14447 .cancel_hv_timer = vmx_cancel_hv_timer,
14448#endif
14449
14450 .setup_mce = vmx_setup_mce,
14451
14452 .get_nested_state = vmx_get_nested_state,
14453 .set_nested_state = vmx_set_nested_state,
14454 .get_vmcs12_pages = nested_get_vmcs12_pages,
14455
14456 .smi_allowed = vmx_smi_allowed,
14457 .pre_enter_smm = vmx_pre_enter_smm,
14458 .pre_leave_smm = vmx_pre_leave_smm,
14459 .enable_smi_window = enable_smi_window,
14460};
14461
14462static void vmx_cleanup_l1d_flush(void)
14463{
14464 if (vmx_l1d_flush_pages) {
14465 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
14466 vmx_l1d_flush_pages = NULL;
14467 }
14468 /* Restore state so sysfs ignores VMX */
14469 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
14470}
14471
14472static void vmx_exit(void)
14473{
14474#ifdef CONFIG_KEXEC_CORE
14475 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
14476 synchronize_rcu();
14477#endif
14478
14479 kvm_exit();
14480
14481#if IS_ENABLED(CONFIG_HYPERV)
14482 if (static_branch_unlikely(&enable_evmcs)) {
14483 int cpu;
14484 struct hv_vp_assist_page *vp_ap;
14485 /*
14486 * Reset everything to support using non-enlightened VMCS
14487 * access later (e.g. when we reload the module with
14488 * enlightened_vmcs=0)
14489 */
14490 for_each_online_cpu(cpu) {
14491 vp_ap = hv_get_vp_assist_page(cpu);
14492
14493 if (!vp_ap)
14494 continue;
14495
14496 vp_ap->current_nested_vmcs = 0;
14497 vp_ap->enlighten_vmentry = 0;
14498 }
14499
14500 static_branch_disable(&enable_evmcs);
14501 }
14502#endif
14503 vmx_cleanup_l1d_flush();
14504}
14505module_exit(vmx_exit);
14506
14507static int __init vmx_init(void)
14508{
14509 int r;
14510
14511#if IS_ENABLED(CONFIG_HYPERV)
14512 /*
14513 * Enlightened VMCS usage should be recommended and the host needs
14514 * to support eVMCS v1 or above. We can also disable eVMCS support
14515 * with module parameter.
14516 */
14517 if (enlightened_vmcs &&
14518 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
14519 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
14520 KVM_EVMCS_VERSION) {
14521 int cpu;
14522
14523 /* Check that we have assist pages on all online CPUs */
14524 for_each_online_cpu(cpu) {
14525 if (!hv_get_vp_assist_page(cpu)) {
14526 enlightened_vmcs = false;
14527 break;
14528 }
14529 }
14530
14531 if (enlightened_vmcs) {
14532 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
14533 static_branch_enable(&enable_evmcs);
14534 }
14535 } else {
14536 enlightened_vmcs = false;
14537 }
14538#endif
14539
14540 r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
14541 __alignof__(struct vcpu_vmx), THIS_MODULE);
14542 if (r)
14543 return r;
14544
14545 /*
14546 * Must be called after kvm_init() so enable_ept is properly set
14547 * up. Hand the parameter mitigation value in which was stored in
14548 * the pre module init parser. If no parameter was given, it will
14549 * contain 'auto' which will be turned into the default 'cond'
14550 * mitigation mode.
14551 */
14552 if (boot_cpu_has(X86_BUG_L1TF)) {
14553 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
14554 if (r) {
14555 vmx_exit();
14556 return r;
14557 }
14558 }
14559
14560#ifdef CONFIG_KEXEC_CORE
14561 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
14562 crash_vmclear_local_loaded_vmcss);
14563#endif
14564 vmx_check_vmcs12_offsets();
14565
14566 return 0;
14567}
14568module_init(vmx_init);