1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Virtual PTP 1588 clock for use with KVM guests
5 * Copyright (C) 2017 Red Hat Inc.
8 #include <linux/device.h>
9 #include <linux/kernel.h>
10 #include <asm/pvclock.h>
11 #include <asm/kvmclock.h>
12 #include <linux/module.h>
13 #include <uapi/asm/kvm_para.h>
14 #include <uapi/linux/kvm_para.h>
15 #include <linux/ptp_clock_kernel.h>
16 #include <linux/ptp_kvm.h>
18 static phys_addr_t clock_pair_gpa;
19 static struct kvm_clock_pairing clock_pair;
21 int kvm_arch_ptp_init(void)
25 if (!kvm_para_available())
28 clock_pair_gpa = slow_virt_to_phys(&clock_pair);
29 if (!pvclock_get_pvti_cpu0_va())
32 ret = kvm_hypercall2(KVM_HC_CLOCK_PAIRING, clock_pair_gpa,
33 KVM_CLOCK_PAIRING_WALLCLOCK);
34 if (ret == -KVM_ENOSYS)
40 int kvm_arch_ptp_get_clock(struct timespec64 *ts)
44 ret = kvm_hypercall2(KVM_HC_CLOCK_PAIRING,
46 KVM_CLOCK_PAIRING_WALLCLOCK);
48 pr_err_ratelimited("clock offset hypercall ret %lu\n", ret);
52 ts->tv_sec = clock_pair.sec;
53 ts->tv_nsec = clock_pair.nsec;
58 int kvm_arch_ptp_get_crosststamp(u64 *cycle, struct timespec64 *tspec,
59 struct clocksource **cs)
61 struct pvclock_vcpu_time_info *src;
65 src = this_cpu_pvti();
69 * We are using a TSC value read in the hosts
70 * kvm_hc_clock_pairing handling.
71 * So any changes to tsc_to_system_mul
72 * and tsc_shift or any other pvclock
73 * data invalidate that measurement.
75 version = pvclock_read_begin(src);
77 ret = kvm_hypercall2(KVM_HC_CLOCK_PAIRING,
79 KVM_CLOCK_PAIRING_WALLCLOCK);
81 pr_err_ratelimited("clock pairing hypercall ret %lu\n", ret);
84 tspec->tv_sec = clock_pair.sec;
85 tspec->tv_nsec = clock_pair.nsec;
86 *cycle = __pvclock_read_cycles(src, clock_pair.tsc);
87 } while (pvclock_read_retry(src, version));