xref: /openbmc/qemu/hw/i386/kvm/clock.c (revision db725815)
1 /*
2  * QEMU KVM support, paravirtual clock device
3  *
4  * Copyright (C) 2011 Siemens AG
5  *
6  * Authors:
7  *  Jan Kiszka        <jan.kiszka@siemens.com>
8  *
9  * This work is licensed under the terms of the GNU GPL version 2.
10  * See the COPYING file in the top-level directory.
11  *
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.
14  */
15 
16 #include "qemu/osdep.h"
17 #include "cpu.h"
18 #include "qemu/host-utils.h"
19 #include "qemu/module.h"
20 #include "sysemu/sysemu.h"
21 #include "sysemu/kvm.h"
22 #include "sysemu/hw_accel.h"
23 #include "kvm_i386.h"
24 #include "migration/vmstate.h"
25 #include "hw/sysbus.h"
26 #include "hw/kvm/clock.h"
27 #include "qapi/error.h"
28 
29 #include <linux/kvm.h>
30 #include "standard-headers/asm-x86/kvm_para.h"
31 
32 #define TYPE_KVM_CLOCK "kvmclock"
33 #define KVM_CLOCK(obj) OBJECT_CHECK(KVMClockState, (obj), TYPE_KVM_CLOCK)
34 
35 typedef struct KVMClockState {
36     /*< private >*/
37     SysBusDevice busdev;
38     /*< public >*/
39 
40     uint64_t clock;
41     bool clock_valid;
42 
43     /* whether machine type supports reliable KVM_GET_CLOCK */
44     bool mach_use_reliable_get_clock;
45 
46     /* whether the 'clock' value was obtained in a host with
47      * reliable KVM_GET_CLOCK */
48     bool clock_is_reliable;
49 } KVMClockState;
50 
51 struct pvclock_vcpu_time_info {
52     uint32_t   version;
53     uint32_t   pad0;
54     uint64_t   tsc_timestamp;
55     uint64_t   system_time;
56     uint32_t   tsc_to_system_mul;
57     int8_t     tsc_shift;
58     uint8_t    flags;
59     uint8_t    pad[2];
60 } __attribute__((__packed__)); /* 32 bytes */
61 
62 static uint64_t kvmclock_current_nsec(KVMClockState *s)
63 {
64     CPUState *cpu = first_cpu;
65     CPUX86State *env = cpu->env_ptr;
66     hwaddr kvmclock_struct_pa;
67     uint64_t migration_tsc = env->tsc;
68     struct pvclock_vcpu_time_info time;
69     uint64_t delta;
70     uint64_t nsec_lo;
71     uint64_t nsec_hi;
72     uint64_t nsec;
73 
74     cpu_synchronize_state(cpu);
75 
76     if (!(env->system_time_msr & 1ULL)) {
77         /* KVM clock not active */
78         return 0;
79     }
80 
81     kvmclock_struct_pa = env->system_time_msr & ~1ULL;
82     cpu_physical_memory_read(kvmclock_struct_pa, &time, sizeof(time));
83 
84     assert(time.tsc_timestamp <= migration_tsc);
85     delta = migration_tsc - time.tsc_timestamp;
86     if (time.tsc_shift < 0) {
87         delta >>= -time.tsc_shift;
88     } else {
89         delta <<= time.tsc_shift;
90     }
91 
92     mulu64(&nsec_lo, &nsec_hi, delta, time.tsc_to_system_mul);
93     nsec = (nsec_lo >> 32) | (nsec_hi << 32);
94     return nsec + time.system_time;
95 }
96 
97 static void kvm_update_clock(KVMClockState *s)
98 {
99     struct kvm_clock_data data;
100     int ret;
101 
102     ret = kvm_vm_ioctl(kvm_state, KVM_GET_CLOCK, &data);
103     if (ret < 0) {
104         fprintf(stderr, "KVM_GET_CLOCK failed: %s\n", strerror(ret));
105                 abort();
106     }
107     s->clock = data.clock;
108 
109     /* If kvm_has_adjust_clock_stable() is false, KVM_GET_CLOCK returns
110      * essentially CLOCK_MONOTONIC plus a guest-specific adjustment.  This
111      * can drift from the TSC-based value that is computed by the guest,
112      * so we need to go through kvmclock_current_nsec().  If
113      * kvm_has_adjust_clock_stable() is true, and the flags contain
114      * KVM_CLOCK_TSC_STABLE, then KVM_GET_CLOCK returns a TSC-based value
115      * and kvmclock_current_nsec() is not necessary.
116      *
117      * Here, however, we need not check KVM_CLOCK_TSC_STABLE.  This is because:
118      *
119      * - if the host has disabled the kvmclock master clock, the guest already
120      *   has protection against time going backwards.  This "safety net" is only
121      *   absent when kvmclock is stable;
122      *
123      * - therefore, we can replace a check like
124      *
125      *       if last KVM_GET_CLOCK was not reliable then
126      *               read from memory
127      *
128      *   with
129      *
130      *       if last KVM_GET_CLOCK was not reliable && masterclock is enabled
131      *               read from memory
132      *
133      * However:
134      *
135      * - if kvm_has_adjust_clock_stable() returns false, the left side is
136      *   always true (KVM_GET_CLOCK is never reliable), and the right side is
137      *   unknown (because we don't have data.flags).  We must assume it's true
138      *   and read from memory.
139      *
140      * - if kvm_has_adjust_clock_stable() returns true, the result of the &&
141      *   is always false (masterclock is enabled iff KVM_GET_CLOCK is reliable)
142      *
143      * So we can just use this instead:
144      *
145      *       if !kvm_has_adjust_clock_stable() then
146      *               read from memory
147      */
148     s->clock_is_reliable = kvm_has_adjust_clock_stable();
149 }
150 
151 static void do_kvmclock_ctrl(CPUState *cpu, run_on_cpu_data data)
152 {
153     int ret = kvm_vcpu_ioctl(cpu, KVM_KVMCLOCK_CTRL, 0);
154 
155     if (ret && ret != -EINVAL) {
156         fprintf(stderr, "%s: %s\n", __func__, strerror(-ret));
157     }
158 }
159 
160 static void kvmclock_vm_state_change(void *opaque, int running,
161                                      RunState state)
162 {
163     KVMClockState *s = opaque;
164     CPUState *cpu;
165     int cap_clock_ctrl = kvm_check_extension(kvm_state, KVM_CAP_KVMCLOCK_CTRL);
166     int ret;
167 
168     if (running) {
169         struct kvm_clock_data data = {};
170 
171         /*
172          * If the host where s->clock was read did not support reliable
173          * KVM_GET_CLOCK, read kvmclock value from memory.
174          */
175         if (!s->clock_is_reliable) {
176             uint64_t pvclock_via_mem = kvmclock_current_nsec(s);
177             /* We can't rely on the saved clock value, just discard it */
178             if (pvclock_via_mem) {
179                 s->clock = pvclock_via_mem;
180             }
181         }
182 
183         s->clock_valid = false;
184 
185         data.clock = s->clock;
186         ret = kvm_vm_ioctl(kvm_state, KVM_SET_CLOCK, &data);
187         if (ret < 0) {
188             fprintf(stderr, "KVM_SET_CLOCK failed: %s\n", strerror(ret));
189             abort();
190         }
191 
192         if (!cap_clock_ctrl) {
193             return;
194         }
195         CPU_FOREACH(cpu) {
196             run_on_cpu(cpu, do_kvmclock_ctrl, RUN_ON_CPU_NULL);
197         }
198     } else {
199 
200         if (s->clock_valid) {
201             return;
202         }
203 
204         kvm_synchronize_all_tsc();
205 
206         kvm_update_clock(s);
207         /*
208          * If the VM is stopped, declare the clock state valid to
209          * avoid re-reading it on next vmsave (which would return
210          * a different value). Will be reset when the VM is continued.
211          */
212         s->clock_valid = true;
213     }
214 }
215 
216 static void kvmclock_realize(DeviceState *dev, Error **errp)
217 {
218     KVMClockState *s = KVM_CLOCK(dev);
219 
220     if (!kvm_enabled()) {
221         error_setg(errp, "kvmclock device requires KVM");
222         return;
223     }
224 
225     kvm_update_clock(s);
226 
227     qemu_add_vm_change_state_handler(kvmclock_vm_state_change, s);
228 }
229 
230 static bool kvmclock_clock_is_reliable_needed(void *opaque)
231 {
232     KVMClockState *s = opaque;
233 
234     return s->mach_use_reliable_get_clock;
235 }
236 
237 static const VMStateDescription kvmclock_reliable_get_clock = {
238     .name = "kvmclock/clock_is_reliable",
239     .version_id = 1,
240     .minimum_version_id = 1,
241     .needed = kvmclock_clock_is_reliable_needed,
242     .fields = (VMStateField[]) {
243         VMSTATE_BOOL(clock_is_reliable, KVMClockState),
244         VMSTATE_END_OF_LIST()
245     }
246 };
247 
248 /*
249  * When migrating, assume the source has an unreliable
250  * KVM_GET_CLOCK unless told otherwise.
251  */
252 static int kvmclock_pre_load(void *opaque)
253 {
254     KVMClockState *s = opaque;
255 
256     s->clock_is_reliable = false;
257 
258     return 0;
259 }
260 
261 /*
262  * When migrating, read the clock just before migration,
263  * so that the guest clock counts during the events
264  * between:
265  *
266  *  * vm_stop()
267  *  *
268  *  * pre_save()
269  *
270  *  This reduces kvmclock difference on migration from 5s
271  *  to 0.1s (when max_downtime == 5s), because sending the
272  *  final pages of memory (which happens between vm_stop()
273  *  and pre_save()) takes max_downtime.
274  */
275 static int kvmclock_pre_save(void *opaque)
276 {
277     KVMClockState *s = opaque;
278 
279     kvm_update_clock(s);
280 
281     return 0;
282 }
283 
284 static const VMStateDescription kvmclock_vmsd = {
285     .name = "kvmclock",
286     .version_id = 1,
287     .minimum_version_id = 1,
288     .pre_load = kvmclock_pre_load,
289     .pre_save = kvmclock_pre_save,
290     .fields = (VMStateField[]) {
291         VMSTATE_UINT64(clock, KVMClockState),
292         VMSTATE_END_OF_LIST()
293     },
294     .subsections = (const VMStateDescription * []) {
295         &kvmclock_reliable_get_clock,
296         NULL
297     }
298 };
299 
300 static Property kvmclock_properties[] = {
301     DEFINE_PROP_BOOL("x-mach-use-reliable-get-clock", KVMClockState,
302                       mach_use_reliable_get_clock, true),
303     DEFINE_PROP_END_OF_LIST(),
304 };
305 
306 static void kvmclock_class_init(ObjectClass *klass, void *data)
307 {
308     DeviceClass *dc = DEVICE_CLASS(klass);
309 
310     dc->realize = kvmclock_realize;
311     dc->vmsd = &kvmclock_vmsd;
312     dc->props = kvmclock_properties;
313 }
314 
315 static const TypeInfo kvmclock_info = {
316     .name          = TYPE_KVM_CLOCK,
317     .parent        = TYPE_SYS_BUS_DEVICE,
318     .instance_size = sizeof(KVMClockState),
319     .class_init    = kvmclock_class_init,
320 };
321 
322 /* Note: Must be called after VCPU initialization. */
323 void kvmclock_create(void)
324 {
325     X86CPU *cpu = X86_CPU(first_cpu);
326 
327     if (kvm_enabled() &&
328         cpu->env.features[FEAT_KVM] & ((1ULL << KVM_FEATURE_CLOCKSOURCE) |
329                                        (1ULL << KVM_FEATURE_CLOCKSOURCE2))) {
330         sysbus_create_simple(TYPE_KVM_CLOCK, -1, NULL);
331     }
332 }
333 
334 static void kvmclock_register_types(void)
335 {
336     type_register_static(&kvmclock_info);
337 }
338 
339 type_init(kvmclock_register_types)
340