2 * QEMU KVM support, paravirtual clock device
4 * Copyright (C) 2011 Siemens AG
9 * This work is licensed under the terms of the GNU GPL version 2.
10 * See the COPYING file in the top-level directory.
12 * Contributions after 2012-01-13 are licensed under the terms of the
13 * GNU GPL, version 2 or (at your option) any later version.
16 #include "qemu-common.h"
17 #include "sysemu/sysemu.h"
18 #include "sysemu/kvm.h"
19 #include "hw/sysbus.h"
20 #include "hw/kvm/clock.h"
22 #include <linux/kvm.h>
23 #include <linux/kvm_para.h>
25 #define TYPE_KVM_CLOCK "kvmclock"
26 #define KVM_CLOCK(obj) OBJECT_CHECK(KVMClockState, (obj), TYPE_KVM_CLOCK)
28 typedef struct KVMClockState {
38 static void kvmclock_vm_state_change(void *opaque, int running,
41 KVMClockState *s = opaque;
43 int cap_clock_ctrl = kvm_check_extension(kvm_state, KVM_CAP_KVMCLOCK_CTRL);
47 struct kvm_clock_data data;
49 s->clock_valid = false;
51 data.clock = s->clock;
53 ret = kvm_vm_ioctl(kvm_state, KVM_SET_CLOCK, &data);
55 fprintf(stderr, "KVM_SET_CLOCK failed: %s\n", strerror(ret));
59 if (!cap_clock_ctrl) {
63 ret = kvm_vcpu_ioctl(cpu, KVM_KVMCLOCK_CTRL, 0);
66 fprintf(stderr, "%s: %s\n", __func__, strerror(-ret));
72 struct kvm_clock_data data;
78 ret = kvm_vm_ioctl(kvm_state, KVM_GET_CLOCK, &data);
80 fprintf(stderr, "KVM_GET_CLOCK failed: %s\n", strerror(ret));
83 s->clock = data.clock;
86 * If the VM is stopped, declare the clock state valid to
87 * avoid re-reading it on next vmsave (which would return
88 * a different value). Will be reset when the VM is continued.
90 s->clock_valid = true;
94 static void kvmclock_realize(DeviceState *dev, Error **errp)
96 KVMClockState *s = KVM_CLOCK(dev);
98 qemu_add_vm_change_state_handler(kvmclock_vm_state_change, s);
101 static const VMStateDescription kvmclock_vmsd = {
104 .minimum_version_id = 1,
105 .minimum_version_id_old = 1,
106 .fields = (VMStateField[]) {
107 VMSTATE_UINT64(clock, KVMClockState),
108 VMSTATE_END_OF_LIST()
112 static void kvmclock_class_init(ObjectClass *klass, void *data)
114 DeviceClass *dc = DEVICE_CLASS(klass);
116 dc->realize = kvmclock_realize;
117 dc->cannot_instantiate_with_device_add_yet = true; /* FIXME explain why */
118 dc->vmsd = &kvmclock_vmsd;
121 static const TypeInfo kvmclock_info = {
122 .name = TYPE_KVM_CLOCK,
123 .parent = TYPE_SYS_BUS_DEVICE,
124 .instance_size = sizeof(KVMClockState),
125 .class_init = kvmclock_class_init,
128 /* Note: Must be called after VCPU initialization. */
129 void kvmclock_create(void)
131 X86CPU *cpu = X86_CPU(first_cpu);
134 cpu->env.features[FEAT_KVM] & ((1ULL << KVM_FEATURE_CLOCKSOURCE) |
135 (1ULL << KVM_FEATURE_CLOCKSOURCE2))) {
136 sysbus_create_simple(TYPE_KVM_CLOCK, -1, NULL);
140 static void kvmclock_register_types(void)
142 type_register_static(&kvmclock_info);
145 type_init(kvmclock_register_types)