2 * Copyright (c) 2009 Adrian Chadd
3 * Copyright (c) 2012 Spectra Logic Corporation
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * \file dev/xen/timer/timer.c
31 * \brief A timer driver for the Xen hypervisor's PV clock.
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
37 #include <sys/param.h>
38 #include <sys/systm.h>
40 #include <sys/kernel.h>
41 #include <sys/module.h>
43 #include <sys/timetc.h>
44 #include <sys/timeet.h>
46 #include <sys/limits.h>
47 #include <sys/clock.h>
50 #include <xen/xen-os.h>
51 #include <xen/features.h>
52 #include <xen/xen_intr.h>
53 #include <xen/hypervisor.h>
54 #include <xen/interface/io/xenbus.h>
55 #include <xen/interface/vcpu.h>
57 #include <machine/cpu.h>
58 #include <machine/cpufunc.h>
59 #include <machine/clock.h>
60 #include <machine/_inttypes.h>
61 #include <machine/smp.h>
63 #include <dev/xen/timer/timer.h>
67 static devclass_t xentimer_devclass;
69 #define NSEC_IN_SEC 1000000000ULL
70 #define NSEC_IN_USEC 1000ULL
71 /* 18446744073 = int(2^64 / NSEC_IN_SC) = 1 ns in 64-bit fractions */
72 #define FRAC_IN_NSEC 18446744073LL
74 /* Xen timers may fire up to 100us off */
75 #define XENTIMER_MIN_PERIOD_IN_NSEC 100*NSEC_IN_USEC
76 #define XENCLOCK_RESOLUTION 10000000
78 #define ETIME 62 /* Xen "bad time" error */
80 #define XENTIMER_QUALITY 950
82 struct xentimer_pcpu_data {
84 uint64_t last_processed;
88 DPCPU_DEFINE(struct xentimer_pcpu_data, xentimer_pcpu);
90 DPCPU_DECLARE(struct vcpu_info *, vcpu_info);
92 struct xentimer_softc {
94 struct timecounter tc;
98 /* Last time; this guarantees a monotonically increasing clock. */
99 volatile uint64_t xen_timer_last_time = 0;
102 xentimer_identify(driver_t *driver, device_t parent)
107 /* Handle all Xen PV timers in one device instance. */
108 if (devclass_get_device(xentimer_devclass, 0))
111 BUS_ADD_CHILD(parent, 0, "xen_et", 0);
115 xentimer_probe(device_t dev)
117 KASSERT((xen_domain()), ("Trying to use Xen timer on bare metal"));
119 * In order to attach, this driver requires the following:
120 * - Vector callback support by the hypervisor, in order to deliver
121 * timer interrupts to the correct CPU for CPUs other than 0.
122 * - Access to the hypervisor shared info page, in order to look up
123 * each VCPU's timer information and the Xen wallclock time.
124 * - The hypervisor must say its PV clock is "safe" to use.
125 * - The hypervisor must support VCPUOP hypercalls.
126 * - The maximum number of CPUs supported by FreeBSD must not exceed
127 * the number of VCPUs supported by the hypervisor.
129 #define XTREQUIRES(condition, reason...) \
130 if (!(condition)) { \
131 device_printf(dev, ## reason); \
132 device_detach(dev); \
136 if (xen_hvm_domain()) {
137 XTREQUIRES(xen_vector_callback_enabled,
138 "vector callbacks unavailable\n");
139 XTREQUIRES(xen_feature(XENFEAT_hvm_safe_pvclock),
140 "HVM safe pvclock unavailable\n");
142 XTREQUIRES(HYPERVISOR_shared_info != NULL,
143 "shared info page unavailable\n");
144 XTREQUIRES(HYPERVISOR_vcpu_op(VCPUOP_stop_periodic_timer, 0, NULL) == 0,
145 "VCPUOPs interface unavailable\n");
147 device_set_desc(dev, "Xen PV Clock");
148 return (BUS_PROBE_NOWILDCARD);
152 * Scale a 64-bit delta by scaling and multiplying by a 32-bit fraction,
153 * yielding a 64-bit result.
155 static inline uint64_t
156 scale_delta(uint64_t delta, uint32_t mul_frac, int shift)
165 #if defined(__i386__)
170 * For i386, the formula looks like:
172 * lower = (mul_frac * (delta & UINT_MAX)) >> 32
173 * upper = mul_frac * (delta >> 32)
174 * product = lower + upper
184 : "=A" (product), "=r" (tmp1), "=r" (tmp2)
185 : "a" ((uint32_t)delta), "1" ((uint32_t)(delta >> 32)),
188 #elif defined(__amd64__)
193 "mulq %[mul_frac] ; shrd $32, %[hi], %[lo]"
194 : [lo]"=a" (product), [hi]"=d" (tmp)
195 : "0" (delta), [mul_frac]"rm"((uint64_t)mul_frac));
198 #error "xentimer: unsupported architecture"
205 get_nsec_offset(struct vcpu_time_info *tinfo)
208 return (scale_delta(rdtsc() - tinfo->tsc_timestamp,
209 tinfo->tsc_to_system_mul, tinfo->tsc_shift));
213 * Read the current hypervisor system uptime value from Xen.
214 * See <xen/interface/xen.h> for a description of how this works.
217 xen_fetch_vcpu_tinfo(struct vcpu_time_info *dst, struct vcpu_time_info *src)
221 dst->version = src->version;
223 dst->tsc_timestamp = src->tsc_timestamp;
224 dst->system_time = src->system_time;
225 dst->tsc_to_system_mul = src->tsc_to_system_mul;
226 dst->tsc_shift = src->tsc_shift;
228 } while ((src->version & 1) | (dst->version ^ src->version));
230 return (dst->version);
234 * \brief Get the current time, in nanoseconds, since the hypervisor booted.
236 * \param vcpu vcpu_info structure to fetch the time from.
238 * \note This function returns the current CPU's idea of this value, unless
239 * it happens to be less than another CPU's previously determined value.
242 xen_fetch_vcpu_time(struct vcpu_info *vcpu)
244 struct vcpu_time_info dst;
245 struct vcpu_time_info *src;
246 uint32_t pre_version;
248 volatile uint64_t last;
253 pre_version = xen_fetch_vcpu_tinfo(&dst, src);
255 now = dst.system_time + get_nsec_offset(&dst);
257 } while (pre_version != src->version);
260 * Enforce a monotonically increasing clock time across all
261 * VCPUs. If our time is too old, use the last time and return.
262 * Otherwise, try to update the last time.
265 last = xen_timer_last_time;
270 } while (!atomic_cmpset_64(&xen_timer_last_time, last, now));
276 xentimer_get_timecount(struct timecounter *tc)
281 * We don't disable preemption here because the worst that can
282 * happen is reading the vcpu_info area of a different CPU than
283 * the one we are currently running on, but that would also
284 * return a valid tc (and we avoid the overhead of
285 * critical_{enter/exit} calls).
287 vcpu_time = xen_fetch_vcpu_time(DPCPU_GET(vcpu_info));
289 return (vcpu_time & UINT32_MAX);
293 * \brief Fetch the hypervisor boot time, known as the "Xen wallclock".
295 * \param ts Timespec to store the current stable value.
296 * \param version Pointer to store the corresponding wallclock version.
298 * \note This value is updated when Domain-0 shifts its clock to follow
299 * clock drift, e.g. as detected by NTP.
302 xen_fetch_wallclock(struct timespec *ts)
304 shared_info_t *src = HYPERVISOR_shared_info;
305 uint32_t version = 0;
308 version = src->wc_version;
310 ts->tv_sec = src->wc_sec;
311 ts->tv_nsec = src->wc_nsec;
313 } while ((src->wc_version & 1) | (version ^ src->wc_version));
317 xen_fetch_uptime(struct timespec *ts)
321 uptime = xen_fetch_vcpu_time(DPCPU_GET(vcpu_info));
323 ts->tv_sec = uptime / NSEC_IN_SEC;
324 ts->tv_nsec = uptime % NSEC_IN_SEC;
328 xentimer_settime(device_t dev __unused, struct timespec *ts)
331 * Don't return EINVAL here; just silently fail if the domain isn't
332 * privileged enough to set the TOD.
338 * \brief Return current time according to the Xen Hypervisor wallclock.
340 * \param dev Xentimer device.
341 * \param ts Pointer to store the wallclock time.
343 * \note The Xen time structures document the hypervisor start time and the
344 * uptime-since-hypervisor-start (in nsec.) They need to be combined
345 * in order to calculate a TOD clock.
348 xentimer_gettime(device_t dev, struct timespec *ts)
350 struct timespec u_ts;
353 xen_fetch_wallclock(ts);
354 xen_fetch_uptime(&u_ts);
355 timespecadd(ts, &u_ts);
361 * \brief Handle a timer interrupt for the Xen PV timer driver.
363 * \param arg Xen timer driver softc that is expecting the interrupt.
366 xentimer_intr(void *arg)
368 struct xentimer_softc *sc = (struct xentimer_softc *)arg;
369 struct xentimer_pcpu_data *pcpu = DPCPU_PTR(xentimer_pcpu);
371 pcpu->last_processed = xen_fetch_vcpu_time(DPCPU_GET(vcpu_info));
372 if (pcpu->timer != 0 && sc->et.et_active)
373 sc->et.et_event_cb(&sc->et, sc->et.et_arg);
375 return (FILTER_HANDLED);
379 xentimer_vcpu_start_timer(int vcpu, uint64_t next_time)
381 struct vcpu_set_singleshot_timer single;
383 single.timeout_abs_ns = next_time;
384 single.flags = VCPU_SSHOTTMR_future;
385 return (HYPERVISOR_vcpu_op(VCPUOP_set_singleshot_timer, vcpu, &single));
389 xentimer_vcpu_stop_timer(int vcpu)
392 return (HYPERVISOR_vcpu_op(VCPUOP_stop_singleshot_timer, vcpu, NULL));
396 * \brief Set the next oneshot time for the current CPU.
398 * \param et Xen timer driver event timer to schedule on.
399 * \param first Delta to the next time to schedule the interrupt for.
400 * \param period Not used.
402 * \note See eventtimers(9) for more information.
408 xentimer_et_start(struct eventtimer *et,
409 sbintime_t first, sbintime_t period)
411 int error = 0, i = 0;
412 struct xentimer_softc *sc = et->et_priv;
413 int cpu = PCPU_GET(vcpu_id);
414 struct xentimer_pcpu_data *pcpu = DPCPU_PTR(xentimer_pcpu);
415 struct vcpu_info *vcpu = DPCPU_GET(vcpu_info);
416 uint64_t first_in_ns, next_time;
418 struct thread *td = curthread;
421 KASSERT(td->td_critnest != 0,
422 ("xentimer_et_start called without preemption disabled"));
424 /* See sbttots() for this formula. */
425 first_in_ns = (((first >> 32) * NSEC_IN_SEC) +
426 (((uint64_t)NSEC_IN_SEC * (uint32_t)first) >> 32));
429 * Retry any timer scheduling failures, where the hypervisor
430 * returns -ETIME. Sometimes even a 100us timer period isn't large
431 * enough, but larger period instances are relatively uncommon.
433 * XXX Remove the panics once et_start() and its consumers are
434 * equipped to deal with start failures.
438 panic("can't schedule timer");
439 next_time = xen_fetch_vcpu_time(vcpu) + first_in_ns;
440 error = xentimer_vcpu_start_timer(cpu, next_time);
441 } while (error == -ETIME);
444 panic("%s: Error %d setting singleshot timer to %"PRIu64"\n",
445 device_get_nameunit(sc->dev), error, next_time);
447 pcpu->timer = next_time;
452 * \brief Cancel the event timer's currently running timer, if any.
455 xentimer_et_stop(struct eventtimer *et)
457 int cpu = PCPU_GET(vcpu_id);
458 struct xentimer_pcpu_data *pcpu = DPCPU_PTR(xentimer_pcpu);
461 return (xentimer_vcpu_stop_timer(cpu));
465 * \brief Attach a Xen PV timer driver instance.
467 * \param dev Bus device object to attach.
473 xentimer_attach(device_t dev)
475 struct xentimer_softc *sc = device_get_softc(dev);
480 /* Bind an event channel to a VIRQ on each VCPU. */
482 struct xentimer_pcpu_data *pcpu;
484 pcpu = DPCPU_ID_PTR(i, xentimer_pcpu);
485 error = HYPERVISOR_vcpu_op(VCPUOP_stop_periodic_timer, i, NULL);
487 device_printf(dev, "Error disabling Xen periodic timer "
492 error = xen_intr_bind_virq(dev, VIRQ_TIMER, i, xentimer_intr,
493 NULL, sc, INTR_TYPE_CLK, &pcpu->irq_handle);
495 device_printf(dev, "Error %d binding VIRQ_TIMER "
496 "to VCPU %d\n", error, i);
499 xen_intr_describe(pcpu->irq_handle, "c%d", i);
502 /* Register the event timer. */
503 sc->et.et_name = "XENTIMER";
504 sc->et.et_quality = XENTIMER_QUALITY;
505 sc->et.et_flags = ET_FLAGS_ONESHOT | ET_FLAGS_PERCPU;
506 sc->et.et_frequency = NSEC_IN_SEC;
507 /* See tstosbt() for this formula */
508 sc->et.et_min_period = (XENTIMER_MIN_PERIOD_IN_NSEC *
509 (((uint64_t)1 << 63) / 500000000) >> 32);
510 sc->et.et_max_period = ((sbintime_t)4 << 32);
511 sc->et.et_start = xentimer_et_start;
512 sc->et.et_stop = xentimer_et_stop;
514 et_register(&sc->et);
516 /* Register the timecounter. */
517 sc->tc.tc_name = "XENTIMER";
518 sc->tc.tc_quality = XENTIMER_QUALITY;
519 sc->tc.tc_flags = TC_FLAGS_SUSPEND_SAFE;
521 * The underlying resolution is in nanoseconds, since the timer info
522 * scales TSC frequencies using a fraction that represents time in
523 * terms of nanoseconds.
525 sc->tc.tc_frequency = NSEC_IN_SEC;
526 sc->tc.tc_counter_mask = ~0u;
527 sc->tc.tc_get_timecount = xentimer_get_timecount;
531 /* Register the Hypervisor wall clock */
532 clock_register(dev, XENCLOCK_RESOLUTION);
538 xentimer_detach(device_t dev)
541 /* Implement Xen PV clock teardown - XXX see hpet_detach ? */
543 * 1. need to deregister timecounter
544 * 2. need to deregister event timer
545 * 3. need to deregister virtual IRQ event channels
551 xentimer_percpu_resume(void *arg)
553 device_t dev = (device_t) arg;
554 struct xentimer_softc *sc = device_get_softc(dev);
556 xentimer_et_start(&sc->et, sc->et.et_min_period, 0);
560 xentimer_resume(device_t dev)
565 /* Disable the periodic timer */
567 error = HYPERVISOR_vcpu_op(VCPUOP_stop_periodic_timer, i, NULL);
570 "Error disabling Xen periodic timer on CPU %d\n",
576 /* Reset the last uptime value */
577 xen_timer_last_time = 0;
579 /* Reset the RTC clock */
580 inittodr(time_second);
582 /* Kick the timers on all CPUs */
583 smp_rendezvous(NULL, xentimer_percpu_resume, NULL, dev);
586 device_printf(dev, "resumed operation after suspension\n");
592 xentimer_suspend(device_t dev)
598 * Xen early clock init
606 * Xen PV DELAY function
608 * When running on PVH mode we don't have an emulated i8524, so
609 * make use of the Xen time info in order to code a simple DELAY
610 * function that can be used during early boot.
615 struct vcpu_info *vcpu = &HYPERVISOR_shared_info->vcpu_info[0];
619 end_ns = xen_fetch_vcpu_time(vcpu);
620 end_ns += n * NSEC_IN_USEC;
623 current = xen_fetch_vcpu_time(vcpu);
624 if (current >= end_ns)
629 static device_method_t xentimer_methods[] = {
630 DEVMETHOD(device_identify, xentimer_identify),
631 DEVMETHOD(device_probe, xentimer_probe),
632 DEVMETHOD(device_attach, xentimer_attach),
633 DEVMETHOD(device_detach, xentimer_detach),
634 DEVMETHOD(device_suspend, xentimer_suspend),
635 DEVMETHOD(device_resume, xentimer_resume),
636 /* clock interface */
637 DEVMETHOD(clock_gettime, xentimer_gettime),
638 DEVMETHOD(clock_settime, xentimer_settime),
642 static driver_t xentimer_driver = {
645 sizeof(struct xentimer_softc),
648 DRIVER_MODULE(xentimer, xenpv, xentimer_driver, xentimer_devclass, 0, 0);
649 MODULE_DEPEND(xentimer, xenpv, 1, 1, 1);