time_drift_fix is x86 only, rather than !ia64
[qemu/qemu-dev-zwu.git] / qemu-kvm.c
blobbe1dac2ca788a3650432eae95595f0bb1b48057c
1 /*
2 * qemu/kvm integration
4 * Copyright (C) 2006-2008 Qumranet Technologies
6 * Licensed under the terms of the GNU GPL version 2 or higher.
7 */
8 #include "config.h"
9 #include "config-host.h"
11 #include <assert.h>
12 #include <string.h>
13 #include "hw/hw.h"
14 #include "sysemu.h"
15 #include "qemu-common.h"
16 #include "console.h"
17 #include "block.h"
18 #include "compatfd.h"
19 #include "gdbstub.h"
20 #include "monitor.h"
22 #include "qemu-kvm.h"
23 #include "libkvm.h"
25 #include <pthread.h>
26 #include <sys/utsname.h>
27 #include <sys/syscall.h>
28 #include <sys/mman.h>
29 #include <sys/ioctl.h>
30 #include "compatfd.h"
31 #include <sys/prctl.h>
33 #define false 0
34 #define true 1
36 #ifndef PR_MCE_KILL
37 #define PR_MCE_KILL 33
38 #endif
40 #ifndef BUS_MCEERR_AR
41 #define BUS_MCEERR_AR 4
42 #endif
43 #ifndef BUS_MCEERR_AO
44 #define BUS_MCEERR_AO 5
45 #endif
47 #define EXPECTED_KVM_API_VERSION 12
49 #if EXPECTED_KVM_API_VERSION != KVM_API_VERSION
50 #error libkvm: userspace and kernel version mismatch
51 #endif
53 int kvm_irqchip = 1;
54 int kvm_pit = 1;
55 int kvm_pit_reinject = 1;
56 int kvm_nested = 0;
59 KVMState *kvm_state;
60 kvm_context_t kvm_context;
62 pthread_mutex_t qemu_mutex = PTHREAD_MUTEX_INITIALIZER;
63 pthread_cond_t qemu_vcpu_cond = PTHREAD_COND_INITIALIZER;
64 pthread_cond_t qemu_system_cond = PTHREAD_COND_INITIALIZER;
65 pthread_cond_t qemu_pause_cond = PTHREAD_COND_INITIALIZER;
66 pthread_cond_t qemu_work_cond = PTHREAD_COND_INITIALIZER;
67 __thread CPUState *current_env;
69 static int qemu_system_ready;
71 #define SIG_IPI (SIGRTMIN+4)
73 pthread_t io_thread;
74 static int io_thread_fd = -1;
75 static int io_thread_sigfd = -1;
77 static CPUState *kvm_debug_cpu_requested;
79 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
80 /* The list of ioperm_data */
81 static QLIST_HEAD(, ioperm_data) ioperm_head;
82 #endif
84 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
86 int kvm_abi = EXPECTED_KVM_API_VERSION;
87 int kvm_page_size;
89 #ifdef KVM_CAP_SET_GUEST_DEBUG
90 static int kvm_debug(CPUState *env,
91 struct kvm_debug_exit_arch *arch_info)
93 int handle = kvm_arch_debug(arch_info);
95 if (handle) {
96 kvm_debug_cpu_requested = env;
97 env->stopped = 1;
99 return handle;
101 #endif
103 static int handle_unhandled(uint64_t reason)
105 fprintf(stderr, "kvm: unhandled exit %" PRIx64 "\n", reason);
106 return -EINVAL;
109 #define VMX_INVALID_GUEST_STATE 0x80000021
111 static int handle_failed_vmentry(uint64_t reason)
113 fprintf(stderr, "kvm: vm entry failed with error 0x%" PRIx64 "\n\n", reason);
115 /* Perhaps we will need to check if this machine is intel since exit reason 0x21
116 has a different interpretation on SVM */
117 if (reason == VMX_INVALID_GUEST_STATE) {
118 fprintf(stderr, "If you're runnning a guest on an Intel machine without\n");
119 fprintf(stderr, "unrestricted mode support, the failure can be most likely\n");
120 fprintf(stderr, "due to the guest entering an invalid state for Intel VT.\n");
121 fprintf(stderr, "For example, the guest maybe running in big real mode\n");
122 fprintf(stderr, "which is not supported on less recent Intel processors.\n\n");
125 return -EINVAL;
128 static inline void set_gsi(kvm_context_t kvm, unsigned int gsi)
130 uint32_t *bitmap = kvm->used_gsi_bitmap;
132 if (gsi < kvm->max_gsi)
133 bitmap[gsi / 32] |= 1U << (gsi % 32);
134 else
135 DPRINTF("Invalid GSI %u\n", gsi);
138 static inline void clear_gsi(kvm_context_t kvm, unsigned int gsi)
140 uint32_t *bitmap = kvm->used_gsi_bitmap;
142 if (gsi < kvm->max_gsi)
143 bitmap[gsi / 32] &= ~(1U << (gsi % 32));
144 else
145 DPRINTF("Invalid GSI %u\n", gsi);
148 static int kvm_create_context(void);
150 int kvm_init(int smp_cpus)
152 int fd;
153 int r, gsi_count;
156 fd = open("/dev/kvm", O_RDWR);
157 if (fd == -1) {
158 perror("open /dev/kvm");
159 return -1;
161 r = ioctl(fd, KVM_GET_API_VERSION, 0);
162 if (r == -1) {
163 fprintf(stderr,
164 "kvm kernel version too old: "
165 "KVM_GET_API_VERSION ioctl not supported\n");
166 goto out_close;
168 if (r < EXPECTED_KVM_API_VERSION) {
169 fprintf(stderr, "kvm kernel version too old: "
170 "We expect API version %d or newer, but got "
171 "version %d\n", EXPECTED_KVM_API_VERSION, r);
172 goto out_close;
174 if (r > EXPECTED_KVM_API_VERSION) {
175 fprintf(stderr, "kvm userspace version too old\n");
176 goto out_close;
178 kvm_abi = r;
179 kvm_page_size = getpagesize();
180 kvm_state = qemu_mallocz(sizeof(*kvm_state));
181 kvm_context = &kvm_state->kvm_context;
183 kvm_state->fd = fd;
184 kvm_state->vmfd = -1;
185 kvm_context->opaque = cpu_single_env;
186 kvm_context->dirty_pages_log_all = 0;
187 kvm_context->no_irqchip_creation = 0;
188 kvm_context->no_pit_creation = 0;
190 #ifdef KVM_CAP_SET_GUEST_DEBUG
191 QTAILQ_INIT(&kvm_state->kvm_sw_breakpoints);
192 #endif
194 gsi_count = kvm_get_gsi_count(kvm_context);
195 if (gsi_count > 0) {
196 int gsi_bits, i;
198 /* Round up so we can search ints using ffs */
199 gsi_bits = ALIGN(gsi_count, 32);
200 kvm_context->used_gsi_bitmap = qemu_mallocz(gsi_bits / 8);
201 kvm_context->max_gsi = gsi_bits;
203 /* Mark any over-allocated bits as already in use */
204 for (i = gsi_count; i < gsi_bits; i++)
205 set_gsi(kvm_context, i);
208 kvm_cpu_register_phys_memory_client();
210 pthread_mutex_lock(&qemu_mutex);
211 return kvm_create_context();
213 out_close:
214 close(fd);
215 return -1;
218 static void kvm_finalize(KVMState *s)
220 /* FIXME
221 if (kvm->vcpu_fd[0] != -1)
222 close(kvm->vcpu_fd[0]);
223 if (kvm->vm_fd != -1)
224 close(kvm->vm_fd);
226 close(s->fd);
227 free(s);
230 void kvm_disable_irqchip_creation(kvm_context_t kvm)
232 kvm->no_irqchip_creation = 1;
235 void kvm_disable_pit_creation(kvm_context_t kvm)
237 kvm->no_pit_creation = 1;
240 static void kvm_reset_vcpu(void *opaque)
242 CPUState *env = opaque;
244 kvm_arch_cpu_reset(env);
247 static void kvm_create_vcpu(CPUState *env, int id)
249 long mmap_size;
250 int r;
251 KVMState *s = kvm_state;
253 r = kvm_vm_ioctl(kvm_state, KVM_CREATE_VCPU, id);
254 if (r < 0) {
255 fprintf(stderr, "kvm_create_vcpu: %m\n");
256 fprintf(stderr, "Failed to create vCPU. Check the -smp parameter.\n");
257 goto err;
260 env->kvm_fd = r;
261 env->kvm_state = kvm_state;
263 mmap_size = kvm_ioctl(kvm_state, KVM_GET_VCPU_MMAP_SIZE, 0);
264 if (mmap_size < 0) {
265 fprintf(stderr, "get vcpu mmap size: %m\n");
266 goto err_fd;
268 env->kvm_run =
269 mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, env->kvm_fd,
271 if (env->kvm_run == MAP_FAILED) {
272 fprintf(stderr, "mmap vcpu area: %m\n");
273 goto err_fd;
276 #ifdef KVM_CAP_COALESCED_MMIO
277 if (s->coalesced_mmio && !s->coalesced_mmio_ring)
278 s->coalesced_mmio_ring = (void *) env->kvm_run +
279 s->coalesced_mmio * PAGE_SIZE;
280 #endif
282 r = kvm_arch_init_vcpu(env);
283 if (r == 0) {
284 qemu_register_reset(kvm_reset_vcpu, env);
287 return;
288 err_fd:
289 close(env->kvm_fd);
290 err:
291 /* We're no good with semi-broken states. */
292 abort();
295 static int kvm_set_boot_vcpu_id(kvm_context_t kvm, uint32_t id)
297 #ifdef KVM_CAP_SET_BOOT_CPU_ID
298 int r = kvm_ioctl(kvm_state, KVM_CHECK_EXTENSION, KVM_CAP_SET_BOOT_CPU_ID);
299 if (r > 0)
300 return kvm_vm_ioctl(kvm_state, KVM_SET_BOOT_CPU_ID, id);
301 return -ENOSYS;
302 #else
303 return -ENOSYS;
304 #endif
307 int kvm_create_vm(kvm_context_t kvm)
309 int fd;
310 #ifdef KVM_CAP_IRQ_ROUTING
311 kvm->irq_routes = qemu_mallocz(sizeof(*kvm->irq_routes));
312 kvm->nr_allocated_irq_routes = 0;
313 #endif
315 fd = kvm_ioctl(kvm_state, KVM_CREATE_VM, 0);
316 if (fd < 0) {
317 fprintf(stderr, "kvm_create_vm: %m\n");
318 return -1;
320 kvm_state->vmfd = fd;
321 return 0;
324 static int kvm_create_default_phys_mem(kvm_context_t kvm,
325 unsigned long phys_mem_bytes,
326 void **vm_mem)
328 #ifdef KVM_CAP_USER_MEMORY
329 int r = kvm_ioctl(kvm_state, KVM_CHECK_EXTENSION, KVM_CAP_USER_MEMORY);
330 if (r > 0)
331 return 0;
332 fprintf(stderr,
333 "Hypervisor too old: KVM_CAP_USER_MEMORY extension not supported\n");
334 #else
335 #error Hypervisor too old: KVM_CAP_USER_MEMORY extension not supported
336 #endif
337 return -1;
340 void kvm_create_irqchip(kvm_context_t kvm)
342 int r;
344 kvm->irqchip_in_kernel = 0;
345 #ifdef KVM_CAP_IRQCHIP
346 if (!kvm->no_irqchip_creation) {
347 r = kvm_ioctl(kvm_state, KVM_CHECK_EXTENSION, KVM_CAP_IRQCHIP);
348 if (r > 0) { /* kernel irqchip supported */
349 r = kvm_vm_ioctl(kvm_state, KVM_CREATE_IRQCHIP);
350 if (r >= 0) {
351 kvm->irqchip_inject_ioctl = KVM_IRQ_LINE;
352 #if defined(KVM_CAP_IRQ_INJECT_STATUS) && defined(KVM_IRQ_LINE_STATUS)
353 r = kvm_ioctl(kvm_state, KVM_CHECK_EXTENSION,
354 KVM_CAP_IRQ_INJECT_STATUS);
355 if (r > 0)
356 kvm->irqchip_inject_ioctl = KVM_IRQ_LINE_STATUS;
357 #endif
358 kvm->irqchip_in_kernel = 1;
359 } else
360 fprintf(stderr, "Create kernel PIC irqchip failed\n");
363 #endif
364 kvm_state->irqchip_in_kernel = kvm->irqchip_in_kernel;
367 int kvm_create(kvm_context_t kvm, unsigned long phys_mem_bytes, void **vm_mem)
369 int r, i;
371 r = kvm_create_vm(kvm);
372 if (r < 0)
373 return r;
374 r = kvm_arch_create(kvm, phys_mem_bytes, vm_mem);
375 if (r < 0)
376 return r;
377 for (i = 0; i < ARRAY_SIZE(kvm_state->slots); i++)
378 kvm_state->slots[i].slot = i;
380 r = kvm_create_default_phys_mem(kvm, phys_mem_bytes, vm_mem);
381 if (r < 0)
382 return r;
383 kvm_create_irqchip(kvm);
385 return 0;
388 #ifdef KVM_CAP_IRQCHIP
390 int kvm_set_irq_level(kvm_context_t kvm, int irq, int level, int *status)
392 struct kvm_irq_level event;
393 int r;
395 if (!kvm->irqchip_in_kernel)
396 return 0;
397 event.level = level;
398 event.irq = irq;
399 r = kvm_vm_ioctl(kvm_state, kvm->irqchip_inject_ioctl, &event);
400 if (r < 0)
401 perror("kvm_set_irq_level");
403 if (status) {
404 #ifdef KVM_CAP_IRQ_INJECT_STATUS
405 *status =
406 (kvm->irqchip_inject_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
407 #else
408 *status = 1;
409 #endif
412 return 1;
415 int kvm_get_irqchip(kvm_context_t kvm, struct kvm_irqchip *chip)
417 int r;
419 if (!kvm->irqchip_in_kernel)
420 return 0;
421 r = kvm_vm_ioctl(kvm_state, KVM_GET_IRQCHIP, chip);
422 if (r < 0) {
423 perror("kvm_get_irqchip\n");
425 return r;
428 int kvm_set_irqchip(kvm_context_t kvm, struct kvm_irqchip *chip)
430 int r;
432 if (!kvm->irqchip_in_kernel)
433 return 0;
434 r = kvm_vm_ioctl(kvm_state, KVM_SET_IRQCHIP, chip);
435 if (r < 0) {
436 perror("kvm_set_irqchip\n");
438 return r;
441 #endif
443 static int handle_debug(CPUState *env)
445 #ifdef KVM_CAP_SET_GUEST_DEBUG
446 struct kvm_run *run = env->kvm_run;
448 return kvm_debug(env, &run->debug.arch);
449 #else
450 return 0;
451 #endif
454 int kvm_get_regs(CPUState *env, struct kvm_regs *regs)
456 return kvm_vcpu_ioctl(env, KVM_GET_REGS, regs);
459 int kvm_set_regs(CPUState *env, struct kvm_regs *regs)
461 return kvm_vcpu_ioctl(env, KVM_SET_REGS, regs);
464 int kvm_get_fpu(CPUState *env, struct kvm_fpu *fpu)
466 return kvm_vcpu_ioctl(env, KVM_GET_FPU, fpu);
469 int kvm_set_fpu(CPUState *env, struct kvm_fpu *fpu)
471 return kvm_vcpu_ioctl(env, KVM_SET_FPU, fpu);
474 int kvm_get_sregs(CPUState *env, struct kvm_sregs *sregs)
476 return kvm_vcpu_ioctl(env, KVM_GET_SREGS, sregs);
479 int kvm_set_sregs(CPUState *env, struct kvm_sregs *sregs)
481 return kvm_vcpu_ioctl(env, KVM_SET_SREGS, sregs);
484 #ifdef KVM_CAP_MP_STATE
485 int kvm_get_mpstate(CPUState *env, struct kvm_mp_state *mp_state)
487 int r;
489 r = kvm_ioctl(kvm_state, KVM_CHECK_EXTENSION, KVM_CAP_MP_STATE);
490 if (r > 0)
491 return kvm_vcpu_ioctl(env, KVM_GET_MP_STATE, mp_state);
492 return -ENOSYS;
495 int kvm_set_mpstate(CPUState *env, struct kvm_mp_state *mp_state)
497 int r;
499 r = kvm_ioctl(kvm_state, KVM_CHECK_EXTENSION, KVM_CAP_MP_STATE);
500 if (r > 0)
501 return kvm_vcpu_ioctl(env, KVM_SET_MP_STATE, mp_state);
502 return -ENOSYS;
504 #endif
506 #ifdef KVM_CAP_XSAVE
507 int kvm_get_xsave(CPUState *env, struct kvm_xsave *xsave)
509 return kvm_vcpu_ioctl(env, KVM_GET_XSAVE, xsave);
512 int kvm_set_xsave(CPUState *env, struct kvm_xsave *xsave)
514 return kvm_vcpu_ioctl(env, KVM_SET_XSAVE, xsave);
516 #endif
518 #ifdef KVM_CAP_XCRS
519 int kvm_get_xcrs(CPUState *env, struct kvm_xcrs *xcrs)
521 return kvm_vcpu_ioctl(env, KVM_GET_XCRS, xcrs);
524 int kvm_set_xcrs(CPUState *env, struct kvm_xcrs *xcrs)
526 return kvm_vcpu_ioctl(env, KVM_SET_XCRS, xcrs);
528 #endif
530 static int handle_mmio(CPUState *env)
532 unsigned long addr = env->kvm_run->mmio.phys_addr;
533 struct kvm_run *kvm_run = env->kvm_run;
534 void *data = kvm_run->mmio.data;
536 /* hack: Red Hat 7.1 generates these weird accesses. */
537 if ((addr > 0xa0000 - 4 && addr <= 0xa0000) && kvm_run->mmio.len == 3)
538 return 0;
540 cpu_physical_memory_rw(addr, data, kvm_run->mmio.len, kvm_run->mmio.is_write);
541 return 0;
544 int handle_io_window(kvm_context_t kvm)
546 return 1;
549 int handle_shutdown(kvm_context_t kvm, CPUState *env)
551 /* stop the current vcpu from going back to guest mode */
552 env->stopped = 1;
554 qemu_system_reset_request();
555 return 1;
558 static inline void push_nmi(kvm_context_t kvm)
560 #ifdef KVM_CAP_USER_NMI
561 kvm_arch_push_nmi(kvm->opaque);
562 #endif /* KVM_CAP_USER_NMI */
565 void post_kvm_run(kvm_context_t kvm, CPUState *env)
567 pthread_mutex_lock(&qemu_mutex);
568 kvm_arch_post_run(env, env->kvm_run);
569 cpu_single_env = env;
572 int pre_kvm_run(kvm_context_t kvm, CPUState *env)
574 kvm_arch_pre_run(env, env->kvm_run);
576 pthread_mutex_unlock(&qemu_mutex);
577 return 0;
580 int kvm_is_ready_for_interrupt_injection(CPUState *env)
582 return env->kvm_run->ready_for_interrupt_injection;
585 int kvm_run(CPUState *env)
587 int r;
588 kvm_context_t kvm = &env->kvm_state->kvm_context;
589 struct kvm_run *run = env->kvm_run;
590 int fd = env->kvm_fd;
592 again:
593 if (env->kvm_vcpu_dirty) {
594 kvm_arch_load_regs(env, KVM_PUT_RUNTIME_STATE);
595 env->kvm_vcpu_dirty = 0;
597 push_nmi(kvm);
598 #if !defined(__s390__)
599 if (!kvm->irqchip_in_kernel)
600 run->request_interrupt_window = kvm_arch_try_push_interrupts(env);
601 #endif
603 r = pre_kvm_run(kvm, env);
604 if (r)
605 return r;
606 r = ioctl(fd, KVM_RUN, 0);
608 if (r == -1 && errno != EINTR && errno != EAGAIN) {
609 r = -errno;
610 post_kvm_run(kvm, env);
611 fprintf(stderr, "kvm_run: %s\n", strerror(-r));
612 return r;
615 post_kvm_run(kvm, env);
617 kvm_flush_coalesced_mmio_buffer();
619 #if !defined(__s390__)
620 if (r == -1) {
621 r = handle_io_window(kvm);
622 goto more;
624 #endif
625 if (1) {
626 switch (run->exit_reason) {
627 case KVM_EXIT_UNKNOWN:
628 r = handle_unhandled(run->hw.hardware_exit_reason);
629 break;
630 case KVM_EXIT_FAIL_ENTRY:
631 r = handle_failed_vmentry(run->fail_entry.hardware_entry_failure_reason);
632 break;
633 case KVM_EXIT_EXCEPTION:
634 fprintf(stderr, "exception %d (%x)\n", run->ex.exception,
635 run->ex.error_code);
636 kvm_show_regs(env);
637 kvm_show_code(env);
638 abort();
639 break;
640 case KVM_EXIT_IO:
641 r = kvm_handle_io(run->io.port,
642 (uint8_t *)run + run->io.data_offset,
643 run->io.direction,
644 run->io.size,
645 run->io.count);
646 r = 0;
647 break;
648 case KVM_EXIT_DEBUG:
649 r = handle_debug(env);
650 break;
651 case KVM_EXIT_MMIO:
652 r = handle_mmio(env);
653 break;
654 case KVM_EXIT_HLT:
655 r = kvm_arch_halt(env);
656 break;
657 case KVM_EXIT_IRQ_WINDOW_OPEN:
658 break;
659 case KVM_EXIT_SHUTDOWN:
660 r = handle_shutdown(kvm, env);
661 break;
662 #if defined(__s390__)
663 case KVM_EXIT_S390_SIEIC:
664 r = kvm_s390_handle_intercept(kvm, env, run);
665 break;
666 case KVM_EXIT_S390_RESET:
667 r = kvm_s390_handle_reset(kvm, env, run);
668 break;
669 #endif
670 case KVM_EXIT_INTERNAL_ERROR:
671 kvm_handle_internal_error(env, run);
672 r = 1;
673 break;
674 default:
675 if (kvm_arch_run(env)) {
676 fprintf(stderr, "unhandled vm exit: 0x%x\n", run->exit_reason);
677 kvm_show_regs(env);
678 abort();
680 break;
683 more:
684 if (!r)
685 goto again;
686 return r;
689 int kvm_inject_irq(CPUState *env, unsigned irq)
691 struct kvm_interrupt intr;
693 intr.irq = irq;
694 return kvm_vcpu_ioctl(env, KVM_INTERRUPT, &intr);
697 int kvm_inject_nmi(CPUState *env)
699 #ifdef KVM_CAP_USER_NMI
700 return kvm_vcpu_ioctl(env, KVM_NMI);
701 #else
702 return -ENOSYS;
703 #endif
706 int kvm_init_coalesced_mmio(kvm_context_t kvm)
708 int r = 0;
709 kvm_state->coalesced_mmio = 0;
710 #ifdef KVM_CAP_COALESCED_MMIO
711 r = kvm_ioctl(kvm_state, KVM_CHECK_EXTENSION, KVM_CAP_COALESCED_MMIO);
712 if (r > 0) {
713 kvm_state->coalesced_mmio = r;
714 return 0;
716 #endif
717 return r;
720 #ifdef KVM_CAP_DEVICE_ASSIGNMENT
721 int kvm_assign_pci_device(kvm_context_t kvm,
722 struct kvm_assigned_pci_dev *assigned_dev)
724 return kvm_vm_ioctl(kvm_state, KVM_ASSIGN_PCI_DEVICE, assigned_dev);
727 static int kvm_old_assign_irq(kvm_context_t kvm,
728 struct kvm_assigned_irq *assigned_irq)
730 return kvm_vm_ioctl(kvm_state, KVM_ASSIGN_IRQ, assigned_irq);
733 #ifdef KVM_CAP_ASSIGN_DEV_IRQ
734 int kvm_assign_irq(kvm_context_t kvm, struct kvm_assigned_irq *assigned_irq)
736 int ret;
738 ret = kvm_ioctl(kvm_state, KVM_CHECK_EXTENSION, KVM_CAP_ASSIGN_DEV_IRQ);
739 if (ret > 0) {
740 return kvm_vm_ioctl(kvm_state, KVM_ASSIGN_DEV_IRQ, assigned_irq);
743 return kvm_old_assign_irq(kvm, assigned_irq);
746 int kvm_deassign_irq(kvm_context_t kvm, struct kvm_assigned_irq *assigned_irq)
748 return kvm_vm_ioctl(kvm_state, KVM_DEASSIGN_DEV_IRQ, assigned_irq);
750 #else
751 int kvm_assign_irq(kvm_context_t kvm, struct kvm_assigned_irq *assigned_irq)
753 return kvm_old_assign_irq(kvm, assigned_irq);
755 #endif
756 #endif
758 #ifdef KVM_CAP_DEVICE_DEASSIGNMENT
759 int kvm_deassign_pci_device(kvm_context_t kvm,
760 struct kvm_assigned_pci_dev *assigned_dev)
762 return kvm_vm_ioctl(kvm_state, KVM_DEASSIGN_PCI_DEVICE, assigned_dev);
764 #endif
766 int kvm_reinject_control(kvm_context_t kvm, int pit_reinject)
768 #ifdef KVM_CAP_REINJECT_CONTROL
769 int r;
770 struct kvm_reinject_control control;
772 control.pit_reinject = pit_reinject;
774 r = kvm_ioctl(kvm_state, KVM_CHECK_EXTENSION, KVM_CAP_REINJECT_CONTROL);
775 if (r > 0) {
776 return kvm_vm_ioctl(kvm_state, KVM_REINJECT_CONTROL, &control);
778 #endif
779 return -ENOSYS;
782 int kvm_has_gsi_routing(kvm_context_t kvm)
784 int r = 0;
786 #ifdef KVM_CAP_IRQ_ROUTING
787 r = kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
788 #endif
789 return r;
792 int kvm_get_gsi_count(kvm_context_t kvm)
794 #ifdef KVM_CAP_IRQ_ROUTING
795 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
796 #else
797 return -EINVAL;
798 #endif
801 int kvm_clear_gsi_routes(kvm_context_t kvm)
803 #ifdef KVM_CAP_IRQ_ROUTING
804 kvm->irq_routes->nr = 0;
805 return 0;
806 #else
807 return -EINVAL;
808 #endif
811 int kvm_add_routing_entry(kvm_context_t kvm,
812 struct kvm_irq_routing_entry *entry)
814 #ifdef KVM_CAP_IRQ_ROUTING
815 struct kvm_irq_routing *z;
816 struct kvm_irq_routing_entry *new;
817 int n, size;
819 if (kvm->irq_routes->nr == kvm->nr_allocated_irq_routes) {
820 n = kvm->nr_allocated_irq_routes * 2;
821 if (n < 64)
822 n = 64;
823 size = sizeof(struct kvm_irq_routing);
824 size += n * sizeof(*new);
825 z = realloc(kvm->irq_routes, size);
826 if (!z)
827 return -ENOMEM;
828 kvm->nr_allocated_irq_routes = n;
829 kvm->irq_routes = z;
831 n = kvm->irq_routes->nr++;
832 new = &kvm->irq_routes->entries[n];
833 memset(new, 0, sizeof(*new));
834 new->gsi = entry->gsi;
835 new->type = entry->type;
836 new->flags = entry->flags;
837 new->u = entry->u;
839 set_gsi(kvm, entry->gsi);
841 return 0;
842 #else
843 return -ENOSYS;
844 #endif
847 int kvm_add_irq_route(kvm_context_t kvm, int gsi, int irqchip, int pin)
849 #ifdef KVM_CAP_IRQ_ROUTING
850 struct kvm_irq_routing_entry e;
852 e.gsi = gsi;
853 e.type = KVM_IRQ_ROUTING_IRQCHIP;
854 e.flags = 0;
855 e.u.irqchip.irqchip = irqchip;
856 e.u.irqchip.pin = pin;
857 return kvm_add_routing_entry(kvm, &e);
858 #else
859 return -ENOSYS;
860 #endif
863 int kvm_del_routing_entry(kvm_context_t kvm,
864 struct kvm_irq_routing_entry *entry)
866 #ifdef KVM_CAP_IRQ_ROUTING
867 struct kvm_irq_routing_entry *e, *p;
868 int i, gsi, found = 0;
870 gsi = entry->gsi;
872 for (i = 0; i < kvm->irq_routes->nr; ++i) {
873 e = &kvm->irq_routes->entries[i];
874 if (e->type == entry->type && e->gsi == gsi) {
875 switch (e->type) {
876 case KVM_IRQ_ROUTING_IRQCHIP:{
877 if (e->u.irqchip.irqchip ==
878 entry->u.irqchip.irqchip
879 && e->u.irqchip.pin == entry->u.irqchip.pin) {
880 p = &kvm->irq_routes->entries[--kvm->irq_routes->nr];
881 *e = *p;
882 found = 1;
884 break;
886 case KVM_IRQ_ROUTING_MSI:{
887 if (e->u.msi.address_lo ==
888 entry->u.msi.address_lo
889 && e->u.msi.address_hi ==
890 entry->u.msi.address_hi
891 && e->u.msi.data == entry->u.msi.data) {
892 p = &kvm->irq_routes->entries[--kvm->irq_routes->nr];
893 *e = *p;
894 found = 1;
896 break;
898 default:
899 break;
901 if (found) {
902 /* If there are no other users of this GSI
903 * mark it available in the bitmap */
904 for (i = 0; i < kvm->irq_routes->nr; i++) {
905 e = &kvm->irq_routes->entries[i];
906 if (e->gsi == gsi)
907 break;
909 if (i == kvm->irq_routes->nr)
910 clear_gsi(kvm, gsi);
912 return 0;
916 return -ESRCH;
917 #else
918 return -ENOSYS;
919 #endif
922 int kvm_update_routing_entry(kvm_context_t kvm,
923 struct kvm_irq_routing_entry *entry,
924 struct kvm_irq_routing_entry *newentry)
926 #ifdef KVM_CAP_IRQ_ROUTING
927 struct kvm_irq_routing_entry *e;
928 int i;
930 if (entry->gsi != newentry->gsi || entry->type != newentry->type) {
931 return -EINVAL;
934 for (i = 0; i < kvm->irq_routes->nr; ++i) {
935 e = &kvm->irq_routes->entries[i];
936 if (e->type != entry->type || e->gsi != entry->gsi) {
937 continue;
939 switch (e->type) {
940 case KVM_IRQ_ROUTING_IRQCHIP:
941 if (e->u.irqchip.irqchip == entry->u.irqchip.irqchip &&
942 e->u.irqchip.pin == entry->u.irqchip.pin) {
943 memcpy(&e->u.irqchip, &newentry->u.irqchip,
944 sizeof e->u.irqchip);
945 return 0;
947 break;
948 case KVM_IRQ_ROUTING_MSI:
949 if (e->u.msi.address_lo == entry->u.msi.address_lo &&
950 e->u.msi.address_hi == entry->u.msi.address_hi &&
951 e->u.msi.data == entry->u.msi.data) {
952 memcpy(&e->u.msi, &newentry->u.msi, sizeof e->u.msi);
953 return 0;
955 break;
956 default:
957 break;
960 return -ESRCH;
961 #else
962 return -ENOSYS;
963 #endif
966 int kvm_del_irq_route(kvm_context_t kvm, int gsi, int irqchip, int pin)
968 #ifdef KVM_CAP_IRQ_ROUTING
969 struct kvm_irq_routing_entry e;
971 e.gsi = gsi;
972 e.type = KVM_IRQ_ROUTING_IRQCHIP;
973 e.flags = 0;
974 e.u.irqchip.irqchip = irqchip;
975 e.u.irqchip.pin = pin;
976 return kvm_del_routing_entry(kvm, &e);
977 #else
978 return -ENOSYS;
979 #endif
982 int kvm_commit_irq_routes(kvm_context_t kvm)
984 #ifdef KVM_CAP_IRQ_ROUTING
985 kvm->irq_routes->flags = 0;
986 return kvm_vm_ioctl(kvm_state, KVM_SET_GSI_ROUTING, kvm->irq_routes);
987 #else
988 return -ENOSYS;
989 #endif
992 int kvm_get_irq_route_gsi(kvm_context_t kvm)
994 int i, bit;
995 uint32_t *buf = kvm->used_gsi_bitmap;
997 /* Return the lowest unused GSI in the bitmap */
998 for (i = 0; i < kvm->max_gsi / 32; i++) {
999 bit = ffs(~buf[i]);
1000 if (!bit)
1001 continue;
1003 return bit - 1 + i * 32;
1006 return -ENOSPC;
1009 #ifdef KVM_CAP_DEVICE_MSIX
1010 int kvm_assign_set_msix_nr(kvm_context_t kvm,
1011 struct kvm_assigned_msix_nr *msix_nr)
1013 return kvm_vm_ioctl(kvm_state, KVM_ASSIGN_SET_MSIX_NR, msix_nr);
1016 int kvm_assign_set_msix_entry(kvm_context_t kvm,
1017 struct kvm_assigned_msix_entry *entry)
1019 return kvm_vm_ioctl(kvm_state, KVM_ASSIGN_SET_MSIX_ENTRY, entry);
1021 #endif
1023 #if defined(KVM_CAP_IRQFD) && defined(CONFIG_EVENTFD)
1025 #include <sys/eventfd.h>
1027 static int _kvm_irqfd(kvm_context_t kvm, int fd, int gsi, int flags)
1029 struct kvm_irqfd data = {
1030 .fd = fd,
1031 .gsi = gsi,
1032 .flags = flags,
1035 return kvm_vm_ioctl(kvm_state, KVM_IRQFD, &data);
1038 int kvm_irqfd(kvm_context_t kvm, int gsi, int flags)
1040 int r;
1041 int fd;
1043 if (!kvm_check_extension(kvm_state, KVM_CAP_IRQFD))
1044 return -ENOENT;
1046 fd = eventfd(0, 0);
1047 if (fd < 0)
1048 return -errno;
1050 r = _kvm_irqfd(kvm, fd, gsi, 0);
1051 if (r < 0) {
1052 close(fd);
1053 return -errno;
1056 return fd;
1059 #else /* KVM_CAP_IRQFD */
1061 int kvm_irqfd(kvm_context_t kvm, int gsi, int flags)
1063 return -ENOSYS;
1066 #endif /* KVM_CAP_IRQFD */
1067 unsigned long kvm_get_thread_id(void)
1069 return syscall(SYS_gettid);
1072 static void qemu_cond_wait(pthread_cond_t *cond)
1074 CPUState *env = cpu_single_env;
1076 pthread_cond_wait(cond, &qemu_mutex);
1077 cpu_single_env = env;
1080 static void sig_ipi_handler(int n)
1084 static void hardware_memory_error(void)
1086 fprintf(stderr, "Hardware memory error!\n");
1087 exit(1);
1090 static void sigbus_reraise(void)
1092 sigset_t set;
1093 struct sigaction action;
1095 memset(&action, 0, sizeof(action));
1096 action.sa_handler = SIG_DFL;
1097 if (!sigaction(SIGBUS, &action, NULL)) {
1098 raise(SIGBUS);
1099 sigemptyset(&set);
1100 sigaddset(&set, SIGBUS);
1101 sigprocmask(SIG_UNBLOCK, &set, NULL);
1103 perror("Failed to re-raise SIGBUS!\n");
1104 abort();
1107 static void sigbus_handler(int n, struct qemu_signalfd_siginfo *siginfo,
1108 void *ctx)
1110 #if defined(KVM_CAP_MCE) && defined(TARGET_I386)
1111 if (first_cpu->mcg_cap && siginfo->ssi_addr
1112 && siginfo->ssi_code == BUS_MCEERR_AO) {
1113 uint64_t status;
1114 unsigned long paddr;
1115 CPUState *cenv;
1117 /* Hope we are lucky for AO MCE */
1118 if (do_qemu_ram_addr_from_host((void *)(intptr_t)siginfo->ssi_addr,
1119 &paddr)) {
1120 fprintf(stderr, "Hardware memory error for memory used by "
1121 "QEMU itself instead of guest system!: %llx\n",
1122 (unsigned long long)siginfo->ssi_addr);
1123 return;
1125 status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN
1126 | MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S
1127 | 0xc0;
1128 kvm_inject_x86_mce(first_cpu, 9, status,
1129 MCG_STATUS_MCIP | MCG_STATUS_RIPV, paddr,
1130 (MCM_ADDR_PHYS << 6) | 0xc, 1);
1131 for (cenv = first_cpu->next_cpu; cenv != NULL; cenv = cenv->next_cpu)
1132 kvm_inject_x86_mce(cenv, 1, MCI_STATUS_VAL | MCI_STATUS_UC,
1133 MCG_STATUS_MCIP | MCG_STATUS_RIPV, 0, 0, 1);
1134 } else
1135 #endif
1137 if (siginfo->ssi_code == BUS_MCEERR_AO)
1138 return;
1139 else if (siginfo->ssi_code == BUS_MCEERR_AR)
1140 hardware_memory_error();
1141 else
1142 sigbus_reraise();
1146 static void on_vcpu(CPUState *env, void (*func)(void *data), void *data)
1148 struct qemu_work_item wi;
1150 if (env == current_env) {
1151 func(data);
1152 return;
1155 wi.func = func;
1156 wi.data = data;
1157 if (!env->kvm_cpu_state.queued_work_first)
1158 env->kvm_cpu_state.queued_work_first = &wi;
1159 else
1160 env->kvm_cpu_state.queued_work_last->next = &wi;
1161 env->kvm_cpu_state.queued_work_last = &wi;
1162 wi.next = NULL;
1163 wi.done = false;
1165 pthread_kill(env->kvm_cpu_state.thread, SIG_IPI);
1166 while (!wi.done)
1167 qemu_cond_wait(&qemu_work_cond);
1170 static void do_kvm_cpu_synchronize_state(void *_env)
1172 CPUState *env = _env;
1174 if (!env->kvm_vcpu_dirty) {
1175 kvm_arch_save_regs(env);
1176 env->kvm_vcpu_dirty = 1;
1180 void kvm_cpu_synchronize_state(CPUState *env)
1182 if (!env->kvm_vcpu_dirty)
1183 on_vcpu(env, do_kvm_cpu_synchronize_state, env);
1186 void kvm_cpu_synchronize_post_reset(CPUState *env)
1188 kvm_arch_load_regs(env, KVM_PUT_RESET_STATE);
1189 env->kvm_vcpu_dirty = 0;
1192 void kvm_cpu_synchronize_post_init(CPUState *env)
1194 kvm_arch_load_regs(env, KVM_PUT_FULL_STATE);
1195 env->kvm_vcpu_dirty = 0;
1198 static void inject_interrupt(void *data)
1200 cpu_interrupt(current_env, (long) data);
1203 void kvm_inject_interrupt(CPUState *env, int mask)
1205 on_vcpu(env, inject_interrupt, (void *) (long) mask);
1208 void kvm_update_interrupt_request(CPUState *env)
1210 int signal = 0;
1212 if (env) {
1213 if (!current_env || !current_env->created)
1214 signal = 1;
1216 * Testing for created here is really redundant
1218 if (current_env && current_env->created &&
1219 env != current_env && !env->kvm_cpu_state.signalled)
1220 signal = 1;
1222 if (signal) {
1223 env->kvm_cpu_state.signalled = 1;
1224 if (env->kvm_cpu_state.thread)
1225 pthread_kill(env->kvm_cpu_state.thread, SIG_IPI);
1230 int kvm_cpu_exec(CPUState *env)
1232 int r;
1234 r = kvm_run(env);
1235 if (r < 0) {
1236 printf("kvm_run returned %d\n", r);
1237 vm_stop(0);
1240 return 0;
1243 int kvm_cpu_is_stopped(CPUState *env)
1245 return !vm_running || env->stopped;
1248 static void flush_queued_work(CPUState *env)
1250 struct qemu_work_item *wi;
1252 if (!env->kvm_cpu_state.queued_work_first)
1253 return;
1255 while ((wi = env->kvm_cpu_state.queued_work_first)) {
1256 env->kvm_cpu_state.queued_work_first = wi->next;
1257 wi->func(wi->data);
1258 wi->done = true;
1260 env->kvm_cpu_state.queued_work_last = NULL;
1261 pthread_cond_broadcast(&qemu_work_cond);
1264 static int kvm_mce_in_exception(CPUState *env)
1266 struct kvm_msr_entry msr_mcg_status = {
1267 .index = MSR_MCG_STATUS,
1269 int r;
1271 r = kvm_get_msrs(env, &msr_mcg_status, 1);
1272 if (r == -1 || r == 0)
1273 return -1;
1274 return !!(msr_mcg_status.data & MCG_STATUS_MCIP);
1277 static void kvm_on_sigbus(CPUState *env, siginfo_t *siginfo)
1279 #if defined(KVM_CAP_MCE) && defined(TARGET_I386)
1280 struct kvm_x86_mce mce = {
1281 .bank = 9,
1283 unsigned long paddr;
1284 int r;
1286 if (env->mcg_cap && siginfo->si_addr
1287 && (siginfo->si_code == BUS_MCEERR_AR
1288 || siginfo->si_code == BUS_MCEERR_AO)) {
1289 if (siginfo->si_code == BUS_MCEERR_AR) {
1290 /* Fake an Intel architectural Data Load SRAR UCR */
1291 mce.status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN
1292 | MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S
1293 | MCI_STATUS_AR | 0x134;
1294 mce.misc = (MCM_ADDR_PHYS << 6) | 0xc;
1295 mce.mcg_status = MCG_STATUS_MCIP | MCG_STATUS_EIPV;
1296 } else {
1298 * If there is an MCE excpetion being processed, ignore
1299 * this SRAO MCE
1301 r = kvm_mce_in_exception(env);
1302 if (r == -1)
1303 fprintf(stderr, "Failed to get MCE status\n");
1304 else if (r)
1305 return;
1306 /* Fake an Intel architectural Memory scrubbing UCR */
1307 mce.status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN
1308 | MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S
1309 | 0xc0;
1310 mce.misc = (MCM_ADDR_PHYS << 6) | 0xc;
1311 mce.mcg_status = MCG_STATUS_MCIP | MCG_STATUS_RIPV;
1313 if (do_qemu_ram_addr_from_host((void *)siginfo->si_addr, &paddr)) {
1314 fprintf(stderr, "Hardware memory error for memory used by "
1315 "QEMU itself instaed of guest system!\n");
1316 /* Hope we are lucky for AO MCE */
1317 if (siginfo->si_code == BUS_MCEERR_AO)
1318 return;
1319 else
1320 hardware_memory_error();
1322 mce.addr = paddr;
1323 r = kvm_set_mce(env, &mce);
1324 if (r < 0) {
1325 fprintf(stderr, "kvm_set_mce: %s\n", strerror(errno));
1326 abort();
1328 } else
1329 #endif
1331 if (siginfo->si_code == BUS_MCEERR_AO)
1332 return;
1333 else if (siginfo->si_code == BUS_MCEERR_AR)
1334 hardware_memory_error();
1335 else
1336 sigbus_reraise();
1340 static void kvm_main_loop_wait(CPUState *env, int timeout)
1342 struct timespec ts;
1343 int r, e;
1344 siginfo_t siginfo;
1345 sigset_t waitset;
1346 sigset_t chkset;
1348 ts.tv_sec = timeout / 1000;
1349 ts.tv_nsec = (timeout % 1000) * 1000000;
1350 sigemptyset(&waitset);
1351 sigaddset(&waitset, SIG_IPI);
1352 sigaddset(&waitset, SIGBUS);
1354 do {
1355 pthread_mutex_unlock(&qemu_mutex);
1357 r = sigtimedwait(&waitset, &siginfo, &ts);
1358 e = errno;
1360 pthread_mutex_lock(&qemu_mutex);
1362 if (r == -1 && !(e == EAGAIN || e == EINTR)) {
1363 printf("sigtimedwait: %s\n", strerror(e));
1364 exit(1);
1367 switch (r) {
1368 case SIGBUS:
1369 kvm_on_sigbus(env, &siginfo);
1370 break;
1371 default:
1372 break;
1375 r = sigpending(&chkset);
1376 if (r == -1) {
1377 printf("sigpending: %s\n", strerror(e));
1378 exit(1);
1380 } while (sigismember(&chkset, SIG_IPI) || sigismember(&chkset, SIGBUS));
1382 cpu_single_env = env;
1383 flush_queued_work(env);
1385 if (env->stop) {
1386 env->stop = 0;
1387 env->stopped = 1;
1388 pthread_cond_signal(&qemu_pause_cond);
1391 env->kvm_cpu_state.signalled = 0;
1394 static int all_threads_paused(void)
1396 CPUState *penv = first_cpu;
1398 while (penv) {
1399 if (penv->stop)
1400 return 0;
1401 penv = (CPUState *) penv->next_cpu;
1404 return 1;
1407 static void pause_all_threads(void)
1409 CPUState *penv = first_cpu;
1411 while (penv) {
1412 if (penv != cpu_single_env) {
1413 penv->stop = 1;
1414 pthread_kill(penv->kvm_cpu_state.thread, SIG_IPI);
1415 } else {
1416 penv->stop = 0;
1417 penv->stopped = 1;
1418 cpu_exit(penv);
1420 penv = (CPUState *) penv->next_cpu;
1423 while (!all_threads_paused())
1424 qemu_cond_wait(&qemu_pause_cond);
1427 static void resume_all_threads(void)
1429 CPUState *penv = first_cpu;
1431 assert(!cpu_single_env);
1433 while (penv) {
1434 penv->stop = 0;
1435 penv->stopped = 0;
1436 pthread_kill(penv->kvm_cpu_state.thread, SIG_IPI);
1437 penv = (CPUState *) penv->next_cpu;
1441 static void kvm_vm_state_change_handler(void *context, int running, int reason)
1443 if (running)
1444 resume_all_threads();
1445 else
1446 pause_all_threads();
1449 static void setup_kernel_sigmask(CPUState *env)
1451 sigset_t set;
1453 sigemptyset(&set);
1454 sigaddset(&set, SIGUSR2);
1455 sigaddset(&set, SIGIO);
1456 sigaddset(&set, SIGALRM);
1457 sigprocmask(SIG_BLOCK, &set, NULL);
1459 sigprocmask(SIG_BLOCK, NULL, &set);
1460 sigdelset(&set, SIG_IPI);
1461 sigdelset(&set, SIGBUS);
1463 kvm_set_signal_mask(env, &set);
1466 static void qemu_kvm_system_reset(void)
1468 pause_all_threads();
1470 qemu_system_reset();
1472 resume_all_threads();
1475 static void process_irqchip_events(CPUState *env)
1477 kvm_arch_process_irqchip_events(env);
1478 if (kvm_arch_has_work(env))
1479 env->halted = 0;
1482 static int kvm_main_loop_cpu(CPUState *env)
1484 while (1) {
1485 int run_cpu = !kvm_cpu_is_stopped(env);
1486 if (run_cpu && !kvm_irqchip_in_kernel()) {
1487 process_irqchip_events(env);
1488 run_cpu = !env->halted;
1490 if (run_cpu) {
1491 kvm_cpu_exec(env);
1492 kvm_main_loop_wait(env, 0);
1493 } else {
1494 kvm_main_loop_wait(env, 1000);
1497 pthread_mutex_unlock(&qemu_mutex);
1498 return 0;
1501 static void *ap_main_loop(void *_env)
1503 CPUState *env = _env;
1504 sigset_t signals;
1505 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
1506 struct ioperm_data *data = NULL;
1507 #endif
1509 current_env = env;
1510 env->thread_id = kvm_get_thread_id();
1511 sigfillset(&signals);
1512 sigprocmask(SIG_BLOCK, &signals, NULL);
1514 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
1515 /* do ioperm for io ports of assigned devices */
1516 QLIST_FOREACH(data, &ioperm_head, entries)
1517 on_vcpu(env, kvm_arch_do_ioperm, data);
1518 #endif
1520 pthread_mutex_lock(&qemu_mutex);
1521 cpu_single_env = env;
1523 kvm_create_vcpu(env, env->cpu_index);
1524 setup_kernel_sigmask(env);
1526 /* signal VCPU creation */
1527 current_env->created = 1;
1528 pthread_cond_signal(&qemu_vcpu_cond);
1530 /* and wait for machine initialization */
1531 while (!qemu_system_ready)
1532 qemu_cond_wait(&qemu_system_cond);
1534 /* re-initialize cpu_single_env after re-acquiring qemu_mutex */
1535 cpu_single_env = env;
1537 kvm_main_loop_cpu(env);
1538 return NULL;
1541 int kvm_init_vcpu(CPUState *env)
1543 pthread_create(&env->kvm_cpu_state.thread, NULL, ap_main_loop, env);
1545 while (env->created == 0)
1546 qemu_cond_wait(&qemu_vcpu_cond);
1548 return 0;
1551 int kvm_vcpu_inited(CPUState *env)
1553 return env->created;
1556 #ifdef TARGET_I386
1557 void kvm_hpet_disable_kpit(void)
1559 struct kvm_pit_state2 ps2;
1561 kvm_get_pit2(kvm_context, &ps2);
1562 ps2.flags |= KVM_PIT_FLAGS_HPET_LEGACY;
1563 kvm_set_pit2(kvm_context, &ps2);
1566 void kvm_hpet_enable_kpit(void)
1568 struct kvm_pit_state2 ps2;
1570 kvm_get_pit2(kvm_context, &ps2);
1571 ps2.flags &= ~KVM_PIT_FLAGS_HPET_LEGACY;
1572 kvm_set_pit2(kvm_context, &ps2);
1574 #endif
1576 int kvm_init_ap(void)
1578 struct sigaction action;
1580 qemu_add_vm_change_state_handler(kvm_vm_state_change_handler, NULL);
1582 signal(SIG_IPI, sig_ipi_handler);
1584 memset(&action, 0, sizeof(action));
1585 action.sa_flags = SA_SIGINFO;
1586 action.sa_sigaction = (void (*)(int, siginfo_t*, void*))sigbus_handler;
1587 sigaction(SIGBUS, &action, NULL);
1588 prctl(PR_MCE_KILL, 1, 1, 0, 0);
1589 return 0;
1592 void qemu_kvm_notify_work(void)
1594 /* Write 8 bytes to be compatible with eventfd. */
1595 static uint64_t val = 1;
1596 ssize_t ret;
1598 if (io_thread_fd == -1)
1599 return;
1601 do {
1602 ret = write(io_thread_fd, &val, sizeof(val));
1603 } while (ret < 0 && errno == EINTR);
1605 /* EAGAIN is fine in case we have a pipe. */
1606 if (ret < 0 && errno != EAGAIN) {
1607 fprintf(stderr, "qemu_kvm_notify_work: write() filed: %s\n",
1608 strerror(errno));
1609 exit (1);
1613 /* If we have signalfd, we mask out the signals we want to handle and then
1614 * use signalfd to listen for them. We rely on whatever the current signal
1615 * handler is to dispatch the signals when we receive them.
1618 static void sigfd_handler(void *opaque)
1620 int fd = (unsigned long) opaque;
1621 struct qemu_signalfd_siginfo info;
1622 struct sigaction action;
1623 ssize_t len;
1625 while (1) {
1626 do {
1627 len = read(fd, &info, sizeof(info));
1628 } while (len == -1 && errno == EINTR);
1630 if (len == -1 && errno == EAGAIN)
1631 break;
1633 if (len != sizeof(info)) {
1634 printf("read from sigfd returned %zd: %m\n", len);
1635 return;
1638 sigaction(info.ssi_signo, NULL, &action);
1639 if ((action.sa_flags & SA_SIGINFO) && action.sa_sigaction)
1640 action.sa_sigaction(info.ssi_signo,
1641 (siginfo_t *)&info, NULL);
1642 else if (action.sa_handler)
1643 action.sa_handler(info.ssi_signo);
1648 /* Used to break IO thread out of select */
1649 static void io_thread_wakeup(void *opaque)
1651 int fd = (unsigned long) opaque;
1652 ssize_t len;
1653 char buffer[512];
1655 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
1656 do {
1657 len = read(fd, buffer, sizeof(buffer));
1658 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
1661 int kvm_main_loop(void)
1663 int fds[2];
1664 sigset_t mask;
1665 int sigfd;
1667 io_thread = pthread_self();
1668 qemu_system_ready = 1;
1670 if (qemu_eventfd(fds) == -1) {
1671 fprintf(stderr, "failed to create eventfd\n");
1672 return -errno;
1675 fcntl(fds[0], F_SETFL, O_NONBLOCK);
1676 fcntl(fds[1], F_SETFL, O_NONBLOCK);
1678 qemu_set_fd_handler2(fds[0], NULL, io_thread_wakeup, NULL,
1679 (void *)(unsigned long) fds[0]);
1681 io_thread_fd = fds[1];
1683 sigemptyset(&mask);
1684 sigaddset(&mask, SIGIO);
1685 sigaddset(&mask, SIGALRM);
1686 sigaddset(&mask, SIGBUS);
1687 sigprocmask(SIG_BLOCK, &mask, NULL);
1689 sigfd = qemu_signalfd(&mask);
1690 if (sigfd == -1) {
1691 fprintf(stderr, "failed to create signalfd\n");
1692 return -errno;
1695 fcntl(sigfd, F_SETFL, O_NONBLOCK);
1697 qemu_set_fd_handler2(sigfd, NULL, sigfd_handler, NULL,
1698 (void *)(unsigned long) sigfd);
1700 pthread_cond_broadcast(&qemu_system_cond);
1702 io_thread_sigfd = sigfd;
1703 cpu_single_env = NULL;
1705 while (1) {
1706 main_loop_wait(0);
1707 if (qemu_shutdown_requested()) {
1708 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
1709 if (qemu_no_shutdown()) {
1710 vm_stop(0);
1711 } else
1712 break;
1713 } else if (qemu_powerdown_requested()) {
1714 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
1715 qemu_irq_raise(qemu_system_powerdown);
1716 } else if (qemu_reset_requested()) {
1717 qemu_kvm_system_reset();
1718 } else if (kvm_debug_cpu_requested) {
1719 gdb_set_stop_cpu(kvm_debug_cpu_requested);
1720 vm_stop(EXCP_DEBUG);
1721 kvm_debug_cpu_requested = NULL;
1725 pause_all_threads();
1726 pthread_mutex_unlock(&qemu_mutex);
1728 return 0;
1731 #if !defined(TARGET_I386)
1732 int kvm_arch_init_irq_routing(void)
1734 return 0;
1736 #endif
1738 extern int no_hpet;
1740 static int kvm_create_context(void)
1742 static const char upgrade_note[] =
1743 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1744 "(see http://sourceforge.net/projects/kvm).\n";
1746 int r;
1748 if (!kvm_irqchip) {
1749 kvm_disable_irqchip_creation(kvm_context);
1751 if (!kvm_pit) {
1752 kvm_disable_pit_creation(kvm_context);
1754 if (kvm_create(kvm_context, 0, NULL) < 0) {
1755 kvm_finalize(kvm_state);
1756 return -1;
1758 r = kvm_arch_qemu_create_context();
1759 if (r < 0) {
1760 kvm_finalize(kvm_state);
1761 return -1;
1763 if (kvm_pit && !kvm_pit_reinject) {
1764 if (kvm_reinject_control(kvm_context, 0)) {
1765 fprintf(stderr, "failure to disable in-kernel PIT reinjection\n");
1766 return -1;
1770 /* There was a nasty bug in < kvm-80 that prevents memory slots from being
1771 * destroyed properly. Since we rely on this capability, refuse to work
1772 * with any kernel without this capability. */
1773 if (!kvm_check_extension(kvm_state, KVM_CAP_DESTROY_MEMORY_REGION_WORKS)) {
1774 fprintf(stderr,
1775 "KVM kernel module broken (DESTROY_MEMORY_REGION).\n%s",
1776 upgrade_note);
1777 return -EINVAL;
1780 r = kvm_arch_init_irq_routing();
1781 if (r < 0) {
1782 return r;
1785 kvm_state->vcpu_events = 0;
1786 #ifdef KVM_CAP_VCPU_EVENTS
1787 kvm_state->vcpu_events = kvm_check_extension(kvm_state, KVM_CAP_VCPU_EVENTS);
1788 #endif
1790 kvm_state->debugregs = 0;
1791 #ifdef KVM_CAP_DEBUGREGS
1792 kvm_state->debugregs = kvm_check_extension(kvm_state, KVM_CAP_DEBUGREGS);
1793 #endif
1795 kvm_init_ap();
1796 if (kvm_irqchip) {
1797 if (!qemu_kvm_has_gsi_routing()) {
1798 irq0override = 0;
1799 #ifdef TARGET_I386
1800 /* if kernel can't do irq routing, interrupt source
1801 * override 0->2 can not be set up as required by hpet,
1802 * so disable hpet.
1804 no_hpet = 1;
1805 } else if (!qemu_kvm_has_pit_state2()) {
1806 no_hpet = 1;
1808 #else
1810 #endif
1813 return 0;
1816 #ifdef KVM_CAP_IRQCHIP
1818 int kvm_set_irq(int irq, int level, int *status)
1820 return kvm_set_irq_level(kvm_context, irq, level, status);
1823 #endif
1825 void kvm_mutex_unlock(void)
1827 assert(!cpu_single_env);
1828 pthread_mutex_unlock(&qemu_mutex);
1831 void kvm_mutex_lock(void)
1833 pthread_mutex_lock(&qemu_mutex);
1834 cpu_single_env = NULL;
1837 void qemu_mutex_unlock_iothread(void)
1839 if (kvm_enabled())
1840 kvm_mutex_unlock();
1843 void qemu_mutex_lock_iothread(void)
1845 if (kvm_enabled())
1846 kvm_mutex_lock();
1849 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
1850 void kvm_add_ioperm_data(struct ioperm_data *data)
1852 QLIST_INSERT_HEAD(&ioperm_head, data, entries);
1855 void kvm_remove_ioperm_data(unsigned long start_port, unsigned long num)
1857 struct ioperm_data *data;
1859 data = QLIST_FIRST(&ioperm_head);
1860 while (data) {
1861 struct ioperm_data *next = QLIST_NEXT(data, entries);
1863 if (data->start_port == start_port && data->num == num) {
1864 QLIST_REMOVE(data, entries);
1865 qemu_free(data);
1868 data = next;
1872 void kvm_ioperm(CPUState *env, void *data)
1874 if (kvm_enabled() && qemu_system_ready)
1875 on_vcpu(env, kvm_arch_do_ioperm, data);
1878 #endif
1880 int kvm_set_boot_cpu_id(uint32_t id)
1882 return kvm_set_boot_vcpu_id(kvm_context, id);
1885 #ifdef TARGET_I386
1886 #ifdef KVM_CAP_MCE
1887 struct kvm_x86_mce_data {
1888 CPUState *env;
1889 struct kvm_x86_mce *mce;
1890 int abort_on_error;
1893 static void kvm_do_inject_x86_mce(void *_data)
1895 struct kvm_x86_mce_data *data = _data;
1896 int r;
1898 /* If there is an MCE excpetion being processed, ignore this SRAO MCE */
1899 r = kvm_mce_in_exception(data->env);
1900 if (r == -1)
1901 fprintf(stderr, "Failed to get MCE status\n");
1902 else if (r && !(data->mce->status & MCI_STATUS_AR))
1903 return;
1904 r = kvm_set_mce(data->env, data->mce);
1905 if (r < 0) {
1906 perror("kvm_set_mce FAILED");
1907 if (data->abort_on_error)
1908 abort();
1911 #endif
1913 void kvm_inject_x86_mce(CPUState *cenv, int bank, uint64_t status,
1914 uint64_t mcg_status, uint64_t addr, uint64_t misc,
1915 int abort_on_error)
1917 #ifdef KVM_CAP_MCE
1918 struct kvm_x86_mce mce = {
1919 .bank = bank,
1920 .status = status,
1921 .mcg_status = mcg_status,
1922 .addr = addr,
1923 .misc = misc,
1925 struct kvm_x86_mce_data data = {
1926 .env = cenv,
1927 .mce = &mce,
1928 .abort_on_error = abort_on_error,
1931 if (!cenv->mcg_cap) {
1932 fprintf(stderr, "MCE support is not enabled!\n");
1933 return;
1935 on_vcpu(cenv, kvm_do_inject_x86_mce, &data);
1936 #else
1937 if (abort_on_error)
1938 abort();
1939 #endif
1941 #endif