1 // SPDX-License-Identifier: GPL-2.0-only
4 * Local APIC virtualization
6 * Copyright (C) 2006 Qumranet, Inc.
7 * Copyright (C) 2007 Novell
8 * Copyright (C) 2007 Intel
9 * Copyright 2009 Red Hat, Inc. and/or its affiliates.
12 * Dor Laor <dor.laor@qumranet.com>
13 * Gregory Haskins <ghaskins@novell.com>
14 * Yaozu (Eddie) Dong <eddie.dong@intel.com>
16 * Based on Xen 3.1 code, Copyright (c) 2004, Intel Corporation.
19 #include <linux/kvm_host.h>
20 #include <linux/kvm.h>
22 #include <linux/highmem.h>
23 #include <linux/smp.h>
24 #include <linux/hrtimer.h>
26 #include <linux/export.h>
27 #include <linux/math64.h>
28 #include <linux/slab.h>
29 #include <asm/processor.h>
32 #include <asm/current.h>
33 #include <asm/apicdef.h>
34 #include <asm/delay.h>
35 #include <linux/atomic.h>
36 #include <linux/jump_label.h>
37 #include "kvm_cache_regs.h"
45 #define mod_64(x, y) ((x) - (y) * div64_u64(x, y))
47 #define mod_64(x, y) ((x) % (y))
55 /* #define apic_debug(fmt,arg...) printk(KERN_WARNING fmt,##arg) */
56 #define apic_debug(fmt, arg...) do {} while (0)
58 /* 14 is the version for Xeon and Pentium 8.4.8*/
59 #define APIC_VERSION (0x14UL | ((KVM_APIC_LVT_NUM - 1) << 16))
60 #define LAPIC_MMIO_LENGTH (1 << 12)
61 /* followed define is not in apicdef.h */
62 #define APIC_SHORT_MASK 0xc0000
63 #define APIC_DEST_NOSHORT 0x0
64 #define APIC_DEST_MASK 0x800
65 #define MAX_APIC_VECTOR 256
66 #define APIC_VECTORS_PER_REG 32
68 #define APIC_BROADCAST 0xFF
69 #define X2APIC_BROADCAST 0xFFFFFFFFul
71 #define LAPIC_TIMER_ADVANCE_ADJUST_DONE 100
72 /* step-by-step approximation to mitigate fluctuation */
73 #define LAPIC_TIMER_ADVANCE_ADJUST_STEP 8
75 static inline int apic_test_vector(int vec, void *bitmap)
77 return test_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
80 bool kvm_apic_pending_eoi(struct kvm_vcpu *vcpu, int vector)
82 struct kvm_lapic *apic = vcpu->arch.apic;
84 return apic_test_vector(vector, apic->regs + APIC_ISR) ||
85 apic_test_vector(vector, apic->regs + APIC_IRR);
88 static inline void apic_clear_vector(int vec, void *bitmap)
90 clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
93 static inline int __apic_test_and_set_vector(int vec, void *bitmap)
95 return __test_and_set_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
98 static inline int __apic_test_and_clear_vector(int vec, void *bitmap)
100 return __test_and_clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
103 struct static_key_deferred apic_hw_disabled __read_mostly;
104 struct static_key_deferred apic_sw_disabled __read_mostly;
106 static inline int apic_enabled(struct kvm_lapic *apic)
108 return kvm_apic_sw_enabled(apic) && kvm_apic_hw_enabled(apic);
112 (APIC_LVT_MASKED | APIC_SEND_PENDING | APIC_VECTOR_MASK)
115 (LVT_MASK | APIC_MODE_MASK | APIC_INPUT_POLARITY | \
116 APIC_LVT_REMOTE_IRR | APIC_LVT_LEVEL_TRIGGER)
118 static inline u8 kvm_xapic_id(struct kvm_lapic *apic)
120 return kvm_lapic_get_reg(apic, APIC_ID) >> 24;
123 static inline u32 kvm_x2apic_id(struct kvm_lapic *apic)
125 return apic->vcpu->vcpu_id;
128 static inline bool kvm_apic_map_get_logical_dest(struct kvm_apic_map *map,
129 u32 dest_id, struct kvm_lapic ***cluster, u16 *mask) {
131 case KVM_APIC_MODE_X2APIC: {
132 u32 offset = (dest_id >> 16) * 16;
133 u32 max_apic_id = map->max_apic_id;
135 if (offset <= max_apic_id) {
136 u8 cluster_size = min(max_apic_id - offset + 1, 16U);
138 offset = array_index_nospec(offset, map->max_apic_id + 1);
139 *cluster = &map->phys_map[offset];
140 *mask = dest_id & (0xffff >> (16 - cluster_size));
147 case KVM_APIC_MODE_XAPIC_FLAT:
148 *cluster = map->xapic_flat_map;
149 *mask = dest_id & 0xff;
151 case KVM_APIC_MODE_XAPIC_CLUSTER:
152 *cluster = map->xapic_cluster_map[(dest_id >> 4) & 0xf];
153 *mask = dest_id & 0xf;
161 static void kvm_apic_map_free(struct rcu_head *rcu)
163 struct kvm_apic_map *map = container_of(rcu, struct kvm_apic_map, rcu);
168 static void recalculate_apic_map(struct kvm *kvm)
170 struct kvm_apic_map *new, *old = NULL;
171 struct kvm_vcpu *vcpu;
173 u32 max_id = 255; /* enough space for any xAPIC ID */
175 mutex_lock(&kvm->arch.apic_map_lock);
177 kvm_for_each_vcpu(i, vcpu, kvm)
178 if (kvm_apic_present(vcpu))
179 max_id = max(max_id, kvm_x2apic_id(vcpu->arch.apic));
181 new = kvzalloc(sizeof(struct kvm_apic_map) +
182 sizeof(struct kvm_lapic *) * ((u64)max_id + 1),
188 new->max_apic_id = max_id;
190 kvm_for_each_vcpu(i, vcpu, kvm) {
191 struct kvm_lapic *apic = vcpu->arch.apic;
192 struct kvm_lapic **cluster;
198 if (!kvm_apic_present(vcpu))
201 xapic_id = kvm_xapic_id(apic);
202 x2apic_id = kvm_x2apic_id(apic);
204 /* Hotplug hack: see kvm_apic_match_physical_addr(), ... */
205 if ((apic_x2apic_mode(apic) || x2apic_id > 0xff) &&
206 x2apic_id <= new->max_apic_id)
207 new->phys_map[x2apic_id] = apic;
209 * ... xAPIC ID of VCPUs with APIC ID > 0xff will wrap-around,
210 * prevent them from masking VCPUs with APIC ID <= 0xff.
212 if (!apic_x2apic_mode(apic) && !new->phys_map[xapic_id])
213 new->phys_map[xapic_id] = apic;
215 ldr = kvm_lapic_get_reg(apic, APIC_LDR);
217 if (apic_x2apic_mode(apic)) {
218 new->mode |= KVM_APIC_MODE_X2APIC;
220 ldr = GET_APIC_LOGICAL_ID(ldr);
221 if (kvm_lapic_get_reg(apic, APIC_DFR) == APIC_DFR_FLAT)
222 new->mode |= KVM_APIC_MODE_XAPIC_FLAT;
224 new->mode |= KVM_APIC_MODE_XAPIC_CLUSTER;
227 if (!kvm_apic_map_get_logical_dest(new, ldr, &cluster, &mask))
231 cluster[ffs(mask) - 1] = apic;
234 old = rcu_dereference_protected(kvm->arch.apic_map,
235 lockdep_is_held(&kvm->arch.apic_map_lock));
236 rcu_assign_pointer(kvm->arch.apic_map, new);
237 mutex_unlock(&kvm->arch.apic_map_lock);
240 call_rcu(&old->rcu, kvm_apic_map_free);
242 kvm_make_scan_ioapic_request(kvm);
245 static inline void apic_set_spiv(struct kvm_lapic *apic, u32 val)
247 bool enabled = val & APIC_SPIV_APIC_ENABLED;
249 kvm_lapic_set_reg(apic, APIC_SPIV, val);
251 if (enabled != apic->sw_enabled) {
252 apic->sw_enabled = enabled;
254 static_key_slow_dec_deferred(&apic_sw_disabled);
256 static_key_slow_inc(&apic_sw_disabled.key);
260 static inline void kvm_apic_set_xapic_id(struct kvm_lapic *apic, u8 id)
262 kvm_lapic_set_reg(apic, APIC_ID, id << 24);
263 recalculate_apic_map(apic->vcpu->kvm);
266 static inline void kvm_apic_set_ldr(struct kvm_lapic *apic, u32 id)
268 kvm_lapic_set_reg(apic, APIC_LDR, id);
269 recalculate_apic_map(apic->vcpu->kvm);
272 static inline u32 kvm_apic_calc_x2apic_ldr(u32 id)
274 return ((id >> 4) << 16) | (1 << (id & 0xf));
277 static inline void kvm_apic_set_x2apic_id(struct kvm_lapic *apic, u32 id)
279 u32 ldr = kvm_apic_calc_x2apic_ldr(id);
281 WARN_ON_ONCE(id != apic->vcpu->vcpu_id);
283 kvm_lapic_set_reg(apic, APIC_ID, id);
284 kvm_lapic_set_reg(apic, APIC_LDR, ldr);
285 recalculate_apic_map(apic->vcpu->kvm);
288 static inline int apic_lvt_enabled(struct kvm_lapic *apic, int lvt_type)
290 return !(kvm_lapic_get_reg(apic, lvt_type) & APIC_LVT_MASKED);
293 static inline int apic_lvt_vector(struct kvm_lapic *apic, int lvt_type)
295 return kvm_lapic_get_reg(apic, lvt_type) & APIC_VECTOR_MASK;
298 static inline int apic_lvtt_oneshot(struct kvm_lapic *apic)
300 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_ONESHOT;
303 static inline int apic_lvtt_period(struct kvm_lapic *apic)
305 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_PERIODIC;
308 static inline int apic_lvtt_tscdeadline(struct kvm_lapic *apic)
310 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_TSCDEADLINE;
313 static inline int apic_lvt_nmi_mode(u32 lvt_val)
315 return (lvt_val & (APIC_MODE_MASK | APIC_LVT_MASKED)) == APIC_DM_NMI;
318 void kvm_apic_set_version(struct kvm_vcpu *vcpu)
320 struct kvm_lapic *apic = vcpu->arch.apic;
321 struct kvm_cpuid_entry2 *feat;
322 u32 v = APIC_VERSION;
324 if (!lapic_in_kernel(vcpu))
328 * KVM emulates 82093AA datasheet (with in-kernel IOAPIC implementation)
329 * which doesn't have EOI register; Some buggy OSes (e.g. Windows with
330 * Hyper-V role) disable EOI broadcast in lapic not checking for IOAPIC
331 * version first and level-triggered interrupts never get EOIed in
334 feat = kvm_find_cpuid_entry(apic->vcpu, 0x1, 0);
335 if (feat && (feat->ecx & (1 << (X86_FEATURE_X2APIC & 31))) &&
336 !ioapic_in_kernel(vcpu->kvm))
337 v |= APIC_LVR_DIRECTED_EOI;
338 kvm_lapic_set_reg(apic, APIC_LVR, v);
341 static const unsigned int apic_lvt_mask[KVM_APIC_LVT_NUM] = {
342 LVT_MASK , /* part LVTT mask, timer mode mask added at runtime */
343 LVT_MASK | APIC_MODE_MASK, /* LVTTHMR */
344 LVT_MASK | APIC_MODE_MASK, /* LVTPC */
345 LINT_MASK, LINT_MASK, /* LVT0-1 */
346 LVT_MASK /* LVTERR */
349 static int find_highest_vector(void *bitmap)
354 for (vec = MAX_APIC_VECTOR - APIC_VECTORS_PER_REG;
355 vec >= 0; vec -= APIC_VECTORS_PER_REG) {
356 reg = bitmap + REG_POS(vec);
358 return __fls(*reg) + vec;
364 static u8 count_vectors(void *bitmap)
370 for (vec = 0; vec < MAX_APIC_VECTOR; vec += APIC_VECTORS_PER_REG) {
371 reg = bitmap + REG_POS(vec);
372 count += hweight32(*reg);
378 bool __kvm_apic_update_irr(u32 *pir, void *regs, int *max_irr)
381 u32 pir_val, irr_val, prev_irr_val;
384 max_updated_irr = -1;
387 for (i = vec = 0; i <= 7; i++, vec += 32) {
388 pir_val = READ_ONCE(pir[i]);
389 irr_val = *((u32 *)(regs + APIC_IRR + i * 0x10));
391 prev_irr_val = irr_val;
392 irr_val |= xchg(&pir[i], 0);
393 *((u32 *)(regs + APIC_IRR + i * 0x10)) = irr_val;
394 if (prev_irr_val != irr_val) {
396 __fls(irr_val ^ prev_irr_val) + vec;
400 *max_irr = __fls(irr_val) + vec;
403 return ((max_updated_irr != -1) &&
404 (max_updated_irr == *max_irr));
406 EXPORT_SYMBOL_GPL(__kvm_apic_update_irr);
408 bool kvm_apic_update_irr(struct kvm_vcpu *vcpu, u32 *pir, int *max_irr)
410 struct kvm_lapic *apic = vcpu->arch.apic;
412 return __kvm_apic_update_irr(pir, apic->regs, max_irr);
414 EXPORT_SYMBOL_GPL(kvm_apic_update_irr);
416 static inline int apic_search_irr(struct kvm_lapic *apic)
418 return find_highest_vector(apic->regs + APIC_IRR);
421 static inline int apic_find_highest_irr(struct kvm_lapic *apic)
426 * Note that irr_pending is just a hint. It will be always
427 * true with virtual interrupt delivery enabled.
429 if (!apic->irr_pending)
432 result = apic_search_irr(apic);
433 ASSERT(result == -1 || result >= 16);
438 static inline void apic_clear_irr(int vec, struct kvm_lapic *apic)
440 struct kvm_vcpu *vcpu;
444 if (unlikely(vcpu->arch.apicv_active)) {
445 /* need to update RVI */
446 apic_clear_vector(vec, apic->regs + APIC_IRR);
447 kvm_x86_ops->hwapic_irr_update(vcpu,
448 apic_find_highest_irr(apic));
450 apic->irr_pending = false;
451 apic_clear_vector(vec, apic->regs + APIC_IRR);
452 if (apic_search_irr(apic) != -1)
453 apic->irr_pending = true;
457 static inline void apic_set_isr(int vec, struct kvm_lapic *apic)
459 struct kvm_vcpu *vcpu;
461 if (__apic_test_and_set_vector(vec, apic->regs + APIC_ISR))
467 * With APIC virtualization enabled, all caching is disabled
468 * because the processor can modify ISR under the hood. Instead
471 if (unlikely(vcpu->arch.apicv_active))
472 kvm_x86_ops->hwapic_isr_update(vcpu, vec);
475 BUG_ON(apic->isr_count > MAX_APIC_VECTOR);
477 * ISR (in service register) bit is set when injecting an interrupt.
478 * The highest vector is injected. Thus the latest bit set matches
479 * the highest bit in ISR.
481 apic->highest_isr_cache = vec;
485 static inline int apic_find_highest_isr(struct kvm_lapic *apic)
490 * Note that isr_count is always 1, and highest_isr_cache
491 * is always -1, with APIC virtualization enabled.
493 if (!apic->isr_count)
495 if (likely(apic->highest_isr_cache != -1))
496 return apic->highest_isr_cache;
498 result = find_highest_vector(apic->regs + APIC_ISR);
499 ASSERT(result == -1 || result >= 16);
504 static inline void apic_clear_isr(int vec, struct kvm_lapic *apic)
506 struct kvm_vcpu *vcpu;
507 if (!__apic_test_and_clear_vector(vec, apic->regs + APIC_ISR))
513 * We do get here for APIC virtualization enabled if the guest
514 * uses the Hyper-V APIC enlightenment. In this case we may need
515 * to trigger a new interrupt delivery by writing the SVI field;
516 * on the other hand isr_count and highest_isr_cache are unused
517 * and must be left alone.
519 if (unlikely(vcpu->arch.apicv_active))
520 kvm_x86_ops->hwapic_isr_update(vcpu,
521 apic_find_highest_isr(apic));
524 BUG_ON(apic->isr_count < 0);
525 apic->highest_isr_cache = -1;
529 int kvm_lapic_find_highest_irr(struct kvm_vcpu *vcpu)
531 /* This may race with setting of irr in __apic_accept_irq() and
532 * value returned may be wrong, but kvm_vcpu_kick() in __apic_accept_irq
533 * will cause vmexit immediately and the value will be recalculated
534 * on the next vmentry.
536 return apic_find_highest_irr(vcpu->arch.apic);
538 EXPORT_SYMBOL_GPL(kvm_lapic_find_highest_irr);
540 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
541 int vector, int level, int trig_mode,
542 struct dest_map *dest_map);
544 int kvm_apic_set_irq(struct kvm_vcpu *vcpu, struct kvm_lapic_irq *irq,
545 struct dest_map *dest_map)
547 struct kvm_lapic *apic = vcpu->arch.apic;
549 return __apic_accept_irq(apic, irq->delivery_mode, irq->vector,
550 irq->level, irq->trig_mode, dest_map);
553 int kvm_pv_send_ipi(struct kvm *kvm, unsigned long ipi_bitmap_low,
554 unsigned long ipi_bitmap_high, u32 min,
555 unsigned long icr, int op_64_bit)
558 struct kvm_apic_map *map;
559 struct kvm_vcpu *vcpu;
560 struct kvm_lapic_irq irq = {0};
561 int cluster_size = op_64_bit ? 64 : 32;
564 irq.vector = icr & APIC_VECTOR_MASK;
565 irq.delivery_mode = icr & APIC_MODE_MASK;
566 irq.level = (icr & APIC_INT_ASSERT) != 0;
567 irq.trig_mode = icr & APIC_INT_LEVELTRIG;
569 if (icr & APIC_DEST_MASK)
571 if (icr & APIC_SHORT_MASK)
575 map = rcu_dereference(kvm->arch.apic_map);
577 if (unlikely(!map)) {
582 if (min > map->max_apic_id)
584 /* Bits above cluster_size are masked in the caller. */
585 for_each_set_bit(i, &ipi_bitmap_low,
586 min((u32)BITS_PER_LONG, (map->max_apic_id - min + 1))) {
587 if (map->phys_map[min + i]) {
588 vcpu = map->phys_map[min + i]->vcpu;
589 count += kvm_apic_set_irq(vcpu, &irq, NULL);
595 if (min > map->max_apic_id)
598 for_each_set_bit(i, &ipi_bitmap_high,
599 min((u32)BITS_PER_LONG, (map->max_apic_id - min + 1))) {
600 if (map->phys_map[min + i]) {
601 vcpu = map->phys_map[min + i]->vcpu;
602 count += kvm_apic_set_irq(vcpu, &irq, NULL);
611 static int pv_eoi_put_user(struct kvm_vcpu *vcpu, u8 val)
614 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, &val,
618 static int pv_eoi_get_user(struct kvm_vcpu *vcpu, u8 *val)
621 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, val,
625 static inline bool pv_eoi_enabled(struct kvm_vcpu *vcpu)
627 return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
630 static bool pv_eoi_get_pending(struct kvm_vcpu *vcpu)
633 if (pv_eoi_get_user(vcpu, &val) < 0)
634 apic_debug("Can't read EOI MSR value: 0x%llx\n",
635 (unsigned long long)vcpu->arch.pv_eoi.msr_val);
639 static void pv_eoi_set_pending(struct kvm_vcpu *vcpu)
641 if (pv_eoi_put_user(vcpu, KVM_PV_EOI_ENABLED) < 0) {
642 apic_debug("Can't set EOI MSR value: 0x%llx\n",
643 (unsigned long long)vcpu->arch.pv_eoi.msr_val);
646 __set_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
649 static void pv_eoi_clr_pending(struct kvm_vcpu *vcpu)
651 if (pv_eoi_put_user(vcpu, KVM_PV_EOI_DISABLED) < 0) {
652 apic_debug("Can't clear EOI MSR value: 0x%llx\n",
653 (unsigned long long)vcpu->arch.pv_eoi.msr_val);
656 __clear_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
659 static int apic_has_interrupt_for_ppr(struct kvm_lapic *apic, u32 ppr)
662 if (apic->vcpu->arch.apicv_active)
663 highest_irr = kvm_x86_ops->sync_pir_to_irr(apic->vcpu);
665 highest_irr = apic_find_highest_irr(apic);
666 if (highest_irr == -1 || (highest_irr & 0xF0) <= ppr)
671 static bool __apic_update_ppr(struct kvm_lapic *apic, u32 *new_ppr)
673 u32 tpr, isrv, ppr, old_ppr;
676 old_ppr = kvm_lapic_get_reg(apic, APIC_PROCPRI);
677 tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI);
678 isr = apic_find_highest_isr(apic);
679 isrv = (isr != -1) ? isr : 0;
681 if ((tpr & 0xf0) >= (isrv & 0xf0))
686 apic_debug("vlapic %p, ppr 0x%x, isr 0x%x, isrv 0x%x",
687 apic, ppr, isr, isrv);
691 kvm_lapic_set_reg(apic, APIC_PROCPRI, ppr);
693 return ppr < old_ppr;
696 static void apic_update_ppr(struct kvm_lapic *apic)
700 if (__apic_update_ppr(apic, &ppr) &&
701 apic_has_interrupt_for_ppr(apic, ppr) != -1)
702 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
705 void kvm_apic_update_ppr(struct kvm_vcpu *vcpu)
707 apic_update_ppr(vcpu->arch.apic);
709 EXPORT_SYMBOL_GPL(kvm_apic_update_ppr);
711 static void apic_set_tpr(struct kvm_lapic *apic, u32 tpr)
713 kvm_lapic_set_reg(apic, APIC_TASKPRI, tpr);
714 apic_update_ppr(apic);
717 static bool kvm_apic_broadcast(struct kvm_lapic *apic, u32 mda)
719 return mda == (apic_x2apic_mode(apic) ?
720 X2APIC_BROADCAST : APIC_BROADCAST);
723 static bool kvm_apic_match_physical_addr(struct kvm_lapic *apic, u32 mda)
725 if (kvm_apic_broadcast(apic, mda))
728 if (apic_x2apic_mode(apic))
729 return mda == kvm_x2apic_id(apic);
732 * Hotplug hack: Make LAPIC in xAPIC mode also accept interrupts as if
733 * it were in x2APIC mode. Hotplugged VCPUs start in xAPIC mode and
734 * this allows unique addressing of VCPUs with APIC ID over 0xff.
735 * The 0xff condition is needed because writeable xAPIC ID.
737 if (kvm_x2apic_id(apic) > 0xff && mda == kvm_x2apic_id(apic))
740 return mda == kvm_xapic_id(apic);
743 static bool kvm_apic_match_logical_addr(struct kvm_lapic *apic, u32 mda)
747 if (kvm_apic_broadcast(apic, mda))
750 logical_id = kvm_lapic_get_reg(apic, APIC_LDR);
752 if (apic_x2apic_mode(apic))
753 return ((logical_id >> 16) == (mda >> 16))
754 && (logical_id & mda & 0xffff) != 0;
756 logical_id = GET_APIC_LOGICAL_ID(logical_id);
758 switch (kvm_lapic_get_reg(apic, APIC_DFR)) {
760 return (logical_id & mda) != 0;
761 case APIC_DFR_CLUSTER:
762 return ((logical_id >> 4) == (mda >> 4))
763 && (logical_id & mda & 0xf) != 0;
765 apic_debug("Bad DFR vcpu %d: %08x\n",
766 apic->vcpu->vcpu_id, kvm_lapic_get_reg(apic, APIC_DFR));
771 /* The KVM local APIC implementation has two quirks:
773 * - Real hardware delivers interrupts destined to x2APIC ID > 0xff to LAPICs
774 * in xAPIC mode if the "destination & 0xff" matches its xAPIC ID.
775 * KVM doesn't do that aliasing.
777 * - in-kernel IOAPIC messages have to be delivered directly to
778 * x2APIC, because the kernel does not support interrupt remapping.
779 * In order to support broadcast without interrupt remapping, x2APIC
780 * rewrites the destination of non-IPI messages from APIC_BROADCAST
781 * to X2APIC_BROADCAST.
783 * The broadcast quirk can be disabled with KVM_CAP_X2APIC_API. This is
784 * important when userspace wants to use x2APIC-format MSIs, because
785 * APIC_BROADCAST (0xff) is a legal route for "cluster 0, CPUs 0-7".
787 static u32 kvm_apic_mda(struct kvm_vcpu *vcpu, unsigned int dest_id,
788 struct kvm_lapic *source, struct kvm_lapic *target)
790 bool ipi = source != NULL;
792 if (!vcpu->kvm->arch.x2apic_broadcast_quirk_disabled &&
793 !ipi && dest_id == APIC_BROADCAST && apic_x2apic_mode(target))
794 return X2APIC_BROADCAST;
799 bool kvm_apic_match_dest(struct kvm_vcpu *vcpu, struct kvm_lapic *source,
800 int short_hand, unsigned int dest, int dest_mode)
802 struct kvm_lapic *target = vcpu->arch.apic;
803 u32 mda = kvm_apic_mda(vcpu, dest, source, target);
805 apic_debug("target %p, source %p, dest 0x%x, "
806 "dest_mode 0x%x, short_hand 0x%x\n",
807 target, source, dest, dest_mode, short_hand);
810 switch (short_hand) {
811 case APIC_DEST_NOSHORT:
812 if (dest_mode == APIC_DEST_PHYSICAL)
813 return kvm_apic_match_physical_addr(target, mda);
815 return kvm_apic_match_logical_addr(target, mda);
817 return target == source;
818 case APIC_DEST_ALLINC:
820 case APIC_DEST_ALLBUT:
821 return target != source;
823 apic_debug("kvm: apic: Bad dest shorthand value %x\n",
828 EXPORT_SYMBOL_GPL(kvm_apic_match_dest);
830 int kvm_vector_to_index(u32 vector, u32 dest_vcpus,
831 const unsigned long *bitmap, u32 bitmap_size)
836 mod = vector % dest_vcpus;
838 for (i = 0; i <= mod; i++) {
839 idx = find_next_bit(bitmap, bitmap_size, idx + 1);
840 BUG_ON(idx == bitmap_size);
846 static void kvm_apic_disabled_lapic_found(struct kvm *kvm)
848 if (!kvm->arch.disabled_lapic_found) {
849 kvm->arch.disabled_lapic_found = true;
851 "Disabled LAPIC found during irq injection\n");
855 static bool kvm_apic_is_broadcast_dest(struct kvm *kvm, struct kvm_lapic **src,
856 struct kvm_lapic_irq *irq, struct kvm_apic_map *map)
858 if (kvm->arch.x2apic_broadcast_quirk_disabled) {
859 if ((irq->dest_id == APIC_BROADCAST &&
860 map->mode != KVM_APIC_MODE_X2APIC))
862 if (irq->dest_id == X2APIC_BROADCAST)
865 bool x2apic_ipi = src && *src && apic_x2apic_mode(*src);
866 if (irq->dest_id == (x2apic_ipi ?
867 X2APIC_BROADCAST : APIC_BROADCAST))
874 /* Return true if the interrupt can be handled by using *bitmap as index mask
875 * for valid destinations in *dst array.
876 * Return false if kvm_apic_map_get_dest_lapic did nothing useful.
877 * Note: we may have zero kvm_lapic destinations when we return true, which
878 * means that the interrupt should be dropped. In this case, *bitmap would be
879 * zero and *dst undefined.
881 static inline bool kvm_apic_map_get_dest_lapic(struct kvm *kvm,
882 struct kvm_lapic **src, struct kvm_lapic_irq *irq,
883 struct kvm_apic_map *map, struct kvm_lapic ***dst,
884 unsigned long *bitmap)
888 if (irq->shorthand == APIC_DEST_SELF && src) {
892 } else if (irq->shorthand)
895 if (!map || kvm_apic_is_broadcast_dest(kvm, src, irq, map))
898 if (irq->dest_mode == APIC_DEST_PHYSICAL) {
899 if (irq->dest_id > map->max_apic_id) {
902 u32 dest_id = array_index_nospec(irq->dest_id, map->max_apic_id + 1);
903 *dst = &map->phys_map[dest_id];
910 if (!kvm_apic_map_get_logical_dest(map, irq->dest_id, dst,
914 if (!kvm_lowest_prio_delivery(irq))
917 if (!kvm_vector_hashing_enabled()) {
919 for_each_set_bit(i, bitmap, 16) {
924 else if (kvm_apic_compare_prio((*dst)[i]->vcpu,
925 (*dst)[lowest]->vcpu) < 0)
932 lowest = kvm_vector_to_index(irq->vector, hweight16(*bitmap),
935 if (!(*dst)[lowest]) {
936 kvm_apic_disabled_lapic_found(kvm);
942 *bitmap = (lowest >= 0) ? 1 << lowest : 0;
947 bool kvm_irq_delivery_to_apic_fast(struct kvm *kvm, struct kvm_lapic *src,
948 struct kvm_lapic_irq *irq, int *r, struct dest_map *dest_map)
950 struct kvm_apic_map *map;
951 unsigned long bitmap;
952 struct kvm_lapic **dst = NULL;
958 if (irq->shorthand == APIC_DEST_SELF) {
959 *r = kvm_apic_set_irq(src->vcpu, irq, dest_map);
964 map = rcu_dereference(kvm->arch.apic_map);
966 ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dst, &bitmap);
969 for_each_set_bit(i, &bitmap, 16) {
972 *r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map);
981 * This routine tries to handler interrupts in posted mode, here is how
982 * it deals with different cases:
983 * - For single-destination interrupts, handle it in posted mode
984 * - Else if vector hashing is enabled and it is a lowest-priority
985 * interrupt, handle it in posted mode and use the following mechanism
986 * to find the destinaiton vCPU.
987 * 1. For lowest-priority interrupts, store all the possible
988 * destination vCPUs in an array.
989 * 2. Use "guest vector % max number of destination vCPUs" to find
990 * the right destination vCPU in the array for the lowest-priority
992 * - Otherwise, use remapped mode to inject the interrupt.
994 bool kvm_intr_is_single_vcpu_fast(struct kvm *kvm, struct kvm_lapic_irq *irq,
995 struct kvm_vcpu **dest_vcpu)
997 struct kvm_apic_map *map;
998 unsigned long bitmap;
999 struct kvm_lapic **dst = NULL;
1006 map = rcu_dereference(kvm->arch.apic_map);
1008 if (kvm_apic_map_get_dest_lapic(kvm, NULL, irq, map, &dst, &bitmap) &&
1009 hweight16(bitmap) == 1) {
1010 unsigned long i = find_first_bit(&bitmap, 16);
1013 *dest_vcpu = dst[i]->vcpu;
1023 * Add a pending IRQ into lapic.
1024 * Return 1 if successfully added and 0 if discarded.
1026 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
1027 int vector, int level, int trig_mode,
1028 struct dest_map *dest_map)
1031 struct kvm_vcpu *vcpu = apic->vcpu;
1033 trace_kvm_apic_accept_irq(vcpu->vcpu_id, delivery_mode,
1035 switch (delivery_mode) {
1036 case APIC_DM_LOWEST:
1037 vcpu->arch.apic_arb_prio++;
1040 if (unlikely(trig_mode && !level))
1043 /* FIXME add logic for vcpu on reset */
1044 if (unlikely(!apic_enabled(apic)))
1050 __set_bit(vcpu->vcpu_id, dest_map->map);
1051 dest_map->vectors[vcpu->vcpu_id] = vector;
1054 if (apic_test_vector(vector, apic->regs + APIC_TMR) != !!trig_mode) {
1056 kvm_lapic_set_vector(vector, apic->regs + APIC_TMR);
1058 apic_clear_vector(vector, apic->regs + APIC_TMR);
1061 if (vcpu->arch.apicv_active)
1062 kvm_x86_ops->deliver_posted_interrupt(vcpu, vector);
1064 kvm_lapic_set_irr(vector, apic);
1066 kvm_make_request(KVM_REQ_EVENT, vcpu);
1067 kvm_vcpu_kick(vcpu);
1073 vcpu->arch.pv.pv_unhalted = 1;
1074 kvm_make_request(KVM_REQ_EVENT, vcpu);
1075 kvm_vcpu_kick(vcpu);
1080 kvm_make_request(KVM_REQ_SMI, vcpu);
1081 kvm_vcpu_kick(vcpu);
1086 kvm_inject_nmi(vcpu);
1087 kvm_vcpu_kick(vcpu);
1091 if (!trig_mode || level) {
1093 /* assumes that there are only KVM_APIC_INIT/SIPI */
1094 apic->pending_events = (1UL << KVM_APIC_INIT);
1095 /* make sure pending_events is visible before sending
1098 kvm_make_request(KVM_REQ_EVENT, vcpu);
1099 kvm_vcpu_kick(vcpu);
1101 apic_debug("Ignoring de-assert INIT to vcpu %d\n",
1106 case APIC_DM_STARTUP:
1107 apic_debug("SIPI to vcpu %d vector 0x%02x\n",
1108 vcpu->vcpu_id, vector);
1110 apic->sipi_vector = vector;
1111 /* make sure sipi_vector is visible for the receiver */
1113 set_bit(KVM_APIC_SIPI, &apic->pending_events);
1114 kvm_make_request(KVM_REQ_EVENT, vcpu);
1115 kvm_vcpu_kick(vcpu);
1118 case APIC_DM_EXTINT:
1120 * Should only be called by kvm_apic_local_deliver() with LVT0,
1121 * before NMI watchdog was enabled. Already handled by
1122 * kvm_apic_accept_pic_intr().
1127 printk(KERN_ERR "TODO: unsupported delivery mode %x\n",
1134 int kvm_apic_compare_prio(struct kvm_vcpu *vcpu1, struct kvm_vcpu *vcpu2)
1136 return vcpu1->arch.apic_arb_prio - vcpu2->arch.apic_arb_prio;
1139 static bool kvm_ioapic_handles_vector(struct kvm_lapic *apic, int vector)
1141 return test_bit(vector, apic->vcpu->arch.ioapic_handled_vectors);
1144 static void kvm_ioapic_send_eoi(struct kvm_lapic *apic, int vector)
1148 /* Eoi the ioapic only if the ioapic doesn't own the vector. */
1149 if (!kvm_ioapic_handles_vector(apic, vector))
1152 /* Request a KVM exit to inform the userspace IOAPIC. */
1153 if (irqchip_split(apic->vcpu->kvm)) {
1154 apic->vcpu->arch.pending_ioapic_eoi = vector;
1155 kvm_make_request(KVM_REQ_IOAPIC_EOI_EXIT, apic->vcpu);
1159 if (apic_test_vector(vector, apic->regs + APIC_TMR))
1160 trigger_mode = IOAPIC_LEVEL_TRIG;
1162 trigger_mode = IOAPIC_EDGE_TRIG;
1164 kvm_ioapic_update_eoi(apic->vcpu, vector, trigger_mode);
1167 static int apic_set_eoi(struct kvm_lapic *apic)
1169 int vector = apic_find_highest_isr(apic);
1171 trace_kvm_eoi(apic, vector);
1174 * Not every write EOI will has corresponding ISR,
1175 * one example is when Kernel check timer on setup_IO_APIC
1180 apic_clear_isr(vector, apic);
1181 apic_update_ppr(apic);
1183 if (test_bit(vector, vcpu_to_synic(apic->vcpu)->vec_bitmap))
1184 kvm_hv_synic_send_eoi(apic->vcpu, vector);
1186 kvm_ioapic_send_eoi(apic, vector);
1187 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1192 * this interface assumes a trap-like exit, which has already finished
1193 * desired side effect including vISR and vPPR update.
1195 void kvm_apic_set_eoi_accelerated(struct kvm_vcpu *vcpu, int vector)
1197 struct kvm_lapic *apic = vcpu->arch.apic;
1199 trace_kvm_eoi(apic, vector);
1201 kvm_ioapic_send_eoi(apic, vector);
1202 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1204 EXPORT_SYMBOL_GPL(kvm_apic_set_eoi_accelerated);
1206 static void apic_send_ipi(struct kvm_lapic *apic)
1208 u32 icr_low = kvm_lapic_get_reg(apic, APIC_ICR);
1209 u32 icr_high = kvm_lapic_get_reg(apic, APIC_ICR2);
1210 struct kvm_lapic_irq irq;
1212 irq.vector = icr_low & APIC_VECTOR_MASK;
1213 irq.delivery_mode = icr_low & APIC_MODE_MASK;
1214 irq.dest_mode = icr_low & APIC_DEST_MASK;
1215 irq.level = (icr_low & APIC_INT_ASSERT) != 0;
1216 irq.trig_mode = icr_low & APIC_INT_LEVELTRIG;
1217 irq.shorthand = icr_low & APIC_SHORT_MASK;
1218 irq.msi_redir_hint = false;
1219 if (apic_x2apic_mode(apic))
1220 irq.dest_id = icr_high;
1222 irq.dest_id = GET_APIC_DEST_FIELD(icr_high);
1224 trace_kvm_apic_ipi(icr_low, irq.dest_id);
1226 apic_debug("icr_high 0x%x, icr_low 0x%x, "
1227 "short_hand 0x%x, dest 0x%x, trig_mode 0x%x, level 0x%x, "
1228 "dest_mode 0x%x, delivery_mode 0x%x, vector 0x%x, "
1229 "msi_redir_hint 0x%x\n",
1230 icr_high, icr_low, irq.shorthand, irq.dest_id,
1231 irq.trig_mode, irq.level, irq.dest_mode, irq.delivery_mode,
1232 irq.vector, irq.msi_redir_hint);
1234 kvm_irq_delivery_to_apic(apic->vcpu->kvm, apic, &irq, NULL);
1237 static u32 apic_get_tmcct(struct kvm_lapic *apic)
1239 ktime_t remaining, now;
1243 ASSERT(apic != NULL);
1245 /* if initial count is 0, current count should also be 0 */
1246 if (kvm_lapic_get_reg(apic, APIC_TMICT) == 0 ||
1247 apic->lapic_timer.period == 0)
1251 remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1252 if (ktime_to_ns(remaining) < 0)
1255 ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
1256 tmcct = div64_u64(ns,
1257 (APIC_BUS_CYCLE_NS * apic->divide_count));
1262 static void __report_tpr_access(struct kvm_lapic *apic, bool write)
1264 struct kvm_vcpu *vcpu = apic->vcpu;
1265 struct kvm_run *run = vcpu->run;
1267 kvm_make_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu);
1268 run->tpr_access.rip = kvm_rip_read(vcpu);
1269 run->tpr_access.is_write = write;
1272 static inline void report_tpr_access(struct kvm_lapic *apic, bool write)
1274 if (apic->vcpu->arch.tpr_access_reporting)
1275 __report_tpr_access(apic, write);
1278 static u32 __apic_read(struct kvm_lapic *apic, unsigned int offset)
1282 if (offset >= LAPIC_MMIO_LENGTH)
1287 apic_debug("Access APIC ARBPRI register which is for P6\n");
1290 case APIC_TMCCT: /* Timer CCR */
1291 if (apic_lvtt_tscdeadline(apic))
1294 val = apic_get_tmcct(apic);
1297 apic_update_ppr(apic);
1298 val = kvm_lapic_get_reg(apic, offset);
1301 report_tpr_access(apic, false);
1304 val = kvm_lapic_get_reg(apic, offset);
1311 static inline struct kvm_lapic *to_lapic(struct kvm_io_device *dev)
1313 return container_of(dev, struct kvm_lapic, dev);
1316 int kvm_lapic_reg_read(struct kvm_lapic *apic, u32 offset, int len,
1319 unsigned char alignment = offset & 0xf;
1321 /* this bitmask has a bit cleared for each reserved register */
1322 static const u64 rmask = 0x43ff01ffffffe70cULL;
1324 if ((alignment + len) > 4) {
1325 apic_debug("KVM_APIC_READ: alignment error %x %d\n",
1330 if (offset > 0x3f0 || !(rmask & (1ULL << (offset >> 4)))) {
1331 apic_debug("KVM_APIC_READ: read reserved register %x\n",
1336 result = __apic_read(apic, offset & ~0xf);
1338 trace_kvm_apic_read(offset, result);
1344 memcpy(data, (char *)&result + alignment, len);
1347 printk(KERN_ERR "Local APIC read with len = %x, "
1348 "should be 1,2, or 4 instead\n", len);
1353 EXPORT_SYMBOL_GPL(kvm_lapic_reg_read);
1355 static int apic_mmio_in_range(struct kvm_lapic *apic, gpa_t addr)
1357 return addr >= apic->base_address &&
1358 addr < apic->base_address + LAPIC_MMIO_LENGTH;
1361 static int apic_mmio_read(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
1362 gpa_t address, int len, void *data)
1364 struct kvm_lapic *apic = to_lapic(this);
1365 u32 offset = address - apic->base_address;
1367 if (!apic_mmio_in_range(apic, address))
1370 if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
1371 if (!kvm_check_has_quirk(vcpu->kvm,
1372 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
1375 memset(data, 0xff, len);
1379 kvm_lapic_reg_read(apic, offset, len, data);
1384 static void update_divide_count(struct kvm_lapic *apic)
1386 u32 tmp1, tmp2, tdcr;
1388 tdcr = kvm_lapic_get_reg(apic, APIC_TDCR);
1390 tmp2 = ((tmp1 & 0x3) | ((tmp1 & 0x8) >> 1)) + 1;
1391 apic->divide_count = 0x1 << (tmp2 & 0x7);
1393 apic_debug("timer divide count is 0x%x\n",
1394 apic->divide_count);
1397 static void limit_periodic_timer_frequency(struct kvm_lapic *apic)
1400 * Do not allow the guest to program periodic timers with small
1401 * interval, since the hrtimers are not throttled by the host
1404 if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
1405 s64 min_period = min_timer_period_us * 1000LL;
1407 if (apic->lapic_timer.period < min_period) {
1408 pr_info_ratelimited(
1409 "kvm: vcpu %i: requested %lld ns "
1410 "lapic timer period limited to %lld ns\n",
1411 apic->vcpu->vcpu_id,
1412 apic->lapic_timer.period, min_period);
1413 apic->lapic_timer.period = min_period;
1418 static void apic_update_lvtt(struct kvm_lapic *apic)
1420 u32 timer_mode = kvm_lapic_get_reg(apic, APIC_LVTT) &
1421 apic->lapic_timer.timer_mode_mask;
1423 if (apic->lapic_timer.timer_mode != timer_mode) {
1424 if (apic_lvtt_tscdeadline(apic) != (timer_mode ==
1425 APIC_LVT_TIMER_TSCDEADLINE)) {
1426 hrtimer_cancel(&apic->lapic_timer.timer);
1427 kvm_lapic_set_reg(apic, APIC_TMICT, 0);
1428 apic->lapic_timer.period = 0;
1429 apic->lapic_timer.tscdeadline = 0;
1431 apic->lapic_timer.timer_mode = timer_mode;
1432 limit_periodic_timer_frequency(apic);
1436 static void apic_timer_expired(struct kvm_lapic *apic)
1438 struct kvm_vcpu *vcpu = apic->vcpu;
1439 struct swait_queue_head *q = &vcpu->wq;
1440 struct kvm_timer *ktimer = &apic->lapic_timer;
1442 if (atomic_read(&apic->lapic_timer.pending))
1445 atomic_inc(&apic->lapic_timer.pending);
1446 kvm_set_pending_timer(vcpu);
1449 * For x86, the atomic_inc() is serialized, thus
1450 * using swait_active() is safe.
1452 if (swait_active(q))
1455 if (apic_lvtt_tscdeadline(apic) || ktimer->hv_timer_in_use)
1456 ktimer->expired_tscdeadline = ktimer->tscdeadline;
1460 * On APICv, this test will cause a busy wait
1461 * during a higher-priority task.
1464 static bool lapic_timer_int_injected(struct kvm_vcpu *vcpu)
1466 struct kvm_lapic *apic = vcpu->arch.apic;
1467 u32 reg = kvm_lapic_get_reg(apic, APIC_LVTT);
1469 if (kvm_apic_hw_enabled(apic)) {
1470 int vec = reg & APIC_VECTOR_MASK;
1471 void *bitmap = apic->regs + APIC_ISR;
1473 if (vcpu->arch.apicv_active)
1474 bitmap = apic->regs + APIC_IRR;
1476 if (apic_test_vector(vec, bitmap))
1482 static inline void __wait_lapic_expire(struct kvm_vcpu *vcpu, u64 guest_cycles)
1484 u64 timer_advance_ns = vcpu->arch.apic->lapic_timer.timer_advance_ns;
1487 * If the guest TSC is running at a different ratio than the host, then
1488 * convert the delay to nanoseconds to achieve an accurate delay. Note
1489 * that __delay() uses delay_tsc whenever the hardware has TSC, thus
1490 * always for VMX enabled hardware.
1492 if (vcpu->arch.tsc_scaling_ratio == kvm_default_tsc_scaling_ratio) {
1493 __delay(min(guest_cycles,
1494 nsec_to_cycles(vcpu, timer_advance_ns)));
1496 u64 delay_ns = guest_cycles * 1000000ULL;
1497 do_div(delay_ns, vcpu->arch.virtual_tsc_khz);
1498 ndelay(min_t(u32, delay_ns, timer_advance_ns));
1502 void wait_lapic_expire(struct kvm_vcpu *vcpu)
1504 struct kvm_lapic *apic = vcpu->arch.apic;
1505 u32 timer_advance_ns = apic->lapic_timer.timer_advance_ns;
1506 u64 guest_tsc, tsc_deadline, ns;
1508 if (apic->lapic_timer.expired_tscdeadline == 0)
1511 if (!lapic_timer_int_injected(vcpu))
1514 tsc_deadline = apic->lapic_timer.expired_tscdeadline;
1515 apic->lapic_timer.expired_tscdeadline = 0;
1516 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1517 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, guest_tsc - tsc_deadline);
1519 if (guest_tsc < tsc_deadline)
1520 __wait_lapic_expire(vcpu, tsc_deadline - guest_tsc);
1522 if (!apic->lapic_timer.timer_advance_adjust_done) {
1524 if (guest_tsc < tsc_deadline) {
1525 ns = (tsc_deadline - guest_tsc) * 1000000ULL;
1526 do_div(ns, vcpu->arch.virtual_tsc_khz);
1527 timer_advance_ns -= min((u32)ns,
1528 timer_advance_ns / LAPIC_TIMER_ADVANCE_ADJUST_STEP);
1531 ns = (guest_tsc - tsc_deadline) * 1000000ULL;
1532 do_div(ns, vcpu->arch.virtual_tsc_khz);
1533 timer_advance_ns += min((u32)ns,
1534 timer_advance_ns / LAPIC_TIMER_ADVANCE_ADJUST_STEP);
1536 if (abs(guest_tsc - tsc_deadline) < LAPIC_TIMER_ADVANCE_ADJUST_DONE)
1537 apic->lapic_timer.timer_advance_adjust_done = true;
1538 if (unlikely(timer_advance_ns > 5000)) {
1539 timer_advance_ns = 0;
1540 apic->lapic_timer.timer_advance_adjust_done = true;
1542 apic->lapic_timer.timer_advance_ns = timer_advance_ns;
1546 static void start_sw_tscdeadline(struct kvm_lapic *apic)
1548 struct kvm_timer *ktimer = &apic->lapic_timer;
1549 u64 guest_tsc, tscdeadline = ktimer->tscdeadline;
1552 struct kvm_vcpu *vcpu = apic->vcpu;
1553 unsigned long this_tsc_khz = vcpu->arch.virtual_tsc_khz;
1554 unsigned long flags;
1557 if (unlikely(!tscdeadline || !this_tsc_khz))
1560 local_irq_save(flags);
1563 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1565 ns = (tscdeadline - guest_tsc) * 1000000ULL;
1566 do_div(ns, this_tsc_khz);
1568 if (likely(tscdeadline > guest_tsc) &&
1569 likely(ns > apic->lapic_timer.timer_advance_ns)) {
1570 expire = ktime_add_ns(now, ns);
1571 expire = ktime_sub_ns(expire, ktimer->timer_advance_ns);
1572 hrtimer_start(&ktimer->timer, expire, HRTIMER_MODE_ABS_PINNED);
1574 apic_timer_expired(apic);
1576 local_irq_restore(flags);
1579 static void update_target_expiration(struct kvm_lapic *apic, uint32_t old_divisor)
1581 ktime_t now, remaining;
1582 u64 ns_remaining_old, ns_remaining_new;
1584 apic->lapic_timer.period = (u64)kvm_lapic_get_reg(apic, APIC_TMICT)
1585 * APIC_BUS_CYCLE_NS * apic->divide_count;
1586 limit_periodic_timer_frequency(apic);
1589 remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1590 if (ktime_to_ns(remaining) < 0)
1593 ns_remaining_old = ktime_to_ns(remaining);
1594 ns_remaining_new = mul_u64_u32_div(ns_remaining_old,
1595 apic->divide_count, old_divisor);
1597 apic->lapic_timer.tscdeadline +=
1598 nsec_to_cycles(apic->vcpu, ns_remaining_new) -
1599 nsec_to_cycles(apic->vcpu, ns_remaining_old);
1600 apic->lapic_timer.target_expiration = ktime_add_ns(now, ns_remaining_new);
1603 static bool set_target_expiration(struct kvm_lapic *apic)
1609 apic->lapic_timer.period = (u64)kvm_lapic_get_reg(apic, APIC_TMICT)
1610 * APIC_BUS_CYCLE_NS * apic->divide_count;
1612 if (!apic->lapic_timer.period) {
1613 apic->lapic_timer.tscdeadline = 0;
1617 limit_periodic_timer_frequency(apic);
1619 apic_debug("%s: bus cycle is %" PRId64 "ns, now 0x%016"
1621 "timer initial count 0x%x, period %lldns, "
1622 "expire @ 0x%016" PRIx64 ".\n", __func__,
1623 APIC_BUS_CYCLE_NS, ktime_to_ns(now),
1624 kvm_lapic_get_reg(apic, APIC_TMICT),
1625 apic->lapic_timer.period,
1626 ktime_to_ns(ktime_add_ns(now,
1627 apic->lapic_timer.period)));
1629 apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
1630 nsec_to_cycles(apic->vcpu, apic->lapic_timer.period);
1631 apic->lapic_timer.target_expiration = ktime_add_ns(now, apic->lapic_timer.period);
1636 static void advance_periodic_target_expiration(struct kvm_lapic *apic)
1638 ktime_t now = ktime_get();
1643 * Synchronize both deadlines to the same time source or
1644 * differences in the periods (caused by differences in the
1645 * underlying clocks or numerical approximation errors) will
1646 * cause the two to drift apart over time as the errors
1649 apic->lapic_timer.target_expiration =
1650 ktime_add_ns(apic->lapic_timer.target_expiration,
1651 apic->lapic_timer.period);
1652 delta = ktime_sub(apic->lapic_timer.target_expiration, now);
1653 apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
1654 nsec_to_cycles(apic->vcpu, delta);
1657 static void start_sw_period(struct kvm_lapic *apic)
1659 if (!apic->lapic_timer.period)
1662 if (ktime_after(ktime_get(),
1663 apic->lapic_timer.target_expiration)) {
1664 apic_timer_expired(apic);
1666 if (apic_lvtt_oneshot(apic))
1669 advance_periodic_target_expiration(apic);
1672 hrtimer_start(&apic->lapic_timer.timer,
1673 apic->lapic_timer.target_expiration,
1674 HRTIMER_MODE_ABS_PINNED);
1677 bool kvm_lapic_hv_timer_in_use(struct kvm_vcpu *vcpu)
1679 if (!lapic_in_kernel(vcpu))
1682 return vcpu->arch.apic->lapic_timer.hv_timer_in_use;
1684 EXPORT_SYMBOL_GPL(kvm_lapic_hv_timer_in_use);
1686 static void cancel_hv_timer(struct kvm_lapic *apic)
1688 WARN_ON(preemptible());
1689 WARN_ON(!apic->lapic_timer.hv_timer_in_use);
1690 kvm_x86_ops->cancel_hv_timer(apic->vcpu);
1691 apic->lapic_timer.hv_timer_in_use = false;
1694 static bool start_hv_timer(struct kvm_lapic *apic)
1696 struct kvm_timer *ktimer = &apic->lapic_timer;
1697 struct kvm_vcpu *vcpu = apic->vcpu;
1700 WARN_ON(preemptible());
1701 if (!kvm_x86_ops->set_hv_timer)
1704 if (!ktimer->tscdeadline)
1707 if (kvm_x86_ops->set_hv_timer(vcpu, ktimer->tscdeadline, &expired))
1710 ktimer->hv_timer_in_use = true;
1711 hrtimer_cancel(&ktimer->timer);
1714 * To simplify handling the periodic timer, leave the hv timer running
1715 * even if the deadline timer has expired, i.e. rely on the resulting
1716 * VM-Exit to recompute the periodic timer's target expiration.
1718 if (!apic_lvtt_period(apic)) {
1720 * Cancel the hv timer if the sw timer fired while the hv timer
1721 * was being programmed, or if the hv timer itself expired.
1723 if (atomic_read(&ktimer->pending)) {
1724 cancel_hv_timer(apic);
1725 } else if (expired) {
1726 apic_timer_expired(apic);
1727 cancel_hv_timer(apic);
1731 trace_kvm_hv_timer_state(vcpu->vcpu_id, ktimer->hv_timer_in_use);
1736 static void start_sw_timer(struct kvm_lapic *apic)
1738 struct kvm_timer *ktimer = &apic->lapic_timer;
1740 WARN_ON(preemptible());
1741 if (apic->lapic_timer.hv_timer_in_use)
1742 cancel_hv_timer(apic);
1743 if (!apic_lvtt_period(apic) && atomic_read(&ktimer->pending))
1746 if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
1747 start_sw_period(apic);
1748 else if (apic_lvtt_tscdeadline(apic))
1749 start_sw_tscdeadline(apic);
1750 trace_kvm_hv_timer_state(apic->vcpu->vcpu_id, false);
1753 static void restart_apic_timer(struct kvm_lapic *apic)
1757 if (!apic_lvtt_period(apic) && atomic_read(&apic->lapic_timer.pending))
1760 if (!start_hv_timer(apic))
1761 start_sw_timer(apic);
1766 void kvm_lapic_expired_hv_timer(struct kvm_vcpu *vcpu)
1768 struct kvm_lapic *apic = vcpu->arch.apic;
1771 /* If the preempt notifier has already run, it also called apic_timer_expired */
1772 if (!apic->lapic_timer.hv_timer_in_use)
1774 WARN_ON(swait_active(&vcpu->wq));
1775 cancel_hv_timer(apic);
1776 apic_timer_expired(apic);
1778 if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
1779 advance_periodic_target_expiration(apic);
1780 restart_apic_timer(apic);
1785 EXPORT_SYMBOL_GPL(kvm_lapic_expired_hv_timer);
1787 void kvm_lapic_switch_to_hv_timer(struct kvm_vcpu *vcpu)
1789 restart_apic_timer(vcpu->arch.apic);
1791 EXPORT_SYMBOL_GPL(kvm_lapic_switch_to_hv_timer);
1793 void kvm_lapic_switch_to_sw_timer(struct kvm_vcpu *vcpu)
1795 struct kvm_lapic *apic = vcpu->arch.apic;
1798 /* Possibly the TSC deadline timer is not enabled yet */
1799 if (apic->lapic_timer.hv_timer_in_use)
1800 start_sw_timer(apic);
1803 EXPORT_SYMBOL_GPL(kvm_lapic_switch_to_sw_timer);
1805 void kvm_lapic_restart_hv_timer(struct kvm_vcpu *vcpu)
1807 struct kvm_lapic *apic = vcpu->arch.apic;
1809 WARN_ON(!apic->lapic_timer.hv_timer_in_use);
1810 restart_apic_timer(apic);
1813 static void start_apic_timer(struct kvm_lapic *apic)
1815 atomic_set(&apic->lapic_timer.pending, 0);
1817 if ((apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
1818 && !set_target_expiration(apic))
1821 restart_apic_timer(apic);
1824 static void apic_manage_nmi_watchdog(struct kvm_lapic *apic, u32 lvt0_val)
1826 bool lvt0_in_nmi_mode = apic_lvt_nmi_mode(lvt0_val);
1828 if (apic->lvt0_in_nmi_mode != lvt0_in_nmi_mode) {
1829 apic->lvt0_in_nmi_mode = lvt0_in_nmi_mode;
1830 if (lvt0_in_nmi_mode) {
1831 apic_debug("Receive NMI setting on APIC_LVT0 "
1832 "for cpu %d\n", apic->vcpu->vcpu_id);
1833 atomic_inc(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
1835 atomic_dec(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
1839 int kvm_lapic_reg_write(struct kvm_lapic *apic, u32 reg, u32 val)
1843 trace_kvm_apic_write(reg, val);
1846 case APIC_ID: /* Local APIC ID */
1847 if (!apic_x2apic_mode(apic))
1848 kvm_apic_set_xapic_id(apic, val >> 24);
1854 report_tpr_access(apic, true);
1855 apic_set_tpr(apic, val & 0xff);
1863 if (!apic_x2apic_mode(apic))
1864 kvm_apic_set_ldr(apic, val & APIC_LDR_MASK);
1870 if (!apic_x2apic_mode(apic)) {
1871 kvm_lapic_set_reg(apic, APIC_DFR, val | 0x0FFFFFFF);
1872 recalculate_apic_map(apic->vcpu->kvm);
1879 if (kvm_lapic_get_reg(apic, APIC_LVR) & APIC_LVR_DIRECTED_EOI)
1880 mask |= APIC_SPIV_DIRECTED_EOI;
1881 apic_set_spiv(apic, val & mask);
1882 if (!(val & APIC_SPIV_APIC_ENABLED)) {
1886 for (i = 0; i < KVM_APIC_LVT_NUM; i++) {
1887 lvt_val = kvm_lapic_get_reg(apic,
1888 APIC_LVTT + 0x10 * i);
1889 kvm_lapic_set_reg(apic, APIC_LVTT + 0x10 * i,
1890 lvt_val | APIC_LVT_MASKED);
1892 apic_update_lvtt(apic);
1893 atomic_set(&apic->lapic_timer.pending, 0);
1899 /* No delay here, so we always clear the pending bit */
1900 kvm_lapic_set_reg(apic, APIC_ICR, val & ~(1 << 12));
1901 apic_send_ipi(apic);
1905 if (!apic_x2apic_mode(apic))
1907 kvm_lapic_set_reg(apic, APIC_ICR2, val);
1911 apic_manage_nmi_watchdog(apic, val);
1917 /* TODO: Check vector */
1918 if (!kvm_apic_sw_enabled(apic))
1919 val |= APIC_LVT_MASKED;
1921 val &= apic_lvt_mask[(reg - APIC_LVTT) >> 4];
1922 kvm_lapic_set_reg(apic, reg, val);
1927 if (!kvm_apic_sw_enabled(apic))
1928 val |= APIC_LVT_MASKED;
1929 val &= (apic_lvt_mask[0] | apic->lapic_timer.timer_mode_mask);
1930 kvm_lapic_set_reg(apic, APIC_LVTT, val);
1931 apic_update_lvtt(apic);
1935 if (apic_lvtt_tscdeadline(apic))
1938 hrtimer_cancel(&apic->lapic_timer.timer);
1939 kvm_lapic_set_reg(apic, APIC_TMICT, val);
1940 start_apic_timer(apic);
1944 uint32_t old_divisor = apic->divide_count;
1947 apic_debug("KVM_WRITE:TDCR %x\n", val);
1948 kvm_lapic_set_reg(apic, APIC_TDCR, val);
1949 update_divide_count(apic);
1950 if (apic->divide_count != old_divisor &&
1951 apic->lapic_timer.period) {
1952 hrtimer_cancel(&apic->lapic_timer.timer);
1953 update_target_expiration(apic, old_divisor);
1954 restart_apic_timer(apic);
1959 if (apic_x2apic_mode(apic) && val != 0) {
1960 apic_debug("KVM_WRITE:ESR not zero %x\n", val);
1966 if (apic_x2apic_mode(apic)) {
1967 kvm_lapic_reg_write(apic, APIC_ICR, 0x40000 | (val & 0xff));
1976 apic_debug("Local APIC Write to read-only register %x\n", reg);
1979 EXPORT_SYMBOL_GPL(kvm_lapic_reg_write);
1981 static int apic_mmio_write(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
1982 gpa_t address, int len, const void *data)
1984 struct kvm_lapic *apic = to_lapic(this);
1985 unsigned int offset = address - apic->base_address;
1988 if (!apic_mmio_in_range(apic, address))
1991 if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
1992 if (!kvm_check_has_quirk(vcpu->kvm,
1993 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
2000 * APIC register must be aligned on 128-bits boundary.
2001 * 32/64/128 bits registers must be accessed thru 32 bits.
2004 if (len != 4 || (offset & 0xf)) {
2005 /* Don't shout loud, $infamous_os would cause only noise. */
2006 apic_debug("apic write: bad size=%d %lx\n", len, (long)address);
2012 /* too common printing */
2013 if (offset != APIC_EOI)
2014 apic_debug("%s: offset 0x%x with length 0x%x, and value is "
2015 "0x%x\n", __func__, offset, len, val);
2017 kvm_lapic_reg_write(apic, offset & 0xff0, val);
2022 void kvm_lapic_set_eoi(struct kvm_vcpu *vcpu)
2024 kvm_lapic_reg_write(vcpu->arch.apic, APIC_EOI, 0);
2026 EXPORT_SYMBOL_GPL(kvm_lapic_set_eoi);
2028 /* emulate APIC access in a trap manner */
2029 void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset)
2033 /* hw has done the conditional check and inst decode */
2036 kvm_lapic_reg_read(vcpu->arch.apic, offset, 4, &val);
2038 /* TODO: optimize to just emulate side effect w/o one more write */
2039 kvm_lapic_reg_write(vcpu->arch.apic, offset, val);
2041 EXPORT_SYMBOL_GPL(kvm_apic_write_nodecode);
2043 void kvm_free_lapic(struct kvm_vcpu *vcpu)
2045 struct kvm_lapic *apic = vcpu->arch.apic;
2047 if (!vcpu->arch.apic)
2050 hrtimer_cancel(&apic->lapic_timer.timer);
2052 if (!(vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE))
2053 static_key_slow_dec_deferred(&apic_hw_disabled);
2055 if (!apic->sw_enabled)
2056 static_key_slow_dec_deferred(&apic_sw_disabled);
2059 free_page((unsigned long)apic->regs);
2065 *----------------------------------------------------------------------
2067 *----------------------------------------------------------------------
2069 u64 kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu)
2071 struct kvm_lapic *apic = vcpu->arch.apic;
2073 if (!lapic_in_kernel(vcpu) ||
2074 !apic_lvtt_tscdeadline(apic))
2077 return apic->lapic_timer.tscdeadline;
2080 void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data)
2082 struct kvm_lapic *apic = vcpu->arch.apic;
2084 if (!lapic_in_kernel(vcpu) || apic_lvtt_oneshot(apic) ||
2085 apic_lvtt_period(apic))
2088 hrtimer_cancel(&apic->lapic_timer.timer);
2089 apic->lapic_timer.tscdeadline = data;
2090 start_apic_timer(apic);
2093 void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8)
2095 struct kvm_lapic *apic = vcpu->arch.apic;
2097 apic_set_tpr(apic, ((cr8 & 0x0f) << 4)
2098 | (kvm_lapic_get_reg(apic, APIC_TASKPRI) & 4));
2101 u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
2105 tpr = (u64) kvm_lapic_get_reg(vcpu->arch.apic, APIC_TASKPRI);
2107 return (tpr & 0xf0) >> 4;
2110 void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
2112 u64 old_value = vcpu->arch.apic_base;
2113 struct kvm_lapic *apic = vcpu->arch.apic;
2116 value |= MSR_IA32_APICBASE_BSP;
2118 vcpu->arch.apic_base = value;
2120 if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE)
2121 kvm_update_cpuid(vcpu);
2126 /* update jump label if enable bit changes */
2127 if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE) {
2128 if (value & MSR_IA32_APICBASE_ENABLE) {
2129 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2130 static_key_slow_dec_deferred(&apic_hw_disabled);
2132 static_key_slow_inc(&apic_hw_disabled.key);
2133 recalculate_apic_map(vcpu->kvm);
2137 if (((old_value ^ value) & X2APIC_ENABLE) && (value & X2APIC_ENABLE))
2138 kvm_apic_set_x2apic_id(apic, vcpu->vcpu_id);
2140 if ((old_value ^ value) & (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE))
2141 kvm_x86_ops->set_virtual_apic_mode(vcpu);
2143 apic->base_address = apic->vcpu->arch.apic_base &
2144 MSR_IA32_APICBASE_BASE;
2146 if ((value & MSR_IA32_APICBASE_ENABLE) &&
2147 apic->base_address != APIC_DEFAULT_PHYS_BASE)
2148 pr_warn_once("APIC base relocation is unsupported by KVM");
2150 /* with FSB delivery interrupt, we can restart APIC functionality */
2151 apic_debug("apic base msr is 0x%016" PRIx64 ", and base address is "
2152 "0x%lx.\n", apic->vcpu->arch.apic_base, apic->base_address);
2156 void kvm_lapic_reset(struct kvm_vcpu *vcpu, bool init_event)
2158 struct kvm_lapic *apic = vcpu->arch.apic;
2164 apic_debug("%s\n", __func__);
2166 /* Stop the timer in case it's a reset to an active apic */
2167 hrtimer_cancel(&apic->lapic_timer.timer);
2170 kvm_lapic_set_base(vcpu, APIC_DEFAULT_PHYS_BASE |
2171 MSR_IA32_APICBASE_ENABLE);
2172 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2174 kvm_apic_set_version(apic->vcpu);
2176 for (i = 0; i < KVM_APIC_LVT_NUM; i++)
2177 kvm_lapic_set_reg(apic, APIC_LVTT + 0x10 * i, APIC_LVT_MASKED);
2178 apic_update_lvtt(apic);
2179 if (kvm_vcpu_is_reset_bsp(vcpu) &&
2180 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_LINT0_REENABLED))
2181 kvm_lapic_set_reg(apic, APIC_LVT0,
2182 SET_APIC_DELIVERY_MODE(0, APIC_MODE_EXTINT));
2183 apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2185 kvm_lapic_set_reg(apic, APIC_DFR, 0xffffffffU);
2186 apic_set_spiv(apic, 0xff);
2187 kvm_lapic_set_reg(apic, APIC_TASKPRI, 0);
2188 if (!apic_x2apic_mode(apic))
2189 kvm_apic_set_ldr(apic, 0);
2190 kvm_lapic_set_reg(apic, APIC_ESR, 0);
2191 kvm_lapic_set_reg(apic, APIC_ICR, 0);
2192 kvm_lapic_set_reg(apic, APIC_ICR2, 0);
2193 kvm_lapic_set_reg(apic, APIC_TDCR, 0);
2194 kvm_lapic_set_reg(apic, APIC_TMICT, 0);
2195 for (i = 0; i < 8; i++) {
2196 kvm_lapic_set_reg(apic, APIC_IRR + 0x10 * i, 0);
2197 kvm_lapic_set_reg(apic, APIC_ISR + 0x10 * i, 0);
2198 kvm_lapic_set_reg(apic, APIC_TMR + 0x10 * i, 0);
2200 apic->irr_pending = vcpu->arch.apicv_active;
2201 apic->isr_count = vcpu->arch.apicv_active ? 1 : 0;
2202 apic->highest_isr_cache = -1;
2203 update_divide_count(apic);
2204 atomic_set(&apic->lapic_timer.pending, 0);
2205 if (kvm_vcpu_is_bsp(vcpu))
2206 kvm_lapic_set_base(vcpu,
2207 vcpu->arch.apic_base | MSR_IA32_APICBASE_BSP);
2208 vcpu->arch.pv_eoi.msr_val = 0;
2209 apic_update_ppr(apic);
2210 if (vcpu->arch.apicv_active) {
2211 kvm_x86_ops->apicv_post_state_restore(vcpu);
2212 kvm_x86_ops->hwapic_irr_update(vcpu, -1);
2213 kvm_x86_ops->hwapic_isr_update(vcpu, -1);
2216 vcpu->arch.apic_arb_prio = 0;
2217 vcpu->arch.apic_attention = 0;
2219 apic_debug("%s: vcpu=%p, id=0x%x, base_msr="
2220 "0x%016" PRIx64 ", base_address=0x%0lx.\n", __func__,
2221 vcpu, kvm_lapic_get_reg(apic, APIC_ID),
2222 vcpu->arch.apic_base, apic->base_address);
2226 *----------------------------------------------------------------------
2228 *----------------------------------------------------------------------
2231 static bool lapic_is_periodic(struct kvm_lapic *apic)
2233 return apic_lvtt_period(apic);
2236 int apic_has_pending_timer(struct kvm_vcpu *vcpu)
2238 struct kvm_lapic *apic = vcpu->arch.apic;
2240 if (apic_enabled(apic) && apic_lvt_enabled(apic, APIC_LVTT))
2241 return atomic_read(&apic->lapic_timer.pending);
2246 int kvm_apic_local_deliver(struct kvm_lapic *apic, int lvt_type)
2248 u32 reg = kvm_lapic_get_reg(apic, lvt_type);
2249 int vector, mode, trig_mode;
2251 if (kvm_apic_hw_enabled(apic) && !(reg & APIC_LVT_MASKED)) {
2252 vector = reg & APIC_VECTOR_MASK;
2253 mode = reg & APIC_MODE_MASK;
2254 trig_mode = reg & APIC_LVT_LEVEL_TRIGGER;
2255 return __apic_accept_irq(apic, mode, vector, 1, trig_mode,
2261 void kvm_apic_nmi_wd_deliver(struct kvm_vcpu *vcpu)
2263 struct kvm_lapic *apic = vcpu->arch.apic;
2266 kvm_apic_local_deliver(apic, APIC_LVT0);
2269 static const struct kvm_io_device_ops apic_mmio_ops = {
2270 .read = apic_mmio_read,
2271 .write = apic_mmio_write,
2274 static enum hrtimer_restart apic_timer_fn(struct hrtimer *data)
2276 struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
2277 struct kvm_lapic *apic = container_of(ktimer, struct kvm_lapic, lapic_timer);
2279 apic_timer_expired(apic);
2281 if (lapic_is_periodic(apic)) {
2282 advance_periodic_target_expiration(apic);
2283 hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
2284 return HRTIMER_RESTART;
2286 return HRTIMER_NORESTART;
2289 int kvm_create_lapic(struct kvm_vcpu *vcpu, int timer_advance_ns)
2291 struct kvm_lapic *apic;
2293 ASSERT(vcpu != NULL);
2294 apic_debug("apic_init %d\n", vcpu->vcpu_id);
2296 apic = kzalloc(sizeof(*apic), GFP_KERNEL_ACCOUNT);
2300 vcpu->arch.apic = apic;
2302 apic->regs = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
2304 printk(KERN_ERR "malloc apic regs error for vcpu %x\n",
2306 goto nomem_free_apic;
2310 hrtimer_init(&apic->lapic_timer.timer, CLOCK_MONOTONIC,
2311 HRTIMER_MODE_ABS_PINNED);
2312 apic->lapic_timer.timer.function = apic_timer_fn;
2313 if (timer_advance_ns == -1) {
2314 apic->lapic_timer.timer_advance_ns = 1000;
2315 apic->lapic_timer.timer_advance_adjust_done = false;
2317 apic->lapic_timer.timer_advance_ns = timer_advance_ns;
2318 apic->lapic_timer.timer_advance_adjust_done = true;
2323 * APIC is created enabled. This will prevent kvm_lapic_set_base from
2324 * thinking that APIC satet has changed.
2326 vcpu->arch.apic_base = MSR_IA32_APICBASE_ENABLE;
2327 static_key_slow_inc(&apic_sw_disabled.key); /* sw disabled at reset */
2328 kvm_iodevice_init(&apic->dev, &apic_mmio_ops);
2337 int kvm_apic_has_interrupt(struct kvm_vcpu *vcpu)
2339 struct kvm_lapic *apic = vcpu->arch.apic;
2342 if (!apic_enabled(apic))
2345 __apic_update_ppr(apic, &ppr);
2346 return apic_has_interrupt_for_ppr(apic, ppr);
2349 int kvm_apic_accept_pic_intr(struct kvm_vcpu *vcpu)
2351 u32 lvt0 = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVT0);
2354 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
2356 if ((lvt0 & APIC_LVT_MASKED) == 0 &&
2357 GET_APIC_DELIVERY_MODE(lvt0) == APIC_MODE_EXTINT)
2362 void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu)
2364 struct kvm_lapic *apic = vcpu->arch.apic;
2366 if (atomic_read(&apic->lapic_timer.pending) > 0) {
2367 kvm_apic_local_deliver(apic, APIC_LVTT);
2368 if (apic_lvtt_tscdeadline(apic))
2369 apic->lapic_timer.tscdeadline = 0;
2370 if (apic_lvtt_oneshot(apic)) {
2371 apic->lapic_timer.tscdeadline = 0;
2372 apic->lapic_timer.target_expiration = 0;
2374 atomic_set(&apic->lapic_timer.pending, 0);
2378 int kvm_get_apic_interrupt(struct kvm_vcpu *vcpu)
2380 int vector = kvm_apic_has_interrupt(vcpu);
2381 struct kvm_lapic *apic = vcpu->arch.apic;
2388 * We get here even with APIC virtualization enabled, if doing
2389 * nested virtualization and L1 runs with the "acknowledge interrupt
2390 * on exit" mode. Then we cannot inject the interrupt via RVI,
2391 * because the process would deliver it through the IDT.
2394 apic_clear_irr(vector, apic);
2395 if (test_bit(vector, vcpu_to_synic(vcpu)->auto_eoi_bitmap)) {
2397 * For auto-EOI interrupts, there might be another pending
2398 * interrupt above PPR, so check whether to raise another
2401 apic_update_ppr(apic);
2404 * For normal interrupts, PPR has been raised and there cannot
2405 * be a higher-priority pending interrupt---except if there was
2406 * a concurrent interrupt injection, but that would have
2407 * triggered KVM_REQ_EVENT already.
2409 apic_set_isr(vector, apic);
2410 __apic_update_ppr(apic, &ppr);
2416 static int kvm_apic_state_fixup(struct kvm_vcpu *vcpu,
2417 struct kvm_lapic_state *s, bool set)
2419 if (apic_x2apic_mode(vcpu->arch.apic)) {
2420 u32 *id = (u32 *)(s->regs + APIC_ID);
2421 u32 *ldr = (u32 *)(s->regs + APIC_LDR);
2423 if (vcpu->kvm->arch.x2apic_format) {
2424 if (*id != vcpu->vcpu_id)
2433 /* In x2APIC mode, the LDR is fixed and based on the id */
2435 *ldr = kvm_apic_calc_x2apic_ldr(*id);
2441 int kvm_apic_get_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2443 memcpy(s->regs, vcpu->arch.apic->regs, sizeof(*s));
2444 return kvm_apic_state_fixup(vcpu, s, false);
2447 int kvm_apic_set_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2449 struct kvm_lapic *apic = vcpu->arch.apic;
2453 kvm_lapic_set_base(vcpu, vcpu->arch.apic_base);
2454 /* set SPIV separately to get count of SW disabled APICs right */
2455 apic_set_spiv(apic, *((u32 *)(s->regs + APIC_SPIV)));
2457 r = kvm_apic_state_fixup(vcpu, s, true);
2460 memcpy(vcpu->arch.apic->regs, s->regs, sizeof(*s));
2462 recalculate_apic_map(vcpu->kvm);
2463 kvm_apic_set_version(vcpu);
2465 apic_update_ppr(apic);
2466 hrtimer_cancel(&apic->lapic_timer.timer);
2467 apic_update_lvtt(apic);
2468 apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2469 update_divide_count(apic);
2470 start_apic_timer(apic);
2471 apic->irr_pending = true;
2472 apic->isr_count = vcpu->arch.apicv_active ?
2473 1 : count_vectors(apic->regs + APIC_ISR);
2474 apic->highest_isr_cache = -1;
2475 if (vcpu->arch.apicv_active) {
2476 kvm_x86_ops->apicv_post_state_restore(vcpu);
2477 kvm_x86_ops->hwapic_irr_update(vcpu,
2478 apic_find_highest_irr(apic));
2479 kvm_x86_ops->hwapic_isr_update(vcpu,
2480 apic_find_highest_isr(apic));
2482 kvm_make_request(KVM_REQ_EVENT, vcpu);
2483 if (ioapic_in_kernel(vcpu->kvm))
2484 kvm_rtc_eoi_tracking_restore_one(vcpu);
2486 vcpu->arch.apic_arb_prio = 0;
2491 void __kvm_migrate_apic_timer(struct kvm_vcpu *vcpu)
2493 struct hrtimer *timer;
2495 if (!lapic_in_kernel(vcpu))
2498 timer = &vcpu->arch.apic->lapic_timer.timer;
2499 if (hrtimer_cancel(timer))
2500 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
2504 * apic_sync_pv_eoi_from_guest - called on vmexit or cancel interrupt
2506 * Detect whether guest triggered PV EOI since the
2507 * last entry. If yes, set EOI on guests's behalf.
2508 * Clear PV EOI in guest memory in any case.
2510 static void apic_sync_pv_eoi_from_guest(struct kvm_vcpu *vcpu,
2511 struct kvm_lapic *apic)
2516 * PV EOI state is derived from KVM_APIC_PV_EOI_PENDING in host
2517 * and KVM_PV_EOI_ENABLED in guest memory as follows:
2519 * KVM_APIC_PV_EOI_PENDING is unset:
2520 * -> host disabled PV EOI.
2521 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is set:
2522 * -> host enabled PV EOI, guest did not execute EOI yet.
2523 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is unset:
2524 * -> host enabled PV EOI, guest executed EOI.
2526 BUG_ON(!pv_eoi_enabled(vcpu));
2527 pending = pv_eoi_get_pending(vcpu);
2529 * Clear pending bit in any case: it will be set again on vmentry.
2530 * While this might not be ideal from performance point of view,
2531 * this makes sure pv eoi is only enabled when we know it's safe.
2533 pv_eoi_clr_pending(vcpu);
2536 vector = apic_set_eoi(apic);
2537 trace_kvm_pv_eoi(apic, vector);
2540 void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
2544 if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
2545 apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
2547 if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
2550 if (kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
2554 apic_set_tpr(vcpu->arch.apic, data & 0xff);
2558 * apic_sync_pv_eoi_to_guest - called before vmentry
2560 * Detect whether it's safe to enable PV EOI and
2563 static void apic_sync_pv_eoi_to_guest(struct kvm_vcpu *vcpu,
2564 struct kvm_lapic *apic)
2566 if (!pv_eoi_enabled(vcpu) ||
2567 /* IRR set or many bits in ISR: could be nested. */
2568 apic->irr_pending ||
2569 /* Cache not set: could be safe but we don't bother. */
2570 apic->highest_isr_cache == -1 ||
2571 /* Need EOI to update ioapic. */
2572 kvm_ioapic_handles_vector(apic, apic->highest_isr_cache)) {
2574 * PV EOI was disabled by apic_sync_pv_eoi_from_guest
2575 * so we need not do anything here.
2580 pv_eoi_set_pending(apic->vcpu);
2583 void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
2586 int max_irr, max_isr;
2587 struct kvm_lapic *apic = vcpu->arch.apic;
2589 apic_sync_pv_eoi_to_guest(vcpu, apic);
2591 if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
2594 tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI) & 0xff;
2595 max_irr = apic_find_highest_irr(apic);
2598 max_isr = apic_find_highest_isr(apic);
2601 data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
2603 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
2607 int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
2610 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2611 &vcpu->arch.apic->vapic_cache,
2612 vapic_addr, sizeof(u32)))
2614 __set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
2616 __clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
2619 vcpu->arch.apic->vapic_addr = vapic_addr;
2623 int kvm_x2apic_msr_write(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2625 struct kvm_lapic *apic = vcpu->arch.apic;
2626 u32 reg = (msr - APIC_BASE_MSR) << 4;
2628 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
2631 if (reg == APIC_ICR2)
2634 /* if this is ICR write vector before command */
2635 if (reg == APIC_ICR)
2636 kvm_lapic_reg_write(apic, APIC_ICR2, (u32)(data >> 32));
2637 return kvm_lapic_reg_write(apic, reg, (u32)data);
2640 int kvm_x2apic_msr_read(struct kvm_vcpu *vcpu, u32 msr, u64 *data)
2642 struct kvm_lapic *apic = vcpu->arch.apic;
2643 u32 reg = (msr - APIC_BASE_MSR) << 4, low, high = 0;
2645 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
2648 if (reg == APIC_DFR || reg == APIC_ICR2) {
2649 apic_debug("KVM_APIC_READ: read x2apic reserved register %x\n",
2654 if (kvm_lapic_reg_read(apic, reg, 4, &low))
2656 if (reg == APIC_ICR)
2657 kvm_lapic_reg_read(apic, APIC_ICR2, 4, &high);
2659 *data = (((u64)high) << 32) | low;
2664 int kvm_hv_vapic_msr_write(struct kvm_vcpu *vcpu, u32 reg, u64 data)
2666 struct kvm_lapic *apic = vcpu->arch.apic;
2668 if (!lapic_in_kernel(vcpu))
2671 /* if this is ICR write vector before command */
2672 if (reg == APIC_ICR)
2673 kvm_lapic_reg_write(apic, APIC_ICR2, (u32)(data >> 32));
2674 return kvm_lapic_reg_write(apic, reg, (u32)data);
2677 int kvm_hv_vapic_msr_read(struct kvm_vcpu *vcpu, u32 reg, u64 *data)
2679 struct kvm_lapic *apic = vcpu->arch.apic;
2682 if (!lapic_in_kernel(vcpu))
2685 if (kvm_lapic_reg_read(apic, reg, 4, &low))
2687 if (reg == APIC_ICR)
2688 kvm_lapic_reg_read(apic, APIC_ICR2, 4, &high);
2690 *data = (((u64)high) << 32) | low;
2695 int kvm_lapic_enable_pv_eoi(struct kvm_vcpu *vcpu, u64 data, unsigned long len)
2697 u64 addr = data & ~KVM_MSR_ENABLED;
2698 struct gfn_to_hva_cache *ghc = &vcpu->arch.pv_eoi.data;
2699 unsigned long new_len;
2701 if (!IS_ALIGNED(addr, 4))
2704 vcpu->arch.pv_eoi.msr_val = data;
2705 if (!pv_eoi_enabled(vcpu))
2708 if (addr == ghc->gpa && len <= ghc->len)
2713 return kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, addr, new_len);
2716 void kvm_apic_accept_events(struct kvm_vcpu *vcpu)
2718 struct kvm_lapic *apic = vcpu->arch.apic;
2722 if (!lapic_in_kernel(vcpu) || !apic->pending_events)
2726 * INITs are latched while in SMM. Because an SMM CPU cannot
2727 * be in KVM_MP_STATE_INIT_RECEIVED state, just eat SIPIs
2728 * and delay processing of INIT until the next RSM.
2731 WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED);
2732 if (test_bit(KVM_APIC_SIPI, &apic->pending_events))
2733 clear_bit(KVM_APIC_SIPI, &apic->pending_events);
2737 pe = xchg(&apic->pending_events, 0);
2738 if (test_bit(KVM_APIC_INIT, &pe)) {
2739 kvm_vcpu_reset(vcpu, true);
2740 if (kvm_vcpu_is_bsp(apic->vcpu))
2741 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
2743 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
2745 if (test_bit(KVM_APIC_SIPI, &pe) &&
2746 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
2747 /* evaluate pending_events before reading the vector */
2749 sipi_vector = apic->sipi_vector;
2750 apic_debug("vcpu %d received sipi with vector # %x\n",
2751 vcpu->vcpu_id, sipi_vector);
2752 kvm_vcpu_deliver_sipi_vector(vcpu, sipi_vector);
2753 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
2757 void kvm_lapic_init(void)
2759 /* do not patch jump label more than once per second */
2760 jump_label_rate_limit(&apic_hw_disabled, HZ);
2761 jump_label_rate_limit(&apic_sw_disabled, HZ);
2764 void kvm_lapic_exit(void)
2766 static_key_deferred_flush(&apic_hw_disabled);
2767 static_key_deferred_flush(&apic_sw_disabled);