Update version for 2.4.0.1 release
[qemu.git] / target-i386 / kvm.c
1 /*
2 * QEMU KVM support
3 *
4 * Copyright (C) 2006-2008 Qumranet Technologies
5 * Copyright IBM, Corp. 2008
6 *
7 * Authors:
8 * Anthony Liguori <aliguori@us.ibm.com>
9 *
10 * This work is licensed under the terms of the GNU GPL, version 2 or later.
11 * See the COPYING file in the top-level directory.
12 *
13 */
14
15 #include <sys/types.h>
16 #include <sys/ioctl.h>
17 #include <sys/mman.h>
18 #include <sys/utsname.h>
19
20 #include <linux/kvm.h>
21 #include <linux/kvm_para.h>
22
23 #include "qemu-common.h"
24 #include "sysemu/sysemu.h"
25 #include "sysemu/kvm_int.h"
26 #include "kvm_i386.h"
27 #include "cpu.h"
28 #include "exec/gdbstub.h"
29 #include "qemu/host-utils.h"
30 #include "qemu/config-file.h"
31 #include "hw/i386/pc.h"
32 #include "hw/i386/apic.h"
33 #include "hw/i386/apic_internal.h"
34 #include "hw/i386/apic-msidef.h"
35 #include "exec/ioport.h"
36 #include <asm/hyperv.h>
37 #include "hw/pci/pci.h"
38 #include "migration/migration.h"
39 #include "exec/memattrs.h"
40
41 //#define DEBUG_KVM
42
43 #ifdef DEBUG_KVM
44 #define DPRINTF(fmt, ...) \
45 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
46 #else
47 #define DPRINTF(fmt, ...) \
48 do { } while (0)
49 #endif
50
51 #define MSR_KVM_WALL_CLOCK 0x11
52 #define MSR_KVM_SYSTEM_TIME 0x12
53
54 #ifndef BUS_MCEERR_AR
55 #define BUS_MCEERR_AR 4
56 #endif
57 #ifndef BUS_MCEERR_AO
58 #define BUS_MCEERR_AO 5
59 #endif
60
61 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
62 KVM_CAP_INFO(SET_TSS_ADDR),
63 KVM_CAP_INFO(EXT_CPUID),
64 KVM_CAP_INFO(MP_STATE),
65 KVM_CAP_LAST_INFO
66 };
67
68 static bool has_msr_star;
69 static bool has_msr_hsave_pa;
70 static bool has_msr_tsc_adjust;
71 static bool has_msr_tsc_deadline;
72 static bool has_msr_feature_control;
73 static bool has_msr_async_pf_en;
74 static bool has_msr_pv_eoi_en;
75 static bool has_msr_misc_enable;
76 static bool has_msr_smbase;
77 static bool has_msr_bndcfgs;
78 static bool has_msr_kvm_steal_time;
79 static int lm_capable_kernel;
80 static bool has_msr_hv_hypercall;
81 static bool has_msr_hv_vapic;
82 static bool has_msr_hv_tsc;
83 static bool has_msr_mtrr;
84 static bool has_msr_xss;
85
86 static bool has_msr_architectural_pmu;
87 static uint32_t num_architectural_pmu_counters;
88
89 bool kvm_has_smm(void)
90 {
91 return kvm_check_extension(kvm_state, KVM_CAP_X86_SMM);
92 }
93
94 bool kvm_allows_irq0_override(void)
95 {
96 return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
97 }
98
99 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
100 {
101 struct kvm_cpuid2 *cpuid;
102 int r, size;
103
104 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
105 cpuid = g_malloc0(size);
106 cpuid->nent = max;
107 r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
108 if (r == 0 && cpuid->nent >= max) {
109 r = -E2BIG;
110 }
111 if (r < 0) {
112 if (r == -E2BIG) {
113 g_free(cpuid);
114 return NULL;
115 } else {
116 fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
117 strerror(-r));
118 exit(1);
119 }
120 }
121 return cpuid;
122 }
123
124 /* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
125 * for all entries.
126 */
127 static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
128 {
129 struct kvm_cpuid2 *cpuid;
130 int max = 1;
131 while ((cpuid = try_get_cpuid(s, max)) == NULL) {
132 max *= 2;
133 }
134 return cpuid;
135 }
136
137 static const struct kvm_para_features {
138 int cap;
139 int feature;
140 } para_features[] = {
141 { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
142 { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
143 { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
144 { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
145 };
146
147 static int get_para_features(KVMState *s)
148 {
149 int i, features = 0;
150
151 for (i = 0; i < ARRAY_SIZE(para_features); i++) {
152 if (kvm_check_extension(s, para_features[i].cap)) {
153 features |= (1 << para_features[i].feature);
154 }
155 }
156
157 return features;
158 }
159
160
161 /* Returns the value for a specific register on the cpuid entry
162 */
163 static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
164 {
165 uint32_t ret = 0;
166 switch (reg) {
167 case R_EAX:
168 ret = entry->eax;
169 break;
170 case R_EBX:
171 ret = entry->ebx;
172 break;
173 case R_ECX:
174 ret = entry->ecx;
175 break;
176 case R_EDX:
177 ret = entry->edx;
178 break;
179 }
180 return ret;
181 }
182
183 /* Find matching entry for function/index on kvm_cpuid2 struct
184 */
185 static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
186 uint32_t function,
187 uint32_t index)
188 {
189 int i;
190 for (i = 0; i < cpuid->nent; ++i) {
191 if (cpuid->entries[i].function == function &&
192 cpuid->entries[i].index == index) {
193 return &cpuid->entries[i];
194 }
195 }
196 /* not found: */
197 return NULL;
198 }
199
200 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
201 uint32_t index, int reg)
202 {
203 struct kvm_cpuid2 *cpuid;
204 uint32_t ret = 0;
205 uint32_t cpuid_1_edx;
206 bool found = false;
207
208 cpuid = get_supported_cpuid(s);
209
210 struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
211 if (entry) {
212 found = true;
213 ret = cpuid_entry_get_reg(entry, reg);
214 }
215
216 /* Fixups for the data returned by KVM, below */
217
218 if (function == 1 && reg == R_EDX) {
219 /* KVM before 2.6.30 misreports the following features */
220 ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
221 } else if (function == 1 && reg == R_ECX) {
222 /* We can set the hypervisor flag, even if KVM does not return it on
223 * GET_SUPPORTED_CPUID
224 */
225 ret |= CPUID_EXT_HYPERVISOR;
226 /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
227 * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
228 * and the irqchip is in the kernel.
229 */
230 if (kvm_irqchip_in_kernel() &&
231 kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
232 ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
233 }
234
235 /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
236 * without the in-kernel irqchip
237 */
238 if (!kvm_irqchip_in_kernel()) {
239 ret &= ~CPUID_EXT_X2APIC;
240 }
241 } else if (function == 6 && reg == R_EAX) {
242 ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
243 } else if (function == 0x80000001 && reg == R_EDX) {
244 /* On Intel, kvm returns cpuid according to the Intel spec,
245 * so add missing bits according to the AMD spec:
246 */
247 cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
248 ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
249 }
250
251 g_free(cpuid);
252
253 /* fallback for older kernels */
254 if ((function == KVM_CPUID_FEATURES) && !found) {
255 ret = get_para_features(s);
256 }
257
258 return ret;
259 }
260
261 typedef struct HWPoisonPage {
262 ram_addr_t ram_addr;
263 QLIST_ENTRY(HWPoisonPage) list;
264 } HWPoisonPage;
265
266 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
267 QLIST_HEAD_INITIALIZER(hwpoison_page_list);
268
269 static void kvm_unpoison_all(void *param)
270 {
271 HWPoisonPage *page, *next_page;
272
273 QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
274 QLIST_REMOVE(page, list);
275 qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
276 g_free(page);
277 }
278 }
279
280 static void kvm_hwpoison_page_add(ram_addr_t ram_addr)
281 {
282 HWPoisonPage *page;
283
284 QLIST_FOREACH(page, &hwpoison_page_list, list) {
285 if (page->ram_addr == ram_addr) {
286 return;
287 }
288 }
289 page = g_new(HWPoisonPage, 1);
290 page->ram_addr = ram_addr;
291 QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
292 }
293
294 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
295 int *max_banks)
296 {
297 int r;
298
299 r = kvm_check_extension(s, KVM_CAP_MCE);
300 if (r > 0) {
301 *max_banks = r;
302 return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
303 }
304 return -ENOSYS;
305 }
306
307 static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
308 {
309 CPUX86State *env = &cpu->env;
310 uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
311 MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
312 uint64_t mcg_status = MCG_STATUS_MCIP;
313
314 if (code == BUS_MCEERR_AR) {
315 status |= MCI_STATUS_AR | 0x134;
316 mcg_status |= MCG_STATUS_EIPV;
317 } else {
318 status |= 0xc0;
319 mcg_status |= MCG_STATUS_RIPV;
320 }
321 cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
322 (MCM_ADDR_PHYS << 6) | 0xc,
323 cpu_x86_support_mca_broadcast(env) ?
324 MCE_INJECT_BROADCAST : 0);
325 }
326
327 static void hardware_memory_error(void)
328 {
329 fprintf(stderr, "Hardware memory error!\n");
330 exit(1);
331 }
332
333 int kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
334 {
335 X86CPU *cpu = X86_CPU(c);
336 CPUX86State *env = &cpu->env;
337 ram_addr_t ram_addr;
338 hwaddr paddr;
339
340 if ((env->mcg_cap & MCG_SER_P) && addr
341 && (code == BUS_MCEERR_AR || code == BUS_MCEERR_AO)) {
342 if (qemu_ram_addr_from_host(addr, &ram_addr) == NULL ||
343 !kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
344 fprintf(stderr, "Hardware memory error for memory used by "
345 "QEMU itself instead of guest system!\n");
346 /* Hope we are lucky for AO MCE */
347 if (code == BUS_MCEERR_AO) {
348 return 0;
349 } else {
350 hardware_memory_error();
351 }
352 }
353 kvm_hwpoison_page_add(ram_addr);
354 kvm_mce_inject(cpu, paddr, code);
355 } else {
356 if (code == BUS_MCEERR_AO) {
357 return 0;
358 } else if (code == BUS_MCEERR_AR) {
359 hardware_memory_error();
360 } else {
361 return 1;
362 }
363 }
364 return 0;
365 }
366
367 int kvm_arch_on_sigbus(int code, void *addr)
368 {
369 X86CPU *cpu = X86_CPU(first_cpu);
370
371 if ((cpu->env.mcg_cap & MCG_SER_P) && addr && code == BUS_MCEERR_AO) {
372 ram_addr_t ram_addr;
373 hwaddr paddr;
374
375 /* Hope we are lucky for AO MCE */
376 if (qemu_ram_addr_from_host(addr, &ram_addr) == NULL ||
377 !kvm_physical_memory_addr_from_host(first_cpu->kvm_state,
378 addr, &paddr)) {
379 fprintf(stderr, "Hardware memory error for memory used by "
380 "QEMU itself instead of guest system!: %p\n", addr);
381 return 0;
382 }
383 kvm_hwpoison_page_add(ram_addr);
384 kvm_mce_inject(X86_CPU(first_cpu), paddr, code);
385 } else {
386 if (code == BUS_MCEERR_AO) {
387 return 0;
388 } else if (code == BUS_MCEERR_AR) {
389 hardware_memory_error();
390 } else {
391 return 1;
392 }
393 }
394 return 0;
395 }
396
397 static int kvm_inject_mce_oldstyle(X86CPU *cpu)
398 {
399 CPUX86State *env = &cpu->env;
400
401 if (!kvm_has_vcpu_events() && env->exception_injected == EXCP12_MCHK) {
402 unsigned int bank, bank_num = env->mcg_cap & 0xff;
403 struct kvm_x86_mce mce;
404
405 env->exception_injected = -1;
406
407 /*
408 * There must be at least one bank in use if an MCE is pending.
409 * Find it and use its values for the event injection.
410 */
411 for (bank = 0; bank < bank_num; bank++) {
412 if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
413 break;
414 }
415 }
416 assert(bank < bank_num);
417
418 mce.bank = bank;
419 mce.status = env->mce_banks[bank * 4 + 1];
420 mce.mcg_status = env->mcg_status;
421 mce.addr = env->mce_banks[bank * 4 + 2];
422 mce.misc = env->mce_banks[bank * 4 + 3];
423
424 return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
425 }
426 return 0;
427 }
428
429 static void cpu_update_state(void *opaque, int running, RunState state)
430 {
431 CPUX86State *env = opaque;
432
433 if (running) {
434 env->tsc_valid = false;
435 }
436 }
437
438 unsigned long kvm_arch_vcpu_id(CPUState *cs)
439 {
440 X86CPU *cpu = X86_CPU(cs);
441 return cpu->apic_id;
442 }
443
444 #ifndef KVM_CPUID_SIGNATURE_NEXT
445 #define KVM_CPUID_SIGNATURE_NEXT 0x40000100
446 #endif
447
448 static bool hyperv_hypercall_available(X86CPU *cpu)
449 {
450 return cpu->hyperv_vapic ||
451 (cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_RETRY);
452 }
453
454 static bool hyperv_enabled(X86CPU *cpu)
455 {
456 CPUState *cs = CPU(cpu);
457 return kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0 &&
458 (hyperv_hypercall_available(cpu) ||
459 cpu->hyperv_time ||
460 cpu->hyperv_relaxed_timing);
461 }
462
463 static Error *invtsc_mig_blocker;
464
465 #define KVM_MAX_CPUID_ENTRIES 100
466
467 int kvm_arch_init_vcpu(CPUState *cs)
468 {
469 struct {
470 struct kvm_cpuid2 cpuid;
471 struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
472 } QEMU_PACKED cpuid_data;
473 X86CPU *cpu = X86_CPU(cs);
474 CPUX86State *env = &cpu->env;
475 uint32_t limit, i, j, cpuid_i;
476 uint32_t unused;
477 struct kvm_cpuid_entry2 *c;
478 uint32_t signature[3];
479 int kvm_base = KVM_CPUID_SIGNATURE;
480 int r;
481
482 memset(&cpuid_data, 0, sizeof(cpuid_data));
483
484 cpuid_i = 0;
485
486 /* Paravirtualization CPUIDs */
487 if (hyperv_enabled(cpu)) {
488 c = &cpuid_data.entries[cpuid_i++];
489 c->function = HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
490 memcpy(signature, "Microsoft Hv", 12);
491 c->eax = HYPERV_CPUID_MIN;
492 c->ebx = signature[0];
493 c->ecx = signature[1];
494 c->edx = signature[2];
495
496 c = &cpuid_data.entries[cpuid_i++];
497 c->function = HYPERV_CPUID_INTERFACE;
498 memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
499 c->eax = signature[0];
500 c->ebx = 0;
501 c->ecx = 0;
502 c->edx = 0;
503
504 c = &cpuid_data.entries[cpuid_i++];
505 c->function = HYPERV_CPUID_VERSION;
506 c->eax = 0x00001bbc;
507 c->ebx = 0x00060001;
508
509 c = &cpuid_data.entries[cpuid_i++];
510 c->function = HYPERV_CPUID_FEATURES;
511 if (cpu->hyperv_relaxed_timing) {
512 c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
513 }
514 if (cpu->hyperv_vapic) {
515 c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
516 c->eax |= HV_X64_MSR_APIC_ACCESS_AVAILABLE;
517 has_msr_hv_vapic = true;
518 }
519 if (cpu->hyperv_time &&
520 kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) > 0) {
521 c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
522 c->eax |= HV_X64_MSR_TIME_REF_COUNT_AVAILABLE;
523 c->eax |= 0x200;
524 has_msr_hv_tsc = true;
525 }
526 c = &cpuid_data.entries[cpuid_i++];
527 c->function = HYPERV_CPUID_ENLIGHTMENT_INFO;
528 if (cpu->hyperv_relaxed_timing) {
529 c->eax |= HV_X64_RELAXED_TIMING_RECOMMENDED;
530 }
531 if (has_msr_hv_vapic) {
532 c->eax |= HV_X64_APIC_ACCESS_RECOMMENDED;
533 }
534 c->ebx = cpu->hyperv_spinlock_attempts;
535
536 c = &cpuid_data.entries[cpuid_i++];
537 c->function = HYPERV_CPUID_IMPLEMENT_LIMITS;
538 c->eax = 0x40;
539 c->ebx = 0x40;
540
541 kvm_base = KVM_CPUID_SIGNATURE_NEXT;
542 has_msr_hv_hypercall = true;
543 }
544
545 if (cpu->expose_kvm) {
546 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
547 c = &cpuid_data.entries[cpuid_i++];
548 c->function = KVM_CPUID_SIGNATURE | kvm_base;
549 c->eax = KVM_CPUID_FEATURES | kvm_base;
550 c->ebx = signature[0];
551 c->ecx = signature[1];
552 c->edx = signature[2];
553
554 c = &cpuid_data.entries[cpuid_i++];
555 c->function = KVM_CPUID_FEATURES | kvm_base;
556 c->eax = env->features[FEAT_KVM];
557
558 has_msr_async_pf_en = c->eax & (1 << KVM_FEATURE_ASYNC_PF);
559
560 has_msr_pv_eoi_en = c->eax & (1 << KVM_FEATURE_PV_EOI);
561
562 has_msr_kvm_steal_time = c->eax & (1 << KVM_FEATURE_STEAL_TIME);
563 }
564
565 cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
566
567 for (i = 0; i <= limit; i++) {
568 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
569 fprintf(stderr, "unsupported level value: 0x%x\n", limit);
570 abort();
571 }
572 c = &cpuid_data.entries[cpuid_i++];
573
574 switch (i) {
575 case 2: {
576 /* Keep reading function 2 till all the input is received */
577 int times;
578
579 c->function = i;
580 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
581 KVM_CPUID_FLAG_STATE_READ_NEXT;
582 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
583 times = c->eax & 0xff;
584
585 for (j = 1; j < times; ++j) {
586 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
587 fprintf(stderr, "cpuid_data is full, no space for "
588 "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
589 abort();
590 }
591 c = &cpuid_data.entries[cpuid_i++];
592 c->function = i;
593 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
594 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
595 }
596 break;
597 }
598 case 4:
599 case 0xb:
600 case 0xd:
601 for (j = 0; ; j++) {
602 if (i == 0xd && j == 64) {
603 break;
604 }
605 c->function = i;
606 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
607 c->index = j;
608 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
609
610 if (i == 4 && c->eax == 0) {
611 break;
612 }
613 if (i == 0xb && !(c->ecx & 0xff00)) {
614 break;
615 }
616 if (i == 0xd && c->eax == 0) {
617 continue;
618 }
619 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
620 fprintf(stderr, "cpuid_data is full, no space for "
621 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
622 abort();
623 }
624 c = &cpuid_data.entries[cpuid_i++];
625 }
626 break;
627 default:
628 c->function = i;
629 c->flags = 0;
630 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
631 break;
632 }
633 }
634
635 if (limit >= 0x0a) {
636 uint32_t ver;
637
638 cpu_x86_cpuid(env, 0x0a, 0, &ver, &unused, &unused, &unused);
639 if ((ver & 0xff) > 0) {
640 has_msr_architectural_pmu = true;
641 num_architectural_pmu_counters = (ver & 0xff00) >> 8;
642
643 /* Shouldn't be more than 32, since that's the number of bits
644 * available in EBX to tell us _which_ counters are available.
645 * Play it safe.
646 */
647 if (num_architectural_pmu_counters > MAX_GP_COUNTERS) {
648 num_architectural_pmu_counters = MAX_GP_COUNTERS;
649 }
650 }
651 }
652
653 cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
654
655 for (i = 0x80000000; i <= limit; i++) {
656 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
657 fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
658 abort();
659 }
660 c = &cpuid_data.entries[cpuid_i++];
661
662 c->function = i;
663 c->flags = 0;
664 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
665 }
666
667 /* Call Centaur's CPUID instructions they are supported. */
668 if (env->cpuid_xlevel2 > 0) {
669 cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
670
671 for (i = 0xC0000000; i <= limit; i++) {
672 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
673 fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
674 abort();
675 }
676 c = &cpuid_data.entries[cpuid_i++];
677
678 c->function = i;
679 c->flags = 0;
680 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
681 }
682 }
683
684 cpuid_data.cpuid.nent = cpuid_i;
685
686 if (((env->cpuid_version >> 8)&0xF) >= 6
687 && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
688 (CPUID_MCE | CPUID_MCA)
689 && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
690 uint64_t mcg_cap;
691 int banks;
692 int ret;
693
694 ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
695 if (ret < 0) {
696 fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
697 return ret;
698 }
699
700 if (banks > MCE_BANKS_DEF) {
701 banks = MCE_BANKS_DEF;
702 }
703 mcg_cap &= MCE_CAP_DEF;
704 mcg_cap |= banks;
705 ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &mcg_cap);
706 if (ret < 0) {
707 fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
708 return ret;
709 }
710
711 env->mcg_cap = mcg_cap;
712 }
713
714 qemu_add_vm_change_state_handler(cpu_update_state, env);
715
716 c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
717 if (c) {
718 has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
719 !!(c->ecx & CPUID_EXT_SMX);
720 }
721
722 c = cpuid_find_entry(&cpuid_data.cpuid, 0x80000007, 0);
723 if (c && (c->edx & 1<<8) && invtsc_mig_blocker == NULL) {
724 /* for migration */
725 error_setg(&invtsc_mig_blocker,
726 "State blocked by non-migratable CPU device"
727 " (invtsc flag)");
728 migrate_add_blocker(invtsc_mig_blocker);
729 /* for savevm */
730 vmstate_x86_cpu.unmigratable = 1;
731 }
732
733 cpuid_data.cpuid.padding = 0;
734 r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
735 if (r) {
736 return r;
737 }
738
739 r = kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL);
740 if (r && env->tsc_khz) {
741 r = kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz);
742 if (r < 0) {
743 fprintf(stderr, "KVM_SET_TSC_KHZ failed\n");
744 return r;
745 }
746 }
747
748 if (kvm_has_xsave()) {
749 env->kvm_xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));
750 }
751
752 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
753 has_msr_mtrr = true;
754 }
755
756 return 0;
757 }
758
759 void kvm_arch_reset_vcpu(X86CPU *cpu)
760 {
761 CPUX86State *env = &cpu->env;
762
763 env->exception_injected = -1;
764 env->interrupt_injected = -1;
765 env->xcr0 = 1;
766 if (kvm_irqchip_in_kernel()) {
767 env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
768 KVM_MP_STATE_UNINITIALIZED;
769 } else {
770 env->mp_state = KVM_MP_STATE_RUNNABLE;
771 }
772 }
773
774 void kvm_arch_do_init_vcpu(X86CPU *cpu)
775 {
776 CPUX86State *env = &cpu->env;
777
778 /* APs get directly into wait-for-SIPI state. */
779 if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
780 env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
781 }
782 }
783
784 static int kvm_get_supported_msrs(KVMState *s)
785 {
786 static int kvm_supported_msrs;
787 int ret = 0;
788
789 /* first time */
790 if (kvm_supported_msrs == 0) {
791 struct kvm_msr_list msr_list, *kvm_msr_list;
792
793 kvm_supported_msrs = -1;
794
795 /* Obtain MSR list from KVM. These are the MSRs that we must
796 * save/restore */
797 msr_list.nmsrs = 0;
798 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
799 if (ret < 0 && ret != -E2BIG) {
800 return ret;
801 }
802 /* Old kernel modules had a bug and could write beyond the provided
803 memory. Allocate at least a safe amount of 1K. */
804 kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
805 msr_list.nmsrs *
806 sizeof(msr_list.indices[0])));
807
808 kvm_msr_list->nmsrs = msr_list.nmsrs;
809 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
810 if (ret >= 0) {
811 int i;
812
813 for (i = 0; i < kvm_msr_list->nmsrs; i++) {
814 if (kvm_msr_list->indices[i] == MSR_STAR) {
815 has_msr_star = true;
816 continue;
817 }
818 if (kvm_msr_list->indices[i] == MSR_VM_HSAVE_PA) {
819 has_msr_hsave_pa = true;
820 continue;
821 }
822 if (kvm_msr_list->indices[i] == MSR_TSC_ADJUST) {
823 has_msr_tsc_adjust = true;
824 continue;
825 }
826 if (kvm_msr_list->indices[i] == MSR_IA32_TSCDEADLINE) {
827 has_msr_tsc_deadline = true;
828 continue;
829 }
830 if (kvm_msr_list->indices[i] == MSR_IA32_SMBASE) {
831 has_msr_smbase = true;
832 continue;
833 }
834 if (kvm_msr_list->indices[i] == MSR_IA32_MISC_ENABLE) {
835 has_msr_misc_enable = true;
836 continue;
837 }
838 if (kvm_msr_list->indices[i] == MSR_IA32_BNDCFGS) {
839 has_msr_bndcfgs = true;
840 continue;
841 }
842 if (kvm_msr_list->indices[i] == MSR_IA32_XSS) {
843 has_msr_xss = true;
844 continue;
845 }
846 }
847 }
848
849 g_free(kvm_msr_list);
850 }
851
852 return ret;
853 }
854
855 static Notifier smram_machine_done;
856 static KVMMemoryListener smram_listener;
857 static AddressSpace smram_address_space;
858 static MemoryRegion smram_as_root;
859 static MemoryRegion smram_as_mem;
860
861 static void register_smram_listener(Notifier *n, void *unused)
862 {
863 MemoryRegion *smram =
864 (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
865
866 /* Outer container... */
867 memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
868 memory_region_set_enabled(&smram_as_root, true);
869
870 /* ... with two regions inside: normal system memory with low
871 * priority, and...
872 */
873 memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
874 get_system_memory(), 0, ~0ull);
875 memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
876 memory_region_set_enabled(&smram_as_mem, true);
877
878 if (smram) {
879 /* ... SMRAM with higher priority */
880 memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
881 memory_region_set_enabled(smram, true);
882 }
883
884 address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
885 kvm_memory_listener_register(kvm_state, &smram_listener,
886 &smram_address_space, 1);
887 }
888
889 int kvm_arch_init(MachineState *ms, KVMState *s)
890 {
891 uint64_t identity_base = 0xfffbc000;
892 uint64_t shadow_mem;
893 int ret;
894 struct utsname utsname;
895
896 ret = kvm_get_supported_msrs(s);
897 if (ret < 0) {
898 return ret;
899 }
900
901 uname(&utsname);
902 lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
903
904 /*
905 * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
906 * In order to use vm86 mode, an EPT identity map and a TSS are needed.
907 * Since these must be part of guest physical memory, we need to allocate
908 * them, both by setting their start addresses in the kernel and by
909 * creating a corresponding e820 entry. We need 4 pages before the BIOS.
910 *
911 * Older KVM versions may not support setting the identity map base. In
912 * that case we need to stick with the default, i.e. a 256K maximum BIOS
913 * size.
914 */
915 if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
916 /* Allows up to 16M BIOSes. */
917 identity_base = 0xfeffc000;
918
919 ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
920 if (ret < 0) {
921 return ret;
922 }
923 }
924
925 /* Set TSS base one page after EPT identity map. */
926 ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
927 if (ret < 0) {
928 return ret;
929 }
930
931 /* Tell fw_cfg to notify the BIOS to reserve the range. */
932 ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
933 if (ret < 0) {
934 fprintf(stderr, "e820_add_entry() table is full\n");
935 return ret;
936 }
937 qemu_register_reset(kvm_unpoison_all, NULL);
938
939 shadow_mem = machine_kvm_shadow_mem(ms);
940 if (shadow_mem != -1) {
941 shadow_mem /= 4096;
942 ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
943 if (ret < 0) {
944 return ret;
945 }
946 }
947
948 if (kvm_check_extension(s, KVM_CAP_X86_SMM)) {
949 smram_machine_done.notify = register_smram_listener;
950 qemu_add_machine_init_done_notifier(&smram_machine_done);
951 }
952 return 0;
953 }
954
955 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
956 {
957 lhs->selector = rhs->selector;
958 lhs->base = rhs->base;
959 lhs->limit = rhs->limit;
960 lhs->type = 3;
961 lhs->present = 1;
962 lhs->dpl = 3;
963 lhs->db = 0;
964 lhs->s = 1;
965 lhs->l = 0;
966 lhs->g = 0;
967 lhs->avl = 0;
968 lhs->unusable = 0;
969 }
970
971 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
972 {
973 unsigned flags = rhs->flags;
974 lhs->selector = rhs->selector;
975 lhs->base = rhs->base;
976 lhs->limit = rhs->limit;
977 lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
978 lhs->present = (flags & DESC_P_MASK) != 0;
979 lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
980 lhs->db = (flags >> DESC_B_SHIFT) & 1;
981 lhs->s = (flags & DESC_S_MASK) != 0;
982 lhs->l = (flags >> DESC_L_SHIFT) & 1;
983 lhs->g = (flags & DESC_G_MASK) != 0;
984 lhs->avl = (flags & DESC_AVL_MASK) != 0;
985 lhs->unusable = 0;
986 lhs->padding = 0;
987 }
988
989 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
990 {
991 lhs->selector = rhs->selector;
992 lhs->base = rhs->base;
993 lhs->limit = rhs->limit;
994 lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
995 (rhs->present * DESC_P_MASK) |
996 (rhs->dpl << DESC_DPL_SHIFT) |
997 (rhs->db << DESC_B_SHIFT) |
998 (rhs->s * DESC_S_MASK) |
999 (rhs->l << DESC_L_SHIFT) |
1000 (rhs->g * DESC_G_MASK) |
1001 (rhs->avl * DESC_AVL_MASK);
1002 }
1003
1004 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
1005 {
1006 if (set) {
1007 *kvm_reg = *qemu_reg;
1008 } else {
1009 *qemu_reg = *kvm_reg;
1010 }
1011 }
1012
1013 static int kvm_getput_regs(X86CPU *cpu, int set)
1014 {
1015 CPUX86State *env = &cpu->env;
1016 struct kvm_regs regs;
1017 int ret = 0;
1018
1019 if (!set) {
1020 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
1021 if (ret < 0) {
1022 return ret;
1023 }
1024 }
1025
1026 kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
1027 kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
1028 kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
1029 kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
1030 kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
1031 kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
1032 kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
1033 kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
1034 #ifdef TARGET_X86_64
1035 kvm_getput_reg(&regs.r8, &env->regs[8], set);
1036 kvm_getput_reg(&regs.r9, &env->regs[9], set);
1037 kvm_getput_reg(&regs.r10, &env->regs[10], set);
1038 kvm_getput_reg(&regs.r11, &env->regs[11], set);
1039 kvm_getput_reg(&regs.r12, &env->regs[12], set);
1040 kvm_getput_reg(&regs.r13, &env->regs[13], set);
1041 kvm_getput_reg(&regs.r14, &env->regs[14], set);
1042 kvm_getput_reg(&regs.r15, &env->regs[15], set);
1043 #endif
1044
1045 kvm_getput_reg(&regs.rflags, &env->eflags, set);
1046 kvm_getput_reg(&regs.rip, &env->eip, set);
1047
1048 if (set) {
1049 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
1050 }
1051
1052 return ret;
1053 }
1054
1055 static int kvm_put_fpu(X86CPU *cpu)
1056 {
1057 CPUX86State *env = &cpu->env;
1058 struct kvm_fpu fpu;
1059 int i;
1060
1061 memset(&fpu, 0, sizeof fpu);
1062 fpu.fsw = env->fpus & ~(7 << 11);
1063 fpu.fsw |= (env->fpstt & 7) << 11;
1064 fpu.fcw = env->fpuc;
1065 fpu.last_opcode = env->fpop;
1066 fpu.last_ip = env->fpip;
1067 fpu.last_dp = env->fpdp;
1068 for (i = 0; i < 8; ++i) {
1069 fpu.ftwx |= (!env->fptags[i]) << i;
1070 }
1071 memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
1072 for (i = 0; i < CPU_NB_REGS; i++) {
1073 stq_p(&fpu.xmm[i][0], env->xmm_regs[i].XMM_Q(0));
1074 stq_p(&fpu.xmm[i][8], env->xmm_regs[i].XMM_Q(1));
1075 }
1076 fpu.mxcsr = env->mxcsr;
1077
1078 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
1079 }
1080
1081 #define XSAVE_FCW_FSW 0
1082 #define XSAVE_FTW_FOP 1
1083 #define XSAVE_CWD_RIP 2
1084 #define XSAVE_CWD_RDP 4
1085 #define XSAVE_MXCSR 6
1086 #define XSAVE_ST_SPACE 8
1087 #define XSAVE_XMM_SPACE 40
1088 #define XSAVE_XSTATE_BV 128
1089 #define XSAVE_YMMH_SPACE 144
1090 #define XSAVE_BNDREGS 240
1091 #define XSAVE_BNDCSR 256
1092 #define XSAVE_OPMASK 272
1093 #define XSAVE_ZMM_Hi256 288
1094 #define XSAVE_Hi16_ZMM 416
1095
1096 static int kvm_put_xsave(X86CPU *cpu)
1097 {
1098 CPUX86State *env = &cpu->env;
1099 struct kvm_xsave* xsave = env->kvm_xsave_buf;
1100 uint16_t cwd, swd, twd;
1101 uint8_t *xmm, *ymmh, *zmmh;
1102 int i, r;
1103
1104 if (!kvm_has_xsave()) {
1105 return kvm_put_fpu(cpu);
1106 }
1107
1108 memset(xsave, 0, sizeof(struct kvm_xsave));
1109 twd = 0;
1110 swd = env->fpus & ~(7 << 11);
1111 swd |= (env->fpstt & 7) << 11;
1112 cwd = env->fpuc;
1113 for (i = 0; i < 8; ++i) {
1114 twd |= (!env->fptags[i]) << i;
1115 }
1116 xsave->region[XSAVE_FCW_FSW] = (uint32_t)(swd << 16) + cwd;
1117 xsave->region[XSAVE_FTW_FOP] = (uint32_t)(env->fpop << 16) + twd;
1118 memcpy(&xsave->region[XSAVE_CWD_RIP], &env->fpip, sizeof(env->fpip));
1119 memcpy(&xsave->region[XSAVE_CWD_RDP], &env->fpdp, sizeof(env->fpdp));
1120 memcpy(&xsave->region[XSAVE_ST_SPACE], env->fpregs,
1121 sizeof env->fpregs);
1122 xsave->region[XSAVE_MXCSR] = env->mxcsr;
1123 *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV] = env->xstate_bv;
1124 memcpy(&xsave->region[XSAVE_BNDREGS], env->bnd_regs,
1125 sizeof env->bnd_regs);
1126 memcpy(&xsave->region[XSAVE_BNDCSR], &env->bndcs_regs,
1127 sizeof(env->bndcs_regs));
1128 memcpy(&xsave->region[XSAVE_OPMASK], env->opmask_regs,
1129 sizeof env->opmask_regs);
1130
1131 xmm = (uint8_t *)&xsave->region[XSAVE_XMM_SPACE];
1132 ymmh = (uint8_t *)&xsave->region[XSAVE_YMMH_SPACE];
1133 zmmh = (uint8_t *)&xsave->region[XSAVE_ZMM_Hi256];
1134 for (i = 0; i < CPU_NB_REGS; i++, xmm += 16, ymmh += 16, zmmh += 32) {
1135 stq_p(xmm, env->xmm_regs[i].XMM_Q(0));
1136 stq_p(xmm+8, env->xmm_regs[i].XMM_Q(1));
1137 stq_p(ymmh, env->xmm_regs[i].XMM_Q(2));
1138 stq_p(ymmh+8, env->xmm_regs[i].XMM_Q(3));
1139 stq_p(zmmh, env->xmm_regs[i].XMM_Q(4));
1140 stq_p(zmmh+8, env->xmm_regs[i].XMM_Q(5));
1141 stq_p(zmmh+16, env->xmm_regs[i].XMM_Q(6));
1142 stq_p(zmmh+24, env->xmm_regs[i].XMM_Q(7));
1143 }
1144
1145 #ifdef TARGET_X86_64
1146 memcpy(&xsave->region[XSAVE_Hi16_ZMM], &env->xmm_regs[16],
1147 16 * sizeof env->xmm_regs[16]);
1148 #endif
1149 r = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
1150 return r;
1151 }
1152
1153 static int kvm_put_xcrs(X86CPU *cpu)
1154 {
1155 CPUX86State *env = &cpu->env;
1156 struct kvm_xcrs xcrs = {};
1157
1158 if (!kvm_has_xcrs()) {
1159 return 0;
1160 }
1161
1162 xcrs.nr_xcrs = 1;
1163 xcrs.flags = 0;
1164 xcrs.xcrs[0].xcr = 0;
1165 xcrs.xcrs[0].value = env->xcr0;
1166 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
1167 }
1168
1169 static int kvm_put_sregs(X86CPU *cpu)
1170 {
1171 CPUX86State *env = &cpu->env;
1172 struct kvm_sregs sregs;
1173
1174 memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
1175 if (env->interrupt_injected >= 0) {
1176 sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
1177 (uint64_t)1 << (env->interrupt_injected % 64);
1178 }
1179
1180 if ((env->eflags & VM_MASK)) {
1181 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
1182 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
1183 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
1184 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
1185 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
1186 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
1187 } else {
1188 set_seg(&sregs.cs, &env->segs[R_CS]);
1189 set_seg(&sregs.ds, &env->segs[R_DS]);
1190 set_seg(&sregs.es, &env->segs[R_ES]);
1191 set_seg(&sregs.fs, &env->segs[R_FS]);
1192 set_seg(&sregs.gs, &env->segs[R_GS]);
1193 set_seg(&sregs.ss, &env->segs[R_SS]);
1194 }
1195
1196 set_seg(&sregs.tr, &env->tr);
1197 set_seg(&sregs.ldt, &env->ldt);
1198
1199 sregs.idt.limit = env->idt.limit;
1200 sregs.idt.base = env->idt.base;
1201 memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
1202 sregs.gdt.limit = env->gdt.limit;
1203 sregs.gdt.base = env->gdt.base;
1204 memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
1205
1206 sregs.cr0 = env->cr[0];
1207 sregs.cr2 = env->cr[2];
1208 sregs.cr3 = env->cr[3];
1209 sregs.cr4 = env->cr[4];
1210
1211 sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
1212 sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
1213
1214 sregs.efer = env->efer;
1215
1216 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
1217 }
1218
1219 static void kvm_msr_entry_set(struct kvm_msr_entry *entry,
1220 uint32_t index, uint64_t value)
1221 {
1222 entry->index = index;
1223 entry->reserved = 0;
1224 entry->data = value;
1225 }
1226
1227 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
1228 {
1229 CPUX86State *env = &cpu->env;
1230 struct {
1231 struct kvm_msrs info;
1232 struct kvm_msr_entry entries[1];
1233 } msr_data;
1234 struct kvm_msr_entry *msrs = msr_data.entries;
1235
1236 if (!has_msr_tsc_deadline) {
1237 return 0;
1238 }
1239
1240 kvm_msr_entry_set(&msrs[0], MSR_IA32_TSCDEADLINE, env->tsc_deadline);
1241
1242 msr_data.info = (struct kvm_msrs) {
1243 .nmsrs = 1,
1244 };
1245
1246 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, &msr_data);
1247 }
1248
1249 /*
1250 * Provide a separate write service for the feature control MSR in order to
1251 * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
1252 * before writing any other state because forcibly leaving nested mode
1253 * invalidates the VCPU state.
1254 */
1255 static int kvm_put_msr_feature_control(X86CPU *cpu)
1256 {
1257 struct {
1258 struct kvm_msrs info;
1259 struct kvm_msr_entry entry;
1260 } msr_data;
1261
1262 kvm_msr_entry_set(&msr_data.entry, MSR_IA32_FEATURE_CONTROL,
1263 cpu->env.msr_ia32_feature_control);
1264
1265 msr_data.info = (struct kvm_msrs) {
1266 .nmsrs = 1,
1267 };
1268
1269 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, &msr_data);
1270 }
1271
1272 static int kvm_put_msrs(X86CPU *cpu, int level)
1273 {
1274 CPUX86State *env = &cpu->env;
1275 struct {
1276 struct kvm_msrs info;
1277 struct kvm_msr_entry entries[150];
1278 } msr_data;
1279 struct kvm_msr_entry *msrs = msr_data.entries;
1280 int n = 0, i;
1281
1282 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_CS, env->sysenter_cs);
1283 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
1284 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
1285 kvm_msr_entry_set(&msrs[n++], MSR_PAT, env->pat);
1286 if (has_msr_star) {
1287 kvm_msr_entry_set(&msrs[n++], MSR_STAR, env->star);
1288 }
1289 if (has_msr_hsave_pa) {
1290 kvm_msr_entry_set(&msrs[n++], MSR_VM_HSAVE_PA, env->vm_hsave);
1291 }
1292 if (has_msr_tsc_adjust) {
1293 kvm_msr_entry_set(&msrs[n++], MSR_TSC_ADJUST, env->tsc_adjust);
1294 }
1295 if (has_msr_misc_enable) {
1296 kvm_msr_entry_set(&msrs[n++], MSR_IA32_MISC_ENABLE,
1297 env->msr_ia32_misc_enable);
1298 }
1299 if (has_msr_smbase) {
1300 kvm_msr_entry_set(&msrs[n++], MSR_IA32_SMBASE, env->smbase);
1301 }
1302 if (has_msr_bndcfgs) {
1303 kvm_msr_entry_set(&msrs[n++], MSR_IA32_BNDCFGS, env->msr_bndcfgs);
1304 }
1305 if (has_msr_xss) {
1306 kvm_msr_entry_set(&msrs[n++], MSR_IA32_XSS, env->xss);
1307 }
1308 #ifdef TARGET_X86_64
1309 if (lm_capable_kernel) {
1310 kvm_msr_entry_set(&msrs[n++], MSR_CSTAR, env->cstar);
1311 kvm_msr_entry_set(&msrs[n++], MSR_KERNELGSBASE, env->kernelgsbase);
1312 kvm_msr_entry_set(&msrs[n++], MSR_FMASK, env->fmask);
1313 kvm_msr_entry_set(&msrs[n++], MSR_LSTAR, env->lstar);
1314 }
1315 #endif
1316 /*
1317 * The following MSRs have side effects on the guest or are too heavy
1318 * for normal writeback. Limit them to reset or full state updates.
1319 */
1320 if (level >= KVM_PUT_RESET_STATE) {
1321 kvm_msr_entry_set(&msrs[n++], MSR_IA32_TSC, env->tsc);
1322 kvm_msr_entry_set(&msrs[n++], MSR_KVM_SYSTEM_TIME,
1323 env->system_time_msr);
1324 kvm_msr_entry_set(&msrs[n++], MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
1325 if (has_msr_async_pf_en) {
1326 kvm_msr_entry_set(&msrs[n++], MSR_KVM_ASYNC_PF_EN,
1327 env->async_pf_en_msr);
1328 }
1329 if (has_msr_pv_eoi_en) {
1330 kvm_msr_entry_set(&msrs[n++], MSR_KVM_PV_EOI_EN,
1331 env->pv_eoi_en_msr);
1332 }
1333 if (has_msr_kvm_steal_time) {
1334 kvm_msr_entry_set(&msrs[n++], MSR_KVM_STEAL_TIME,
1335 env->steal_time_msr);
1336 }
1337 if (has_msr_architectural_pmu) {
1338 /* Stop the counter. */
1339 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
1340 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_GLOBAL_CTRL, 0);
1341
1342 /* Set the counter values. */
1343 for (i = 0; i < MAX_FIXED_COUNTERS; i++) {
1344 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_FIXED_CTR0 + i,
1345 env->msr_fixed_counters[i]);
1346 }
1347 for (i = 0; i < num_architectural_pmu_counters; i++) {
1348 kvm_msr_entry_set(&msrs[n++], MSR_P6_PERFCTR0 + i,
1349 env->msr_gp_counters[i]);
1350 kvm_msr_entry_set(&msrs[n++], MSR_P6_EVNTSEL0 + i,
1351 env->msr_gp_evtsel[i]);
1352 }
1353 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_GLOBAL_STATUS,
1354 env->msr_global_status);
1355 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1356 env->msr_global_ovf_ctrl);
1357
1358 /* Now start the PMU. */
1359 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_FIXED_CTR_CTRL,
1360 env->msr_fixed_ctr_ctrl);
1361 kvm_msr_entry_set(&msrs[n++], MSR_CORE_PERF_GLOBAL_CTRL,
1362 env->msr_global_ctrl);
1363 }
1364 if (has_msr_hv_hypercall) {
1365 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_GUEST_OS_ID,
1366 env->msr_hv_guest_os_id);
1367 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_HYPERCALL,
1368 env->msr_hv_hypercall);
1369 }
1370 if (has_msr_hv_vapic) {
1371 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_APIC_ASSIST_PAGE,
1372 env->msr_hv_vapic);
1373 }
1374 if (has_msr_hv_tsc) {
1375 kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_REFERENCE_TSC,
1376 env->msr_hv_tsc);
1377 }
1378 if (has_msr_mtrr) {
1379 kvm_msr_entry_set(&msrs[n++], MSR_MTRRdefType, env->mtrr_deftype);
1380 kvm_msr_entry_set(&msrs[n++],
1381 MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
1382 kvm_msr_entry_set(&msrs[n++],
1383 MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
1384 kvm_msr_entry_set(&msrs[n++],
1385 MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
1386 kvm_msr_entry_set(&msrs[n++],
1387 MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
1388 kvm_msr_entry_set(&msrs[n++],
1389 MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
1390 kvm_msr_entry_set(&msrs[n++],
1391 MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
1392 kvm_msr_entry_set(&msrs[n++],
1393 MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
1394 kvm_msr_entry_set(&msrs[n++],
1395 MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
1396 kvm_msr_entry_set(&msrs[n++],
1397 MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
1398 kvm_msr_entry_set(&msrs[n++],
1399 MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
1400 kvm_msr_entry_set(&msrs[n++],
1401 MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
1402 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
1403 kvm_msr_entry_set(&msrs[n++],
1404 MSR_MTRRphysBase(i), env->mtrr_var[i].base);
1405 kvm_msr_entry_set(&msrs[n++],
1406 MSR_MTRRphysMask(i), env->mtrr_var[i].mask);
1407 }
1408 }
1409
1410 /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
1411 * kvm_put_msr_feature_control. */
1412 }
1413 if (env->mcg_cap) {
1414 int i;
1415
1416 kvm_msr_entry_set(&msrs[n++], MSR_MCG_STATUS, env->mcg_status);
1417 kvm_msr_entry_set(&msrs[n++], MSR_MCG_CTL, env->mcg_ctl);
1418 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1419 kvm_msr_entry_set(&msrs[n++], MSR_MC0_CTL + i, env->mce_banks[i]);
1420 }
1421 }
1422
1423 msr_data.info = (struct kvm_msrs) {
1424 .nmsrs = n,
1425 };
1426
1427 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, &msr_data);
1428
1429 }
1430
1431
1432 static int kvm_get_fpu(X86CPU *cpu)
1433 {
1434 CPUX86State *env = &cpu->env;
1435 struct kvm_fpu fpu;
1436 int i, ret;
1437
1438 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
1439 if (ret < 0) {
1440 return ret;
1441 }
1442
1443 env->fpstt = (fpu.fsw >> 11) & 7;
1444 env->fpus = fpu.fsw;
1445 env->fpuc = fpu.fcw;
1446 env->fpop = fpu.last_opcode;
1447 env->fpip = fpu.last_ip;
1448 env->fpdp = fpu.last_dp;
1449 for (i = 0; i < 8; ++i) {
1450 env->fptags[i] = !((fpu.ftwx >> i) & 1);
1451 }
1452 memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
1453 for (i = 0; i < CPU_NB_REGS; i++) {
1454 env->xmm_regs[i].XMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
1455 env->xmm_regs[i].XMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
1456 }
1457 env->mxcsr = fpu.mxcsr;
1458
1459 return 0;
1460 }
1461
1462 static int kvm_get_xsave(X86CPU *cpu)
1463 {
1464 CPUX86State *env = &cpu->env;
1465 struct kvm_xsave* xsave = env->kvm_xsave_buf;
1466 int ret, i;
1467 const uint8_t *xmm, *ymmh, *zmmh;
1468 uint16_t cwd, swd, twd;
1469
1470 if (!kvm_has_xsave()) {
1471 return kvm_get_fpu(cpu);
1472 }
1473
1474 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
1475 if (ret < 0) {
1476 return ret;
1477 }
1478
1479 cwd = (uint16_t)xsave->region[XSAVE_FCW_FSW];
1480 swd = (uint16_t)(xsave->region[XSAVE_FCW_FSW] >> 16);
1481 twd = (uint16_t)xsave->region[XSAVE_FTW_FOP];
1482 env->fpop = (uint16_t)(xsave->region[XSAVE_FTW_FOP] >> 16);
1483 env->fpstt = (swd >> 11) & 7;
1484 env->fpus = swd;
1485 env->fpuc = cwd;
1486 for (i = 0; i < 8; ++i) {
1487 env->fptags[i] = !((twd >> i) & 1);
1488 }
1489 memcpy(&env->fpip, &xsave->region[XSAVE_CWD_RIP], sizeof(env->fpip));
1490 memcpy(&env->fpdp, &xsave->region[XSAVE_CWD_RDP], sizeof(env->fpdp));
1491 env->mxcsr = xsave->region[XSAVE_MXCSR];
1492 memcpy(env->fpregs, &xsave->region[XSAVE_ST_SPACE],
1493 sizeof env->fpregs);
1494 env->xstate_bv = *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV];
1495 memcpy(env->bnd_regs, &xsave->region[XSAVE_BNDREGS],
1496 sizeof env->bnd_regs);
1497 memcpy(&env->bndcs_regs, &xsave->region[XSAVE_BNDCSR],
1498 sizeof(env->bndcs_regs));
1499 memcpy(env->opmask_regs, &xsave->region[XSAVE_OPMASK],
1500 sizeof env->opmask_regs);
1501
1502 xmm = (const uint8_t *)&xsave->region[XSAVE_XMM_SPACE];
1503 ymmh = (const uint8_t *)&xsave->region[XSAVE_YMMH_SPACE];
1504 zmmh = (const uint8_t *)&xsave->region[XSAVE_ZMM_Hi256];
1505 for (i = 0; i < CPU_NB_REGS; i++, xmm += 16, ymmh += 16, zmmh += 32) {
1506 env->xmm_regs[i].XMM_Q(0) = ldq_p(xmm);
1507 env->xmm_regs[i].XMM_Q(1) = ldq_p(xmm+8);
1508 env->xmm_regs[i].XMM_Q(2) = ldq_p(ymmh);
1509 env->xmm_regs[i].XMM_Q(3) = ldq_p(ymmh+8);
1510 env->xmm_regs[i].XMM_Q(4) = ldq_p(zmmh);
1511 env->xmm_regs[i].XMM_Q(5) = ldq_p(zmmh+8);
1512 env->xmm_regs[i].XMM_Q(6) = ldq_p(zmmh+16);
1513 env->xmm_regs[i].XMM_Q(7) = ldq_p(zmmh+24);
1514 }
1515
1516 #ifdef TARGET_X86_64
1517 memcpy(&env->xmm_regs[16], &xsave->region[XSAVE_Hi16_ZMM],
1518 16 * sizeof env->xmm_regs[16]);
1519 #endif
1520 return 0;
1521 }
1522
1523 static int kvm_get_xcrs(X86CPU *cpu)
1524 {
1525 CPUX86State *env = &cpu->env;
1526 int i, ret;
1527 struct kvm_xcrs xcrs;
1528
1529 if (!kvm_has_xcrs()) {
1530 return 0;
1531 }
1532
1533 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
1534 if (ret < 0) {
1535 return ret;
1536 }
1537
1538 for (i = 0; i < xcrs.nr_xcrs; i++) {
1539 /* Only support xcr0 now */
1540 if (xcrs.xcrs[i].xcr == 0) {
1541 env->xcr0 = xcrs.xcrs[i].value;
1542 break;
1543 }
1544 }
1545 return 0;
1546 }
1547
1548 static int kvm_get_sregs(X86CPU *cpu)
1549 {
1550 CPUX86State *env = &cpu->env;
1551 struct kvm_sregs sregs;
1552 uint32_t hflags;
1553 int bit, i, ret;
1554
1555 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
1556 if (ret < 0) {
1557 return ret;
1558 }
1559
1560 /* There can only be one pending IRQ set in the bitmap at a time, so try
1561 to find it and save its number instead (-1 for none). */
1562 env->interrupt_injected = -1;
1563 for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
1564 if (sregs.interrupt_bitmap[i]) {
1565 bit = ctz64(sregs.interrupt_bitmap[i]);
1566 env->interrupt_injected = i * 64 + bit;
1567 break;
1568 }
1569 }
1570
1571 get_seg(&env->segs[R_CS], &sregs.cs);
1572 get_seg(&env->segs[R_DS], &sregs.ds);
1573 get_seg(&env->segs[R_ES], &sregs.es);
1574 get_seg(&env->segs[R_FS], &sregs.fs);
1575 get_seg(&env->segs[R_GS], &sregs.gs);
1576 get_seg(&env->segs[R_SS], &sregs.ss);
1577
1578 get_seg(&env->tr, &sregs.tr);
1579 get_seg(&env->ldt, &sregs.ldt);
1580
1581 env->idt.limit = sregs.idt.limit;
1582 env->idt.base = sregs.idt.base;
1583 env->gdt.limit = sregs.gdt.limit;
1584 env->gdt.base = sregs.gdt.base;
1585
1586 env->cr[0] = sregs.cr0;
1587 env->cr[2] = sregs.cr2;
1588 env->cr[3] = sregs.cr3;
1589 env->cr[4] = sregs.cr4;
1590
1591 env->efer = sregs.efer;
1592
1593 /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
1594
1595 #define HFLAG_COPY_MASK \
1596 ~( HF_CPL_MASK | HF_PE_MASK | HF_MP_MASK | HF_EM_MASK | \
1597 HF_TS_MASK | HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK | \
1598 HF_OSFXSR_MASK | HF_LMA_MASK | HF_CS32_MASK | \
1599 HF_SS32_MASK | HF_CS64_MASK | HF_ADDSEG_MASK)
1600
1601 hflags = (env->segs[R_SS].flags >> DESC_DPL_SHIFT) & HF_CPL_MASK;
1602 hflags |= (env->cr[0] & CR0_PE_MASK) << (HF_PE_SHIFT - CR0_PE_SHIFT);
1603 hflags |= (env->cr[0] << (HF_MP_SHIFT - CR0_MP_SHIFT)) &
1604 (HF_MP_MASK | HF_EM_MASK | HF_TS_MASK);
1605 hflags |= (env->eflags & (HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK));
1606 hflags |= (env->cr[4] & CR4_OSFXSR_MASK) <<
1607 (HF_OSFXSR_SHIFT - CR4_OSFXSR_SHIFT);
1608
1609 if (env->efer & MSR_EFER_LMA) {
1610 hflags |= HF_LMA_MASK;
1611 }
1612
1613 if ((hflags & HF_LMA_MASK) && (env->segs[R_CS].flags & DESC_L_MASK)) {
1614 hflags |= HF_CS32_MASK | HF_SS32_MASK | HF_CS64_MASK;
1615 } else {
1616 hflags |= (env->segs[R_CS].flags & DESC_B_MASK) >>
1617 (DESC_B_SHIFT - HF_CS32_SHIFT);
1618 hflags |= (env->segs[R_SS].flags & DESC_B_MASK) >>
1619 (DESC_B_SHIFT - HF_SS32_SHIFT);
1620 if (!(env->cr[0] & CR0_PE_MASK) || (env->eflags & VM_MASK) ||
1621 !(hflags & HF_CS32_MASK)) {
1622 hflags |= HF_ADDSEG_MASK;
1623 } else {
1624 hflags |= ((env->segs[R_DS].base | env->segs[R_ES].base |
1625 env->segs[R_SS].base) != 0) << HF_ADDSEG_SHIFT;
1626 }
1627 }
1628 env->hflags = (env->hflags & HFLAG_COPY_MASK) | hflags;
1629
1630 return 0;
1631 }
1632
1633 static int kvm_get_msrs(X86CPU *cpu)
1634 {
1635 CPUX86State *env = &cpu->env;
1636 struct {
1637 struct kvm_msrs info;
1638 struct kvm_msr_entry entries[150];
1639 } msr_data;
1640 struct kvm_msr_entry *msrs = msr_data.entries;
1641 int ret, i, n;
1642
1643 n = 0;
1644 msrs[n++].index = MSR_IA32_SYSENTER_CS;
1645 msrs[n++].index = MSR_IA32_SYSENTER_ESP;
1646 msrs[n++].index = MSR_IA32_SYSENTER_EIP;
1647 msrs[n++].index = MSR_PAT;
1648 if (has_msr_star) {
1649 msrs[n++].index = MSR_STAR;
1650 }
1651 if (has_msr_hsave_pa) {
1652 msrs[n++].index = MSR_VM_HSAVE_PA;
1653 }
1654 if (has_msr_tsc_adjust) {
1655 msrs[n++].index = MSR_TSC_ADJUST;
1656 }
1657 if (has_msr_tsc_deadline) {
1658 msrs[n++].index = MSR_IA32_TSCDEADLINE;
1659 }
1660 if (has_msr_misc_enable) {
1661 msrs[n++].index = MSR_IA32_MISC_ENABLE;
1662 }
1663 if (has_msr_smbase) {
1664 msrs[n++].index = MSR_IA32_SMBASE;
1665 }
1666 if (has_msr_feature_control) {
1667 msrs[n++].index = MSR_IA32_FEATURE_CONTROL;
1668 }
1669 if (has_msr_bndcfgs) {
1670 msrs[n++].index = MSR_IA32_BNDCFGS;
1671 }
1672 if (has_msr_xss) {
1673 msrs[n++].index = MSR_IA32_XSS;
1674 }
1675
1676
1677 if (!env->tsc_valid) {
1678 msrs[n++].index = MSR_IA32_TSC;
1679 env->tsc_valid = !runstate_is_running();
1680 }
1681
1682 #ifdef TARGET_X86_64
1683 if (lm_capable_kernel) {
1684 msrs[n++].index = MSR_CSTAR;
1685 msrs[n++].index = MSR_KERNELGSBASE;
1686 msrs[n++].index = MSR_FMASK;
1687 msrs[n++].index = MSR_LSTAR;
1688 }
1689 #endif
1690 msrs[n++].index = MSR_KVM_SYSTEM_TIME;
1691 msrs[n++].index = MSR_KVM_WALL_CLOCK;
1692 if (has_msr_async_pf_en) {
1693 msrs[n++].index = MSR_KVM_ASYNC_PF_EN;
1694 }
1695 if (has_msr_pv_eoi_en) {
1696 msrs[n++].index = MSR_KVM_PV_EOI_EN;
1697 }
1698 if (has_msr_kvm_steal_time) {
1699 msrs[n++].index = MSR_KVM_STEAL_TIME;
1700 }
1701 if (has_msr_architectural_pmu) {
1702 msrs[n++].index = MSR_CORE_PERF_FIXED_CTR_CTRL;
1703 msrs[n++].index = MSR_CORE_PERF_GLOBAL_CTRL;
1704 msrs[n++].index = MSR_CORE_PERF_GLOBAL_STATUS;
1705 msrs[n++].index = MSR_CORE_PERF_GLOBAL_OVF_CTRL;
1706 for (i = 0; i < MAX_FIXED_COUNTERS; i++) {
1707 msrs[n++].index = MSR_CORE_PERF_FIXED_CTR0 + i;
1708 }
1709 for (i = 0; i < num_architectural_pmu_counters; i++) {
1710 msrs[n++].index = MSR_P6_PERFCTR0 + i;
1711 msrs[n++].index = MSR_P6_EVNTSEL0 + i;
1712 }
1713 }
1714
1715 if (env->mcg_cap) {
1716 msrs[n++].index = MSR_MCG_STATUS;
1717 msrs[n++].index = MSR_MCG_CTL;
1718 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1719 msrs[n++].index = MSR_MC0_CTL + i;
1720 }
1721 }
1722
1723 if (has_msr_hv_hypercall) {
1724 msrs[n++].index = HV_X64_MSR_HYPERCALL;
1725 msrs[n++].index = HV_X64_MSR_GUEST_OS_ID;
1726 }
1727 if (has_msr_hv_vapic) {
1728 msrs[n++].index = HV_X64_MSR_APIC_ASSIST_PAGE;
1729 }
1730 if (has_msr_hv_tsc) {
1731 msrs[n++].index = HV_X64_MSR_REFERENCE_TSC;
1732 }
1733 if (has_msr_mtrr) {
1734 msrs[n++].index = MSR_MTRRdefType;
1735 msrs[n++].index = MSR_MTRRfix64K_00000;
1736 msrs[n++].index = MSR_MTRRfix16K_80000;
1737 msrs[n++].index = MSR_MTRRfix16K_A0000;
1738 msrs[n++].index = MSR_MTRRfix4K_C0000;
1739 msrs[n++].index = MSR_MTRRfix4K_C8000;
1740 msrs[n++].index = MSR_MTRRfix4K_D0000;
1741 msrs[n++].index = MSR_MTRRfix4K_D8000;
1742 msrs[n++].index = MSR_MTRRfix4K_E0000;
1743 msrs[n++].index = MSR_MTRRfix4K_E8000;
1744 msrs[n++].index = MSR_MTRRfix4K_F0000;
1745 msrs[n++].index = MSR_MTRRfix4K_F8000;
1746 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
1747 msrs[n++].index = MSR_MTRRphysBase(i);
1748 msrs[n++].index = MSR_MTRRphysMask(i);
1749 }
1750 }
1751
1752 msr_data.info = (struct kvm_msrs) {
1753 .nmsrs = n,
1754 };
1755
1756 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
1757 if (ret < 0) {
1758 return ret;
1759 }
1760
1761 for (i = 0; i < ret; i++) {
1762 uint32_t index = msrs[i].index;
1763 switch (index) {
1764 case MSR_IA32_SYSENTER_CS:
1765 env->sysenter_cs = msrs[i].data;
1766 break;
1767 case MSR_IA32_SYSENTER_ESP:
1768 env->sysenter_esp = msrs[i].data;
1769 break;
1770 case MSR_IA32_SYSENTER_EIP:
1771 env->sysenter_eip = msrs[i].data;
1772 break;
1773 case MSR_PAT:
1774 env->pat = msrs[i].data;
1775 break;
1776 case MSR_STAR:
1777 env->star = msrs[i].data;
1778 break;
1779 #ifdef TARGET_X86_64
1780 case MSR_CSTAR:
1781 env->cstar = msrs[i].data;
1782 break;
1783 case MSR_KERNELGSBASE:
1784 env->kernelgsbase = msrs[i].data;
1785 break;
1786 case MSR_FMASK:
1787 env->fmask = msrs[i].data;
1788 break;
1789 case MSR_LSTAR:
1790 env->lstar = msrs[i].data;
1791 break;
1792 #endif
1793 case MSR_IA32_TSC:
1794 env->tsc = msrs[i].data;
1795 break;
1796 case MSR_TSC_ADJUST:
1797 env->tsc_adjust = msrs[i].data;
1798 break;
1799 case MSR_IA32_TSCDEADLINE:
1800 env->tsc_deadline = msrs[i].data;
1801 break;
1802 case MSR_VM_HSAVE_PA:
1803 env->vm_hsave = msrs[i].data;
1804 break;
1805 case MSR_KVM_SYSTEM_TIME:
1806 env->system_time_msr = msrs[i].data;
1807 break;
1808 case MSR_KVM_WALL_CLOCK:
1809 env->wall_clock_msr = msrs[i].data;
1810 break;
1811 case MSR_MCG_STATUS:
1812 env->mcg_status = msrs[i].data;
1813 break;
1814 case MSR_MCG_CTL:
1815 env->mcg_ctl = msrs[i].data;
1816 break;
1817 case MSR_IA32_MISC_ENABLE:
1818 env->msr_ia32_misc_enable = msrs[i].data;
1819 break;
1820 case MSR_IA32_SMBASE:
1821 env->smbase = msrs[i].data;
1822 break;
1823 case MSR_IA32_FEATURE_CONTROL:
1824 env->msr_ia32_feature_control = msrs[i].data;
1825 break;
1826 case MSR_IA32_BNDCFGS:
1827 env->msr_bndcfgs = msrs[i].data;
1828 break;
1829 case MSR_IA32_XSS:
1830 env->xss = msrs[i].data;
1831 break;
1832 default:
1833 if (msrs[i].index >= MSR_MC0_CTL &&
1834 msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
1835 env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
1836 }
1837 break;
1838 case MSR_KVM_ASYNC_PF_EN:
1839 env->async_pf_en_msr = msrs[i].data;
1840 break;
1841 case MSR_KVM_PV_EOI_EN:
1842 env->pv_eoi_en_msr = msrs[i].data;
1843 break;
1844 case MSR_KVM_STEAL_TIME:
1845 env->steal_time_msr = msrs[i].data;
1846 break;
1847 case MSR_CORE_PERF_FIXED_CTR_CTRL:
1848 env->msr_fixed_ctr_ctrl = msrs[i].data;
1849 break;
1850 case MSR_CORE_PERF_GLOBAL_CTRL:
1851 env->msr_global_ctrl = msrs[i].data;
1852 break;
1853 case MSR_CORE_PERF_GLOBAL_STATUS:
1854 env->msr_global_status = msrs[i].data;
1855 break;
1856 case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
1857 env->msr_global_ovf_ctrl = msrs[i].data;
1858 break;
1859 case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
1860 env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
1861 break;
1862 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
1863 env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
1864 break;
1865 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
1866 env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
1867 break;
1868 case HV_X64_MSR_HYPERCALL:
1869 env->msr_hv_hypercall = msrs[i].data;
1870 break;
1871 case HV_X64_MSR_GUEST_OS_ID:
1872 env->msr_hv_guest_os_id = msrs[i].data;
1873 break;
1874 case HV_X64_MSR_APIC_ASSIST_PAGE:
1875 env->msr_hv_vapic = msrs[i].data;
1876 break;
1877 case HV_X64_MSR_REFERENCE_TSC:
1878 env->msr_hv_tsc = msrs[i].data;
1879 break;
1880 case MSR_MTRRdefType:
1881 env->mtrr_deftype = msrs[i].data;
1882 break;
1883 case MSR_MTRRfix64K_00000:
1884 env->mtrr_fixed[0] = msrs[i].data;
1885 break;
1886 case MSR_MTRRfix16K_80000:
1887 env->mtrr_fixed[1] = msrs[i].data;
1888 break;
1889 case MSR_MTRRfix16K_A0000:
1890 env->mtrr_fixed[2] = msrs[i].data;
1891 break;
1892 case MSR_MTRRfix4K_C0000:
1893 env->mtrr_fixed[3] = msrs[i].data;
1894 break;
1895 case MSR_MTRRfix4K_C8000:
1896 env->mtrr_fixed[4] = msrs[i].data;
1897 break;
1898 case MSR_MTRRfix4K_D0000:
1899 env->mtrr_fixed[5] = msrs[i].data;
1900 break;
1901 case MSR_MTRRfix4K_D8000:
1902 env->mtrr_fixed[6] = msrs[i].data;
1903 break;
1904 case MSR_MTRRfix4K_E0000:
1905 env->mtrr_fixed[7] = msrs[i].data;
1906 break;
1907 case MSR_MTRRfix4K_E8000:
1908 env->mtrr_fixed[8] = msrs[i].data;
1909 break;
1910 case MSR_MTRRfix4K_F0000:
1911 env->mtrr_fixed[9] = msrs[i].data;
1912 break;
1913 case MSR_MTRRfix4K_F8000:
1914 env->mtrr_fixed[10] = msrs[i].data;
1915 break;
1916 case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
1917 if (index & 1) {
1918 env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data;
1919 } else {
1920 env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
1921 }
1922 break;
1923 }
1924 }
1925
1926 return 0;
1927 }
1928
1929 static int kvm_put_mp_state(X86CPU *cpu)
1930 {
1931 struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
1932
1933 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
1934 }
1935
1936 static int kvm_get_mp_state(X86CPU *cpu)
1937 {
1938 CPUState *cs = CPU(cpu);
1939 CPUX86State *env = &cpu->env;
1940 struct kvm_mp_state mp_state;
1941 int ret;
1942
1943 ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
1944 if (ret < 0) {
1945 return ret;
1946 }
1947 env->mp_state = mp_state.mp_state;
1948 if (kvm_irqchip_in_kernel()) {
1949 cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
1950 }
1951 return 0;
1952 }
1953
1954 static int kvm_get_apic(X86CPU *cpu)
1955 {
1956 DeviceState *apic = cpu->apic_state;
1957 struct kvm_lapic_state kapic;
1958 int ret;
1959
1960 if (apic && kvm_irqchip_in_kernel()) {
1961 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
1962 if (ret < 0) {
1963 return ret;
1964 }
1965
1966 kvm_get_apic_state(apic, &kapic);
1967 }
1968 return 0;
1969 }
1970
1971 static int kvm_put_apic(X86CPU *cpu)
1972 {
1973 DeviceState *apic = cpu->apic_state;
1974 struct kvm_lapic_state kapic;
1975
1976 if (apic && kvm_irqchip_in_kernel()) {
1977 kvm_put_apic_state(apic, &kapic);
1978
1979 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_LAPIC, &kapic);
1980 }
1981 return 0;
1982 }
1983
1984 static int kvm_put_vcpu_events(X86CPU *cpu, int level)
1985 {
1986 CPUState *cs = CPU(cpu);
1987 CPUX86State *env = &cpu->env;
1988 struct kvm_vcpu_events events = {};
1989
1990 if (!kvm_has_vcpu_events()) {
1991 return 0;
1992 }
1993
1994 events.exception.injected = (env->exception_injected >= 0);
1995 events.exception.nr = env->exception_injected;
1996 events.exception.has_error_code = env->has_error_code;
1997 events.exception.error_code = env->error_code;
1998 events.exception.pad = 0;
1999
2000 events.interrupt.injected = (env->interrupt_injected >= 0);
2001 events.interrupt.nr = env->interrupt_injected;
2002 events.interrupt.soft = env->soft_interrupt;
2003
2004 events.nmi.injected = env->nmi_injected;
2005 events.nmi.pending = env->nmi_pending;
2006 events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
2007 events.nmi.pad = 0;
2008
2009 events.sipi_vector = env->sipi_vector;
2010
2011 if (has_msr_smbase) {
2012 events.smi.smm = !!(env->hflags & HF_SMM_MASK);
2013 events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
2014 if (kvm_irqchip_in_kernel()) {
2015 /* As soon as these are moved to the kernel, remove them
2016 * from cs->interrupt_request.
2017 */
2018 events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
2019 events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
2020 cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
2021 } else {
2022 /* Keep these in cs->interrupt_request. */
2023 events.smi.pending = 0;
2024 events.smi.latched_init = 0;
2025 }
2026 events.flags |= KVM_VCPUEVENT_VALID_SMM;
2027 }
2028
2029 events.flags = 0;
2030 if (level >= KVM_PUT_RESET_STATE) {
2031 events.flags |=
2032 KVM_VCPUEVENT_VALID_NMI_PENDING | KVM_VCPUEVENT_VALID_SIPI_VECTOR;
2033 }
2034
2035 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
2036 }
2037
2038 static int kvm_get_vcpu_events(X86CPU *cpu)
2039 {
2040 CPUX86State *env = &cpu->env;
2041 struct kvm_vcpu_events events;
2042 int ret;
2043
2044 if (!kvm_has_vcpu_events()) {
2045 return 0;
2046 }
2047
2048 memset(&events, 0, sizeof(events));
2049 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
2050 if (ret < 0) {
2051 return ret;
2052 }
2053 env->exception_injected =
2054 events.exception.injected ? events.exception.nr : -1;
2055 env->has_error_code = events.exception.has_error_code;
2056 env->error_code = events.exception.error_code;
2057
2058 env->interrupt_injected =
2059 events.interrupt.injected ? events.interrupt.nr : -1;
2060 env->soft_interrupt = events.interrupt.soft;
2061
2062 env->nmi_injected = events.nmi.injected;
2063 env->nmi_pending = events.nmi.pending;
2064 if (events.nmi.masked) {
2065 env->hflags2 |= HF2_NMI_MASK;
2066 } else {
2067 env->hflags2 &= ~HF2_NMI_MASK;
2068 }
2069
2070 if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
2071 if (events.smi.smm) {
2072 env->hflags |= HF_SMM_MASK;
2073 } else {
2074 env->hflags &= ~HF_SMM_MASK;
2075 }
2076 if (events.smi.pending) {
2077 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2078 } else {
2079 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2080 }
2081 if (events.smi.smm_inside_nmi) {
2082 env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
2083 } else {
2084 env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
2085 }
2086 if (events.smi.latched_init) {
2087 cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2088 } else {
2089 cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2090 }
2091 }
2092
2093 env->sipi_vector = events.sipi_vector;
2094
2095 return 0;
2096 }
2097
2098 static int kvm_guest_debug_workarounds(X86CPU *cpu)
2099 {
2100 CPUState *cs = CPU(cpu);
2101 CPUX86State *env = &cpu->env;
2102 int ret = 0;
2103 unsigned long reinject_trap = 0;
2104
2105 if (!kvm_has_vcpu_events()) {
2106 if (env->exception_injected == 1) {
2107 reinject_trap = KVM_GUESTDBG_INJECT_DB;
2108 } else if (env->exception_injected == 3) {
2109 reinject_trap = KVM_GUESTDBG_INJECT_BP;
2110 }
2111 env->exception_injected = -1;
2112 }
2113
2114 /*
2115 * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
2116 * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
2117 * by updating the debug state once again if single-stepping is on.
2118 * Another reason to call kvm_update_guest_debug here is a pending debug
2119 * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
2120 * reinject them via SET_GUEST_DEBUG.
2121 */
2122 if (reinject_trap ||
2123 (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
2124 ret = kvm_update_guest_debug(cs, reinject_trap);
2125 }
2126 return ret;
2127 }
2128
2129 static int kvm_put_debugregs(X86CPU *cpu)
2130 {
2131 CPUX86State *env = &cpu->env;
2132 struct kvm_debugregs dbgregs;
2133 int i;
2134
2135 if (!kvm_has_debugregs()) {
2136 return 0;
2137 }
2138
2139 for (i = 0; i < 4; i++) {
2140 dbgregs.db[i] = env->dr[i];
2141 }
2142 dbgregs.dr6 = env->dr[6];
2143 dbgregs.dr7 = env->dr[7];
2144 dbgregs.flags = 0;
2145
2146 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
2147 }
2148
2149 static int kvm_get_debugregs(X86CPU *cpu)
2150 {
2151 CPUX86State *env = &cpu->env;
2152 struct kvm_debugregs dbgregs;
2153 int i, ret;
2154
2155 if (!kvm_has_debugregs()) {
2156 return 0;
2157 }
2158
2159 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
2160 if (ret < 0) {
2161 return ret;
2162 }
2163 for (i = 0; i < 4; i++) {
2164 env->dr[i] = dbgregs.db[i];
2165 }
2166 env->dr[4] = env->dr[6] = dbgregs.dr6;
2167 env->dr[5] = env->dr[7] = dbgregs.dr7;
2168
2169 return 0;
2170 }
2171
2172 int kvm_arch_put_registers(CPUState *cpu, int level)
2173 {
2174 X86CPU *x86_cpu = X86_CPU(cpu);
2175 int ret;
2176
2177 assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
2178
2179 if (level >= KVM_PUT_RESET_STATE && has_msr_feature_control) {
2180 ret = kvm_put_msr_feature_control(x86_cpu);
2181 if (ret < 0) {
2182 return ret;
2183 }
2184 }
2185
2186 ret = kvm_getput_regs(x86_cpu, 1);
2187 if (ret < 0) {
2188 return ret;
2189 }
2190 ret = kvm_put_xsave(x86_cpu);
2191 if (ret < 0) {
2192 return ret;
2193 }
2194 ret = kvm_put_xcrs(x86_cpu);
2195 if (ret < 0) {
2196 return ret;
2197 }
2198 ret = kvm_put_sregs(x86_cpu);
2199 if (ret < 0) {
2200 return ret;
2201 }
2202 /* must be before kvm_put_msrs */
2203 ret = kvm_inject_mce_oldstyle(x86_cpu);
2204 if (ret < 0) {
2205 return ret;
2206 }
2207 ret = kvm_put_msrs(x86_cpu, level);
2208 if (ret < 0) {
2209 return ret;
2210 }
2211 if (level >= KVM_PUT_RESET_STATE) {
2212 ret = kvm_put_mp_state(x86_cpu);
2213 if (ret < 0) {
2214 return ret;
2215 }
2216 ret = kvm_put_apic(x86_cpu);
2217 if (ret < 0) {
2218 return ret;
2219 }
2220 }
2221
2222 ret = kvm_put_tscdeadline_msr(x86_cpu);
2223 if (ret < 0) {
2224 return ret;
2225 }
2226
2227 ret = kvm_put_vcpu_events(x86_cpu, level);
2228 if (ret < 0) {
2229 return ret;
2230 }
2231 ret = kvm_put_debugregs(x86_cpu);
2232 if (ret < 0) {
2233 return ret;
2234 }
2235 /* must be last */
2236 ret = kvm_guest_debug_workarounds(x86_cpu);
2237 if (ret < 0) {
2238 return ret;
2239 }
2240 return 0;
2241 }
2242
2243 int kvm_arch_get_registers(CPUState *cs)
2244 {
2245 X86CPU *cpu = X86_CPU(cs);
2246 int ret;
2247
2248 assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
2249
2250 ret = kvm_getput_regs(cpu, 0);
2251 if (ret < 0) {
2252 return ret;
2253 }
2254 ret = kvm_get_xsave(cpu);
2255 if (ret < 0) {
2256 return ret;
2257 }
2258 ret = kvm_get_xcrs(cpu);
2259 if (ret < 0) {
2260 return ret;
2261 }
2262 ret = kvm_get_sregs(cpu);
2263 if (ret < 0) {
2264 return ret;
2265 }
2266 ret = kvm_get_msrs(cpu);
2267 if (ret < 0) {
2268 return ret;
2269 }
2270 ret = kvm_get_mp_state(cpu);
2271 if (ret < 0) {
2272 return ret;
2273 }
2274 ret = kvm_get_apic(cpu);
2275 if (ret < 0) {
2276 return ret;
2277 }
2278 ret = kvm_get_vcpu_events(cpu);
2279 if (ret < 0) {
2280 return ret;
2281 }
2282 ret = kvm_get_debugregs(cpu);
2283 if (ret < 0) {
2284 return ret;
2285 }
2286 return 0;
2287 }
2288
2289 void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
2290 {
2291 X86CPU *x86_cpu = X86_CPU(cpu);
2292 CPUX86State *env = &x86_cpu->env;
2293 int ret;
2294
2295 /* Inject NMI */
2296 if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
2297 if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
2298 qemu_mutex_lock_iothread();
2299 cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
2300 qemu_mutex_unlock_iothread();
2301 DPRINTF("injected NMI\n");
2302 ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
2303 if (ret < 0) {
2304 fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
2305 strerror(-ret));
2306 }
2307 }
2308 if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
2309 qemu_mutex_lock_iothread();
2310 cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
2311 qemu_mutex_unlock_iothread();
2312 DPRINTF("injected SMI\n");
2313 ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
2314 if (ret < 0) {
2315 fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
2316 strerror(-ret));
2317 }
2318 }
2319 }
2320
2321 if (!kvm_irqchip_in_kernel()) {
2322 qemu_mutex_lock_iothread();
2323 }
2324
2325 /* Force the VCPU out of its inner loop to process any INIT requests
2326 * or (for userspace APIC, but it is cheap to combine the checks here)
2327 * pending TPR access reports.
2328 */
2329 if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
2330 if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
2331 !(env->hflags & HF_SMM_MASK)) {
2332 cpu->exit_request = 1;
2333 }
2334 if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
2335 cpu->exit_request = 1;
2336 }
2337 }
2338
2339 if (!kvm_irqchip_in_kernel()) {
2340 /* Try to inject an interrupt if the guest can accept it */
2341 if (run->ready_for_interrupt_injection &&
2342 (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
2343 (env->eflags & IF_MASK)) {
2344 int irq;
2345
2346 cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
2347 irq = cpu_get_pic_interrupt(env);
2348 if (irq >= 0) {
2349 struct kvm_interrupt intr;
2350
2351 intr.irq = irq;
2352 DPRINTF("injected interrupt %d\n", irq);
2353 ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
2354 if (ret < 0) {
2355 fprintf(stderr,
2356 "KVM: injection failed, interrupt lost (%s)\n",
2357 strerror(-ret));
2358 }
2359 }
2360 }
2361
2362 /* If we have an interrupt but the guest is not ready to receive an
2363 * interrupt, request an interrupt window exit. This will
2364 * cause a return to userspace as soon as the guest is ready to
2365 * receive interrupts. */
2366 if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
2367 run->request_interrupt_window = 1;
2368 } else {
2369 run->request_interrupt_window = 0;
2370 }
2371
2372 DPRINTF("setting tpr\n");
2373 run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
2374
2375 qemu_mutex_unlock_iothread();
2376 }
2377 }
2378
2379 MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
2380 {
2381 X86CPU *x86_cpu = X86_CPU(cpu);
2382 CPUX86State *env = &x86_cpu->env;
2383
2384 if (run->flags & KVM_RUN_X86_SMM) {
2385 env->hflags |= HF_SMM_MASK;
2386 } else {
2387 env->hflags &= HF_SMM_MASK;
2388 }
2389 if (run->if_flag) {
2390 env->eflags |= IF_MASK;
2391 } else {
2392 env->eflags &= ~IF_MASK;
2393 }
2394
2395 /* We need to protect the apic state against concurrent accesses from
2396 * different threads in case the userspace irqchip is used. */
2397 if (!kvm_irqchip_in_kernel()) {
2398 qemu_mutex_lock_iothread();
2399 }
2400 cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
2401 cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
2402 if (!kvm_irqchip_in_kernel()) {
2403 qemu_mutex_unlock_iothread();
2404 }
2405 return cpu_get_mem_attrs(env);
2406 }
2407
2408 int kvm_arch_process_async_events(CPUState *cs)
2409 {
2410 X86CPU *cpu = X86_CPU(cs);
2411 CPUX86State *env = &cpu->env;
2412
2413 if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
2414 /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
2415 assert(env->mcg_cap);
2416
2417 cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
2418
2419 kvm_cpu_synchronize_state(cs);
2420
2421 if (env->exception_injected == EXCP08_DBLE) {
2422 /* this means triple fault */
2423 qemu_system_reset_request();
2424 cs->exit_request = 1;
2425 return 0;
2426 }
2427 env->exception_injected = EXCP12_MCHK;
2428 env->has_error_code = 0;
2429
2430 cs->halted = 0;
2431 if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
2432 env->mp_state = KVM_MP_STATE_RUNNABLE;
2433 }
2434 }
2435
2436 if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
2437 !(env->hflags & HF_SMM_MASK)) {
2438 kvm_cpu_synchronize_state(cs);
2439 do_cpu_init(cpu);
2440 }
2441
2442 if (kvm_irqchip_in_kernel()) {
2443 return 0;
2444 }
2445
2446 if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
2447 cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
2448 apic_poll_irq(cpu->apic_state);
2449 }
2450 if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
2451 (env->eflags & IF_MASK)) ||
2452 (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
2453 cs->halted = 0;
2454 }
2455 if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
2456 kvm_cpu_synchronize_state(cs);
2457 do_cpu_sipi(cpu);
2458 }
2459 if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
2460 cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
2461 kvm_cpu_synchronize_state(cs);
2462 apic_handle_tpr_access_report(cpu->apic_state, env->eip,
2463 env->tpr_access_type);
2464 }
2465
2466 return cs->halted;
2467 }
2468
2469 static int kvm_handle_halt(X86CPU *cpu)
2470 {
2471 CPUState *cs = CPU(cpu);
2472 CPUX86State *env = &cpu->env;
2473
2474 if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
2475 (env->eflags & IF_MASK)) &&
2476 !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
2477 cs->halted = 1;
2478 return EXCP_HLT;
2479 }
2480
2481 return 0;
2482 }
2483
2484 static int kvm_handle_tpr_access(X86CPU *cpu)
2485 {
2486 CPUState *cs = CPU(cpu);
2487 struct kvm_run *run = cs->kvm_run;
2488
2489 apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
2490 run->tpr_access.is_write ? TPR_ACCESS_WRITE
2491 : TPR_ACCESS_READ);
2492 return 1;
2493 }
2494
2495 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2496 {
2497 static const uint8_t int3 = 0xcc;
2498
2499 if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
2500 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
2501 return -EINVAL;
2502 }
2503 return 0;
2504 }
2505
2506 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2507 {
2508 uint8_t int3;
2509
2510 if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
2511 cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
2512 return -EINVAL;
2513 }
2514 return 0;
2515 }
2516
2517 static struct {
2518 target_ulong addr;
2519 int len;
2520 int type;
2521 } hw_breakpoint[4];
2522
2523 static int nb_hw_breakpoint;
2524
2525 static int find_hw_breakpoint(target_ulong addr, int len, int type)
2526 {
2527 int n;
2528
2529 for (n = 0; n < nb_hw_breakpoint; n++) {
2530 if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
2531 (hw_breakpoint[n].len == len || len == -1)) {
2532 return n;
2533 }
2534 }
2535 return -1;
2536 }
2537
2538 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
2539 target_ulong len, int type)
2540 {
2541 switch (type) {
2542 case GDB_BREAKPOINT_HW:
2543 len = 1;
2544 break;
2545 case GDB_WATCHPOINT_WRITE:
2546 case GDB_WATCHPOINT_ACCESS:
2547 switch (len) {
2548 case 1:
2549 break;
2550 case 2:
2551 case 4:
2552 case 8:
2553 if (addr & (len - 1)) {
2554 return -EINVAL;
2555 }
2556 break;
2557 default:
2558 return -EINVAL;
2559 }
2560 break;
2561 default:
2562 return -ENOSYS;
2563 }
2564
2565 if (nb_hw_breakpoint == 4) {
2566 return -ENOBUFS;
2567 }
2568 if (find_hw_breakpoint(addr, len, type) >= 0) {
2569 return -EEXIST;
2570 }
2571 hw_breakpoint[nb_hw_breakpoint].addr = addr;
2572 hw_breakpoint[nb_hw_breakpoint].len = len;
2573 hw_breakpoint[nb_hw_breakpoint].type = type;
2574 nb_hw_breakpoint++;
2575
2576 return 0;
2577 }
2578
2579 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
2580 target_ulong len, int type)
2581 {
2582 int n;
2583
2584 n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
2585 if (n < 0) {
2586 return -ENOENT;
2587 }
2588 nb_hw_breakpoint--;
2589 hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
2590
2591 return 0;
2592 }
2593
2594 void kvm_arch_remove_all_hw_breakpoints(void)
2595 {
2596 nb_hw_breakpoint = 0;
2597 }
2598
2599 static CPUWatchpoint hw_watchpoint;
2600
2601 static int kvm_handle_debug(X86CPU *cpu,
2602 struct kvm_debug_exit_arch *arch_info)
2603 {
2604 CPUState *cs = CPU(cpu);
2605 CPUX86State *env = &cpu->env;
2606 int ret = 0;
2607 int n;
2608
2609 if (arch_info->exception == 1) {
2610 if (arch_info->dr6 & (1 << 14)) {
2611 if (cs->singlestep_enabled) {
2612 ret = EXCP_DEBUG;
2613 }
2614 } else {
2615 for (n = 0; n < 4; n++) {
2616 if (arch_info->dr6 & (1 << n)) {
2617 switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
2618 case 0x0:
2619 ret = EXCP_DEBUG;
2620 break;
2621 case 0x1:
2622 ret = EXCP_DEBUG;
2623 cs->watchpoint_hit = &hw_watchpoint;
2624 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
2625 hw_watchpoint.flags = BP_MEM_WRITE;
2626 break;
2627 case 0x3:
2628 ret = EXCP_DEBUG;
2629 cs->watchpoint_hit = &hw_watchpoint;
2630 hw_watchpoint.vaddr = hw_breakpoint[n].addr;
2631 hw_watchpoint.flags = BP_MEM_ACCESS;
2632 break;
2633 }
2634 }
2635 }
2636 }
2637 } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
2638 ret = EXCP_DEBUG;
2639 }
2640 if (ret == 0) {
2641 cpu_synchronize_state(cs);
2642 assert(env->exception_injected == -1);
2643
2644 /* pass to guest */
2645 env->exception_injected = arch_info->exception;
2646 env->has_error_code = 0;
2647 }
2648
2649 return ret;
2650 }
2651
2652 void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
2653 {
2654 const uint8_t type_code[] = {
2655 [GDB_BREAKPOINT_HW] = 0x0,
2656 [GDB_WATCHPOINT_WRITE] = 0x1,
2657 [GDB_WATCHPOINT_ACCESS] = 0x3
2658 };
2659 const uint8_t len_code[] = {
2660 [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
2661 };
2662 int n;
2663
2664 if (kvm_sw_breakpoints_active(cpu)) {
2665 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
2666 }
2667 if (nb_hw_breakpoint > 0) {
2668 dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
2669 dbg->arch.debugreg[7] = 0x0600;
2670 for (n = 0; n < nb_hw_breakpoint; n++) {
2671 dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
2672 dbg->arch.debugreg[7] |= (2 << (n * 2)) |
2673 (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
2674 ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
2675 }
2676 }
2677 }
2678
2679 static bool host_supports_vmx(void)
2680 {
2681 uint32_t ecx, unused;
2682
2683 host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
2684 return ecx & CPUID_EXT_VMX;
2685 }
2686
2687 #define VMX_INVALID_GUEST_STATE 0x80000021
2688
2689 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
2690 {
2691 X86CPU *cpu = X86_CPU(cs);
2692 uint64_t code;
2693 int ret;
2694
2695 switch (run->exit_reason) {
2696 case KVM_EXIT_HLT:
2697 DPRINTF("handle_hlt\n");
2698 qemu_mutex_lock_iothread();
2699 ret = kvm_handle_halt(cpu);
2700 qemu_mutex_unlock_iothread();
2701 break;
2702 case KVM_EXIT_SET_TPR:
2703 ret = 0;
2704 break;
2705 case KVM_EXIT_TPR_ACCESS:
2706 qemu_mutex_lock_iothread();
2707 ret = kvm_handle_tpr_access(cpu);
2708 qemu_mutex_unlock_iothread();
2709 break;
2710 case KVM_EXIT_FAIL_ENTRY:
2711 code = run->fail_entry.hardware_entry_failure_reason;
2712 fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
2713 code);
2714 if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
2715 fprintf(stderr,
2716 "\nIf you're running a guest on an Intel machine without "
2717 "unrestricted mode\n"
2718 "support, the failure can be most likely due to the guest "
2719 "entering an invalid\n"
2720 "state for Intel VT. For example, the guest maybe running "
2721 "in big real mode\n"
2722 "which is not supported on less recent Intel processors."
2723 "\n\n");
2724 }
2725 ret = -1;
2726 break;
2727 case KVM_EXIT_EXCEPTION:
2728 fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
2729 run->ex.exception, run->ex.error_code);
2730 ret = -1;
2731 break;
2732 case KVM_EXIT_DEBUG:
2733 DPRINTF("kvm_exit_debug\n");
2734 qemu_mutex_lock_iothread();
2735 ret = kvm_handle_debug(cpu, &run->debug.arch);
2736 qemu_mutex_unlock_iothread();
2737 break;
2738 default:
2739 fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
2740 ret = -1;
2741 break;
2742 }
2743
2744 return ret;
2745 }
2746
2747 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
2748 {
2749 X86CPU *cpu = X86_CPU(cs);
2750 CPUX86State *env = &cpu->env;
2751
2752 kvm_cpu_synchronize_state(cs);
2753 return !(env->cr[0] & CR0_PE_MASK) ||
2754 ((env->segs[R_CS].selector & 3) != 3);
2755 }
2756
2757 void kvm_arch_init_irq_routing(KVMState *s)
2758 {
2759 if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
2760 /* If kernel can't do irq routing, interrupt source
2761 * override 0->2 cannot be set up as required by HPET.
2762 * So we have to disable it.
2763 */
2764 no_hpet = 1;
2765 }
2766 /* We know at this point that we're using the in-kernel
2767 * irqchip, so we can use irqfds, and on x86 we know
2768 * we can use msi via irqfd and GSI routing.
2769 */
2770 kvm_msi_via_irqfd_allowed = true;
2771 kvm_gsi_routing_allowed = true;
2772 }
2773
2774 /* Classic KVM device assignment interface. Will remain x86 only. */
2775 int kvm_device_pci_assign(KVMState *s, PCIHostDeviceAddress *dev_addr,
2776 uint32_t flags, uint32_t *dev_id)
2777 {
2778 struct kvm_assigned_pci_dev dev_data = {
2779 .segnr = dev_addr->domain,
2780 .busnr = dev_addr->bus,
2781 .devfn = PCI_DEVFN(dev_addr->slot, dev_addr->function),
2782 .flags = flags,
2783 };
2784 int ret;
2785
2786 dev_data.assigned_dev_id =
2787 (dev_addr->domain << 16) | (dev_addr->bus << 8) | dev_data.devfn;
2788
2789 ret = kvm_vm_ioctl(s, KVM_ASSIGN_PCI_DEVICE, &dev_data);
2790 if (ret < 0) {
2791 return ret;
2792 }
2793
2794 *dev_id = dev_data.assigned_dev_id;
2795
2796 return 0;
2797 }
2798
2799 int kvm_device_pci_deassign(KVMState *s, uint32_t dev_id)
2800 {
2801 struct kvm_assigned_pci_dev dev_data = {
2802 .assigned_dev_id = dev_id,
2803 };
2804
2805 return kvm_vm_ioctl(s, KVM_DEASSIGN_PCI_DEVICE, &dev_data);
2806 }
2807
2808 static int kvm_assign_irq_internal(KVMState *s, uint32_t dev_id,
2809 uint32_t irq_type, uint32_t guest_irq)
2810 {
2811 struct kvm_assigned_irq assigned_irq = {
2812 .assigned_dev_id = dev_id,
2813 .guest_irq = guest_irq,
2814 .flags = irq_type,
2815 };
2816
2817 if (kvm_check_extension(s, KVM_CAP_ASSIGN_DEV_IRQ)) {
2818 return kvm_vm_ioctl(s, KVM_ASSIGN_DEV_IRQ, &assigned_irq);
2819 } else {
2820 return kvm_vm_ioctl(s, KVM_ASSIGN_IRQ, &assigned_irq);
2821 }
2822 }
2823
2824 int kvm_device_intx_assign(KVMState *s, uint32_t dev_id, bool use_host_msi,
2825 uint32_t guest_irq)
2826 {
2827 uint32_t irq_type = KVM_DEV_IRQ_GUEST_INTX |
2828 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX);
2829
2830 return kvm_assign_irq_internal(s, dev_id, irq_type, guest_irq);
2831 }
2832
2833 int kvm_device_intx_set_mask(KVMState *s, uint32_t dev_id, bool masked)
2834 {
2835 struct kvm_assigned_pci_dev dev_data = {
2836 .assigned_dev_id = dev_id,
2837 .flags = masked ? KVM_DEV_ASSIGN_MASK_INTX : 0,
2838 };
2839
2840 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_INTX_MASK, &dev_data);
2841 }
2842
2843 static int kvm_deassign_irq_internal(KVMState *s, uint32_t dev_id,
2844 uint32_t type)
2845 {
2846 struct kvm_assigned_irq assigned_irq = {
2847 .assigned_dev_id = dev_id,
2848 .flags = type,
2849 };
2850
2851 return kvm_vm_ioctl(s, KVM_DEASSIGN_DEV_IRQ, &assigned_irq);
2852 }
2853
2854 int kvm_device_intx_deassign(KVMState *s, uint32_t dev_id, bool use_host_msi)
2855 {
2856 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_INTX |
2857 (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX));
2858 }
2859
2860 int kvm_device_msi_assign(KVMState *s, uint32_t dev_id, int virq)
2861 {
2862 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSI |
2863 KVM_DEV_IRQ_GUEST_MSI, virq);
2864 }
2865
2866 int kvm_device_msi_deassign(KVMState *s, uint32_t dev_id)
2867 {
2868 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSI |
2869 KVM_DEV_IRQ_HOST_MSI);
2870 }
2871
2872 bool kvm_device_msix_supported(KVMState *s)
2873 {
2874 /* The kernel lacks a corresponding KVM_CAP, so we probe by calling
2875 * KVM_ASSIGN_SET_MSIX_NR with an invalid parameter. */
2876 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, NULL) == -EFAULT;
2877 }
2878
2879 int kvm_device_msix_init_vectors(KVMState *s, uint32_t dev_id,
2880 uint32_t nr_vectors)
2881 {
2882 struct kvm_assigned_msix_nr msix_nr = {
2883 .assigned_dev_id = dev_id,
2884 .entry_nr = nr_vectors,
2885 };
2886
2887 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, &msix_nr);
2888 }
2889
2890 int kvm_device_msix_set_vector(KVMState *s, uint32_t dev_id, uint32_t vector,
2891 int virq)
2892 {
2893 struct kvm_assigned_msix_entry msix_entry = {
2894 .assigned_dev_id = dev_id,
2895 .gsi = virq,
2896 .entry = vector,
2897 };
2898
2899 return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_ENTRY, &msix_entry);
2900 }
2901
2902 int kvm_device_msix_assign(KVMState *s, uint32_t dev_id)
2903 {
2904 return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSIX |
2905 KVM_DEV_IRQ_GUEST_MSIX, 0);
2906 }
2907
2908 int kvm_device_msix_deassign(KVMState *s, uint32_t dev_id)
2909 {
2910 return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSIX |
2911 KVM_DEV_IRQ_HOST_MSIX);
2912 }
2913
2914 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
2915 uint64_t address, uint32_t data)
2916 {
2917 return 0;
2918 }
2919
2920 int kvm_arch_msi_data_to_gsi(uint32_t data)
2921 {
2922 abort();
2923 }