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