2 * 8253/8254 interval timer emulation
4 * Copyright (c) 2003-2004 Fabrice Bellard
5 * Copyright (c) 2006 Intel Corporation
6 * Copyright (c) 2007 Keir Fraser, XenSource Inc
7 * Copyright (c) 2008 Intel Corporation
8 * Copyright 2009 Red Hat, Inc. and/or its affiliates.
10 * Permission is hereby granted, free of charge, to any person obtaining a copy
11 * of this software and associated documentation files (the "Software"), to deal
12 * in the Software without restriction, including without limitation the rights
13 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 * copies of the Software, and to permit persons to whom the Software is
15 * furnished to do so, subject to the following conditions:
17 * The above copyright notice and this permission notice shall be included in
18 * all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30 * Based on QEMU and Xen.
33 #define pr_fmt(fmt) "pit: " fmt
35 #include <linux/kvm_host.h>
36 #include <linux/slab.h>
44 #define mod_64(x, y) ((x) - (y) * div64_u64(x, y))
46 #define mod_64(x, y) ((x) % (y))
49 #define RW_STATE_LSB 1
50 #define RW_STATE_MSB 2
51 #define RW_STATE_WORD0 3
52 #define RW_STATE_WORD1 4
54 static void pit_set_gate(struct kvm_pit *pit, int channel, u32 val)
56 struct kvm_kpit_channel_state *c = &pit->pit_state.channels[channel];
62 /* XXX: just disable/enable counting */
68 /* Restart counting on rising edge. */
70 c->count_load_time = ktime_get();
77 static int pit_get_gate(struct kvm_pit *pit, int channel)
79 return pit->pit_state.channels[channel].gate;
82 static s64 __kpit_elapsed(struct kvm_pit *pit)
86 struct kvm_kpit_state *ps = &pit->pit_state;
92 * The Counter does not stop when it reaches zero. In
93 * Modes 0, 1, 4, and 5 the Counter ``wraps around'' to
94 * the highest count, either FFFF hex for binary counting
95 * or 9999 for BCD counting, and continues counting.
96 * Modes 2 and 3 are periodic; the Counter reloads
97 * itself with the initial count and continues counting
100 remaining = hrtimer_get_remaining(&ps->timer);
101 elapsed = ps->period - ktime_to_ns(remaining);
106 static s64 kpit_elapsed(struct kvm_pit *pit, struct kvm_kpit_channel_state *c,
110 return __kpit_elapsed(pit);
112 return ktime_to_ns(ktime_sub(ktime_get(), c->count_load_time));
115 static int pit_get_count(struct kvm_pit *pit, int channel)
117 struct kvm_kpit_channel_state *c = &pit->pit_state.channels[channel];
121 t = kpit_elapsed(pit, c, channel);
122 d = mul_u64_u32_div(t, KVM_PIT_FREQ, NSEC_PER_SEC);
129 counter = (c->count - d) & 0xffff;
132 /* XXX: may be incorrect for odd counts */
133 counter = c->count - (mod_64((2 * d), c->count));
136 counter = c->count - mod_64(d, c->count);
142 static int pit_get_out(struct kvm_pit *pit, int channel)
144 struct kvm_kpit_channel_state *c = &pit->pit_state.channels[channel];
148 t = kpit_elapsed(pit, c, channel);
149 d = mul_u64_u32_div(t, KVM_PIT_FREQ, NSEC_PER_SEC);
154 out = (d >= c->count);
157 out = (d < c->count);
160 out = ((mod_64(d, c->count) == 0) && (d != 0));
163 out = (mod_64(d, c->count) < ((c->count + 1) >> 1));
167 out = (d == c->count);
174 static void pit_latch_count(struct kvm_pit *pit, int channel)
176 struct kvm_kpit_channel_state *c = &pit->pit_state.channels[channel];
178 if (!c->count_latched) {
179 c->latched_count = pit_get_count(pit, channel);
180 c->count_latched = c->rw_mode;
184 static void pit_latch_status(struct kvm_pit *pit, int channel)
186 struct kvm_kpit_channel_state *c = &pit->pit_state.channels[channel];
188 if (!c->status_latched) {
189 /* TODO: Return NULL COUNT (bit 6). */
190 c->status = ((pit_get_out(pit, channel) << 7) |
194 c->status_latched = 1;
198 static inline struct kvm_pit *pit_state_to_pit(struct kvm_kpit_state *ps)
200 return container_of(ps, struct kvm_pit, pit_state);
203 static void kvm_pit_ack_irq(struct kvm_irq_ack_notifier *kian)
205 struct kvm_kpit_state *ps = container_of(kian, struct kvm_kpit_state,
207 struct kvm_pit *pit = pit_state_to_pit(ps);
209 atomic_set(&ps->irq_ack, 1);
210 /* irq_ack should be set before pending is read. Order accesses with
211 * inc(pending) in pit_timer_fn and xchg(irq_ack, 0) in pit_do_work.
214 if (atomic_dec_if_positive(&ps->pending) > 0)
215 kthread_queue_work(pit->worker, &pit->expired);
218 void __kvm_migrate_pit_timer(struct kvm_vcpu *vcpu)
220 struct kvm_pit *pit = vcpu->kvm->arch.vpit;
221 struct hrtimer *timer;
223 /* Somewhat arbitrarily make vcpu0 the owner of the PIT. */
224 if (vcpu->vcpu_id || !pit)
227 timer = &pit->pit_state.timer;
228 mutex_lock(&pit->pit_state.lock);
229 if (hrtimer_cancel(timer))
230 hrtimer_start_expires(timer, HRTIMER_MODE_ABS);
231 mutex_unlock(&pit->pit_state.lock);
234 static void destroy_pit_timer(struct kvm_pit *pit)
236 hrtimer_cancel(&pit->pit_state.timer);
237 kthread_flush_work(&pit->expired);
240 static void pit_do_work(struct kthread_work *work)
242 struct kvm_pit *pit = container_of(work, struct kvm_pit, expired);
243 struct kvm *kvm = pit->kvm;
244 struct kvm_vcpu *vcpu;
246 struct kvm_kpit_state *ps = &pit->pit_state;
248 if (atomic_read(&ps->reinject) && !atomic_xchg(&ps->irq_ack, 0))
251 kvm_set_irq(kvm, pit->irq_source_id, 0, 1, false);
252 kvm_set_irq(kvm, pit->irq_source_id, 0, 0, false);
255 * Provides NMI watchdog support via Virtual Wire mode.
256 * The route is: PIT -> LVT0 in NMI mode.
258 * Note: Our Virtual Wire implementation does not follow
259 * the MP specification. We propagate a PIT interrupt to all
260 * VCPUs and only when LVT0 is in NMI mode. The interrupt can
261 * also be simultaneously delivered through PIC and IOAPIC.
263 if (atomic_read(&kvm->arch.vapics_in_nmi_mode) > 0)
264 kvm_for_each_vcpu(i, vcpu, kvm)
265 kvm_apic_nmi_wd_deliver(vcpu);
268 static enum hrtimer_restart pit_timer_fn(struct hrtimer *data)
270 struct kvm_kpit_state *ps = container_of(data, struct kvm_kpit_state, timer);
271 struct kvm_pit *pt = pit_state_to_pit(ps);
273 if (atomic_read(&ps->reinject))
274 atomic_inc(&ps->pending);
276 kthread_queue_work(pt->worker, &pt->expired);
278 if (ps->is_periodic) {
279 hrtimer_add_expires_ns(&ps->timer, ps->period);
280 return HRTIMER_RESTART;
282 return HRTIMER_NORESTART;
285 static inline void kvm_pit_reset_reinject(struct kvm_pit *pit)
287 atomic_set(&pit->pit_state.pending, 0);
288 atomic_set(&pit->pit_state.irq_ack, 1);
291 void kvm_pit_set_reinject(struct kvm_pit *pit, bool reinject)
293 struct kvm_kpit_state *ps = &pit->pit_state;
294 struct kvm *kvm = pit->kvm;
296 if (atomic_read(&ps->reinject) == reinject)
300 * AMD SVM AVIC accelerates EOI write and does not trap.
301 * This cause in-kernel PIT re-inject mode to fail
302 * since it checks ps->irq_ack before kvm_set_irq()
303 * and relies on the ack notifier to timely queue
304 * the pt->worker work iterm and reinject the missed tick.
305 * So, deactivate APICv when PIT is in reinject mode.
308 kvm_request_apicv_update(kvm, false,
309 APICV_INHIBIT_REASON_PIT_REINJ);
310 /* The initial state is preserved while ps->reinject == 0. */
311 kvm_pit_reset_reinject(pit);
312 kvm_register_irq_ack_notifier(kvm, &ps->irq_ack_notifier);
313 kvm_register_irq_mask_notifier(kvm, 0, &pit->mask_notifier);
315 kvm_request_apicv_update(kvm, true,
316 APICV_INHIBIT_REASON_PIT_REINJ);
317 kvm_unregister_irq_ack_notifier(kvm, &ps->irq_ack_notifier);
318 kvm_unregister_irq_mask_notifier(kvm, 0, &pit->mask_notifier);
321 atomic_set(&ps->reinject, reinject);
324 static void create_pit_timer(struct kvm_pit *pit, u32 val, int is_period)
326 struct kvm_kpit_state *ps = &pit->pit_state;
327 struct kvm *kvm = pit->kvm;
330 if (!ioapic_in_kernel(kvm) ||
331 ps->flags & KVM_PIT_FLAGS_HPET_LEGACY)
334 interval = mul_u64_u32_div(val, NSEC_PER_SEC, KVM_PIT_FREQ);
336 pr_debug("create pit timer, interval is %llu nsec\n", interval);
338 /* TODO The new value only affected after the retriggered */
339 hrtimer_cancel(&ps->timer);
340 kthread_flush_work(&pit->expired);
341 ps->period = interval;
342 ps->is_periodic = is_period;
344 kvm_pit_reset_reinject(pit);
347 * Do not allow the guest to program periodic timers with small
348 * interval, since the hrtimers are not throttled by the host
351 if (ps->is_periodic) {
352 s64 min_period = min_timer_period_us * 1000LL;
354 if (ps->period < min_period) {
356 "kvm: requested %lld ns "
357 "i8254 timer period limited to %lld ns\n",
358 ps->period, min_period);
359 ps->period = min_period;
363 hrtimer_start(&ps->timer, ktime_add_ns(ktime_get(), interval),
367 static void pit_load_count(struct kvm_pit *pit, int channel, u32 val)
369 struct kvm_kpit_state *ps = &pit->pit_state;
371 pr_debug("load_count val is %u, channel is %d\n", val, channel);
374 * The largest possible initial count is 0; this is equivalent
375 * to 216 for binary counting and 104 for BCD counting.
380 ps->channels[channel].count = val;
383 ps->channels[channel].count_load_time = ktime_get();
387 /* Two types of timer
388 * mode 1 is one shot, mode 2 is period, otherwise del timer */
389 switch (ps->channels[0].mode) {
392 /* FIXME: enhance mode 4 precision */
394 create_pit_timer(pit, val, 0);
398 create_pit_timer(pit, val, 1);
401 destroy_pit_timer(pit);
405 void kvm_pit_load_count(struct kvm_pit *pit, int channel, u32 val,
406 int hpet_legacy_start)
410 WARN_ON_ONCE(!mutex_is_locked(&pit->pit_state.lock));
412 if (hpet_legacy_start) {
413 /* save existing mode for later reenablement */
414 WARN_ON(channel != 0);
415 saved_mode = pit->pit_state.channels[0].mode;
416 pit->pit_state.channels[0].mode = 0xff; /* disable timer */
417 pit_load_count(pit, channel, val);
418 pit->pit_state.channels[0].mode = saved_mode;
420 pit_load_count(pit, channel, val);
424 static inline struct kvm_pit *dev_to_pit(struct kvm_io_device *dev)
426 return container_of(dev, struct kvm_pit, dev);
429 static inline struct kvm_pit *speaker_to_pit(struct kvm_io_device *dev)
431 return container_of(dev, struct kvm_pit, speaker_dev);
434 static inline int pit_in_range(gpa_t addr)
436 return ((addr >= KVM_PIT_BASE_ADDRESS) &&
437 (addr < KVM_PIT_BASE_ADDRESS + KVM_PIT_MEM_LENGTH));
440 static int pit_ioport_write(struct kvm_vcpu *vcpu,
441 struct kvm_io_device *this,
442 gpa_t addr, int len, const void *data)
444 struct kvm_pit *pit = dev_to_pit(this);
445 struct kvm_kpit_state *pit_state = &pit->pit_state;
447 struct kvm_kpit_channel_state *s;
448 u32 val = *(u32 *) data;
449 if (!pit_in_range(addr))
453 addr &= KVM_PIT_CHANNEL_MASK;
455 mutex_lock(&pit_state->lock);
458 pr_debug("write addr is 0x%x, len is %d, val is 0x%x\n",
459 (unsigned int)addr, len, val);
464 /* Read-Back Command. */
465 for (channel = 0; channel < 3; channel++) {
466 if (val & (2 << channel)) {
468 pit_latch_count(pit, channel);
470 pit_latch_status(pit, channel);
474 /* Select Counter <channel>. */
475 s = &pit_state->channels[channel];
476 access = (val >> 4) & KVM_PIT_CHANNEL_MASK;
478 pit_latch_count(pit, channel);
481 s->read_state = access;
482 s->write_state = access;
483 s->mode = (val >> 1) & 7;
491 s = &pit_state->channels[addr];
492 switch (s->write_state) {
495 pit_load_count(pit, addr, val);
498 pit_load_count(pit, addr, val << 8);
501 s->write_latch = val;
502 s->write_state = RW_STATE_WORD1;
505 pit_load_count(pit, addr, s->write_latch | (val << 8));
506 s->write_state = RW_STATE_WORD0;
511 mutex_unlock(&pit_state->lock);
515 static int pit_ioport_read(struct kvm_vcpu *vcpu,
516 struct kvm_io_device *this,
517 gpa_t addr, int len, void *data)
519 struct kvm_pit *pit = dev_to_pit(this);
520 struct kvm_kpit_state *pit_state = &pit->pit_state;
522 struct kvm_kpit_channel_state *s;
523 if (!pit_in_range(addr))
526 addr &= KVM_PIT_CHANNEL_MASK;
530 s = &pit_state->channels[addr];
532 mutex_lock(&pit_state->lock);
534 if (s->status_latched) {
535 s->status_latched = 0;
537 } else if (s->count_latched) {
538 switch (s->count_latched) {
541 ret = s->latched_count & 0xff;
542 s->count_latched = 0;
545 ret = s->latched_count >> 8;
546 s->count_latched = 0;
549 ret = s->latched_count & 0xff;
550 s->count_latched = RW_STATE_MSB;
554 switch (s->read_state) {
557 count = pit_get_count(pit, addr);
561 count = pit_get_count(pit, addr);
562 ret = (count >> 8) & 0xff;
565 count = pit_get_count(pit, addr);
567 s->read_state = RW_STATE_WORD1;
570 count = pit_get_count(pit, addr);
571 ret = (count >> 8) & 0xff;
572 s->read_state = RW_STATE_WORD0;
577 if (len > sizeof(ret))
579 memcpy(data, (char *)&ret, len);
581 mutex_unlock(&pit_state->lock);
585 static int speaker_ioport_write(struct kvm_vcpu *vcpu,
586 struct kvm_io_device *this,
587 gpa_t addr, int len, const void *data)
589 struct kvm_pit *pit = speaker_to_pit(this);
590 struct kvm_kpit_state *pit_state = &pit->pit_state;
591 u32 val = *(u32 *) data;
592 if (addr != KVM_SPEAKER_BASE_ADDRESS)
595 mutex_lock(&pit_state->lock);
596 pit_state->speaker_data_on = (val >> 1) & 1;
597 pit_set_gate(pit, 2, val & 1);
598 mutex_unlock(&pit_state->lock);
602 static int speaker_ioport_read(struct kvm_vcpu *vcpu,
603 struct kvm_io_device *this,
604 gpa_t addr, int len, void *data)
606 struct kvm_pit *pit = speaker_to_pit(this);
607 struct kvm_kpit_state *pit_state = &pit->pit_state;
608 unsigned int refresh_clock;
610 if (addr != KVM_SPEAKER_BASE_ADDRESS)
613 /* Refresh clock toggles at about 15us. We approximate as 2^14ns. */
614 refresh_clock = ((unsigned int)ktime_to_ns(ktime_get()) >> 14) & 1;
616 mutex_lock(&pit_state->lock);
617 ret = ((pit_state->speaker_data_on << 1) | pit_get_gate(pit, 2) |
618 (pit_get_out(pit, 2) << 5) | (refresh_clock << 4));
619 if (len > sizeof(ret))
621 memcpy(data, (char *)&ret, len);
622 mutex_unlock(&pit_state->lock);
626 static void kvm_pit_reset(struct kvm_pit *pit)
629 struct kvm_kpit_channel_state *c;
631 pit->pit_state.flags = 0;
632 for (i = 0; i < 3; i++) {
633 c = &pit->pit_state.channels[i];
636 pit_load_count(pit, i, 0);
639 kvm_pit_reset_reinject(pit);
642 static void pit_mask_notifer(struct kvm_irq_mask_notifier *kimn, bool mask)
644 struct kvm_pit *pit = container_of(kimn, struct kvm_pit, mask_notifier);
647 kvm_pit_reset_reinject(pit);
650 static const struct kvm_io_device_ops pit_dev_ops = {
651 .read = pit_ioport_read,
652 .write = pit_ioport_write,
655 static const struct kvm_io_device_ops speaker_dev_ops = {
656 .read = speaker_ioport_read,
657 .write = speaker_ioport_write,
660 struct kvm_pit *kvm_create_pit(struct kvm *kvm, u32 flags)
663 struct kvm_kpit_state *pit_state;
668 pit = kzalloc(sizeof(struct kvm_pit), GFP_KERNEL_ACCOUNT);
672 pit->irq_source_id = kvm_request_irq_source_id(kvm);
673 if (pit->irq_source_id < 0)
676 mutex_init(&pit->pit_state.lock);
678 pid = get_pid(task_tgid(current));
679 pid_nr = pid_vnr(pid);
682 pit->worker = kthread_create_worker(0, "kvm-pit/%d", pid_nr);
683 if (IS_ERR(pit->worker))
686 kthread_init_work(&pit->expired, pit_do_work);
690 pit_state = &pit->pit_state;
691 hrtimer_init(&pit_state->timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
692 pit_state->timer.function = pit_timer_fn;
694 pit_state->irq_ack_notifier.gsi = 0;
695 pit_state->irq_ack_notifier.irq_acked = kvm_pit_ack_irq;
696 pit->mask_notifier.func = pit_mask_notifer;
700 kvm_pit_set_reinject(pit, true);
702 mutex_lock(&kvm->slots_lock);
703 kvm_iodevice_init(&pit->dev, &pit_dev_ops);
704 ret = kvm_io_bus_register_dev(kvm, KVM_PIO_BUS, KVM_PIT_BASE_ADDRESS,
705 KVM_PIT_MEM_LENGTH, &pit->dev);
707 goto fail_register_pit;
709 if (flags & KVM_PIT_SPEAKER_DUMMY) {
710 kvm_iodevice_init(&pit->speaker_dev, &speaker_dev_ops);
711 ret = kvm_io_bus_register_dev(kvm, KVM_PIO_BUS,
712 KVM_SPEAKER_BASE_ADDRESS, 4,
715 goto fail_register_speaker;
717 mutex_unlock(&kvm->slots_lock);
721 fail_register_speaker:
722 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS, &pit->dev);
724 mutex_unlock(&kvm->slots_lock);
725 kvm_pit_set_reinject(pit, false);
726 kthread_destroy_worker(pit->worker);
728 kvm_free_irq_source_id(kvm, pit->irq_source_id);
734 void kvm_free_pit(struct kvm *kvm)
736 struct kvm_pit *pit = kvm->arch.vpit;
739 mutex_lock(&kvm->slots_lock);
740 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS, &pit->dev);
741 kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS, &pit->speaker_dev);
742 mutex_unlock(&kvm->slots_lock);
743 kvm_pit_set_reinject(pit, false);
744 hrtimer_cancel(&pit->pit_state.timer);
745 kthread_destroy_worker(pit->worker);
746 kvm_free_irq_source_id(kvm, pit->irq_source_id);