xref: /linux/arch/x86/kvm/lapic.c (revision 3efc57369a0ce8f76bf0804f7e673982384e4ac9)
120c8ccb1SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
2edf88417SAvi Kivity 
3edf88417SAvi Kivity /*
4edf88417SAvi Kivity  * Local APIC virtualization
5edf88417SAvi Kivity  *
6edf88417SAvi Kivity  * Copyright (C) 2006 Qumranet, Inc.
7edf88417SAvi Kivity  * Copyright (C) 2007 Novell
8edf88417SAvi Kivity  * Copyright (C) 2007 Intel
99611c187SNicolas Kaiser  * Copyright 2009 Red Hat, Inc. and/or its affiliates.
10edf88417SAvi Kivity  *
11edf88417SAvi Kivity  * Authors:
12edf88417SAvi Kivity  *   Dor Laor <dor.laor@qumranet.com>
13edf88417SAvi Kivity  *   Gregory Haskins <ghaskins@novell.com>
14edf88417SAvi Kivity  *   Yaozu (Eddie) Dong <eddie.dong@intel.com>
15edf88417SAvi Kivity  *
16edf88417SAvi Kivity  * Based on Xen 3.1 code, Copyright (c) 2004, Intel Corporation.
17edf88417SAvi Kivity  */
188d20bd63SSean Christopherson #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
19edf88417SAvi Kivity 
20edf88417SAvi Kivity #include <linux/kvm_host.h>
21edf88417SAvi Kivity #include <linux/kvm.h>
22edf88417SAvi Kivity #include <linux/mm.h>
23edf88417SAvi Kivity #include <linux/highmem.h>
24edf88417SAvi Kivity #include <linux/smp.h>
25edf88417SAvi Kivity #include <linux/hrtimer.h>
26edf88417SAvi Kivity #include <linux/io.h>
271767e931SPaul Gortmaker #include <linux/export.h>
286f6d6a1aSRoman Zippel #include <linux/math64.h>
295a0e3ad6STejun Heo #include <linux/slab.h>
30edf88417SAvi Kivity #include <asm/processor.h>
314b903561SJue Wang #include <asm/mce.h>
32edf88417SAvi Kivity #include <asm/msr.h>
33edf88417SAvi Kivity #include <asm/page.h>
34edf88417SAvi Kivity #include <asm/current.h>
35edf88417SAvi Kivity #include <asm/apicdef.h>
36d0659d94SMarcelo Tosatti #include <asm/delay.h>
3760063497SArun Sharma #include <linux/atomic.h>
38c5cc421bSGleb Natapov #include <linux/jump_label.h>
395fdbf976SMarcelo Tosatti #include "kvm_cache_regs.h"
40edf88417SAvi Kivity #include "irq.h"
4188197e6aS彭浩(Richard) #include "ioapic.h"
42229456fcSMarcelo Tosatti #include "trace.h"
43fc61b800SGleb Natapov #include "x86.h"
448e62bf2bSDavid Woodhouse #include "xen.h"
4500b27a3eSAvi Kivity #include "cpuid.h"
465c919412SAndrey Smetanin #include "hyperv.h"
47b0b42197SPaolo Bonzini #include "smm.h"
48edf88417SAvi Kivity 
49b682b814SMarcelo Tosatti #ifndef CONFIG_X86_64
50b682b814SMarcelo Tosatti #define mod_64(x, y) ((x) - (y) * div64_u64(x, y))
51b682b814SMarcelo Tosatti #else
52b682b814SMarcelo Tosatti #define mod_64(x, y) ((x) % (y))
53b682b814SMarcelo Tosatti #endif
54b682b814SMarcelo Tosatti 
55edf88417SAvi Kivity /* 14 is the version for Xeon and Pentium 8.4.8*/
56951ceb94SJue Wang #define APIC_VERSION			0x14UL
57edf88417SAvi Kivity #define LAPIC_MMIO_LENGTH		(1 << 12)
58edf88417SAvi Kivity /* followed define is not in apicdef.h */
59edf88417SAvi Kivity #define MAX_APIC_VECTOR			256
60ecba9a52STakuya Yoshikawa #define APIC_VECTORS_PER_REG		32
61edf88417SAvi Kivity 
6289a58812SSean Christopherson /*
6389a58812SSean Christopherson  * Enable local APIC timer advancement (tscdeadline mode only) with adaptive
6489a58812SSean Christopherson  * tuning.  When enabled, KVM programs the host timer event to fire early, i.e.
6589a58812SSean Christopherson  * before the deadline expires, to account for the delay between taking the
6689a58812SSean Christopherson  * VM-Exit (to inject the guest event) and the subsequent VM-Enter to resume
6789a58812SSean Christopherson  * the guest, i.e. so that the interrupt arrives in the guest with minimal
6889a58812SSean Christopherson  * latency relative to the deadline programmed by the guest.
6989a58812SSean Christopherson  */
7089a58812SSean Christopherson static bool lapic_timer_advance __read_mostly = true;
7189a58812SSean Christopherson module_param(lapic_timer_advance, bool, 0444);
7289a58812SSean Christopherson 
73a0f0037eSWanpeng Li #define LAPIC_TIMER_ADVANCE_ADJUST_MIN	100	/* clock cycles */
74a0f0037eSWanpeng Li #define LAPIC_TIMER_ADVANCE_ADJUST_MAX	10000	/* clock cycles */
75a0f0037eSWanpeng Li #define LAPIC_TIMER_ADVANCE_NS_INIT	1000
76a0f0037eSWanpeng Li #define LAPIC_TIMER_ADVANCE_NS_MAX     5000
773b8a5df6SWanpeng Li /* step-by-step approximation to mitigate fluctuation */
783b8a5df6SWanpeng Li #define LAPIC_TIMER_ADVANCE_ADJUST_STEP 8
795413bcbaSZeng Guang static int kvm_lapic_msr_read(struct kvm_lapic *apic, u32 reg, u64 *data);
801bd9dfecSSuravee Suthikulpanit static int kvm_lapic_msr_write(struct kvm_lapic *apic, u32 reg, u64 data);
813b8a5df6SWanpeng Li 
__kvm_lapic_set_reg(char * regs,int reg_off,u32 val)82b9964ee3SSean Christopherson static inline void __kvm_lapic_set_reg(char *regs, int reg_off, u32 val)
83b9964ee3SSean Christopherson {
84b9964ee3SSean Christopherson 	*((u32 *) (regs + reg_off)) = val;
85b9964ee3SSean Christopherson }
86b9964ee3SSean Christopherson 
kvm_lapic_set_reg(struct kvm_lapic * apic,int reg_off,u32 val)87b9964ee3SSean Christopherson static inline void kvm_lapic_set_reg(struct kvm_lapic *apic, int reg_off, u32 val)
88b9964ee3SSean Christopherson {
89b9964ee3SSean Christopherson 	__kvm_lapic_set_reg(apic->regs, reg_off, val);
90b9964ee3SSean Christopherson }
91b9964ee3SSean Christopherson 
__kvm_lapic_get_reg64(char * regs,int reg)92a57a3168SSean Christopherson static __always_inline u64 __kvm_lapic_get_reg64(char *regs, int reg)
93a57a3168SSean Christopherson {
94a57a3168SSean Christopherson 	BUILD_BUG_ON(reg != APIC_ICR);
95a57a3168SSean Christopherson 	return *((u64 *) (regs + reg));
96a57a3168SSean Christopherson }
97a57a3168SSean Christopherson 
kvm_lapic_get_reg64(struct kvm_lapic * apic,int reg)98a57a3168SSean Christopherson static __always_inline u64 kvm_lapic_get_reg64(struct kvm_lapic *apic, int reg)
99a57a3168SSean Christopherson {
100a57a3168SSean Christopherson 	return __kvm_lapic_get_reg64(apic->regs, reg);
101a57a3168SSean Christopherson }
102a57a3168SSean Christopherson 
__kvm_lapic_set_reg64(char * regs,int reg,u64 val)103a57a3168SSean Christopherson static __always_inline void __kvm_lapic_set_reg64(char *regs, int reg, u64 val)
104a57a3168SSean Christopherson {
105a57a3168SSean Christopherson 	BUILD_BUG_ON(reg != APIC_ICR);
106a57a3168SSean Christopherson 	*((u64 *) (regs + reg)) = val;
107a57a3168SSean Christopherson }
108a57a3168SSean Christopherson 
kvm_lapic_set_reg64(struct kvm_lapic * apic,int reg,u64 val)109a57a3168SSean Christopherson static __always_inline void kvm_lapic_set_reg64(struct kvm_lapic *apic,
110a57a3168SSean Christopherson 						int reg, u64 val)
111a57a3168SSean Christopherson {
112a57a3168SSean Christopherson 	__kvm_lapic_set_reg64(apic->regs, reg, val);
113a57a3168SSean Christopherson }
114a57a3168SSean Christopherson 
apic_test_vector(int vec,void * bitmap)115a0c9a822SMichael S. Tsirkin static inline int apic_test_vector(int vec, void *bitmap)
116a0c9a822SMichael S. Tsirkin {
117a0c9a822SMichael S. Tsirkin 	return test_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
118a0c9a822SMichael S. Tsirkin }
119a0c9a822SMichael S. Tsirkin 
kvm_apic_pending_eoi(struct kvm_vcpu * vcpu,int vector)12010606919SYang Zhang bool kvm_apic_pending_eoi(struct kvm_vcpu *vcpu, int vector)
12110606919SYang Zhang {
12210606919SYang Zhang 	struct kvm_lapic *apic = vcpu->arch.apic;
12310606919SYang Zhang 
12410606919SYang Zhang 	return apic_test_vector(vector, apic->regs + APIC_ISR) ||
12510606919SYang Zhang 		apic_test_vector(vector, apic->regs + APIC_IRR);
12610606919SYang Zhang }
12710606919SYang Zhang 
__apic_test_and_set_vector(int vec,void * bitmap)1288680b94bSMichael S. Tsirkin static inline int __apic_test_and_set_vector(int vec, void *bitmap)
1298680b94bSMichael S. Tsirkin {
1308680b94bSMichael S. Tsirkin 	return __test_and_set_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
1318680b94bSMichael S. Tsirkin }
1328680b94bSMichael S. Tsirkin 
__apic_test_and_clear_vector(int vec,void * bitmap)1338680b94bSMichael S. Tsirkin static inline int __apic_test_and_clear_vector(int vec, void *bitmap)
1348680b94bSMichael S. Tsirkin {
1358680b94bSMichael S. Tsirkin 	return __test_and_clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
1368680b94bSMichael S. Tsirkin }
1378680b94bSMichael S. Tsirkin 
138a78d9046SSean Christopherson __read_mostly DEFINE_STATIC_KEY_FALSE(kvm_has_noapic_vcpu);
139a78d9046SSean Christopherson EXPORT_SYMBOL_GPL(kvm_has_noapic_vcpu);
140a78d9046SSean Christopherson 
1416e4e3b4dSCun Li __read_mostly DEFINE_STATIC_KEY_DEFERRED_FALSE(apic_hw_disabled, HZ);
1426e4e3b4dSCun Li __read_mostly DEFINE_STATIC_KEY_DEFERRED_FALSE(apic_sw_disabled, HZ);
143f8c1ea10SGleb Natapov 
apic_enabled(struct kvm_lapic * apic)144edf88417SAvi Kivity static inline int apic_enabled(struct kvm_lapic *apic)
145edf88417SAvi Kivity {
146c48f1496SGleb Natapov 	return kvm_apic_sw_enabled(apic) &&	kvm_apic_hw_enabled(apic);
14754e9818fSGleb Natapov }
14854e9818fSGleb Natapov 
149edf88417SAvi Kivity #define LVT_MASK	\
150edf88417SAvi Kivity 	(APIC_LVT_MASKED | APIC_SEND_PENDING | APIC_VECTOR_MASK)
151edf88417SAvi Kivity 
152edf88417SAvi Kivity #define LINT_MASK	\
153edf88417SAvi Kivity 	(LVT_MASK | APIC_MODE_MASK | APIC_INPUT_POLARITY | \
154edf88417SAvi Kivity 	 APIC_LVT_REMOTE_IRR | APIC_LVT_LEVEL_TRIGGER)
155edf88417SAvi Kivity 
kvm_x2apic_id(struct kvm_lapic * apic)1566e500439SRadim Krčmář static inline u32 kvm_x2apic_id(struct kvm_lapic *apic)
1576e500439SRadim Krčmář {
1586e500439SRadim Krčmář 	return apic->vcpu->vcpu_id;
1596e500439SRadim Krčmář }
1606e500439SRadim Krčmář 
kvm_can_post_timer_interrupt(struct kvm_vcpu * vcpu)161199a8b84SPaolo Bonzini static bool kvm_can_post_timer_interrupt(struct kvm_vcpu *vcpu)
1620c5f81daSWanpeng Li {
1631714a4ebSWanpeng Li 	return pi_inject_timer && kvm_vcpu_apicv_active(vcpu) &&
1641714a4ebSWanpeng Li 		(kvm_mwait_in_guest(vcpu->kvm) || kvm_hlt_in_guest(vcpu->kvm));
1650c5f81daSWanpeng Li }
166199a8b84SPaolo Bonzini 
kvm_can_use_hv_timer(struct kvm_vcpu * vcpu)167199a8b84SPaolo Bonzini bool kvm_can_use_hv_timer(struct kvm_vcpu *vcpu)
168199a8b84SPaolo Bonzini {
169199a8b84SPaolo Bonzini 	return kvm_x86_ops.set_hv_timer
170199a8b84SPaolo Bonzini 	       && !(kvm_mwait_in_guest(vcpu->kvm) ||
171199a8b84SPaolo Bonzini 		    kvm_can_post_timer_interrupt(vcpu));
172199a8b84SPaolo Bonzini }
1730c5f81daSWanpeng Li 
kvm_use_posted_timer_interrupt(struct kvm_vcpu * vcpu)1740c5f81daSWanpeng Li static bool kvm_use_posted_timer_interrupt(struct kvm_vcpu *vcpu)
1750c5f81daSWanpeng Li {
1760c5f81daSWanpeng Li 	return kvm_can_post_timer_interrupt(vcpu) && vcpu->mode == IN_GUEST_MODE;
1770c5f81daSWanpeng Li }
1780c5f81daSWanpeng Li 
kvm_apic_calc_x2apic_ldr(u32 id)17976e52750SSean Christopherson static inline u32 kvm_apic_calc_x2apic_ldr(u32 id)
18076e52750SSean Christopherson {
18176e52750SSean Christopherson 	return ((id >> 4) << 16) | (1 << (id & 0xf));
18276e52750SSean Christopherson }
18376e52750SSean Christopherson 
kvm_apic_map_get_logical_dest(struct kvm_apic_map * map,u32 dest_id,struct kvm_lapic *** cluster,u16 * mask)184e45115b6SRadim Krčmář static inline bool kvm_apic_map_get_logical_dest(struct kvm_apic_map *map,
185e45115b6SRadim Krčmář 		u32 dest_id, struct kvm_lapic ***cluster, u16 *mask) {
18635366901SSean Christopherson 	switch (map->logical_mode) {
18735366901SSean Christopherson 	case KVM_APIC_MODE_SW_DISABLED:
18835366901SSean Christopherson 		/* Arbitrarily use the flat map so that @cluster isn't NULL. */
18935366901SSean Christopherson 		*cluster = map->xapic_flat_map;
19035366901SSean Christopherson 		*mask = 0;
19135366901SSean Christopherson 		return true;
192e45115b6SRadim Krčmář 	case KVM_APIC_MODE_X2APIC: {
193e45115b6SRadim Krčmář 		u32 offset = (dest_id >> 16) * 16;
1940ca52e7bSRadim Krčmář 		u32 max_apic_id = map->max_apic_id;
195e45115b6SRadim Krčmář 
196e45115b6SRadim Krčmář 		if (offset <= max_apic_id) {
197e45115b6SRadim Krčmář 			u8 cluster_size = min(max_apic_id - offset + 1, 16U);
198e45115b6SRadim Krčmář 
1991d487e9bSPaolo Bonzini 			offset = array_index_nospec(offset, map->max_apic_id + 1);
200e45115b6SRadim Krčmář 			*cluster = &map->phys_map[offset];
201e45115b6SRadim Krčmář 			*mask = dest_id & (0xffff >> (16 - cluster_size));
202e45115b6SRadim Krčmář 		} else {
203e45115b6SRadim Krčmář 			*mask = 0;
2043548a259SRadim Krčmář 		}
2053548a259SRadim Krčmář 
206e45115b6SRadim Krčmář 		return true;
207e45115b6SRadim Krčmář 		}
208e45115b6SRadim Krčmář 	case KVM_APIC_MODE_XAPIC_FLAT:
209e45115b6SRadim Krčmář 		*cluster = map->xapic_flat_map;
210e45115b6SRadim Krčmář 		*mask = dest_id & 0xff;
211e45115b6SRadim Krčmář 		return true;
212e45115b6SRadim Krčmář 	case KVM_APIC_MODE_XAPIC_CLUSTER:
213444fdad8SRadim Krčmář 		*cluster = map->xapic_cluster_map[(dest_id >> 4) & 0xf];
214e45115b6SRadim Krčmář 		*mask = dest_id & 0xf;
215e45115b6SRadim Krčmář 		return true;
21635366901SSean Christopherson 	case KVM_APIC_MODE_MAP_DISABLED:
21735366901SSean Christopherson 		return false;
218e45115b6SRadim Krčmář 	default:
21935366901SSean Christopherson 		WARN_ON_ONCE(1);
220e45115b6SRadim Krčmář 		return false;
221e45115b6SRadim Krčmář 	}
2223b5a5ffaSRadim Krčmář }
2233b5a5ffaSRadim Krčmář 
kvm_apic_map_free(struct rcu_head * rcu)224af1bae54SRadim Krčmář static void kvm_apic_map_free(struct rcu_head *rcu)
225edf88417SAvi Kivity {
226af1bae54SRadim Krčmář 	struct kvm_apic_map *map = container_of(rcu, struct kvm_apic_map, rcu);
227edf88417SAvi Kivity 
228af1bae54SRadim Krčmář 	kvfree(map);
229edf88417SAvi Kivity }
230edf88417SAvi Kivity 
kvm_recalculate_phys_map(struct kvm_apic_map * new,struct kvm_vcpu * vcpu,bool * xapic_id_mismatch)23172c70ceeSSean Christopherson static int kvm_recalculate_phys_map(struct kvm_apic_map *new,
23272c70ceeSSean Christopherson 				    struct kvm_vcpu *vcpu,
23372c70ceeSSean Christopherson 				    bool *xapic_id_mismatch)
23472c70ceeSSean Christopherson {
23572c70ceeSSean Christopherson 	struct kvm_lapic *apic = vcpu->arch.apic;
23672c70ceeSSean Christopherson 	u32 x2apic_id = kvm_x2apic_id(apic);
23772c70ceeSSean Christopherson 	u32 xapic_id = kvm_xapic_id(apic);
23872c70ceeSSean Christopherson 	u32 physical_id;
23972c70ceeSSean Christopherson 
24072c70ceeSSean Christopherson 	/*
2414364b287SSean Christopherson 	 * For simplicity, KVM always allocates enough space for all possible
2424364b287SSean Christopherson 	 * xAPIC IDs.  Yell, but don't kill the VM, as KVM can continue on
2434364b287SSean Christopherson 	 * without the optimized map.
2444364b287SSean Christopherson 	 */
2454364b287SSean Christopherson 	if (WARN_ON_ONCE(xapic_id > new->max_apic_id))
2464364b287SSean Christopherson 		return -EINVAL;
2474364b287SSean Christopherson 
2484364b287SSean Christopherson 	/*
2494364b287SSean Christopherson 	 * Bail if a vCPU was added and/or enabled its APIC between allocating
2504364b287SSean Christopherson 	 * the map and doing the actual calculations for the map.  Note, KVM
2514364b287SSean Christopherson 	 * hardcodes the x2APIC ID to vcpu_id, i.e. there's no TOCTOU bug if
2524364b287SSean Christopherson 	 * the compiler decides to reload x2apic_id after this check.
2534364b287SSean Christopherson 	 */
2544364b287SSean Christopherson 	if (x2apic_id > new->max_apic_id)
2554364b287SSean Christopherson 		return -E2BIG;
2564364b287SSean Christopherson 
2574364b287SSean Christopherson 	/*
25872c70ceeSSean Christopherson 	 * Deliberately truncate the vCPU ID when detecting a mismatched APIC
25972c70ceeSSean Christopherson 	 * ID to avoid false positives if the vCPU ID, i.e. x2APIC ID, is a
26072c70ceeSSean Christopherson 	 * 32-bit value.  Any unwanted aliasing due to truncation results will
26172c70ceeSSean Christopherson 	 * be detected below.
26272c70ceeSSean Christopherson 	 */
26372c70ceeSSean Christopherson 	if (!apic_x2apic_mode(apic) && xapic_id != (u8)vcpu->vcpu_id)
26472c70ceeSSean Christopherson 		*xapic_id_mismatch = true;
26572c70ceeSSean Christopherson 
26672c70ceeSSean Christopherson 	/*
26772c70ceeSSean Christopherson 	 * Apply KVM's hotplug hack if userspace has enable 32-bit APIC IDs.
26872c70ceeSSean Christopherson 	 * Allow sending events to vCPUs by their x2APIC ID even if the target
26972c70ceeSSean Christopherson 	 * vCPU is in legacy xAPIC mode, and silently ignore aliased xAPIC IDs
27072c70ceeSSean Christopherson 	 * (the x2APIC ID is truncated to 8 bits, causing IDs > 0xff to wrap
27172c70ceeSSean Christopherson 	 * and collide).
27272c70ceeSSean Christopherson 	 *
27372c70ceeSSean Christopherson 	 * Honor the architectural (and KVM's non-optimized) behavior if
27472c70ceeSSean Christopherson 	 * userspace has not enabled 32-bit x2APIC IDs.  Each APIC is supposed
27572c70ceeSSean Christopherson 	 * to process messages independently.  If multiple vCPUs have the same
27672c70ceeSSean Christopherson 	 * effective APIC ID, e.g. due to the x2APIC wrap or because the guest
27772c70ceeSSean Christopherson 	 * manually modified its xAPIC IDs, events targeting that ID are
27872c70ceeSSean Christopherson 	 * supposed to be recognized by all vCPUs with said ID.
27972c70ceeSSean Christopherson 	 */
28072c70ceeSSean Christopherson 	if (vcpu->kvm->arch.x2apic_format) {
28172c70ceeSSean Christopherson 		/* See also kvm_apic_match_physical_addr(). */
2824364b287SSean Christopherson 		if (apic_x2apic_mode(apic) || x2apic_id > 0xff)
28372c70ceeSSean Christopherson 			new->phys_map[x2apic_id] = apic;
28472c70ceeSSean Christopherson 
28572c70ceeSSean Christopherson 		if (!apic_x2apic_mode(apic) && !new->phys_map[xapic_id])
28672c70ceeSSean Christopherson 			new->phys_map[xapic_id] = apic;
28772c70ceeSSean Christopherson 	} else {
28872c70ceeSSean Christopherson 		/*
28972c70ceeSSean Christopherson 		 * Disable the optimized map if the physical APIC ID is already
29072c70ceeSSean Christopherson 		 * mapped, i.e. is aliased to multiple vCPUs.  The optimized
29172c70ceeSSean Christopherson 		 * map requires a strict 1:1 mapping between IDs and vCPUs.
29272c70ceeSSean Christopherson 		 */
29372c70ceeSSean Christopherson 		if (apic_x2apic_mode(apic))
29472c70ceeSSean Christopherson 			physical_id = x2apic_id;
29572c70ceeSSean Christopherson 		else
29672c70ceeSSean Christopherson 			physical_id = xapic_id;
29772c70ceeSSean Christopherson 
29872c70ceeSSean Christopherson 		if (new->phys_map[physical_id])
29972c70ceeSSean Christopherson 			return -EINVAL;
30072c70ceeSSean Christopherson 
30172c70ceeSSean Christopherson 		new->phys_map[physical_id] = apic;
30272c70ceeSSean Christopherson 	}
30372c70ceeSSean Christopherson 
30472c70ceeSSean Christopherson 	return 0;
30572c70ceeSSean Christopherson }
30672c70ceeSSean Christopherson 
kvm_recalculate_logical_map(struct kvm_apic_map * new,struct kvm_vcpu * vcpu)30772c70ceeSSean Christopherson static void kvm_recalculate_logical_map(struct kvm_apic_map *new,
30872c70ceeSSean Christopherson 					struct kvm_vcpu *vcpu)
30972c70ceeSSean Christopherson {
31072c70ceeSSean Christopherson 	struct kvm_lapic *apic = vcpu->arch.apic;
31172c70ceeSSean Christopherson 	enum kvm_apic_logical_mode logical_mode;
31272c70ceeSSean Christopherson 	struct kvm_lapic **cluster;
31372c70ceeSSean Christopherson 	u16 mask;
31472c70ceeSSean Christopherson 	u32 ldr;
31572c70ceeSSean Christopherson 
31672c70ceeSSean Christopherson 	if (new->logical_mode == KVM_APIC_MODE_MAP_DISABLED)
31772c70ceeSSean Christopherson 		return;
31872c70ceeSSean Christopherson 
31972c70ceeSSean Christopherson 	if (!kvm_apic_sw_enabled(apic))
32072c70ceeSSean Christopherson 		return;
32172c70ceeSSean Christopherson 
32272c70ceeSSean Christopherson 	ldr = kvm_lapic_get_reg(apic, APIC_LDR);
32372c70ceeSSean Christopherson 	if (!ldr)
32472c70ceeSSean Christopherson 		return;
32572c70ceeSSean Christopherson 
32672c70ceeSSean Christopherson 	if (apic_x2apic_mode(apic)) {
32772c70ceeSSean Christopherson 		logical_mode = KVM_APIC_MODE_X2APIC;
32872c70ceeSSean Christopherson 	} else {
32972c70ceeSSean Christopherson 		ldr = GET_APIC_LOGICAL_ID(ldr);
33072c70ceeSSean Christopherson 		if (kvm_lapic_get_reg(apic, APIC_DFR) == APIC_DFR_FLAT)
33172c70ceeSSean Christopherson 			logical_mode = KVM_APIC_MODE_XAPIC_FLAT;
33272c70ceeSSean Christopherson 		else
33372c70ceeSSean Christopherson 			logical_mode = KVM_APIC_MODE_XAPIC_CLUSTER;
33472c70ceeSSean Christopherson 	}
33572c70ceeSSean Christopherson 
33672c70ceeSSean Christopherson 	/*
33772c70ceeSSean Christopherson 	 * To optimize logical mode delivery, all software-enabled APICs must
33872c70ceeSSean Christopherson 	 * be configured for the same mode.
33972c70ceeSSean Christopherson 	 */
34072c70ceeSSean Christopherson 	if (new->logical_mode == KVM_APIC_MODE_SW_DISABLED) {
34172c70ceeSSean Christopherson 		new->logical_mode = logical_mode;
34272c70ceeSSean Christopherson 	} else if (new->logical_mode != logical_mode) {
34372c70ceeSSean Christopherson 		new->logical_mode = KVM_APIC_MODE_MAP_DISABLED;
34472c70ceeSSean Christopherson 		return;
34572c70ceeSSean Christopherson 	}
34672c70ceeSSean Christopherson 
34772c70ceeSSean Christopherson 	/*
34872c70ceeSSean Christopherson 	 * In x2APIC mode, the LDR is read-only and derived directly from the
34972c70ceeSSean Christopherson 	 * x2APIC ID, thus is guaranteed to be addressable.  KVM reuses
35072c70ceeSSean Christopherson 	 * kvm_apic_map.phys_map to optimize logical mode x2APIC interrupts by
35172c70ceeSSean Christopherson 	 * reversing the LDR calculation to get cluster of APICs, i.e. no
35272c70ceeSSean Christopherson 	 * additional work is required.
35372c70ceeSSean Christopherson 	 */
3544b7c3f6dSSean Christopherson 	if (apic_x2apic_mode(apic))
35572c70ceeSSean Christopherson 		return;
35672c70ceeSSean Christopherson 
35772c70ceeSSean Christopherson 	if (WARN_ON_ONCE(!kvm_apic_map_get_logical_dest(new, ldr,
35872c70ceeSSean Christopherson 							&cluster, &mask))) {
35972c70ceeSSean Christopherson 		new->logical_mode = KVM_APIC_MODE_MAP_DISABLED;
36072c70ceeSSean Christopherson 		return;
36172c70ceeSSean Christopherson 	}
36272c70ceeSSean Christopherson 
36372c70ceeSSean Christopherson 	if (!mask)
36472c70ceeSSean Christopherson 		return;
36572c70ceeSSean Christopherson 
36672c70ceeSSean Christopherson 	ldr = ffs(mask) - 1;
36772c70ceeSSean Christopherson 	if (!is_power_of_2(mask) || cluster[ldr])
36872c70ceeSSean Christopherson 		new->logical_mode = KVM_APIC_MODE_MAP_DISABLED;
36972c70ceeSSean Christopherson 	else
37072c70ceeSSean Christopherson 		cluster[ldr] = apic;
37172c70ceeSSean Christopherson }
37272c70ceeSSean Christopherson 
37344d52717SPaolo Bonzini /*
37444d52717SPaolo Bonzini  * CLEAN -> DIRTY and UPDATE_IN_PROGRESS -> DIRTY changes happen without a lock.
37544d52717SPaolo Bonzini  *
37644d52717SPaolo Bonzini  * DIRTY -> UPDATE_IN_PROGRESS and UPDATE_IN_PROGRESS -> CLEAN happen with
37744d52717SPaolo Bonzini  * apic_map_lock_held.
37844d52717SPaolo Bonzini  */
37944d52717SPaolo Bonzini enum {
38044d52717SPaolo Bonzini 	CLEAN,
38144d52717SPaolo Bonzini 	UPDATE_IN_PROGRESS,
38244d52717SPaolo Bonzini 	DIRTY
38344d52717SPaolo Bonzini };
38444d52717SPaolo Bonzini 
kvm_recalculate_apic_map(struct kvm * kvm)3854abaffceSWanpeng Li void kvm_recalculate_apic_map(struct kvm *kvm)
3861e08ec4aSGleb Natapov {
3871e08ec4aSGleb Natapov 	struct kvm_apic_map *new, *old = NULL;
3881e08ec4aSGleb Natapov 	struct kvm_vcpu *vcpu;
38946808a4cSMarc Zyngier 	unsigned long i;
3906e500439SRadim Krčmář 	u32 max_id = 255; /* enough space for any xAPIC ID */
39141e90a69SSean Christopherson 	bool xapic_id_mismatch;
39241e90a69SSean Christopherson 	int r;
3931e08ec4aSGleb Natapov 
39444d52717SPaolo Bonzini 	/* Read kvm->arch.apic_map_dirty before kvm->arch.apic_map.  */
39544d52717SPaolo Bonzini 	if (atomic_read_acquire(&kvm->arch.apic_map_dirty) == CLEAN)
3964abaffceSWanpeng Li 		return;
3974abaffceSWanpeng Li 
398c2f79a65SSean Christopherson 	WARN_ONCE(!irqchip_in_kernel(kvm),
399c2f79a65SSean Christopherson 		  "Dirty APIC map without an in-kernel local APIC");
400c2f79a65SSean Christopherson 
4011e08ec4aSGleb Natapov 	mutex_lock(&kvm->arch.apic_map_lock);
40241e90a69SSean Christopherson 
40341e90a69SSean Christopherson retry:
40444d52717SPaolo Bonzini 	/*
40541e90a69SSean Christopherson 	 * Read kvm->arch.apic_map_dirty before kvm->arch.apic_map (if clean)
40641e90a69SSean Christopherson 	 * or the APIC registers (if dirty).  Note, on retry the map may have
40741e90a69SSean Christopherson 	 * not yet been marked dirty by whatever task changed a vCPU's x2APIC
40841e90a69SSean Christopherson 	 * ID, i.e. the map may still show up as in-progress.  In that case
40941e90a69SSean Christopherson 	 * this task still needs to retry and complete its calculation.
41044d52717SPaolo Bonzini 	 */
41144d52717SPaolo Bonzini 	if (atomic_cmpxchg_acquire(&kvm->arch.apic_map_dirty,
41244d52717SPaolo Bonzini 				   DIRTY, UPDATE_IN_PROGRESS) == CLEAN) {
4134abaffceSWanpeng Li 		/* Someone else has updated the map. */
4144abaffceSWanpeng Li 		mutex_unlock(&kvm->arch.apic_map_lock);
4154abaffceSWanpeng Li 		return;
4164abaffceSWanpeng Li 	}
4171e08ec4aSGleb Natapov 
41841e90a69SSean Christopherson 	/*
41941e90a69SSean Christopherson 	 * Reset the mismatch flag between attempts so that KVM does the right
42041e90a69SSean Christopherson 	 * thing if a vCPU changes its xAPIC ID, but do NOT reset max_id, i.e.
42141e90a69SSean Christopherson 	 * keep max_id strictly increasing.  Disallowing max_id from shrinking
42241e90a69SSean Christopherson 	 * ensures KVM won't get stuck in an infinite loop, e.g. if the vCPU
42341e90a69SSean Christopherson 	 * with the highest x2APIC ID is toggling its APIC on and off.
42441e90a69SSean Christopherson 	 */
42541e90a69SSean Christopherson 	xapic_id_mismatch = false;
42641e90a69SSean Christopherson 
4270ca52e7bSRadim Krčmář 	kvm_for_each_vcpu(i, vcpu, kvm)
4280ca52e7bSRadim Krčmář 		if (kvm_apic_present(vcpu))
4296e500439SRadim Krčmář 			max_id = max(max_id, kvm_x2apic_id(vcpu->arch.apic));
4300ca52e7bSRadim Krčmář 
431a7c3e901SMichal Hocko 	new = kvzalloc(sizeof(struct kvm_apic_map) +
432254272ceSBen Gardon 	                   sizeof(struct kvm_lapic *) * ((u64)max_id + 1),
433254272ceSBen Gardon 			   GFP_KERNEL_ACCOUNT);
4340ca52e7bSRadim Krčmář 
4351e08ec4aSGleb Natapov 	if (!new)
4361e08ec4aSGleb Natapov 		goto out;
4371e08ec4aSGleb Natapov 
4380ca52e7bSRadim Krčmář 	new->max_apic_id = max_id;
43935366901SSean Christopherson 	new->logical_mode = KVM_APIC_MODE_SW_DISABLED;
4400ca52e7bSRadim Krčmář 
441173beedcSNadav Amit 	kvm_for_each_vcpu(i, vcpu, kvm) {
442df04d1d1SRadim Krčmář 		if (!kvm_apic_present(vcpu))
443df04d1d1SRadim Krčmář 			continue;
444df04d1d1SRadim Krčmář 
44541e90a69SSean Christopherson 		r = kvm_recalculate_phys_map(new, vcpu, &xapic_id_mismatch);
44641e90a69SSean Christopherson 		if (r) {
4475b84b029SSean Christopherson 			kvfree(new);
4485b84b029SSean Christopherson 			new = NULL;
44941e90a69SSean Christopherson 			if (r == -E2BIG) {
45041e90a69SSean Christopherson 				cond_resched();
45141e90a69SSean Christopherson 				goto retry;
45241e90a69SSean Christopherson 			}
45341e90a69SSean Christopherson 
4545b84b029SSean Christopherson 			goto out;
4553b5a5ffaSRadim Krčmář 		}
4563b5a5ffaSRadim Krčmář 
45772c70ceeSSean Christopherson 		kvm_recalculate_logical_map(new, vcpu);
4581e08ec4aSGleb Natapov 	}
4591e08ec4aSGleb Natapov out:
4605063c41bSSean Christopherson 	/*
4615063c41bSSean Christopherson 	 * The optimized map is effectively KVM's internal version of APICv,
4625063c41bSSean Christopherson 	 * and all unwanted aliasing that results in disabling the optimized
4635063c41bSSean Christopherson 	 * map also applies to APICv.
4645063c41bSSean Christopherson 	 */
4655063c41bSSean Christopherson 	if (!new)
4665063c41bSSean Christopherson 		kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_PHYSICAL_ID_ALIASED);
4675063c41bSSean Christopherson 	else
4685063c41bSSean Christopherson 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_PHYSICAL_ID_ALIASED);
4695063c41bSSean Christopherson 
4709a364857SSean Christopherson 	if (!new || new->logical_mode == KVM_APIC_MODE_MAP_DISABLED)
4719a364857SSean Christopherson 		kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_LOGICAL_ID_ALIASED);
4729a364857SSean Christopherson 	else
4739a364857SSean Christopherson 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_LOGICAL_ID_ALIASED);
4749a364857SSean Christopherson 
475d471bd85SGreg Edwards 	if (xapic_id_mismatch)
476d471bd85SGreg Edwards 		kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_APIC_ID_MODIFIED);
477d471bd85SGreg Edwards 	else
478d471bd85SGreg Edwards 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_APIC_ID_MODIFIED);
479d471bd85SGreg Edwards 
4801e08ec4aSGleb Natapov 	old = rcu_dereference_protected(kvm->arch.apic_map,
4811e08ec4aSGleb Natapov 			lockdep_is_held(&kvm->arch.apic_map_lock));
4821e08ec4aSGleb Natapov 	rcu_assign_pointer(kvm->arch.apic_map, new);
4834abaffceSWanpeng Li 	/*
48444d52717SPaolo Bonzini 	 * Write kvm->arch.apic_map before clearing apic->apic_map_dirty.
48544d52717SPaolo Bonzini 	 * If another update has come in, leave it DIRTY.
4864abaffceSWanpeng Li 	 */
48744d52717SPaolo Bonzini 	atomic_cmpxchg_release(&kvm->arch.apic_map_dirty,
48844d52717SPaolo Bonzini 			       UPDATE_IN_PROGRESS, CLEAN);
4891e08ec4aSGleb Natapov 	mutex_unlock(&kvm->arch.apic_map_lock);
4901e08ec4aSGleb Natapov 
4911e08ec4aSGleb Natapov 	if (old)
492af1bae54SRadim Krčmář 		call_rcu(&old->rcu, kvm_apic_map_free);
493c7c9c56cSYang Zhang 
494b053b2aeSSteve Rutherford 	kvm_make_scan_ioapic_request(kvm);
4951e08ec4aSGleb Natapov }
4961e08ec4aSGleb Natapov 
apic_set_spiv(struct kvm_lapic * apic,u32 val)4971e1b6c26SNadav Amit static inline void apic_set_spiv(struct kvm_lapic *apic, u32 val)
4981e1b6c26SNadav Amit {
499e462755cSRadim Krčmář 	bool enabled = val & APIC_SPIV_APIC_ENABLED;
5001e1b6c26SNadav Amit 
5011e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_SPIV, val);
502e462755cSRadim Krčmář 
503e462755cSRadim Krčmář 	if (enabled != apic->sw_enabled) {
504e462755cSRadim Krčmář 		apic->sw_enabled = enabled;
505eb1ff0a9SPeng Hao 		if (enabled)
5066e4e3b4dSCun Li 			static_branch_slow_dec_deferred(&apic_sw_disabled);
507eb1ff0a9SPeng Hao 		else
5086e4e3b4dSCun Li 			static_branch_inc(&apic_sw_disabled.key);
509b14c876bSRadim Krcmar 
51044d52717SPaolo Bonzini 		atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
5111e1b6c26SNadav Amit 	}
5122f15d027SVitaly Kuznetsov 
5132f15d027SVitaly Kuznetsov 	/* Check if there are APF page ready requests pending */
5148e62bf2bSDavid Woodhouse 	if (enabled) {
5152f15d027SVitaly Kuznetsov 		kvm_make_request(KVM_REQ_APF_READY, apic->vcpu);
5168e62bf2bSDavid Woodhouse 		kvm_xen_sw_enable_lapic(apic->vcpu);
5178e62bf2bSDavid Woodhouse 	}
5181e1b6c26SNadav Amit }
5191e1b6c26SNadav Amit 
kvm_apic_set_xapic_id(struct kvm_lapic * apic,u8 id)520a92e2543SRadim Krčmář static inline void kvm_apic_set_xapic_id(struct kvm_lapic *apic, u8 id)
5211e08ec4aSGleb Natapov {
5221e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_ID, id << 24);
52344d52717SPaolo Bonzini 	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
5241e08ec4aSGleb Natapov }
5251e08ec4aSGleb Natapov 
kvm_apic_set_ldr(struct kvm_lapic * apic,u32 id)5261e08ec4aSGleb Natapov static inline void kvm_apic_set_ldr(struct kvm_lapic *apic, u32 id)
5271e08ec4aSGleb Natapov {
5281e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_LDR, id);
52944d52717SPaolo Bonzini 	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
5301e08ec4aSGleb Natapov }
5311e08ec4aSGleb Natapov 
kvm_apic_set_dfr(struct kvm_lapic * apic,u32 val)532ae6f2496SWanpeng Li static inline void kvm_apic_set_dfr(struct kvm_lapic *apic, u32 val)
533ae6f2496SWanpeng Li {
534ae6f2496SWanpeng Li 	kvm_lapic_set_reg(apic, APIC_DFR, val);
535ae6f2496SWanpeng Li 	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
536ae6f2496SWanpeng Li }
537ae6f2496SWanpeng Li 
kvm_apic_set_x2apic_id(struct kvm_lapic * apic,u32 id)538a92e2543SRadim Krčmář static inline void kvm_apic_set_x2apic_id(struct kvm_lapic *apic, u32 id)
539257b9a5fSRadim Krčmář {
540e872fa94SDr. David Alan Gilbert 	u32 ldr = kvm_apic_calc_x2apic_ldr(id);
541257b9a5fSRadim Krčmář 
5426e500439SRadim Krčmář 	WARN_ON_ONCE(id != apic->vcpu->vcpu_id);
5436e500439SRadim Krčmář 
544a92e2543SRadim Krčmář 	kvm_lapic_set_reg(apic, APIC_ID, id);
5451e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_LDR, ldr);
54644d52717SPaolo Bonzini 	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
547257b9a5fSRadim Krčmář }
548257b9a5fSRadim Krčmář 
apic_lvt_enabled(struct kvm_lapic * apic,int lvt_type)549edf88417SAvi Kivity static inline int apic_lvt_enabled(struct kvm_lapic *apic, int lvt_type)
550edf88417SAvi Kivity {
551dfb95954SSuravee Suthikulpanit 	return !(kvm_lapic_get_reg(apic, lvt_type) & APIC_LVT_MASKED);
552edf88417SAvi Kivity }
553edf88417SAvi Kivity 
apic_lvtt_oneshot(struct kvm_lapic * apic)554a3e06bbeSLiu, Jinsong static inline int apic_lvtt_oneshot(struct kvm_lapic *apic)
555a3e06bbeSLiu, Jinsong {
556f30ebc31SRadim Krčmář 	return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_ONESHOT;
557a3e06bbeSLiu, Jinsong }
558a3e06bbeSLiu, Jinsong 
apic_lvtt_period(struct kvm_lapic * apic)559edf88417SAvi Kivity static inline int apic_lvtt_period(struct kvm_lapic *apic)
560edf88417SAvi Kivity {
561f30ebc31SRadim Krčmář 	return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_PERIODIC;
562a3e06bbeSLiu, Jinsong }
563a3e06bbeSLiu, Jinsong 
apic_lvtt_tscdeadline(struct kvm_lapic * apic)564a3e06bbeSLiu, Jinsong static inline int apic_lvtt_tscdeadline(struct kvm_lapic *apic)
565a3e06bbeSLiu, Jinsong {
566f30ebc31SRadim Krčmář 	return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_TSCDEADLINE;
567edf88417SAvi Kivity }
568edf88417SAvi Kivity 
apic_lvt_nmi_mode(u32 lvt_val)569cc6e462cSJan Kiszka static inline int apic_lvt_nmi_mode(u32 lvt_val)
570cc6e462cSJan Kiszka {
571cc6e462cSJan Kiszka 	return (lvt_val & (APIC_MODE_MASK | APIC_LVT_MASKED)) == APIC_DM_NMI;
572cc6e462cSJan Kiszka }
573cc6e462cSJan Kiszka 
kvm_lapic_lvt_supported(struct kvm_lapic * apic,int lvt_index)5744b903561SJue Wang static inline bool kvm_lapic_lvt_supported(struct kvm_lapic *apic, int lvt_index)
5754b903561SJue Wang {
5764b903561SJue Wang 	return apic->nr_lvt_entries > lvt_index;
5774b903561SJue Wang }
5784b903561SJue Wang 
kvm_apic_calc_nr_lvt_entries(struct kvm_vcpu * vcpu)57903d84f96SSean Christopherson static inline int kvm_apic_calc_nr_lvt_entries(struct kvm_vcpu *vcpu)
58003d84f96SSean Christopherson {
58103d84f96SSean Christopherson 	return KVM_APIC_MAX_NR_LVT_ENTRIES - !(vcpu->arch.mcg_cap & MCG_CMCI_P);
58203d84f96SSean Christopherson }
58303d84f96SSean Christopherson 
kvm_apic_set_version(struct kvm_vcpu * vcpu)584fc61b800SGleb Natapov void kvm_apic_set_version(struct kvm_vcpu *vcpu)
585fc61b800SGleb Natapov {
586fc61b800SGleb Natapov 	struct kvm_lapic *apic = vcpu->arch.apic;
5874b903561SJue Wang 	u32 v = 0;
588fc61b800SGleb Natapov 
589bce87cceSPaolo Bonzini 	if (!lapic_in_kernel(vcpu))
590fc61b800SGleb Natapov 		return;
591fc61b800SGleb Natapov 
5924b903561SJue Wang 	v = APIC_VERSION | ((apic->nr_lvt_entries - 1) << 16);
5934b903561SJue Wang 
5940bcc3fb9SVitaly Kuznetsov 	/*
5950bcc3fb9SVitaly Kuznetsov 	 * KVM emulates 82093AA datasheet (with in-kernel IOAPIC implementation)
5960bcc3fb9SVitaly Kuznetsov 	 * which doesn't have EOI register; Some buggy OSes (e.g. Windows with
5970bcc3fb9SVitaly Kuznetsov 	 * Hyper-V role) disable EOI broadcast in lapic not checking for IOAPIC
5980bcc3fb9SVitaly Kuznetsov 	 * version first and level-triggered interrupts never get EOIed in
5990bcc3fb9SVitaly Kuznetsov 	 * IOAPIC.
6000bcc3fb9SVitaly Kuznetsov 	 */
601565b7820SXiaoyao Li 	if (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) &&
6020bcc3fb9SVitaly Kuznetsov 	    !ioapic_in_kernel(vcpu->kvm))
603fc61b800SGleb Natapov 		v |= APIC_LVR_DIRECTED_EOI;
6041e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_LVR, v);
605fc61b800SGleb Natapov }
606fc61b800SGleb Natapov 
kvm_apic_after_set_mcg_cap(struct kvm_vcpu * vcpu)607f83894b2SSean Christopherson void kvm_apic_after_set_mcg_cap(struct kvm_vcpu *vcpu)
608f83894b2SSean Christopherson {
609f83894b2SSean Christopherson 	int nr_lvt_entries = kvm_apic_calc_nr_lvt_entries(vcpu);
610f83894b2SSean Christopherson 	struct kvm_lapic *apic = vcpu->arch.apic;
611f83894b2SSean Christopherson 	int i;
612f83894b2SSean Christopherson 
613f83894b2SSean Christopherson 	if (!lapic_in_kernel(vcpu) || nr_lvt_entries == apic->nr_lvt_entries)
614f83894b2SSean Christopherson 		return;
615f83894b2SSean Christopherson 
616f83894b2SSean Christopherson 	/* Initialize/mask any "new" LVT entries. */
617f83894b2SSean Christopherson 	for (i = apic->nr_lvt_entries; i < nr_lvt_entries; i++)
618f83894b2SSean Christopherson 		kvm_lapic_set_reg(apic, APIC_LVTx(i), APIC_LVT_MASKED);
619f83894b2SSean Christopherson 
620f83894b2SSean Christopherson 	apic->nr_lvt_entries = nr_lvt_entries;
621f83894b2SSean Christopherson 
622f83894b2SSean Christopherson 	/* The number of LVT entries is reflected in the version register. */
623f83894b2SSean Christopherson 	kvm_apic_set_version(vcpu);
624f83894b2SSean Christopherson }
625f83894b2SSean Christopherson 
6261d8c681fSJue Wang static const unsigned int apic_lvt_mask[KVM_APIC_MAX_NR_LVT_ENTRIES] = {
6271d8c681fSJue Wang 	[LVT_TIMER] = LVT_MASK,      /* timer mode mask added at runtime */
6281d8c681fSJue Wang 	[LVT_THERMAL_MONITOR] = LVT_MASK | APIC_MODE_MASK,
6291d8c681fSJue Wang 	[LVT_PERFORMANCE_COUNTER] = LVT_MASK | APIC_MODE_MASK,
6301d8c681fSJue Wang 	[LVT_LINT0] = LINT_MASK,
6311d8c681fSJue Wang 	[LVT_LINT1] = LINT_MASK,
6324b903561SJue Wang 	[LVT_ERROR] = LVT_MASK,
6334b903561SJue Wang 	[LVT_CMCI] = LVT_MASK | APIC_MODE_MASK
634edf88417SAvi Kivity };
635edf88417SAvi Kivity 
find_highest_vector(void * bitmap)636edf88417SAvi Kivity static int find_highest_vector(void *bitmap)
637edf88417SAvi Kivity {
638ecba9a52STakuya Yoshikawa 	int vec;
639ecba9a52STakuya Yoshikawa 	u32 *reg;
640edf88417SAvi Kivity 
641ecba9a52STakuya Yoshikawa 	for (vec = MAX_APIC_VECTOR - APIC_VECTORS_PER_REG;
642ecba9a52STakuya Yoshikawa 	     vec >= 0; vec -= APIC_VECTORS_PER_REG) {
643ecba9a52STakuya Yoshikawa 		reg = bitmap + REG_POS(vec);
644ecba9a52STakuya Yoshikawa 		if (*reg)
645810e6defSPaolo Bonzini 			return __fls(*reg) + vec;
646ecba9a52STakuya Yoshikawa 	}
647edf88417SAvi Kivity 
648edf88417SAvi Kivity 	return -1;
649edf88417SAvi Kivity }
650edf88417SAvi Kivity 
count_vectors(void * bitmap)6518680b94bSMichael S. Tsirkin static u8 count_vectors(void *bitmap)
6528680b94bSMichael S. Tsirkin {
653ecba9a52STakuya Yoshikawa 	int vec;
654ecba9a52STakuya Yoshikawa 	u32 *reg;
6558680b94bSMichael S. Tsirkin 	u8 count = 0;
656ecba9a52STakuya Yoshikawa 
657ecba9a52STakuya Yoshikawa 	for (vec = 0; vec < MAX_APIC_VECTOR; vec += APIC_VECTORS_PER_REG) {
658ecba9a52STakuya Yoshikawa 		reg = bitmap + REG_POS(vec);
659ecba9a52STakuya Yoshikawa 		count += hweight32(*reg);
660ecba9a52STakuya Yoshikawa 	}
661ecba9a52STakuya Yoshikawa 
6628680b94bSMichael S. Tsirkin 	return count;
6638680b94bSMichael S. Tsirkin }
6648680b94bSMichael S. Tsirkin 
__kvm_apic_update_irr(u32 * pir,void * regs,int * max_irr)665e7387b0eSLiran Alon bool __kvm_apic_update_irr(u32 *pir, void *regs, int *max_irr)
666a20ed54dSYang Zhang {
667810e6defSPaolo Bonzini 	u32 i, vec;
668e7387b0eSLiran Alon 	u32 pir_val, irr_val, prev_irr_val;
669e7387b0eSLiran Alon 	int max_updated_irr;
670e7387b0eSLiran Alon 
671e7387b0eSLiran Alon 	max_updated_irr = -1;
672e7387b0eSLiran Alon 	*max_irr = -1;
673a20ed54dSYang Zhang 
674810e6defSPaolo Bonzini 	for (i = vec = 0; i <= 7; i++, vec += 32) {
675514946d1SMaxim Levitsky 		u32 *p_irr = (u32 *)(regs + APIC_IRR + i * 0x10);
676514946d1SMaxim Levitsky 
677514946d1SMaxim Levitsky 		irr_val = *p_irr;
678ad361091SPaolo Bonzini 		pir_val = READ_ONCE(pir[i]);
679514946d1SMaxim Levitsky 
680ad361091SPaolo Bonzini 		if (pir_val) {
681514946d1SMaxim Levitsky 			pir_val = xchg(&pir[i], 0);
682514946d1SMaxim Levitsky 
683e7387b0eSLiran Alon 			prev_irr_val = irr_val;
684514946d1SMaxim Levitsky 			do {
685514946d1SMaxim Levitsky 				irr_val = prev_irr_val | pir_val;
686514946d1SMaxim Levitsky 			} while (prev_irr_val != irr_val &&
687514946d1SMaxim Levitsky 				 !try_cmpxchg(p_irr, &prev_irr_val, irr_val));
688514946d1SMaxim Levitsky 
689514946d1SMaxim Levitsky 			if (prev_irr_val != irr_val)
690514946d1SMaxim Levitsky 				max_updated_irr = __fls(irr_val ^ prev_irr_val) + vec;
691a20ed54dSYang Zhang 		}
692810e6defSPaolo Bonzini 		if (irr_val)
693e7387b0eSLiran Alon 			*max_irr = __fls(irr_val) + vec;
694a20ed54dSYang Zhang 	}
695810e6defSPaolo Bonzini 
696e7387b0eSLiran Alon 	return ((max_updated_irr != -1) &&
697e7387b0eSLiran Alon 		(max_updated_irr == *max_irr));
698ad361091SPaolo Bonzini }
699705699a1SWincy Van EXPORT_SYMBOL_GPL(__kvm_apic_update_irr);
700705699a1SWincy Van 
kvm_apic_update_irr(struct kvm_vcpu * vcpu,u32 * pir,int * max_irr)701e7387b0eSLiran Alon bool kvm_apic_update_irr(struct kvm_vcpu *vcpu, u32 *pir, int *max_irr)
702705699a1SWincy Van {
703705699a1SWincy Van 	struct kvm_lapic *apic = vcpu->arch.apic;
704cff540ebSMaxim Levitsky 	bool irr_updated = __kvm_apic_update_irr(pir, apic->regs, max_irr);
705705699a1SWincy Van 
706cff540ebSMaxim Levitsky 	if (unlikely(!apic->apicv_active && irr_updated))
707cff540ebSMaxim Levitsky 		apic->irr_pending = true;
708cff540ebSMaxim Levitsky 	return irr_updated;
709705699a1SWincy Van }
710a20ed54dSYang Zhang EXPORT_SYMBOL_GPL(kvm_apic_update_irr);
711a20ed54dSYang Zhang 
apic_search_irr(struct kvm_lapic * apic)71233e4c686SGleb Natapov static inline int apic_search_irr(struct kvm_lapic *apic)
713edf88417SAvi Kivity {
71433e4c686SGleb Natapov 	return find_highest_vector(apic->regs + APIC_IRR);
715edf88417SAvi Kivity }
716edf88417SAvi Kivity 
apic_find_highest_irr(struct kvm_lapic * apic)717edf88417SAvi Kivity static inline int apic_find_highest_irr(struct kvm_lapic *apic)
718edf88417SAvi Kivity {
719edf88417SAvi Kivity 	int result;
720edf88417SAvi Kivity 
721c7c9c56cSYang Zhang 	/*
722c7c9c56cSYang Zhang 	 * Note that irr_pending is just a hint. It will be always
723c7c9c56cSYang Zhang 	 * true with virtual interrupt delivery enabled.
724c7c9c56cSYang Zhang 	 */
72533e4c686SGleb Natapov 	if (!apic->irr_pending)
72633e4c686SGleb Natapov 		return -1;
72733e4c686SGleb Natapov 
72833e4c686SGleb Natapov 	result = apic_search_irr(apic);
729edf88417SAvi Kivity 	ASSERT(result == -1 || result >= 16);
730edf88417SAvi Kivity 
731edf88417SAvi Kivity 	return result;
732edf88417SAvi Kivity }
733edf88417SAvi Kivity 
apic_clear_irr(int vec,struct kvm_lapic * apic)73433e4c686SGleb Natapov static inline void apic_clear_irr(int vec, struct kvm_lapic *apic)
73533e4c686SGleb Natapov {
736ce0a58f4SSean Christopherson 	if (unlikely(apic->apicv_active)) {
737b95234c8SPaolo Bonzini 		/* need to update RVI */
738ee171d2fSWei Yang 		kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
73989604647SWei Wang 		kvm_x86_call(hwapic_irr_update)(apic->vcpu,
740ce0a58f4SSean Christopherson 						apic_find_highest_irr(apic));
741f210f757SNadav Amit 	} else {
742f210f757SNadav Amit 		apic->irr_pending = false;
743ee171d2fSWei Yang 		kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
744f210f757SNadav Amit 		if (apic_search_irr(apic) != -1)
745f210f757SNadav Amit 			apic->irr_pending = true;
74656cc2406SWanpeng Li 	}
74733e4c686SGleb Natapov }
74833e4c686SGleb Natapov 
kvm_apic_clear_irr(struct kvm_vcpu * vcpu,int vec)74925bb2cf9SSean Christopherson void kvm_apic_clear_irr(struct kvm_vcpu *vcpu, int vec)
75025bb2cf9SSean Christopherson {
75125bb2cf9SSean Christopherson 	apic_clear_irr(vec, vcpu->arch.apic);
75225bb2cf9SSean Christopherson }
75325bb2cf9SSean Christopherson EXPORT_SYMBOL_GPL(kvm_apic_clear_irr);
75425bb2cf9SSean Christopherson 
apic_set_isr(int vec,struct kvm_lapic * apic)7558680b94bSMichael S. Tsirkin static inline void apic_set_isr(int vec, struct kvm_lapic *apic)
7568680b94bSMichael S. Tsirkin {
75756cc2406SWanpeng Li 	if (__apic_test_and_set_vector(vec, apic->regs + APIC_ISR))
75856cc2406SWanpeng Li 		return;
75956cc2406SWanpeng Li 
76056cc2406SWanpeng Li 	/*
76156cc2406SWanpeng Li 	 * With APIC virtualization enabled, all caching is disabled
76256cc2406SWanpeng Li 	 * because the processor can modify ISR under the hood.  Instead
76356cc2406SWanpeng Li 	 * just set SVI.
76456cc2406SWanpeng Li 	 */
765ce0a58f4SSean Christopherson 	if (unlikely(apic->apicv_active))
76689604647SWei Wang 		kvm_x86_call(hwapic_isr_update)(vec);
76756cc2406SWanpeng Li 	else {
7688680b94bSMichael S. Tsirkin 		++apic->isr_count;
7698680b94bSMichael S. Tsirkin 		BUG_ON(apic->isr_count > MAX_APIC_VECTOR);
7708680b94bSMichael S. Tsirkin 		/*
7718680b94bSMichael S. Tsirkin 		 * ISR (in service register) bit is set when injecting an interrupt.
7728680b94bSMichael S. Tsirkin 		 * The highest vector is injected. Thus the latest bit set matches
7738680b94bSMichael S. Tsirkin 		 * the highest bit in ISR.
7748680b94bSMichael S. Tsirkin 		 */
7758680b94bSMichael S. Tsirkin 		apic->highest_isr_cache = vec;
7768680b94bSMichael S. Tsirkin 	}
77756cc2406SWanpeng Li }
7788680b94bSMichael S. Tsirkin 
apic_find_highest_isr(struct kvm_lapic * apic)779fc57ac2cSPaolo Bonzini static inline int apic_find_highest_isr(struct kvm_lapic *apic)
780fc57ac2cSPaolo Bonzini {
781fc57ac2cSPaolo Bonzini 	int result;
782fc57ac2cSPaolo Bonzini 
783fc57ac2cSPaolo Bonzini 	/*
784fc57ac2cSPaolo Bonzini 	 * Note that isr_count is always 1, and highest_isr_cache
785fc57ac2cSPaolo Bonzini 	 * is always -1, with APIC virtualization enabled.
786fc57ac2cSPaolo Bonzini 	 */
787fc57ac2cSPaolo Bonzini 	if (!apic->isr_count)
788fc57ac2cSPaolo Bonzini 		return -1;
789fc57ac2cSPaolo Bonzini 	if (likely(apic->highest_isr_cache != -1))
790fc57ac2cSPaolo Bonzini 		return apic->highest_isr_cache;
791fc57ac2cSPaolo Bonzini 
792fc57ac2cSPaolo Bonzini 	result = find_highest_vector(apic->regs + APIC_ISR);
793fc57ac2cSPaolo Bonzini 	ASSERT(result == -1 || result >= 16);
794fc57ac2cSPaolo Bonzini 
795fc57ac2cSPaolo Bonzini 	return result;
796fc57ac2cSPaolo Bonzini }
797fc57ac2cSPaolo Bonzini 
apic_clear_isr(int vec,struct kvm_lapic * apic)7988680b94bSMichael S. Tsirkin static inline void apic_clear_isr(int vec, struct kvm_lapic *apic)
7998680b94bSMichael S. Tsirkin {
800fc57ac2cSPaolo Bonzini 	if (!__apic_test_and_clear_vector(vec, apic->regs + APIC_ISR))
801fc57ac2cSPaolo Bonzini 		return;
802fc57ac2cSPaolo Bonzini 
803fc57ac2cSPaolo Bonzini 	/*
804fc57ac2cSPaolo Bonzini 	 * We do get here for APIC virtualization enabled if the guest
805fc57ac2cSPaolo Bonzini 	 * uses the Hyper-V APIC enlightenment.  In this case we may need
806fc57ac2cSPaolo Bonzini 	 * to trigger a new interrupt delivery by writing the SVI field;
807fc57ac2cSPaolo Bonzini 	 * on the other hand isr_count and highest_isr_cache are unused
808fc57ac2cSPaolo Bonzini 	 * and must be left alone.
809fc57ac2cSPaolo Bonzini 	 */
810ce0a58f4SSean Christopherson 	if (unlikely(apic->apicv_active))
81189604647SWei Wang 		kvm_x86_call(hwapic_isr_update)(apic_find_highest_isr(apic));
812fc57ac2cSPaolo Bonzini 	else {
8138680b94bSMichael S. Tsirkin 		--apic->isr_count;
8148680b94bSMichael S. Tsirkin 		BUG_ON(apic->isr_count < 0);
8158680b94bSMichael S. Tsirkin 		apic->highest_isr_cache = -1;
8168680b94bSMichael S. Tsirkin 	}
817fc57ac2cSPaolo Bonzini }
8188680b94bSMichael S. Tsirkin 
kvm_lapic_find_highest_irr(struct kvm_vcpu * vcpu)819edf88417SAvi Kivity int kvm_lapic_find_highest_irr(struct kvm_vcpu *vcpu)
820edf88417SAvi Kivity {
82133e4c686SGleb Natapov 	/* This may race with setting of irr in __apic_accept_irq() and
82233e4c686SGleb Natapov 	 * value returned may be wrong, but kvm_vcpu_kick() in __apic_accept_irq
82333e4c686SGleb Natapov 	 * will cause vmexit immediately and the value will be recalculated
82433e4c686SGleb Natapov 	 * on the next vmentry.
82533e4c686SGleb Natapov 	 */
826f8543d6aSPaolo Bonzini 	return apic_find_highest_irr(vcpu->arch.apic);
827edf88417SAvi Kivity }
82876dfafd5SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_lapic_find_highest_irr);
829edf88417SAvi Kivity 
8306da7e3f6SGleb Natapov static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
831b4f2225cSYang Zhang 			     int vector, int level, int trig_mode,
8329e4aabe2SJoerg Roedel 			     struct dest_map *dest_map);
8336da7e3f6SGleb Natapov 
kvm_apic_set_irq(struct kvm_vcpu * vcpu,struct kvm_lapic_irq * irq,struct dest_map * dest_map)834b4f2225cSYang Zhang int kvm_apic_set_irq(struct kvm_vcpu *vcpu, struct kvm_lapic_irq *irq,
8359e4aabe2SJoerg Roedel 		     struct dest_map *dest_map)
836edf88417SAvi Kivity {
837edf88417SAvi Kivity 	struct kvm_lapic *apic = vcpu->arch.apic;
838edf88417SAvi Kivity 
83958c2dde1SGleb Natapov 	return __apic_accept_irq(apic, irq->delivery_mode, irq->vector,
840b4f2225cSYang Zhang 			irq->level, irq->trig_mode, dest_map);
841edf88417SAvi Kivity }
842edf88417SAvi Kivity 
__pv_send_ipi(unsigned long * ipi_bitmap,struct kvm_apic_map * map,struct kvm_lapic_irq * irq,u32 min)8431a686237SMiaohe Lin static int __pv_send_ipi(unsigned long *ipi_bitmap, struct kvm_apic_map *map,
8441a686237SMiaohe Lin 			 struct kvm_lapic_irq *irq, u32 min)
8451a686237SMiaohe Lin {
8461a686237SMiaohe Lin 	int i, count = 0;
8471a686237SMiaohe Lin 	struct kvm_vcpu *vcpu;
8481a686237SMiaohe Lin 
8491a686237SMiaohe Lin 	if (min > map->max_apic_id)
8501a686237SMiaohe Lin 		return 0;
8511a686237SMiaohe Lin 
8521a686237SMiaohe Lin 	for_each_set_bit(i, ipi_bitmap,
8531a686237SMiaohe Lin 		min((u32)BITS_PER_LONG, (map->max_apic_id - min + 1))) {
8541a686237SMiaohe Lin 		if (map->phys_map[min + i]) {
8551a686237SMiaohe Lin 			vcpu = map->phys_map[min + i]->vcpu;
8561a686237SMiaohe Lin 			count += kvm_apic_set_irq(vcpu, irq, NULL);
8571a686237SMiaohe Lin 		}
8581a686237SMiaohe Lin 	}
8591a686237SMiaohe Lin 
8601a686237SMiaohe Lin 	return count;
8611a686237SMiaohe Lin }
8621a686237SMiaohe Lin 
kvm_pv_send_ipi(struct kvm * kvm,unsigned long ipi_bitmap_low,unsigned long ipi_bitmap_high,u32 min,unsigned long icr,int op_64_bit)8634180bf1bSWanpeng Li int kvm_pv_send_ipi(struct kvm *kvm, unsigned long ipi_bitmap_low,
864bdf7ffc8SWanpeng Li 		    unsigned long ipi_bitmap_high, u32 min,
8654180bf1bSWanpeng Li 		    unsigned long icr, int op_64_bit)
8664180bf1bSWanpeng Li {
8674180bf1bSWanpeng Li 	struct kvm_apic_map *map;
8684180bf1bSWanpeng Li 	struct kvm_lapic_irq irq = {0};
8694180bf1bSWanpeng Li 	int cluster_size = op_64_bit ? 64 : 32;
8701a686237SMiaohe Lin 	int count;
8711a686237SMiaohe Lin 
8721a686237SMiaohe Lin 	if (icr & (APIC_DEST_MASK | APIC_SHORT_MASK))
8731a686237SMiaohe Lin 		return -KVM_EINVAL;
8744180bf1bSWanpeng Li 
8754180bf1bSWanpeng Li 	irq.vector = icr & APIC_VECTOR_MASK;
8764180bf1bSWanpeng Li 	irq.delivery_mode = icr & APIC_MODE_MASK;
8774180bf1bSWanpeng Li 	irq.level = (icr & APIC_INT_ASSERT) != 0;
8784180bf1bSWanpeng Li 	irq.trig_mode = icr & APIC_INT_LEVELTRIG;
8794180bf1bSWanpeng Li 
8804180bf1bSWanpeng Li 	rcu_read_lock();
8814180bf1bSWanpeng Li 	map = rcu_dereference(kvm->arch.apic_map);
8824180bf1bSWanpeng Li 
88338ab012fSWanpeng Li 	count = -EOPNOTSUPP;
8841a686237SMiaohe Lin 	if (likely(map)) {
8851a686237SMiaohe Lin 		count = __pv_send_ipi(&ipi_bitmap_low, map, &irq, min);
8864180bf1bSWanpeng Li 		min += cluster_size;
8871a686237SMiaohe Lin 		count += __pv_send_ipi(&ipi_bitmap_high, map, &irq, min);
888bdf7ffc8SWanpeng Li 	}
8894180bf1bSWanpeng Li 
8904180bf1bSWanpeng Li 	rcu_read_unlock();
8914180bf1bSWanpeng Li 	return count;
8924180bf1bSWanpeng Li }
8934180bf1bSWanpeng Li 
pv_eoi_put_user(struct kvm_vcpu * vcpu,u8 val)894ae7a2a3fSMichael S. Tsirkin static int pv_eoi_put_user(struct kvm_vcpu *vcpu, u8 val)
895ae7a2a3fSMichael S. Tsirkin {
8964e335d9eSPaolo Bonzini 
8974e335d9eSPaolo Bonzini 	return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, &val,
898ae7a2a3fSMichael S. Tsirkin 				      sizeof(val));
899ae7a2a3fSMichael S. Tsirkin }
900ae7a2a3fSMichael S. Tsirkin 
pv_eoi_get_user(struct kvm_vcpu * vcpu,u8 * val)901ae7a2a3fSMichael S. Tsirkin static int pv_eoi_get_user(struct kvm_vcpu *vcpu, u8 *val)
902ae7a2a3fSMichael S. Tsirkin {
9034e335d9eSPaolo Bonzini 
9044e335d9eSPaolo Bonzini 	return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, val,
905ae7a2a3fSMichael S. Tsirkin 				      sizeof(*val));
906ae7a2a3fSMichael S. Tsirkin }
907ae7a2a3fSMichael S. Tsirkin 
pv_eoi_enabled(struct kvm_vcpu * vcpu)908ae7a2a3fSMichael S. Tsirkin static inline bool pv_eoi_enabled(struct kvm_vcpu *vcpu)
909ae7a2a3fSMichael S. Tsirkin {
910ae7a2a3fSMichael S. Tsirkin 	return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
911ae7a2a3fSMichael S. Tsirkin }
912ae7a2a3fSMichael S. Tsirkin 
pv_eoi_set_pending(struct kvm_vcpu * vcpu)913ae7a2a3fSMichael S. Tsirkin static void pv_eoi_set_pending(struct kvm_vcpu *vcpu)
914ae7a2a3fSMichael S. Tsirkin {
915ce5977b1SLi RongQing 	if (pv_eoi_put_user(vcpu, KVM_PV_EOI_ENABLED) < 0)
916ae7a2a3fSMichael S. Tsirkin 		return;
917ce5977b1SLi RongQing 
918ae7a2a3fSMichael S. Tsirkin 	__set_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
919ae7a2a3fSMichael S. Tsirkin }
920ae7a2a3fSMichael S. Tsirkin 
pv_eoi_test_and_clr_pending(struct kvm_vcpu * vcpu)92151b1209cSLi RongQing static bool pv_eoi_test_and_clr_pending(struct kvm_vcpu *vcpu)
922ae7a2a3fSMichael S. Tsirkin {
92351b1209cSLi RongQing 	u8 val;
924ce5977b1SLi RongQing 
92551b1209cSLi RongQing 	if (pv_eoi_get_user(vcpu, &val) < 0)
92651b1209cSLi RongQing 		return false;
92751b1209cSLi RongQing 
92851b1209cSLi RongQing 	val &= KVM_PV_EOI_ENABLED;
92951b1209cSLi RongQing 
93051b1209cSLi RongQing 	if (val && pv_eoi_put_user(vcpu, KVM_PV_EOI_DISABLED) < 0)
93151b1209cSLi RongQing 		return false;
93251b1209cSLi RongQing 
93351b1209cSLi RongQing 	/*
93451b1209cSLi RongQing 	 * Clear pending bit in any case: it will be set again on vmentry.
93551b1209cSLi RongQing 	 * While this might not be ideal from performance point of view,
93651b1209cSLi RongQing 	 * this makes sure pv eoi is only enabled when we know it's safe.
93751b1209cSLi RongQing 	 */
938ae7a2a3fSMichael S. Tsirkin 	__clear_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
93951b1209cSLi RongQing 
94051b1209cSLi RongQing 	return val;
941ae7a2a3fSMichael S. Tsirkin }
942ae7a2a3fSMichael S. Tsirkin 
apic_has_interrupt_for_ppr(struct kvm_lapic * apic,u32 ppr)943b3c045d3SPaolo Bonzini static int apic_has_interrupt_for_ppr(struct kvm_lapic *apic, u32 ppr)
944b3c045d3SPaolo Bonzini {
9453d92789fSPaolo Bonzini 	int highest_irr;
94637c4dbf3SPaolo Bonzini 	if (kvm_x86_ops.sync_pir_to_irr)
94789604647SWei Wang 		highest_irr = kvm_x86_call(sync_pir_to_irr)(apic->vcpu);
94876dfafd5SPaolo Bonzini 	else
9493d92789fSPaolo Bonzini 		highest_irr = apic_find_highest_irr(apic);
950b3c045d3SPaolo Bonzini 	if (highest_irr == -1 || (highest_irr & 0xF0) <= ppr)
951b3c045d3SPaolo Bonzini 		return -1;
952b3c045d3SPaolo Bonzini 	return highest_irr;
953b3c045d3SPaolo Bonzini }
954b3c045d3SPaolo Bonzini 
__apic_update_ppr(struct kvm_lapic * apic,u32 * new_ppr)955b3c045d3SPaolo Bonzini static bool __apic_update_ppr(struct kvm_lapic *apic, u32 *new_ppr)
956edf88417SAvi Kivity {
9573842d135SAvi Kivity 	u32 tpr, isrv, ppr, old_ppr;
958edf88417SAvi Kivity 	int isr;
959edf88417SAvi Kivity 
960dfb95954SSuravee Suthikulpanit 	old_ppr = kvm_lapic_get_reg(apic, APIC_PROCPRI);
961dfb95954SSuravee Suthikulpanit 	tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI);
962edf88417SAvi Kivity 	isr = apic_find_highest_isr(apic);
963edf88417SAvi Kivity 	isrv = (isr != -1) ? isr : 0;
964edf88417SAvi Kivity 
965edf88417SAvi Kivity 	if ((tpr & 0xf0) >= (isrv & 0xf0))
966edf88417SAvi Kivity 		ppr = tpr & 0xff;
967edf88417SAvi Kivity 	else
968edf88417SAvi Kivity 		ppr = isrv & 0xf0;
969edf88417SAvi Kivity 
970b3c045d3SPaolo Bonzini 	*new_ppr = ppr;
971b3c045d3SPaolo Bonzini 	if (old_ppr != ppr)
9721e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, APIC_PROCPRI, ppr);
973b3c045d3SPaolo Bonzini 
974b3c045d3SPaolo Bonzini 	return ppr < old_ppr;
9753842d135SAvi Kivity }
976b3c045d3SPaolo Bonzini 
apic_update_ppr(struct kvm_lapic * apic)977b3c045d3SPaolo Bonzini static void apic_update_ppr(struct kvm_lapic *apic)
978b3c045d3SPaolo Bonzini {
979b3c045d3SPaolo Bonzini 	u32 ppr;
980b3c045d3SPaolo Bonzini 
98126fbbee5SPaolo Bonzini 	if (__apic_update_ppr(apic, &ppr) &&
98226fbbee5SPaolo Bonzini 	    apic_has_interrupt_for_ppr(apic, ppr) != -1)
983b3c045d3SPaolo Bonzini 		kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
984edf88417SAvi Kivity }
985edf88417SAvi Kivity 
kvm_apic_update_ppr(struct kvm_vcpu * vcpu)986eb90f341SPaolo Bonzini void kvm_apic_update_ppr(struct kvm_vcpu *vcpu)
987eb90f341SPaolo Bonzini {
988eb90f341SPaolo Bonzini 	apic_update_ppr(vcpu->arch.apic);
989eb90f341SPaolo Bonzini }
990eb90f341SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_apic_update_ppr);
991eb90f341SPaolo Bonzini 
apic_set_tpr(struct kvm_lapic * apic,u32 tpr)992edf88417SAvi Kivity static void apic_set_tpr(struct kvm_lapic *apic, u32 tpr)
993edf88417SAvi Kivity {
9941e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_TASKPRI, tpr);
995edf88417SAvi Kivity 	apic_update_ppr(apic);
996edf88417SAvi Kivity }
997edf88417SAvi Kivity 
kvm_apic_broadcast(struct kvm_lapic * apic,u32 mda)99803d2249eSRadim Krčmář static bool kvm_apic_broadcast(struct kvm_lapic *apic, u32 mda)
999edf88417SAvi Kivity {
1000b4535b58SRadim Krčmář 	return mda == (apic_x2apic_mode(apic) ?
1001b4535b58SRadim Krčmář 			X2APIC_BROADCAST : APIC_BROADCAST);
1002edf88417SAvi Kivity }
1003edf88417SAvi Kivity 
kvm_apic_match_physical_addr(struct kvm_lapic * apic,u32 mda)100403d2249eSRadim Krčmář static bool kvm_apic_match_physical_addr(struct kvm_lapic *apic, u32 mda)
1005394457a9SNadav Amit {
100603d2249eSRadim Krčmář 	if (kvm_apic_broadcast(apic, mda))
100703d2249eSRadim Krčmář 		return true;
100803d2249eSRadim Krčmář 
10095bd5db38SRadim Krčmář 	/*
10108031d87aSSean Christopherson 	 * Hotplug hack: Accept interrupts for vCPUs in xAPIC mode as if they
10118031d87aSSean Christopherson 	 * were in x2APIC mode if the target APIC ID can't be encoded as an
10128031d87aSSean Christopherson 	 * xAPIC ID.  This allows unique addressing of hotplugged vCPUs (which
10138031d87aSSean Christopherson 	 * start in xAPIC mode) with an APIC ID that is unaddressable in xAPIC
10148031d87aSSean Christopherson 	 * mode.  Match the x2APIC ID if and only if the target APIC ID can't
10158031d87aSSean Christopherson 	 * be encoded in xAPIC to avoid spurious matches against a vCPU that
10168031d87aSSean Christopherson 	 * changed its (addressable) xAPIC ID (which is writable).
10175bd5db38SRadim Krčmář 	 */
10188031d87aSSean Christopherson 	if (apic_x2apic_mode(apic) || mda > 0xff)
10198031d87aSSean Christopherson 		return mda == kvm_x2apic_id(apic);
10205bd5db38SRadim Krčmář 
1021b4535b58SRadim Krčmář 	return mda == kvm_xapic_id(apic);
1022394457a9SNadav Amit }
1023394457a9SNadav Amit 
kvm_apic_match_logical_addr(struct kvm_lapic * apic,u32 mda)102452c233a4SRadim Krčmář static bool kvm_apic_match_logical_addr(struct kvm_lapic *apic, u32 mda)
1025edf88417SAvi Kivity {
10260105d1a5SGleb Natapov 	u32 logical_id;
10270105d1a5SGleb Natapov 
1028394457a9SNadav Amit 	if (kvm_apic_broadcast(apic, mda))
10299368b567SRadim Krčmář 		return true;
1030394457a9SNadav Amit 
1031dfb95954SSuravee Suthikulpanit 	logical_id = kvm_lapic_get_reg(apic, APIC_LDR);
1032edf88417SAvi Kivity 
10339368b567SRadim Krčmář 	if (apic_x2apic_mode(apic))
10348a395363SRadim Krčmář 		return ((logical_id >> 16) == (mda >> 16))
10358a395363SRadim Krčmář 		       && (logical_id & mda & 0xffff) != 0;
10369368b567SRadim Krčmář 
10379368b567SRadim Krčmář 	logical_id = GET_APIC_LOGICAL_ID(logical_id);
1038edf88417SAvi Kivity 
1039dfb95954SSuravee Suthikulpanit 	switch (kvm_lapic_get_reg(apic, APIC_DFR)) {
1040edf88417SAvi Kivity 	case APIC_DFR_FLAT:
10419368b567SRadim Krčmář 		return (logical_id & mda) != 0;
1042edf88417SAvi Kivity 	case APIC_DFR_CLUSTER:
10439368b567SRadim Krčmář 		return ((logical_id >> 4) == (mda >> 4))
10449368b567SRadim Krčmář 		       && (logical_id & mda & 0xf) != 0;
1045edf88417SAvi Kivity 	default:
10469368b567SRadim Krčmář 		return false;
1047edf88417SAvi Kivity 	}
1048edf88417SAvi Kivity }
1049edf88417SAvi Kivity 
1050c519265fSRadim Krčmář /* The KVM local APIC implementation has two quirks:
1051c519265fSRadim Krčmář  *
1052b4535b58SRadim Krčmář  *  - Real hardware delivers interrupts destined to x2APIC ID > 0xff to LAPICs
1053b4535b58SRadim Krčmář  *    in xAPIC mode if the "destination & 0xff" matches its xAPIC ID.
1054b4535b58SRadim Krčmář  *    KVM doesn't do that aliasing.
1055c519265fSRadim Krčmář  *
1056c519265fSRadim Krčmář  *  - in-kernel IOAPIC messages have to be delivered directly to
1057c519265fSRadim Krčmář  *    x2APIC, because the kernel does not support interrupt remapping.
1058c519265fSRadim Krčmář  *    In order to support broadcast without interrupt remapping, x2APIC
1059c519265fSRadim Krčmář  *    rewrites the destination of non-IPI messages from APIC_BROADCAST
1060c519265fSRadim Krčmář  *    to X2APIC_BROADCAST.
1061c519265fSRadim Krčmář  *
1062c519265fSRadim Krčmář  * The broadcast quirk can be disabled with KVM_CAP_X2APIC_API.  This is
1063c519265fSRadim Krčmář  * important when userspace wants to use x2APIC-format MSIs, because
1064c519265fSRadim Krčmář  * APIC_BROADCAST (0xff) is a legal route for "cluster 0, CPUs 0-7".
106503d2249eSRadim Krčmář  */
kvm_apic_mda(struct kvm_vcpu * vcpu,unsigned int dest_id,struct kvm_lapic * source,struct kvm_lapic * target)1066c519265fSRadim Krčmář static u32 kvm_apic_mda(struct kvm_vcpu *vcpu, unsigned int dest_id,
1067c519265fSRadim Krčmář 		struct kvm_lapic *source, struct kvm_lapic *target)
106803d2249eSRadim Krčmář {
106903d2249eSRadim Krčmář 	bool ipi = source != NULL;
107003d2249eSRadim Krčmář 
1071c519265fSRadim Krčmář 	if (!vcpu->kvm->arch.x2apic_broadcast_quirk_disabled &&
1072b4535b58SRadim Krčmář 	    !ipi && dest_id == APIC_BROADCAST && apic_x2apic_mode(target))
107303d2249eSRadim Krčmář 		return X2APIC_BROADCAST;
107403d2249eSRadim Krčmář 
1075b4535b58SRadim Krčmář 	return dest_id;
107603d2249eSRadim Krčmář }
107703d2249eSRadim Krčmář 
kvm_apic_match_dest(struct kvm_vcpu * vcpu,struct kvm_lapic * source,int shorthand,unsigned int dest,int dest_mode)107852c233a4SRadim Krčmář bool kvm_apic_match_dest(struct kvm_vcpu *vcpu, struct kvm_lapic *source,
10795c69d5c1SPeter Xu 			   int shorthand, unsigned int dest, int dest_mode)
1080edf88417SAvi Kivity {
1081edf88417SAvi Kivity 	struct kvm_lapic *target = vcpu->arch.apic;
1082c519265fSRadim Krčmář 	u32 mda = kvm_apic_mda(vcpu, dest, source, target);
1083edf88417SAvi Kivity 
1084bd371396SZachary Amsden 	ASSERT(target);
10855c69d5c1SPeter Xu 	switch (shorthand) {
1086edf88417SAvi Kivity 	case APIC_DEST_NOSHORT:
10873697f302SRadim Krčmář 		if (dest_mode == APIC_DEST_PHYSICAL)
108803d2249eSRadim Krčmář 			return kvm_apic_match_physical_addr(target, mda);
1089343f94feSGleb Natapov 		else
109003d2249eSRadim Krčmář 			return kvm_apic_match_logical_addr(target, mda);
1091edf88417SAvi Kivity 	case APIC_DEST_SELF:
10929368b567SRadim Krčmář 		return target == source;
1093edf88417SAvi Kivity 	case APIC_DEST_ALLINC:
10949368b567SRadim Krčmář 		return true;
1095edf88417SAvi Kivity 	case APIC_DEST_ALLBUT:
10969368b567SRadim Krčmář 		return target != source;
1097edf88417SAvi Kivity 	default:
10989368b567SRadim Krčmář 		return false;
1099edf88417SAvi Kivity 	}
1100edf88417SAvi Kivity }
11011e6e2755SSuravee Suthikulpanit EXPORT_SYMBOL_GPL(kvm_apic_match_dest);
1102edf88417SAvi Kivity 
kvm_vector_to_index(u32 vector,u32 dest_vcpus,const unsigned long * bitmap,u32 bitmap_size)110352004014SFeng Wu int kvm_vector_to_index(u32 vector, u32 dest_vcpus,
110452004014SFeng Wu 		       const unsigned long *bitmap, u32 bitmap_size)
110552004014SFeng Wu {
110652004014SFeng Wu 	u32 mod;
110752004014SFeng Wu 	int i, idx = -1;
110852004014SFeng Wu 
110952004014SFeng Wu 	mod = vector % dest_vcpus;
111052004014SFeng Wu 
111152004014SFeng Wu 	for (i = 0; i <= mod; i++) {
111252004014SFeng Wu 		idx = find_next_bit(bitmap, bitmap_size, idx + 1);
111352004014SFeng Wu 		BUG_ON(idx == bitmap_size);
111452004014SFeng Wu 	}
111552004014SFeng Wu 
111652004014SFeng Wu 	return idx;
111752004014SFeng Wu }
111852004014SFeng Wu 
kvm_apic_disabled_lapic_found(struct kvm * kvm)11194efd805fSRadim Krčmář static void kvm_apic_disabled_lapic_found(struct kvm *kvm)
11204efd805fSRadim Krčmář {
11214efd805fSRadim Krčmář 	if (!kvm->arch.disabled_lapic_found) {
11224efd805fSRadim Krčmář 		kvm->arch.disabled_lapic_found = true;
11238d20bd63SSean Christopherson 		pr_info("Disabled LAPIC found during irq injection\n");
11244efd805fSRadim Krčmář 	}
11254efd805fSRadim Krčmář }
11264efd805fSRadim Krčmář 
kvm_apic_is_broadcast_dest(struct kvm * kvm,struct kvm_lapic ** src,struct kvm_lapic_irq * irq,struct kvm_apic_map * map)1127c519265fSRadim Krčmář static bool kvm_apic_is_broadcast_dest(struct kvm *kvm, struct kvm_lapic **src,
1128c519265fSRadim Krčmář 		struct kvm_lapic_irq *irq, struct kvm_apic_map *map)
1129c519265fSRadim Krčmář {
1130c519265fSRadim Krčmář 	if (kvm->arch.x2apic_broadcast_quirk_disabled) {
1131c519265fSRadim Krčmář 		if ((irq->dest_id == APIC_BROADCAST &&
113235366901SSean Christopherson 		     map->logical_mode != KVM_APIC_MODE_X2APIC))
1133c519265fSRadim Krčmář 			return true;
1134c519265fSRadim Krčmář 		if (irq->dest_id == X2APIC_BROADCAST)
1135c519265fSRadim Krčmář 			return true;
1136c519265fSRadim Krčmář 	} else {
1137c519265fSRadim Krčmář 		bool x2apic_ipi = src && *src && apic_x2apic_mode(*src);
1138c519265fSRadim Krčmář 		if (irq->dest_id == (x2apic_ipi ?
1139c519265fSRadim Krčmář 		                     X2APIC_BROADCAST : APIC_BROADCAST))
1140c519265fSRadim Krčmář 			return true;
1141c519265fSRadim Krčmář 	}
1142c519265fSRadim Krčmář 
1143c519265fSRadim Krčmář 	return false;
1144c519265fSRadim Krčmář }
1145c519265fSRadim Krčmář 
114664aa47bfSRadim Krčmář /* Return true if the interrupt can be handled by using *bitmap as index mask
114764aa47bfSRadim Krčmář  * for valid destinations in *dst array.
114864aa47bfSRadim Krčmář  * Return false if kvm_apic_map_get_dest_lapic did nothing useful.
114964aa47bfSRadim Krčmář  * Note: we may have zero kvm_lapic destinations when we return true, which
115064aa47bfSRadim Krčmář  * means that the interrupt should be dropped.  In this case, *bitmap would be
115164aa47bfSRadim Krčmář  * zero and *dst undefined.
115264aa47bfSRadim Krčmář  */
kvm_apic_map_get_dest_lapic(struct kvm * kvm,struct kvm_lapic ** src,struct kvm_lapic_irq * irq,struct kvm_apic_map * map,struct kvm_lapic *** dst,unsigned long * bitmap)115364aa47bfSRadim Krčmář static inline bool kvm_apic_map_get_dest_lapic(struct kvm *kvm,
115464aa47bfSRadim Krčmář 		struct kvm_lapic **src, struct kvm_lapic_irq *irq,
115564aa47bfSRadim Krčmář 		struct kvm_apic_map *map, struct kvm_lapic ***dst,
115664aa47bfSRadim Krčmář 		unsigned long *bitmap)
115764aa47bfSRadim Krčmář {
115864aa47bfSRadim Krčmář 	int i, lowest;
115964aa47bfSRadim Krčmář 
116064aa47bfSRadim Krčmář 	if (irq->shorthand == APIC_DEST_SELF && src) {
116164aa47bfSRadim Krčmář 		*dst = src;
116264aa47bfSRadim Krčmář 		*bitmap = 1;
116364aa47bfSRadim Krčmář 		return true;
116464aa47bfSRadim Krčmář 	} else if (irq->shorthand)
116564aa47bfSRadim Krčmář 		return false;
116664aa47bfSRadim Krčmář 
1167c519265fSRadim Krčmář 	if (!map || kvm_apic_is_broadcast_dest(kvm, src, irq, map))
116864aa47bfSRadim Krčmář 		return false;
116964aa47bfSRadim Krčmář 
117064aa47bfSRadim Krčmář 	if (irq->dest_mode == APIC_DEST_PHYSICAL) {
11710ca52e7bSRadim Krčmář 		if (irq->dest_id > map->max_apic_id) {
117264aa47bfSRadim Krčmář 			*bitmap = 0;
117364aa47bfSRadim Krčmář 		} else {
11741d487e9bSPaolo Bonzini 			u32 dest_id = array_index_nospec(irq->dest_id, map->max_apic_id + 1);
11751d487e9bSPaolo Bonzini 			*dst = &map->phys_map[dest_id];
117664aa47bfSRadim Krčmář 			*bitmap = 1;
117764aa47bfSRadim Krčmář 		}
117864aa47bfSRadim Krčmář 		return true;
117964aa47bfSRadim Krčmář 	}
118064aa47bfSRadim Krčmář 
118164aa47bfSRadim Krčmář 	*bitmap = 0;
1182e45115b6SRadim Krčmář 	if (!kvm_apic_map_get_logical_dest(map, irq->dest_id, dst,
1183e45115b6SRadim Krčmář 				(u16 *)bitmap))
1184e45115b6SRadim Krčmář 		return false;
118564aa47bfSRadim Krčmář 
118664aa47bfSRadim Krčmář 	if (!kvm_lowest_prio_delivery(irq))
118764aa47bfSRadim Krčmář 		return true;
118864aa47bfSRadim Krčmář 
118964aa47bfSRadim Krčmář 	if (!kvm_vector_hashing_enabled()) {
119064aa47bfSRadim Krčmář 		lowest = -1;
119164aa47bfSRadim Krčmář 		for_each_set_bit(i, bitmap, 16) {
119264aa47bfSRadim Krčmář 			if (!(*dst)[i])
119364aa47bfSRadim Krčmář 				continue;
119464aa47bfSRadim Krčmář 			if (lowest < 0)
119564aa47bfSRadim Krčmář 				lowest = i;
119664aa47bfSRadim Krčmář 			else if (kvm_apic_compare_prio((*dst)[i]->vcpu,
119764aa47bfSRadim Krčmář 						(*dst)[lowest]->vcpu) < 0)
119864aa47bfSRadim Krčmář 				lowest = i;
119964aa47bfSRadim Krčmář 		}
120064aa47bfSRadim Krčmář 	} else {
120164aa47bfSRadim Krčmář 		if (!*bitmap)
120264aa47bfSRadim Krčmář 			return true;
120364aa47bfSRadim Krčmář 
120464aa47bfSRadim Krčmář 		lowest = kvm_vector_to_index(irq->vector, hweight16(*bitmap),
120564aa47bfSRadim Krčmář 				bitmap, 16);
120664aa47bfSRadim Krčmář 
120764aa47bfSRadim Krčmář 		if (!(*dst)[lowest]) {
120864aa47bfSRadim Krčmář 			kvm_apic_disabled_lapic_found(kvm);
120964aa47bfSRadim Krčmář 			*bitmap = 0;
121064aa47bfSRadim Krčmář 			return true;
121164aa47bfSRadim Krčmář 		}
121264aa47bfSRadim Krčmář 	}
121364aa47bfSRadim Krčmář 
121464aa47bfSRadim Krčmář 	*bitmap = (lowest >= 0) ? 1 << lowest : 0;
121564aa47bfSRadim Krčmář 
121664aa47bfSRadim Krčmář 	return true;
121764aa47bfSRadim Krčmář }
121864aa47bfSRadim Krčmář 
kvm_irq_delivery_to_apic_fast(struct kvm * kvm,struct kvm_lapic * src,struct kvm_lapic_irq * irq,int * r,struct dest_map * dest_map)12191e08ec4aSGleb Natapov bool kvm_irq_delivery_to_apic_fast(struct kvm *kvm, struct kvm_lapic *src,
12209e4aabe2SJoerg Roedel 		struct kvm_lapic_irq *irq, int *r, struct dest_map *dest_map)
12211e08ec4aSGleb Natapov {
12221e08ec4aSGleb Natapov 	struct kvm_apic_map *map;
122364aa47bfSRadim Krčmář 	unsigned long bitmap;
122464aa47bfSRadim Krčmář 	struct kvm_lapic **dst = NULL;
12251e08ec4aSGleb Natapov 	int i;
122664aa47bfSRadim Krčmář 	bool ret;
12271e08ec4aSGleb Natapov 
12281e08ec4aSGleb Natapov 	*r = -1;
12291e08ec4aSGleb Natapov 
12301e08ec4aSGleb Natapov 	if (irq->shorthand == APIC_DEST_SELF) {
123100b5f371SVitaly Kuznetsov 		if (KVM_BUG_ON(!src, kvm)) {
123200b5f371SVitaly Kuznetsov 			*r = 0;
123300b5f371SVitaly Kuznetsov 			return true;
123400b5f371SVitaly Kuznetsov 		}
1235b4f2225cSYang Zhang 		*r = kvm_apic_set_irq(src->vcpu, irq, dest_map);
12361e08ec4aSGleb Natapov 		return true;
12371e08ec4aSGleb Natapov 	}
12381e08ec4aSGleb Natapov 
12391e08ec4aSGleb Natapov 	rcu_read_lock();
12401e08ec4aSGleb Natapov 	map = rcu_dereference(kvm->arch.apic_map);
12411e08ec4aSGleb Natapov 
124264aa47bfSRadim Krčmář 	ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dst, &bitmap);
12430624fca9SPaolo Bonzini 	if (ret) {
12440624fca9SPaolo Bonzini 		*r = 0;
12451e08ec4aSGleb Natapov 		for_each_set_bit(i, &bitmap, 16) {
12461e08ec4aSGleb Natapov 			if (!dst[i])
12471e08ec4aSGleb Natapov 				continue;
1248b4f2225cSYang Zhang 			*r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map);
12491e08ec4aSGleb Natapov 		}
12500624fca9SPaolo Bonzini 	}
125164aa47bfSRadim Krčmář 
12521e08ec4aSGleb Natapov 	rcu_read_unlock();
12531e08ec4aSGleb Natapov 	return ret;
12541e08ec4aSGleb Natapov }
12551e08ec4aSGleb Natapov 
12566228a0daSFeng Wu /*
125700116795SMiaohe Lin  * This routine tries to handle interrupts in posted mode, here is how
12586228a0daSFeng Wu  * it deals with different cases:
12596228a0daSFeng Wu  * - For single-destination interrupts, handle it in posted mode
12606228a0daSFeng Wu  * - Else if vector hashing is enabled and it is a lowest-priority
12616228a0daSFeng Wu  *   interrupt, handle it in posted mode and use the following mechanism
126267b0ae43SMiaohe Lin  *   to find the destination vCPU.
12636228a0daSFeng Wu  *	1. For lowest-priority interrupts, store all the possible
12646228a0daSFeng Wu  *	   destination vCPUs in an array.
12656228a0daSFeng Wu  *	2. Use "guest vector % max number of destination vCPUs" to find
12666228a0daSFeng Wu  *	   the right destination vCPU in the array for the lowest-priority
12676228a0daSFeng Wu  *	   interrupt.
12686228a0daSFeng Wu  * - Otherwise, use remapped mode to inject the interrupt.
12696228a0daSFeng Wu  */
kvm_intr_is_single_vcpu_fast(struct kvm * kvm,struct kvm_lapic_irq * irq,struct kvm_vcpu ** dest_vcpu)12708feb4a04SFeng Wu bool kvm_intr_is_single_vcpu_fast(struct kvm *kvm, struct kvm_lapic_irq *irq,
12718feb4a04SFeng Wu 			struct kvm_vcpu **dest_vcpu)
12728feb4a04SFeng Wu {
12738feb4a04SFeng Wu 	struct kvm_apic_map *map;
127464aa47bfSRadim Krčmář 	unsigned long bitmap;
127564aa47bfSRadim Krčmář 	struct kvm_lapic **dst = NULL;
12768feb4a04SFeng Wu 	bool ret = false;
12778feb4a04SFeng Wu 
12788feb4a04SFeng Wu 	if (irq->shorthand)
12798feb4a04SFeng Wu 		return false;
12808feb4a04SFeng Wu 
12818feb4a04SFeng Wu 	rcu_read_lock();
12828feb4a04SFeng Wu 	map = rcu_dereference(kvm->arch.apic_map);
12838feb4a04SFeng Wu 
128464aa47bfSRadim Krčmář 	if (kvm_apic_map_get_dest_lapic(kvm, NULL, irq, map, &dst, &bitmap) &&
128564aa47bfSRadim Krčmář 			hweight16(bitmap) == 1) {
128664aa47bfSRadim Krčmář 		unsigned long i = find_first_bit(&bitmap, 16);
12878feb4a04SFeng Wu 
128864aa47bfSRadim Krčmář 		if (dst[i]) {
128964aa47bfSRadim Krčmář 			*dest_vcpu = dst[i]->vcpu;
12908feb4a04SFeng Wu 			ret = true;
129164aa47bfSRadim Krčmář 		}
129264aa47bfSRadim Krčmář 	}
129364aa47bfSRadim Krčmář 
12948feb4a04SFeng Wu 	rcu_read_unlock();
12958feb4a04SFeng Wu 	return ret;
12968feb4a04SFeng Wu }
12978feb4a04SFeng Wu 
1298edf88417SAvi Kivity /*
1299edf88417SAvi Kivity  * Add a pending IRQ into lapic.
1300edf88417SAvi Kivity  * Return 1 if successfully added and 0 if discarded.
1301edf88417SAvi Kivity  */
__apic_accept_irq(struct kvm_lapic * apic,int delivery_mode,int vector,int level,int trig_mode,struct dest_map * dest_map)1302edf88417SAvi Kivity static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
1303b4f2225cSYang Zhang 			     int vector, int level, int trig_mode,
13049e4aabe2SJoerg Roedel 			     struct dest_map *dest_map)
1305edf88417SAvi Kivity {
13066da7e3f6SGleb Natapov 	int result = 0;
1307edf88417SAvi Kivity 	struct kvm_vcpu *vcpu = apic->vcpu;
1308edf88417SAvi Kivity 
1309a183b638SPaolo Bonzini 	trace_kvm_apic_accept_irq(vcpu->vcpu_id, delivery_mode,
1310a183b638SPaolo Bonzini 				  trig_mode, vector);
1311edf88417SAvi Kivity 	switch (delivery_mode) {
1312edf88417SAvi Kivity 	case APIC_DM_LOWEST:
1313e1035715SGleb Natapov 		vcpu->arch.apic_arb_prio++;
1314df561f66SGustavo A. R. Silva 		fallthrough;
1315e1035715SGleb Natapov 	case APIC_DM_FIXED:
1316bdaffe1dSPaolo Bonzini 		if (unlikely(trig_mode && !level))
1317bdaffe1dSPaolo Bonzini 			break;
1318bdaffe1dSPaolo Bonzini 
1319edf88417SAvi Kivity 		/* FIXME add logic for vcpu on reset */
1320edf88417SAvi Kivity 		if (unlikely(!apic_enabled(apic)))
1321edf88417SAvi Kivity 			break;
1322edf88417SAvi Kivity 
132311f5cc05SJan Kiszka 		result = 1;
132411f5cc05SJan Kiszka 
13259daa5007SJoerg Roedel 		if (dest_map) {
13269e4aabe2SJoerg Roedel 			__set_bit(vcpu->vcpu_id, dest_map->map);
13279daa5007SJoerg Roedel 			dest_map->vectors[vcpu->vcpu_id] = vector;
13289daa5007SJoerg Roedel 		}
1329a5d36f82SAvi Kivity 
1330bdaffe1dSPaolo Bonzini 		if (apic_test_vector(vector, apic->regs + APIC_TMR) != !!trig_mode) {
1331bdaffe1dSPaolo Bonzini 			if (trig_mode)
1332ee171d2fSWei Yang 				kvm_lapic_set_vector(vector,
1333ee171d2fSWei Yang 						     apic->regs + APIC_TMR);
1334bdaffe1dSPaolo Bonzini 			else
1335ee171d2fSWei Yang 				kvm_lapic_clear_vector(vector,
1336ee171d2fSWei Yang 						       apic->regs + APIC_TMR);
1337bdaffe1dSPaolo Bonzini 		}
1338bdaffe1dSPaolo Bonzini 
133989604647SWei Wang 		kvm_x86_call(deliver_interrupt)(apic, delivery_mode,
13408e819d75SMaxim Levitsky 						trig_mode, vector);
1341edf88417SAvi Kivity 		break;
1342edf88417SAvi Kivity 
1343edf88417SAvi Kivity 	case APIC_DM_REMRD:
134424d2166bSRaghavendra K T 		result = 1;
134524d2166bSRaghavendra K T 		vcpu->arch.pv.pv_unhalted = 1;
134624d2166bSRaghavendra K T 		kvm_make_request(KVM_REQ_EVENT, vcpu);
134724d2166bSRaghavendra K T 		kvm_vcpu_kick(vcpu);
1348edf88417SAvi Kivity 		break;
1349edf88417SAvi Kivity 
1350edf88417SAvi Kivity 	case APIC_DM_SMI:
1351b0b42197SPaolo Bonzini 		if (!kvm_inject_smi(vcpu)) {
135264d60670SPaolo Bonzini 			kvm_vcpu_kick(vcpu);
1353b0b42197SPaolo Bonzini 			result = 1;
1354b0b42197SPaolo Bonzini 		}
1355edf88417SAvi Kivity 		break;
13563419ffc8SSheng Yang 
1357edf88417SAvi Kivity 	case APIC_DM_NMI:
13586da7e3f6SGleb Natapov 		result = 1;
13593419ffc8SSheng Yang 		kvm_inject_nmi(vcpu);
136026df99c6SJan Kiszka 		kvm_vcpu_kick(vcpu);
1361edf88417SAvi Kivity 		break;
1362edf88417SAvi Kivity 
1363edf88417SAvi Kivity 	case APIC_DM_INIT:
1364a52315e1SJulian Stecklina 		if (!trig_mode || level) {
13656da7e3f6SGleb Natapov 			result = 1;
136666450a21SJan Kiszka 			/* assumes that there are only KVM_APIC_INIT/SIPI */
136766450a21SJan Kiszka 			apic->pending_events = (1UL << KVM_APIC_INIT);
13683842d135SAvi Kivity 			kvm_make_request(KVM_REQ_EVENT, vcpu);
1369edf88417SAvi Kivity 			kvm_vcpu_kick(vcpu);
1370edf88417SAvi Kivity 		}
1371edf88417SAvi Kivity 		break;
1372edf88417SAvi Kivity 
1373edf88417SAvi Kivity 	case APIC_DM_STARTUP:
13746da7e3f6SGleb Natapov 		result = 1;
137566450a21SJan Kiszka 		apic->sipi_vector = vector;
137666450a21SJan Kiszka 		/* make sure sipi_vector is visible for the receiver */
137766450a21SJan Kiszka 		smp_wmb();
137866450a21SJan Kiszka 		set_bit(KVM_APIC_SIPI, &apic->pending_events);
13793842d135SAvi Kivity 		kvm_make_request(KVM_REQ_EVENT, vcpu);
1380d7690175SMarcelo Tosatti 		kvm_vcpu_kick(vcpu);
1381edf88417SAvi Kivity 		break;
1382edf88417SAvi Kivity 
138323930f95SJan Kiszka 	case APIC_DM_EXTINT:
138423930f95SJan Kiszka 		/*
138523930f95SJan Kiszka 		 * Should only be called by kvm_apic_local_deliver() with LVT0,
138623930f95SJan Kiszka 		 * before NMI watchdog was enabled. Already handled by
138723930f95SJan Kiszka 		 * kvm_apic_accept_pic_intr().
138823930f95SJan Kiszka 		 */
138923930f95SJan Kiszka 		break;
139023930f95SJan Kiszka 
1391edf88417SAvi Kivity 	default:
1392edf88417SAvi Kivity 		printk(KERN_ERR "TODO: unsupported delivery mode %x\n",
1393edf88417SAvi Kivity 		       delivery_mode);
1394edf88417SAvi Kivity 		break;
1395edf88417SAvi Kivity 	}
1396edf88417SAvi Kivity 	return result;
1397edf88417SAvi Kivity }
1398edf88417SAvi Kivity 
13997ee30bc1SNitesh Narayan Lal /*
14007ee30bc1SNitesh Narayan Lal  * This routine identifies the destination vcpus mask meant to receive the
14017ee30bc1SNitesh Narayan Lal  * IOAPIC interrupts. It either uses kvm_apic_map_get_dest_lapic() to find
14027ee30bc1SNitesh Narayan Lal  * out the destination vcpus array and set the bitmap or it traverses to
14037ee30bc1SNitesh Narayan Lal  * each available vcpu to identify the same.
14047ee30bc1SNitesh Narayan Lal  */
kvm_bitmap_or_dest_vcpus(struct kvm * kvm,struct kvm_lapic_irq * irq,unsigned long * vcpu_bitmap)14057ee30bc1SNitesh Narayan Lal void kvm_bitmap_or_dest_vcpus(struct kvm *kvm, struct kvm_lapic_irq *irq,
14067ee30bc1SNitesh Narayan Lal 			      unsigned long *vcpu_bitmap)
14077ee30bc1SNitesh Narayan Lal {
14087ee30bc1SNitesh Narayan Lal 	struct kvm_lapic **dest_vcpu = NULL;
14097ee30bc1SNitesh Narayan Lal 	struct kvm_lapic *src = NULL;
14107ee30bc1SNitesh Narayan Lal 	struct kvm_apic_map *map;
14117ee30bc1SNitesh Narayan Lal 	struct kvm_vcpu *vcpu;
141246808a4cSMarc Zyngier 	unsigned long bitmap, i;
141346808a4cSMarc Zyngier 	int vcpu_idx;
14147ee30bc1SNitesh Narayan Lal 	bool ret;
14157ee30bc1SNitesh Narayan Lal 
14167ee30bc1SNitesh Narayan Lal 	rcu_read_lock();
14177ee30bc1SNitesh Narayan Lal 	map = rcu_dereference(kvm->arch.apic_map);
14187ee30bc1SNitesh Narayan Lal 
14197ee30bc1SNitesh Narayan Lal 	ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dest_vcpu,
14207ee30bc1SNitesh Narayan Lal 					  &bitmap);
14217ee30bc1SNitesh Narayan Lal 	if (ret) {
14227ee30bc1SNitesh Narayan Lal 		for_each_set_bit(i, &bitmap, 16) {
14237ee30bc1SNitesh Narayan Lal 			if (!dest_vcpu[i])
14247ee30bc1SNitesh Narayan Lal 				continue;
14257ee30bc1SNitesh Narayan Lal 			vcpu_idx = dest_vcpu[i]->vcpu->vcpu_idx;
14267ee30bc1SNitesh Narayan Lal 			__set_bit(vcpu_idx, vcpu_bitmap);
14277ee30bc1SNitesh Narayan Lal 		}
14287ee30bc1SNitesh Narayan Lal 	} else {
14297ee30bc1SNitesh Narayan Lal 		kvm_for_each_vcpu(i, vcpu, kvm) {
14307ee30bc1SNitesh Narayan Lal 			if (!kvm_apic_present(vcpu))
14317ee30bc1SNitesh Narayan Lal 				continue;
14327ee30bc1SNitesh Narayan Lal 			if (!kvm_apic_match_dest(vcpu, NULL,
1433b4b29636SPeter Xu 						 irq->shorthand,
14347ee30bc1SNitesh Narayan Lal 						 irq->dest_id,
14357ee30bc1SNitesh Narayan Lal 						 irq->dest_mode))
14367ee30bc1SNitesh Narayan Lal 				continue;
14377ee30bc1SNitesh Narayan Lal 			__set_bit(i, vcpu_bitmap);
14387ee30bc1SNitesh Narayan Lal 		}
14397ee30bc1SNitesh Narayan Lal 	}
14407ee30bc1SNitesh Narayan Lal 	rcu_read_unlock();
14417ee30bc1SNitesh Narayan Lal }
14427ee30bc1SNitesh Narayan Lal 
kvm_apic_compare_prio(struct kvm_vcpu * vcpu1,struct kvm_vcpu * vcpu2)1443e1035715SGleb Natapov int kvm_apic_compare_prio(struct kvm_vcpu *vcpu1, struct kvm_vcpu *vcpu2)
1444edf88417SAvi Kivity {
1445e1035715SGleb Natapov 	return vcpu1->arch.apic_arb_prio - vcpu2->arch.apic_arb_prio;
1446edf88417SAvi Kivity }
1447edf88417SAvi Kivity 
kvm_ioapic_handles_vector(struct kvm_lapic * apic,int vector)14483bb345f3SPaolo Bonzini static bool kvm_ioapic_handles_vector(struct kvm_lapic *apic, int vector)
14493bb345f3SPaolo Bonzini {
14506308630bSAndrey Smetanin 	return test_bit(vector, apic->vcpu->arch.ioapic_handled_vectors);
14513bb345f3SPaolo Bonzini }
14523bb345f3SPaolo Bonzini 
kvm_ioapic_send_eoi(struct kvm_lapic * apic,int vector)1453c7c9c56cSYang Zhang static void kvm_ioapic_send_eoi(struct kvm_lapic *apic, int vector)
1454c7c9c56cSYang Zhang {
1455c7c9c56cSYang Zhang 	int trigger_mode;
14567543a635SSteve Rutherford 
14577543a635SSteve Rutherford 	/* Eoi the ioapic only if the ioapic doesn't own the vector. */
14587543a635SSteve Rutherford 	if (!kvm_ioapic_handles_vector(apic, vector))
14597543a635SSteve Rutherford 		return;
14607543a635SSteve Rutherford 
14617543a635SSteve Rutherford 	/* Request a KVM exit to inform the userspace IOAPIC. */
14627543a635SSteve Rutherford 	if (irqchip_split(apic->vcpu->kvm)) {
14637543a635SSteve Rutherford 		apic->vcpu->arch.pending_ioapic_eoi = vector;
14647543a635SSteve Rutherford 		kvm_make_request(KVM_REQ_IOAPIC_EOI_EXIT, apic->vcpu);
14657543a635SSteve Rutherford 		return;
14667543a635SSteve Rutherford 	}
14677543a635SSteve Rutherford 
1468c7c9c56cSYang Zhang 	if (apic_test_vector(vector, apic->regs + APIC_TMR))
1469c7c9c56cSYang Zhang 		trigger_mode = IOAPIC_LEVEL_TRIG;
1470c7c9c56cSYang Zhang 	else
1471c7c9c56cSYang Zhang 		trigger_mode = IOAPIC_EDGE_TRIG;
14723bb345f3SPaolo Bonzini 
14731fcc7890SYang Zhang 	kvm_ioapic_update_eoi(apic->vcpu, vector, trigger_mode);
1474c7c9c56cSYang Zhang }
1475c7c9c56cSYang Zhang 
apic_set_eoi(struct kvm_lapic * apic)1476ae7a2a3fSMichael S. Tsirkin static int apic_set_eoi(struct kvm_lapic *apic)
1477edf88417SAvi Kivity {
1478edf88417SAvi Kivity 	int vector = apic_find_highest_isr(apic);
1479ae7a2a3fSMichael S. Tsirkin 
1480ae7a2a3fSMichael S. Tsirkin 	trace_kvm_eoi(apic, vector);
1481ae7a2a3fSMichael S. Tsirkin 
1482edf88417SAvi Kivity 	/*
1483edf88417SAvi Kivity 	 * Not every write EOI will has corresponding ISR,
1484edf88417SAvi Kivity 	 * one example is when Kernel check timer on setup_IO_APIC
1485edf88417SAvi Kivity 	 */
1486edf88417SAvi Kivity 	if (vector == -1)
1487ae7a2a3fSMichael S. Tsirkin 		return vector;
1488edf88417SAvi Kivity 
14898680b94bSMichael S. Tsirkin 	apic_clear_isr(vector, apic);
1490edf88417SAvi Kivity 	apic_update_ppr(apic);
1491edf88417SAvi Kivity 
14920659262aSVitaly Kuznetsov 	if (kvm_hv_synic_has_vector(apic->vcpu, vector))
14935c919412SAndrey Smetanin 		kvm_hv_synic_send_eoi(apic->vcpu, vector);
14945c919412SAndrey Smetanin 
1495c7c9c56cSYang Zhang 	kvm_ioapic_send_eoi(apic, vector);
14963842d135SAvi Kivity 	kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1497ae7a2a3fSMichael S. Tsirkin 	return vector;
1498fc61b800SGleb Natapov }
1499edf88417SAvi Kivity 
1500c7c9c56cSYang Zhang /*
1501c7c9c56cSYang Zhang  * this interface assumes a trap-like exit, which has already finished
1502c7c9c56cSYang Zhang  * desired side effect including vISR and vPPR update.
1503c7c9c56cSYang Zhang  */
kvm_apic_set_eoi_accelerated(struct kvm_vcpu * vcpu,int vector)1504c7c9c56cSYang Zhang void kvm_apic_set_eoi_accelerated(struct kvm_vcpu *vcpu, int vector)
1505c7c9c56cSYang Zhang {
1506c7c9c56cSYang Zhang 	struct kvm_lapic *apic = vcpu->arch.apic;
1507c7c9c56cSYang Zhang 
1508c7c9c56cSYang Zhang 	trace_kvm_eoi(apic, vector);
1509c7c9c56cSYang Zhang 
1510c7c9c56cSYang Zhang 	kvm_ioapic_send_eoi(apic, vector);
1511c7c9c56cSYang Zhang 	kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1512c7c9c56cSYang Zhang }
1513c7c9c56cSYang Zhang EXPORT_SYMBOL_GPL(kvm_apic_set_eoi_accelerated);
1514c7c9c56cSYang Zhang 
kvm_apic_send_ipi(struct kvm_lapic * apic,u32 icr_low,u32 icr_high)1515d5361678SWanpeng Li void kvm_apic_send_ipi(struct kvm_lapic *apic, u32 icr_low, u32 icr_high)
1516edf88417SAvi Kivity {
151758c2dde1SGleb Natapov 	struct kvm_lapic_irq irq;
1518edf88417SAvi Kivity 
1519bd17f417SSean Christopherson 	/* KVM has no delay and should always clear the BUSY/PENDING flag. */
1520bd17f417SSean Christopherson 	WARN_ON_ONCE(icr_low & APIC_ICR_BUSY);
1521bd17f417SSean Christopherson 
152258c2dde1SGleb Natapov 	irq.vector = icr_low & APIC_VECTOR_MASK;
152358c2dde1SGleb Natapov 	irq.delivery_mode = icr_low & APIC_MODE_MASK;
152458c2dde1SGleb Natapov 	irq.dest_mode = icr_low & APIC_DEST_MASK;
1525b7cb2231SPaolo Bonzini 	irq.level = (icr_low & APIC_INT_ASSERT) != 0;
152658c2dde1SGleb Natapov 	irq.trig_mode = icr_low & APIC_INT_LEVELTRIG;
152758c2dde1SGleb Natapov 	irq.shorthand = icr_low & APIC_SHORT_MASK;
152893bbf0b8SJames Sullivan 	irq.msi_redir_hint = false;
15290105d1a5SGleb Natapov 	if (apic_x2apic_mode(apic))
15300105d1a5SGleb Natapov 		irq.dest_id = icr_high;
15310105d1a5SGleb Natapov 	else
1532bf348f66SSuravee Suthikulpanit 		irq.dest_id = GET_XAPIC_DEST_FIELD(icr_high);
1533edf88417SAvi Kivity 
15341000ff8dSGleb Natapov 	trace_kvm_apic_ipi(icr_low, irq.dest_id);
15351000ff8dSGleb Natapov 
1536b4f2225cSYang Zhang 	kvm_irq_delivery_to_apic(apic->vcpu->kvm, apic, &irq, NULL);
1537edf88417SAvi Kivity }
1538b51818afSSean Christopherson EXPORT_SYMBOL_GPL(kvm_apic_send_ipi);
1539edf88417SAvi Kivity 
apic_get_tmcct(struct kvm_lapic * apic)1540edf88417SAvi Kivity static u32 apic_get_tmcct(struct kvm_lapic *apic)
1541edf88417SAvi Kivity {
15428003c9aeSWanpeng Li 	ktime_t remaining, now;
1543b682b814SMarcelo Tosatti 	s64 ns;
1544edf88417SAvi Kivity 
1545edf88417SAvi Kivity 	ASSERT(apic != NULL);
1546edf88417SAvi Kivity 
1547edf88417SAvi Kivity 	/* if initial count is 0, current count should also be 0 */
1548dfb95954SSuravee Suthikulpanit 	if (kvm_lapic_get_reg(apic, APIC_TMICT) == 0 ||
1549b963a22eSAndy Honig 		apic->lapic_timer.period == 0)
1550edf88417SAvi Kivity 		return 0;
1551edf88417SAvi Kivity 
15525587859fSPaolo Bonzini 	now = ktime_get();
15538003c9aeSWanpeng Li 	remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1554b682b814SMarcelo Tosatti 	if (ktime_to_ns(remaining) < 0)
15558b0e1953SThomas Gleixner 		remaining = 0;
1556edf88417SAvi Kivity 
1557d3c7b77dSMarcelo Tosatti 	ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
1558b460256bSIsaku Yamahata 	return div64_u64(ns, (apic->vcpu->kvm->arch.apic_bus_cycle_ns *
1559b460256bSIsaku Yamahata 			      apic->divide_count));
1560edf88417SAvi Kivity }
1561edf88417SAvi Kivity 
__report_tpr_access(struct kvm_lapic * apic,bool write)1562b209749fSAvi Kivity static void __report_tpr_access(struct kvm_lapic *apic, bool write)
1563b209749fSAvi Kivity {
1564b209749fSAvi Kivity 	struct kvm_vcpu *vcpu = apic->vcpu;
1565b209749fSAvi Kivity 	struct kvm_run *run = vcpu->run;
1566b209749fSAvi Kivity 
1567a8eeb04aSAvi Kivity 	kvm_make_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu);
15685fdbf976SMarcelo Tosatti 	run->tpr_access.rip = kvm_rip_read(vcpu);
1569b209749fSAvi Kivity 	run->tpr_access.is_write = write;
1570b209749fSAvi Kivity }
1571b209749fSAvi Kivity 
report_tpr_access(struct kvm_lapic * apic,bool write)1572b209749fSAvi Kivity static inline void report_tpr_access(struct kvm_lapic *apic, bool write)
1573b209749fSAvi Kivity {
1574b209749fSAvi Kivity 	if (apic->vcpu->arch.tpr_access_reporting)
1575b209749fSAvi Kivity 		__report_tpr_access(apic, write);
1576b209749fSAvi Kivity }
1577b209749fSAvi Kivity 
__apic_read(struct kvm_lapic * apic,unsigned int offset)1578edf88417SAvi Kivity static u32 __apic_read(struct kvm_lapic *apic, unsigned int offset)
1579edf88417SAvi Kivity {
1580edf88417SAvi Kivity 	u32 val = 0;
1581edf88417SAvi Kivity 
1582edf88417SAvi Kivity 	if (offset >= LAPIC_MMIO_LENGTH)
1583edf88417SAvi Kivity 		return 0;
1584edf88417SAvi Kivity 
1585edf88417SAvi Kivity 	switch (offset) {
1586edf88417SAvi Kivity 	case APIC_ARBPRI:
1587edf88417SAvi Kivity 		break;
1588edf88417SAvi Kivity 
1589edf88417SAvi Kivity 	case APIC_TMCCT:	/* Timer CCR */
1590a3e06bbeSLiu, Jinsong 		if (apic_lvtt_tscdeadline(apic))
1591a3e06bbeSLiu, Jinsong 			return 0;
1592a3e06bbeSLiu, Jinsong 
1593edf88417SAvi Kivity 		val = apic_get_tmcct(apic);
1594edf88417SAvi Kivity 		break;
15954a4541a4SAvi Kivity 	case APIC_PROCPRI:
15964a4541a4SAvi Kivity 		apic_update_ppr(apic);
1597dfb95954SSuravee Suthikulpanit 		val = kvm_lapic_get_reg(apic, offset);
15984a4541a4SAvi Kivity 		break;
1599b209749fSAvi Kivity 	case APIC_TASKPRI:
1600b209749fSAvi Kivity 		report_tpr_access(apic, false);
1601df561f66SGustavo A. R. Silva 		fallthrough;
1602edf88417SAvi Kivity 	default:
1603dfb95954SSuravee Suthikulpanit 		val = kvm_lapic_get_reg(apic, offset);
1604edf88417SAvi Kivity 		break;
1605edf88417SAvi Kivity 	}
1606edf88417SAvi Kivity 
1607edf88417SAvi Kivity 	return val;
1608edf88417SAvi Kivity }
1609edf88417SAvi Kivity 
to_lapic(struct kvm_io_device * dev)1610d76685c4SGregory Haskins static inline struct kvm_lapic *to_lapic(struct kvm_io_device *dev)
1611d76685c4SGregory Haskins {
1612d76685c4SGregory Haskins 	return container_of(dev, struct kvm_lapic, dev);
1613d76685c4SGregory Haskins }
1614d76685c4SGregory Haskins 
161501402cf8SPaolo Bonzini #define APIC_REG_MASK(reg)	(1ull << ((reg) >> 4))
161601402cf8SPaolo Bonzini #define APIC_REGS_MASK(first, count) \
161701402cf8SPaolo Bonzini 	(APIC_REG_MASK(first) * ((1ull << (count)) - 1))
161801402cf8SPaolo Bonzini 
kvm_lapic_readable_reg_mask(struct kvm_lapic * apic)1619b5fcc59bSSean Christopherson u64 kvm_lapic_readable_reg_mask(struct kvm_lapic *apic)
1620bda9020eSMichael S. Tsirkin {
1621b5fcc59bSSean Christopherson 	/* Leave bits '0' for reserved and write-only registers. */
162201402cf8SPaolo Bonzini 	u64 valid_reg_mask =
162301402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_ID) |
162401402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_LVR) |
162501402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_TASKPRI) |
162601402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_PROCPRI) |
162701402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_LDR) |
162801402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_SPIV) |
162901402cf8SPaolo Bonzini 		APIC_REGS_MASK(APIC_ISR, APIC_ISR_NR) |
163001402cf8SPaolo Bonzini 		APIC_REGS_MASK(APIC_TMR, APIC_ISR_NR) |
163101402cf8SPaolo Bonzini 		APIC_REGS_MASK(APIC_IRR, APIC_ISR_NR) |
163201402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_ESR) |
163301402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_ICR) |
163401402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_LVTT) |
163501402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_LVTTHMR) |
163601402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_LVTPC) |
163701402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_LVT0) |
163801402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_LVT1) |
163901402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_LVTERR) |
164001402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_TMICT) |
164101402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_TMCCT) |
164201402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_TDCR);
1643edf88417SAvi Kivity 
16444b903561SJue Wang 	if (kvm_lapic_lvt_supported(apic, LVT_CMCI))
16454b903561SJue Wang 		valid_reg_mask |= APIC_REG_MASK(APIC_LVTCMCI);
16464b903561SJue Wang 
1647b5fcc59bSSean Christopherson 	/* ARBPRI, DFR, and ICR2 are not valid in x2APIC mode. */
164801402cf8SPaolo Bonzini 	if (!apic_x2apic_mode(apic))
1649a57a3168SSean Christopherson 		valid_reg_mask |= APIC_REG_MASK(APIC_ARBPRI) |
1650b2236495SSean Christopherson 				  APIC_REG_MASK(APIC_DFR) |
1651a57a3168SSean Christopherson 				  APIC_REG_MASK(APIC_ICR2);
1652b5fcc59bSSean Christopherson 
1653b5fcc59bSSean Christopherson 	return valid_reg_mask;
1654b5fcc59bSSean Christopherson }
1655b5fcc59bSSean Christopherson EXPORT_SYMBOL_GPL(kvm_lapic_readable_reg_mask);
1656b5fcc59bSSean Christopherson 
kvm_lapic_reg_read(struct kvm_lapic * apic,u32 offset,int len,void * data)1657b5fcc59bSSean Christopherson static int kvm_lapic_reg_read(struct kvm_lapic *apic, u32 offset, int len,
1658b5fcc59bSSean Christopherson 			      void *data)
1659b5fcc59bSSean Christopherson {
1660b5fcc59bSSean Christopherson 	unsigned char alignment = offset & 0xf;
1661b5fcc59bSSean Christopherson 	u32 result;
1662b5fcc59bSSean Christopherson 
1663b5fcc59bSSean Christopherson 	/*
1664b5fcc59bSSean Christopherson 	 * WARN if KVM reads ICR in x2APIC mode, as it's an 8-byte register in
1665b5fcc59bSSean Christopherson 	 * x2APIC and needs to be manually handled by the caller.
1666b5fcc59bSSean Christopherson 	 */
1667b5fcc59bSSean Christopherson 	WARN_ON_ONCE(apic_x2apic_mode(apic) && offset == APIC_ICR);
16680105d1a5SGleb Natapov 
1669218bf772SJim Mattson 	if (alignment + len > 4)
1670218bf772SJim Mattson 		return 1;
1671218bf772SJim Mattson 
1672b5fcc59bSSean Christopherson 	if (offset > 0x3f0 ||
1673b5fcc59bSSean Christopherson 	    !(kvm_lapic_readable_reg_mask(apic) & APIC_REG_MASK(offset)))
16740105d1a5SGleb Natapov 		return 1;
16750105d1a5SGleb Natapov 
1676edf88417SAvi Kivity 	result = __apic_read(apic, offset & ~0xf);
1677edf88417SAvi Kivity 
1678229456fcSMarcelo Tosatti 	trace_kvm_apic_read(offset, result);
1679229456fcSMarcelo Tosatti 
1680edf88417SAvi Kivity 	switch (len) {
1681edf88417SAvi Kivity 	case 1:
1682edf88417SAvi Kivity 	case 2:
1683edf88417SAvi Kivity 	case 4:
1684edf88417SAvi Kivity 		memcpy(data, (char *)&result + alignment, len);
1685edf88417SAvi Kivity 		break;
1686edf88417SAvi Kivity 	default:
1687edf88417SAvi Kivity 		printk(KERN_ERR "Local APIC read with len = %x, "
1688edf88417SAvi Kivity 		       "should be 1,2, or 4 instead\n", len);
1689edf88417SAvi Kivity 		break;
1690edf88417SAvi Kivity 	}
1691bda9020eSMichael S. Tsirkin 	return 0;
1692edf88417SAvi Kivity }
1693edf88417SAvi Kivity 
apic_mmio_in_range(struct kvm_lapic * apic,gpa_t addr)16940105d1a5SGleb Natapov static int apic_mmio_in_range(struct kvm_lapic *apic, gpa_t addr)
16950105d1a5SGleb Natapov {
1696d1766202SVitaly Kuznetsov 	return addr >= apic->base_address &&
16970105d1a5SGleb Natapov 		addr < apic->base_address + LAPIC_MMIO_LENGTH;
16980105d1a5SGleb Natapov }
16990105d1a5SGleb Natapov 
apic_mmio_read(struct kvm_vcpu * vcpu,struct kvm_io_device * this,gpa_t address,int len,void * data)1700e32edf4fSNikolay Nikolaev static int apic_mmio_read(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
17010105d1a5SGleb Natapov 			   gpa_t address, int len, void *data)
17020105d1a5SGleb Natapov {
17030105d1a5SGleb Natapov 	struct kvm_lapic *apic = to_lapic(this);
17040105d1a5SGleb Natapov 	u32 offset = address - apic->base_address;
17050105d1a5SGleb Natapov 
17060105d1a5SGleb Natapov 	if (!apic_mmio_in_range(apic, address))
17070105d1a5SGleb Natapov 		return -EOPNOTSUPP;
17080105d1a5SGleb Natapov 
1709d1766202SVitaly Kuznetsov 	if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
1710d1766202SVitaly Kuznetsov 		if (!kvm_check_has_quirk(vcpu->kvm,
1711d1766202SVitaly Kuznetsov 					 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
1712d1766202SVitaly Kuznetsov 			return -EOPNOTSUPP;
1713d1766202SVitaly Kuznetsov 
1714d1766202SVitaly Kuznetsov 		memset(data, 0xff, len);
1715d1766202SVitaly Kuznetsov 		return 0;
1716d1766202SVitaly Kuznetsov 	}
1717d1766202SVitaly Kuznetsov 
17181e6e2755SSuravee Suthikulpanit 	kvm_lapic_reg_read(apic, offset, len, data);
17190105d1a5SGleb Natapov 
17200105d1a5SGleb Natapov 	return 0;
17210105d1a5SGleb Natapov }
17220105d1a5SGleb Natapov 
update_divide_count(struct kvm_lapic * apic)1723edf88417SAvi Kivity static void update_divide_count(struct kvm_lapic *apic)
1724edf88417SAvi Kivity {
1725edf88417SAvi Kivity 	u32 tmp1, tmp2, tdcr;
1726edf88417SAvi Kivity 
1727dfb95954SSuravee Suthikulpanit 	tdcr = kvm_lapic_get_reg(apic, APIC_TDCR);
1728edf88417SAvi Kivity 	tmp1 = tdcr & 0xf;
1729edf88417SAvi Kivity 	tmp2 = ((tmp1 & 0x3) | ((tmp1 & 0x8) >> 1)) + 1;
1730d3c7b77dSMarcelo Tosatti 	apic->divide_count = 0x1 << (tmp2 & 0x7);
1731edf88417SAvi Kivity }
1732edf88417SAvi Kivity 
limit_periodic_timer_frequency(struct kvm_lapic * apic)1733ccbfa1d3SWanpeng Li static void limit_periodic_timer_frequency(struct kvm_lapic *apic)
1734ccbfa1d3SWanpeng Li {
1735ccbfa1d3SWanpeng Li 	/*
1736ccbfa1d3SWanpeng Li 	 * Do not allow the guest to program periodic timers with small
1737ccbfa1d3SWanpeng Li 	 * interval, since the hrtimers are not throttled by the host
1738ccbfa1d3SWanpeng Li 	 * scheduler.
1739ccbfa1d3SWanpeng Li 	 */
1740dedf9c5eSWanpeng Li 	if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
1741ccbfa1d3SWanpeng Li 		s64 min_period = min_timer_period_us * 1000LL;
1742ccbfa1d3SWanpeng Li 
1743ccbfa1d3SWanpeng Li 		if (apic->lapic_timer.period < min_period) {
17440005ca20SJim Mattson 			pr_info_once(
17458d20bd63SSean Christopherson 			    "vcpu %i: requested %lld ns "
1746ccbfa1d3SWanpeng Li 			    "lapic timer period limited to %lld ns\n",
1747ccbfa1d3SWanpeng Li 			    apic->vcpu->vcpu_id,
1748ccbfa1d3SWanpeng Li 			    apic->lapic_timer.period, min_period);
1749ccbfa1d3SWanpeng Li 			apic->lapic_timer.period = min_period;
1750ccbfa1d3SWanpeng Li 		}
1751ccbfa1d3SWanpeng Li 	}
1752ccbfa1d3SWanpeng Li }
1753ccbfa1d3SWanpeng Li 
175494be4b85SWanpeng Li static void cancel_hv_timer(struct kvm_lapic *apic);
175594be4b85SWanpeng Li 
cancel_apic_timer(struct kvm_lapic * apic)1756e898da78SWanpeng Li static void cancel_apic_timer(struct kvm_lapic *apic)
1757e898da78SWanpeng Li {
1758e898da78SWanpeng Li 	hrtimer_cancel(&apic->lapic_timer.timer);
1759e898da78SWanpeng Li 	preempt_disable();
1760e898da78SWanpeng Li 	if (apic->lapic_timer.hv_timer_in_use)
1761e898da78SWanpeng Li 		cancel_hv_timer(apic);
1762e898da78SWanpeng Li 	preempt_enable();
1763619f51daSWanpeng Li 	atomic_set(&apic->lapic_timer.pending, 0);
1764e898da78SWanpeng Li }
1765e898da78SWanpeng Li 
apic_update_lvtt(struct kvm_lapic * apic)1766b6ac0695SRadim Krčmář static void apic_update_lvtt(struct kvm_lapic *apic)
1767b6ac0695SRadim Krčmář {
1768dfb95954SSuravee Suthikulpanit 	u32 timer_mode = kvm_lapic_get_reg(apic, APIC_LVTT) &
1769b6ac0695SRadim Krčmář 			apic->lapic_timer.timer_mode_mask;
1770b6ac0695SRadim Krčmář 
1771b6ac0695SRadim Krčmář 	if (apic->lapic_timer.timer_mode != timer_mode) {
1772c69518c8SWanpeng Li 		if (apic_lvtt_tscdeadline(apic) != (timer_mode ==
1773dedf9c5eSWanpeng Li 				APIC_LVT_TIMER_TSCDEADLINE)) {
1774e898da78SWanpeng Li 			cancel_apic_timer(apic);
177544275932SRadim Krčmář 			kvm_lapic_set_reg(apic, APIC_TMICT, 0);
177644275932SRadim Krčmář 			apic->lapic_timer.period = 0;
177744275932SRadim Krčmář 			apic->lapic_timer.tscdeadline = 0;
1778b6ac0695SRadim Krčmář 		}
1779dedf9c5eSWanpeng Li 		apic->lapic_timer.timer_mode = timer_mode;
1780dedf9c5eSWanpeng Li 		limit_periodic_timer_frequency(apic);
1781b6ac0695SRadim Krčmář 	}
1782b6ac0695SRadim Krčmář }
1783b6ac0695SRadim Krčmář 
1784d0659d94SMarcelo Tosatti /*
1785d0659d94SMarcelo Tosatti  * On APICv, this test will cause a busy wait
1786d0659d94SMarcelo Tosatti  * during a higher-priority task.
1787d0659d94SMarcelo Tosatti  */
1788d0659d94SMarcelo Tosatti 
lapic_timer_int_injected(struct kvm_vcpu * vcpu)1789d0659d94SMarcelo Tosatti static bool lapic_timer_int_injected(struct kvm_vcpu *vcpu)
1790d0659d94SMarcelo Tosatti {
1791d0659d94SMarcelo Tosatti 	struct kvm_lapic *apic = vcpu->arch.apic;
1792dfb95954SSuravee Suthikulpanit 	u32 reg = kvm_lapic_get_reg(apic, APIC_LVTT);
1793d0659d94SMarcelo Tosatti 
1794d0659d94SMarcelo Tosatti 	if (kvm_apic_hw_enabled(apic)) {
1795d0659d94SMarcelo Tosatti 		int vec = reg & APIC_VECTOR_MASK;
1796f9339860SMarcelo Tosatti 		void *bitmap = apic->regs + APIC_ISR;
1797d0659d94SMarcelo Tosatti 
1798ce0a58f4SSean Christopherson 		if (apic->apicv_active)
1799f9339860SMarcelo Tosatti 			bitmap = apic->regs + APIC_IRR;
1800f9339860SMarcelo Tosatti 
1801f9339860SMarcelo Tosatti 		if (apic_test_vector(vec, bitmap))
1802d0659d94SMarcelo Tosatti 			return true;
1803d0659d94SMarcelo Tosatti 	}
1804d0659d94SMarcelo Tosatti 	return false;
1805d0659d94SMarcelo Tosatti }
1806d0659d94SMarcelo Tosatti 
__wait_lapic_expire(struct kvm_vcpu * vcpu,u64 guest_cycles)1807b6aa57c6SSean Christopherson static inline void __wait_lapic_expire(struct kvm_vcpu *vcpu, u64 guest_cycles)
1808b6aa57c6SSean Christopherson {
1809b6aa57c6SSean Christopherson 	u64 timer_advance_ns = vcpu->arch.apic->lapic_timer.timer_advance_ns;
1810b6aa57c6SSean Christopherson 
1811b6aa57c6SSean Christopherson 	/*
1812b6aa57c6SSean Christopherson 	 * If the guest TSC is running at a different ratio than the host, then
1813b6aa57c6SSean Christopherson 	 * convert the delay to nanoseconds to achieve an accurate delay.  Note
1814b6aa57c6SSean Christopherson 	 * that __delay() uses delay_tsc whenever the hardware has TSC, thus
1815b6aa57c6SSean Christopherson 	 * always for VMX enabled hardware.
1816b6aa57c6SSean Christopherson 	 */
1817938c8745SSean Christopherson 	if (vcpu->arch.tsc_scaling_ratio == kvm_caps.default_tsc_scaling_ratio) {
1818b6aa57c6SSean Christopherson 		__delay(min(guest_cycles,
1819b6aa57c6SSean Christopherson 			nsec_to_cycles(vcpu, timer_advance_ns)));
1820b6aa57c6SSean Christopherson 	} else {
1821b6aa57c6SSean Christopherson 		u64 delay_ns = guest_cycles * 1000000ULL;
1822b6aa57c6SSean Christopherson 		do_div(delay_ns, vcpu->arch.virtual_tsc_khz);
1823b6aa57c6SSean Christopherson 		ndelay(min_t(u32, delay_ns, timer_advance_ns));
1824b6aa57c6SSean Christopherson 	}
1825b6aa57c6SSean Christopherson }
1826b6aa57c6SSean Christopherson 
adjust_lapic_timer_advance(struct kvm_vcpu * vcpu,s64 advance_expire_delta)182784ea3acaSWanpeng Li static inline void adjust_lapic_timer_advance(struct kvm_vcpu *vcpu,
1828ec0671d5SWanpeng Li 					      s64 advance_expire_delta)
1829d0659d94SMarcelo Tosatti {
1830d0659d94SMarcelo Tosatti 	struct kvm_lapic *apic = vcpu->arch.apic;
183139497d76SSean Christopherson 	u32 timer_advance_ns = apic->lapic_timer.timer_advance_ns;
183284ea3acaSWanpeng Li 	u64 ns;
183384ea3acaSWanpeng Li 
1834d0f5a86aSWanpeng Li 	/* Do not adjust for tiny fluctuations or large random spikes. */
1835d0f5a86aSWanpeng Li 	if (abs(advance_expire_delta) > LAPIC_TIMER_ADVANCE_ADJUST_MAX ||
1836d0f5a86aSWanpeng Li 	    abs(advance_expire_delta) < LAPIC_TIMER_ADVANCE_ADJUST_MIN)
1837d0f5a86aSWanpeng Li 		return;
1838d0f5a86aSWanpeng Li 
183984ea3acaSWanpeng Li 	/* too early */
1840ec0671d5SWanpeng Li 	if (advance_expire_delta < 0) {
1841ec0671d5SWanpeng Li 		ns = -advance_expire_delta * 1000000ULL;
184284ea3acaSWanpeng Li 		do_div(ns, vcpu->arch.virtual_tsc_khz);
1843d0f5a86aSWanpeng Li 		timer_advance_ns -= ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
184484ea3acaSWanpeng Li 	} else {
184584ea3acaSWanpeng Li 	/* too late */
1846ec0671d5SWanpeng Li 		ns = advance_expire_delta * 1000000ULL;
184784ea3acaSWanpeng Li 		do_div(ns, vcpu->arch.virtual_tsc_khz);
1848d0f5a86aSWanpeng Li 		timer_advance_ns += ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
184984ea3acaSWanpeng Li 	}
185084ea3acaSWanpeng Li 
1851a0f0037eSWanpeng Li 	if (unlikely(timer_advance_ns > LAPIC_TIMER_ADVANCE_NS_MAX))
1852a0f0037eSWanpeng Li 		timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
185384ea3acaSWanpeng Li 	apic->lapic_timer.timer_advance_ns = timer_advance_ns;
185484ea3acaSWanpeng Li }
185584ea3acaSWanpeng Li 
__kvm_wait_lapic_expire(struct kvm_vcpu * vcpu)18560c5f81daSWanpeng Li static void __kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
185784ea3acaSWanpeng Li {
185884ea3acaSWanpeng Li 	struct kvm_lapic *apic = vcpu->arch.apic;
185984ea3acaSWanpeng Li 	u64 guest_tsc, tsc_deadline;
1860d0659d94SMarcelo Tosatti 
1861d0659d94SMarcelo Tosatti 	tsc_deadline = apic->lapic_timer.expired_tscdeadline;
1862d0659d94SMarcelo Tosatti 	apic->lapic_timer.expired_tscdeadline = 0;
18634ba76538SHaozhong Zhang 	guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1864e0ac5351SWanpeng Li 	trace_kvm_wait_lapic_expire(vcpu->vcpu_id, guest_tsc - tsc_deadline);
1865d0659d94SMarcelo Tosatti 
1866e0ac5351SWanpeng Li 	adjust_lapic_timer_advance(vcpu, guest_tsc - tsc_deadline);
186789a58812SSean Christopherson 
18689805cf03SWanpeng Li 	/*
186989a58812SSean Christopherson 	 * If the timer fired early, reread the TSC to account for the overhead
187089a58812SSean Christopherson 	 * of the above adjustment to avoid waiting longer than is necessary.
18719805cf03SWanpeng Li 	 */
18729805cf03SWanpeng Li 	if (guest_tsc < tsc_deadline)
18739805cf03SWanpeng Li 		guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
18749805cf03SWanpeng Li 
1875d0659d94SMarcelo Tosatti 	if (guest_tsc < tsc_deadline)
1876b6aa57c6SSean Christopherson 		__wait_lapic_expire(vcpu, tsc_deadline - guest_tsc);
18773b8a5df6SWanpeng Li }
18780c5f81daSWanpeng Li 
kvm_wait_lapic_expire(struct kvm_vcpu * vcpu)18790c5f81daSWanpeng Li void kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
18800c5f81daSWanpeng Li {
1881010fd37fSWanpeng Li 	if (lapic_in_kernel(vcpu) &&
1882010fd37fSWanpeng Li 	    vcpu->arch.apic->lapic_timer.expired_tscdeadline &&
1883010fd37fSWanpeng Li 	    vcpu->arch.apic->lapic_timer.timer_advance_ns &&
1884010fd37fSWanpeng Li 	    lapic_timer_int_injected(vcpu))
18850c5f81daSWanpeng Li 		__kvm_wait_lapic_expire(vcpu);
18860c5f81daSWanpeng Li }
1887b6c4bc65SWanpeng Li EXPORT_SYMBOL_GPL(kvm_wait_lapic_expire);
18885d87db71SRadim Krčmář 
kvm_apic_inject_pending_timer_irqs(struct kvm_lapic * apic)18890c5f81daSWanpeng Li static void kvm_apic_inject_pending_timer_irqs(struct kvm_lapic *apic)
18900c5f81daSWanpeng Li {
18910c5f81daSWanpeng Li 	struct kvm_timer *ktimer = &apic->lapic_timer;
18920c5f81daSWanpeng Li 
18930c5f81daSWanpeng Li 	kvm_apic_local_deliver(apic, APIC_LVTT);
189417ac43a8SHaiwei Li 	if (apic_lvtt_tscdeadline(apic)) {
18950c5f81daSWanpeng Li 		ktimer->tscdeadline = 0;
189617ac43a8SHaiwei Li 	} else if (apic_lvtt_oneshot(apic)) {
18970c5f81daSWanpeng Li 		ktimer->tscdeadline = 0;
18980c5f81daSWanpeng Li 		ktimer->target_expiration = 0;
18990c5f81daSWanpeng Li 	}
19000c5f81daSWanpeng Li }
19010c5f81daSWanpeng Li 
apic_timer_expired(struct kvm_lapic * apic,bool from_timer_fn)1902ae95f566SWanpeng Li static void apic_timer_expired(struct kvm_lapic *apic, bool from_timer_fn)
19030c5f81daSWanpeng Li {
19040c5f81daSWanpeng Li 	struct kvm_vcpu *vcpu = apic->vcpu;
19050c5f81daSWanpeng Li 	struct kvm_timer *ktimer = &apic->lapic_timer;
19060c5f81daSWanpeng Li 
19070c5f81daSWanpeng Li 	if (atomic_read(&apic->lapic_timer.pending))
19080c5f81daSWanpeng Li 		return;
19090c5f81daSWanpeng Li 
19100c5f81daSWanpeng Li 	if (apic_lvtt_tscdeadline(apic) || ktimer->hv_timer_in_use)
19110c5f81daSWanpeng Li 		ktimer->expired_tscdeadline = ktimer->tscdeadline;
19120c5f81daSWanpeng Li 
1913ce0a58f4SSean Christopherson 	if (!from_timer_fn && apic->apicv_active) {
1914ae95f566SWanpeng Li 		WARN_ON(kvm_get_running_vcpu() != vcpu);
1915ae95f566SWanpeng Li 		kvm_apic_inject_pending_timer_irqs(apic);
1916ae95f566SWanpeng Li 		return;
1917ae95f566SWanpeng Li 	}
1918ae95f566SWanpeng Li 
19190c5f81daSWanpeng Li 	if (kvm_use_posted_timer_interrupt(apic->vcpu)) {
1920beda4301SSean Christopherson 		/*
1921beda4301SSean Christopherson 		 * Ensure the guest's timer has truly expired before posting an
1922beda4301SSean Christopherson 		 * interrupt.  Open code the relevant checks to avoid querying
1923beda4301SSean Christopherson 		 * lapic_timer_int_injected(), which will be false since the
1924beda4301SSean Christopherson 		 * interrupt isn't yet injected.  Waiting until after injecting
1925beda4301SSean Christopherson 		 * is not an option since that won't help a posted interrupt.
1926beda4301SSean Christopherson 		 */
1927beda4301SSean Christopherson 		if (vcpu->arch.apic->lapic_timer.expired_tscdeadline &&
1928beda4301SSean Christopherson 		    vcpu->arch.apic->lapic_timer.timer_advance_ns)
1929beda4301SSean Christopherson 			__kvm_wait_lapic_expire(vcpu);
19300c5f81daSWanpeng Li 		kvm_apic_inject_pending_timer_irqs(apic);
19310c5f81daSWanpeng Li 		return;
19320c5f81daSWanpeng Li 	}
19330c5f81daSWanpeng Li 
19340c5f81daSWanpeng Li 	atomic_inc(&apic->lapic_timer.pending);
1935084071d5SMarcelo Tosatti 	kvm_make_request(KVM_REQ_UNBLOCK, vcpu);
193668ca7663SWanpeng Li 	if (from_timer_fn)
193768ca7663SWanpeng Li 		kvm_vcpu_kick(vcpu);
19380c5f81daSWanpeng Li }
19390c5f81daSWanpeng Li 
start_sw_tscdeadline(struct kvm_lapic * apic)194053f9eedfSYunhong Jiang static void start_sw_tscdeadline(struct kvm_lapic *apic)
194153f9eedfSYunhong Jiang {
194239497d76SSean Christopherson 	struct kvm_timer *ktimer = &apic->lapic_timer;
194339497d76SSean Christopherson 	u64 guest_tsc, tscdeadline = ktimer->tscdeadline;
194453f9eedfSYunhong Jiang 	u64 ns = 0;
194553f9eedfSYunhong Jiang 	ktime_t expire;
194653f9eedfSYunhong Jiang 	struct kvm_vcpu *vcpu = apic->vcpu;
19471448d4a9SThorsten Blum 	u32 this_tsc_khz = vcpu->arch.virtual_tsc_khz;
194853f9eedfSYunhong Jiang 	unsigned long flags;
194953f9eedfSYunhong Jiang 	ktime_t now;
195053f9eedfSYunhong Jiang 
195153f9eedfSYunhong Jiang 	if (unlikely(!tscdeadline || !this_tsc_khz))
195253f9eedfSYunhong Jiang 		return;
195353f9eedfSYunhong Jiang 
195453f9eedfSYunhong Jiang 	local_irq_save(flags);
195553f9eedfSYunhong Jiang 
19565587859fSPaolo Bonzini 	now = ktime_get();
195753f9eedfSYunhong Jiang 	guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1958c09d65d9SLiran Alon 
195953f9eedfSYunhong Jiang 	ns = (tscdeadline - guest_tsc) * 1000000ULL;
196053f9eedfSYunhong Jiang 	do_div(ns, this_tsc_khz);
1961c09d65d9SLiran Alon 
1962c09d65d9SLiran Alon 	if (likely(tscdeadline > guest_tsc) &&
196339497d76SSean Christopherson 	    likely(ns > apic->lapic_timer.timer_advance_ns)) {
196453f9eedfSYunhong Jiang 		expire = ktime_add_ns(now, ns);
196539497d76SSean Christopherson 		expire = ktime_sub_ns(expire, ktimer->timer_advance_ns);
19662c0d278fSSebastian Andrzej Siewior 		hrtimer_start(&ktimer->timer, expire, HRTIMER_MODE_ABS_HARD);
196753f9eedfSYunhong Jiang 	} else
1968ae95f566SWanpeng Li 		apic_timer_expired(apic, false);
196953f9eedfSYunhong Jiang 
197053f9eedfSYunhong Jiang 	local_irq_restore(flags);
197153f9eedfSYunhong Jiang }
197253f9eedfSYunhong Jiang 
tmict_to_ns(struct kvm_lapic * apic,u32 tmict)197324647e0aSPeter Shier static inline u64 tmict_to_ns(struct kvm_lapic *apic, u32 tmict)
197424647e0aSPeter Shier {
1975b460256bSIsaku Yamahata 	return (u64)tmict * apic->vcpu->kvm->arch.apic_bus_cycle_ns *
1976b460256bSIsaku Yamahata 		(u64)apic->divide_count;
197724647e0aSPeter Shier }
197824647e0aSPeter Shier 
update_target_expiration(struct kvm_lapic * apic,uint32_t old_divisor)1979c301b909SWanpeng Li static void update_target_expiration(struct kvm_lapic *apic, uint32_t old_divisor)
1980c301b909SWanpeng Li {
1981c301b909SWanpeng Li 	ktime_t now, remaining;
1982c301b909SWanpeng Li 	u64 ns_remaining_old, ns_remaining_new;
1983c301b909SWanpeng Li 
198424647e0aSPeter Shier 	apic->lapic_timer.period =
198524647e0aSPeter Shier 			tmict_to_ns(apic, kvm_lapic_get_reg(apic, APIC_TMICT));
1986c301b909SWanpeng Li 	limit_periodic_timer_frequency(apic);
1987c301b909SWanpeng Li 
1988c301b909SWanpeng Li 	now = ktime_get();
1989c301b909SWanpeng Li 	remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1990c301b909SWanpeng Li 	if (ktime_to_ns(remaining) < 0)
1991c301b909SWanpeng Li 		remaining = 0;
1992c301b909SWanpeng Li 
1993c301b909SWanpeng Li 	ns_remaining_old = ktime_to_ns(remaining);
1994c301b909SWanpeng Li 	ns_remaining_new = mul_u64_u32_div(ns_remaining_old,
1995c301b909SWanpeng Li 	                                   apic->divide_count, old_divisor);
1996c301b909SWanpeng Li 
1997c301b909SWanpeng Li 	apic->lapic_timer.tscdeadline +=
1998c301b909SWanpeng Li 		nsec_to_cycles(apic->vcpu, ns_remaining_new) -
1999c301b909SWanpeng Li 		nsec_to_cycles(apic->vcpu, ns_remaining_old);
2000c301b909SWanpeng Li 	apic->lapic_timer.target_expiration = ktime_add_ns(now, ns_remaining_new);
2001c301b909SWanpeng Li }
2002c301b909SWanpeng Li 
set_target_expiration(struct kvm_lapic * apic,u32 count_reg)200324647e0aSPeter Shier static bool set_target_expiration(struct kvm_lapic *apic, u32 count_reg)
2004edf88417SAvi Kivity {
2005a3e06bbeSLiu, Jinsong 	ktime_t now;
20068003c9aeSWanpeng Li 	u64 tscl = rdtsc();
200724647e0aSPeter Shier 	s64 deadline;
2008d0659d94SMarcelo Tosatti 
20095587859fSPaolo Bonzini 	now = ktime_get();
201024647e0aSPeter Shier 	apic->lapic_timer.period =
201124647e0aSPeter Shier 			tmict_to_ns(apic, kvm_lapic_get_reg(apic, APIC_TMICT));
2012a3e06bbeSLiu, Jinsong 
20135d74a699SRadim Krčmář 	if (!apic->lapic_timer.period) {
20145d74a699SRadim Krčmář 		apic->lapic_timer.tscdeadline = 0;
20158003c9aeSWanpeng Li 		return false;
20169bc5791dSJan Kiszka 	}
20171444885aSMarcelo Tosatti 
2018ccbfa1d3SWanpeng Li 	limit_periodic_timer_frequency(apic);
201924647e0aSPeter Shier 	deadline = apic->lapic_timer.period;
202024647e0aSPeter Shier 
202124647e0aSPeter Shier 	if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic)) {
202224647e0aSPeter Shier 		if (unlikely(count_reg != APIC_TMICT)) {
202324647e0aSPeter Shier 			deadline = tmict_to_ns(apic,
202424647e0aSPeter Shier 				     kvm_lapic_get_reg(apic, count_reg));
20258e6ed96cSLi RongQing 			if (unlikely(deadline <= 0)) {
20268e6ed96cSLi RongQing 				if (apic_lvtt_period(apic))
202724647e0aSPeter Shier 					deadline = apic->lapic_timer.period;
20288e6ed96cSLi RongQing 				else
20298e6ed96cSLi RongQing 					deadline = 0;
20308e6ed96cSLi RongQing 			}
203124647e0aSPeter Shier 			else if (unlikely(deadline > apic->lapic_timer.period)) {
203224647e0aSPeter Shier 				pr_info_ratelimited(
20338d20bd63SSean Christopherson 				    "vcpu %i: requested lapic timer restore with "
203424647e0aSPeter Shier 				    "starting count register %#x=%u (%lld ns) > initial count (%lld ns). "
203524647e0aSPeter Shier 				    "Using initial count to start timer.\n",
203624647e0aSPeter Shier 				    apic->vcpu->vcpu_id,
203724647e0aSPeter Shier 				    count_reg,
203824647e0aSPeter Shier 				    kvm_lapic_get_reg(apic, count_reg),
203924647e0aSPeter Shier 				    deadline, apic->lapic_timer.period);
204024647e0aSPeter Shier 				kvm_lapic_set_reg(apic, count_reg, 0);
204124647e0aSPeter Shier 				deadline = apic->lapic_timer.period;
204224647e0aSPeter Shier 			}
204324647e0aSPeter Shier 		}
204424647e0aSPeter Shier 	}
20450b975a3cSAvi Kivity 
20468003c9aeSWanpeng Li 	apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
204724647e0aSPeter Shier 		nsec_to_cycles(apic->vcpu, deadline);
204824647e0aSPeter Shier 	apic->lapic_timer.target_expiration = ktime_add_ns(now, deadline);
20498003c9aeSWanpeng Li 
20508003c9aeSWanpeng Li 	return true;
20518003c9aeSWanpeng Li }
20528003c9aeSWanpeng Li 
advance_periodic_target_expiration(struct kvm_lapic * apic)20538003c9aeSWanpeng Li static void advance_periodic_target_expiration(struct kvm_lapic *apic)
20548003c9aeSWanpeng Li {
2055d8f2f498SDavid Vrabel 	ktime_t now = ktime_get();
2056d8f2f498SDavid Vrabel 	u64 tscl = rdtsc();
2057d8f2f498SDavid Vrabel 	ktime_t delta;
2058d8f2f498SDavid Vrabel 
2059d8f2f498SDavid Vrabel 	/*
2060d8f2f498SDavid Vrabel 	 * Synchronize both deadlines to the same time source or
2061d8f2f498SDavid Vrabel 	 * differences in the periods (caused by differences in the
2062d8f2f498SDavid Vrabel 	 * underlying clocks or numerical approximation errors) will
2063d8f2f498SDavid Vrabel 	 * cause the two to drift apart over time as the errors
2064d8f2f498SDavid Vrabel 	 * accumulate.
2065d8f2f498SDavid Vrabel 	 */
20668003c9aeSWanpeng Li 	apic->lapic_timer.target_expiration =
20678003c9aeSWanpeng Li 		ktime_add_ns(apic->lapic_timer.target_expiration,
20688003c9aeSWanpeng Li 				apic->lapic_timer.period);
2069d8f2f498SDavid Vrabel 	delta = ktime_sub(apic->lapic_timer.target_expiration, now);
2070d8f2f498SDavid Vrabel 	apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
2071d8f2f498SDavid Vrabel 		nsec_to_cycles(apic->vcpu, delta);
20727d7f7da2SWanpeng Li }
20737d7f7da2SWanpeng Li 
start_sw_period(struct kvm_lapic * apic)2074ecf08dadSAnthoine Bourgeois static void start_sw_period(struct kvm_lapic *apic)
2075ecf08dadSAnthoine Bourgeois {
2076ecf08dadSAnthoine Bourgeois 	if (!apic->lapic_timer.period)
2077ecf08dadSAnthoine Bourgeois 		return;
2078ecf08dadSAnthoine Bourgeois 
2079ecf08dadSAnthoine Bourgeois 	if (ktime_after(ktime_get(),
2080ecf08dadSAnthoine Bourgeois 			apic->lapic_timer.target_expiration)) {
2081ae95f566SWanpeng Li 		apic_timer_expired(apic, false);
2082ecf08dadSAnthoine Bourgeois 
2083ecf08dadSAnthoine Bourgeois 		if (apic_lvtt_oneshot(apic))
2084ecf08dadSAnthoine Bourgeois 			return;
2085ecf08dadSAnthoine Bourgeois 
2086ecf08dadSAnthoine Bourgeois 		advance_periodic_target_expiration(apic);
2087ecf08dadSAnthoine Bourgeois 	}
2088ecf08dadSAnthoine Bourgeois 
2089ecf08dadSAnthoine Bourgeois 	hrtimer_start(&apic->lapic_timer.timer,
2090ecf08dadSAnthoine Bourgeois 		apic->lapic_timer.target_expiration,
2091edec6e01SHe Zhe 		HRTIMER_MODE_ABS_HARD);
2092ecf08dadSAnthoine Bourgeois }
2093ecf08dadSAnthoine Bourgeois 
kvm_lapic_hv_timer_in_use(struct kvm_vcpu * vcpu)2094edf88417SAvi Kivity bool kvm_lapic_hv_timer_in_use(struct kvm_vcpu *vcpu)
2095edf88417SAvi Kivity {
2096edf88417SAvi Kivity 	if (!lapic_in_kernel(vcpu))
2097edf88417SAvi Kivity 		return false;
2098edf88417SAvi Kivity 
2099edf88417SAvi Kivity 	return vcpu->arch.apic->lapic_timer.hv_timer_in_use;
2100edf88417SAvi Kivity }
2101edf88417SAvi Kivity 
cancel_hv_timer(struct kvm_lapic * apic)21027e810a38SWanpeng Li static void cancel_hv_timer(struct kvm_lapic *apic)
2103edf88417SAvi Kivity {
21041d518c68SWanpeng Li 	WARN_ON(preemptible());
2105a749e247SPaolo Bonzini 	WARN_ON(!apic->lapic_timer.hv_timer_in_use);
210689604647SWei Wang 	kvm_x86_call(cancel_hv_timer)(apic->vcpu);
2107edf88417SAvi Kivity 	apic->lapic_timer.hv_timer_in_use = false;
2108edf88417SAvi Kivity }
2109edf88417SAvi Kivity 
start_hv_timer(struct kvm_lapic * apic)2110a749e247SPaolo Bonzini static bool start_hv_timer(struct kvm_lapic *apic)
211135ee9e48SPaolo Bonzini {
211235ee9e48SPaolo Bonzini 	struct kvm_timer *ktimer = &apic->lapic_timer;
2113f9927982SSean Christopherson 	struct kvm_vcpu *vcpu = apic->vcpu;
2114f9927982SSean Christopherson 	bool expired;
211535ee9e48SPaolo Bonzini 
21161d518c68SWanpeng Li 	WARN_ON(preemptible());
2117199a8b84SPaolo Bonzini 	if (!kvm_can_use_hv_timer(vcpu))
2118a749e247SPaolo Bonzini 		return false;
2119a749e247SPaolo Bonzini 
212086bbc1e6SRadim Krčmář 	if (!ktimer->tscdeadline)
212186bbc1e6SRadim Krčmář 		return false;
212286bbc1e6SRadim Krčmář 
212389604647SWei Wang 	if (kvm_x86_call(set_hv_timer)(vcpu, ktimer->tscdeadline, &expired))
212435ee9e48SPaolo Bonzini 		return false;
212535ee9e48SPaolo Bonzini 
212635ee9e48SPaolo Bonzini 	ktimer->hv_timer_in_use = true;
212735ee9e48SPaolo Bonzini 	hrtimer_cancel(&ktimer->timer);
212835ee9e48SPaolo Bonzini 
212935ee9e48SPaolo Bonzini 	/*
2130f1ba5cfbSSean Christopherson 	 * To simplify handling the periodic timer, leave the hv timer running
2131f1ba5cfbSSean Christopherson 	 * even if the deadline timer has expired, i.e. rely on the resulting
2132f1ba5cfbSSean Christopherson 	 * VM-Exit to recompute the periodic timer's target expiration.
213335ee9e48SPaolo Bonzini 	 */
2134f1ba5cfbSSean Christopherson 	if (!apic_lvtt_period(apic)) {
2135f1ba5cfbSSean Christopherson 		/*
2136f1ba5cfbSSean Christopherson 		 * Cancel the hv timer if the sw timer fired while the hv timer
2137f1ba5cfbSSean Christopherson 		 * was being programmed, or if the hv timer itself expired.
2138f1ba5cfbSSean Christopherson 		 */
2139f1ba5cfbSSean Christopherson 		if (atomic_read(&ktimer->pending)) {
2140f1ba5cfbSSean Christopherson 			cancel_hv_timer(apic);
2141f9927982SSean Christopherson 		} else if (expired) {
2142ae95f566SWanpeng Li 			apic_timer_expired(apic, false);
2143f1ba5cfbSSean Christopherson 			cancel_hv_timer(apic);
2144f1ba5cfbSSean Christopherson 		}
2145c8533544SWanpeng Li 	}
2146a749e247SPaolo Bonzini 
2147f9927982SSean Christopherson 	trace_kvm_hv_timer_state(vcpu->vcpu_id, ktimer->hv_timer_in_use);
2148f1ba5cfbSSean Christopherson 
214935ee9e48SPaolo Bonzini 	return true;
215035ee9e48SPaolo Bonzini }
215135ee9e48SPaolo Bonzini 
start_sw_timer(struct kvm_lapic * apic)2152a749e247SPaolo Bonzini static void start_sw_timer(struct kvm_lapic *apic)
2153edf88417SAvi Kivity {
2154a749e247SPaolo Bonzini 	struct kvm_timer *ktimer = &apic->lapic_timer;
21551d518c68SWanpeng Li 
21561d518c68SWanpeng Li 	WARN_ON(preemptible());
2157edf88417SAvi Kivity 	if (apic->lapic_timer.hv_timer_in_use)
21587e810a38SWanpeng Li 		cancel_hv_timer(apic);
2159a749e247SPaolo Bonzini 	if (!apic_lvtt_period(apic) && atomic_read(&ktimer->pending))
2160a749e247SPaolo Bonzini 		return;
2161a749e247SPaolo Bonzini 
2162a749e247SPaolo Bonzini 	if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
2163a749e247SPaolo Bonzini 		start_sw_period(apic);
2164a749e247SPaolo Bonzini 	else if (apic_lvtt_tscdeadline(apic))
2165a749e247SPaolo Bonzini 		start_sw_tscdeadline(apic);
2166a749e247SPaolo Bonzini 	trace_kvm_hv_timer_state(apic->vcpu->vcpu_id, false);
2167edf88417SAvi Kivity }
216835ee9e48SPaolo Bonzini 
restart_apic_timer(struct kvm_lapic * apic)2169a749e247SPaolo Bonzini static void restart_apic_timer(struct kvm_lapic *apic)
2170a749e247SPaolo Bonzini {
21711d518c68SWanpeng Li 	preempt_disable();
21724ca88b3fSSean Christopherson 
21734ca88b3fSSean Christopherson 	if (!apic_lvtt_period(apic) && atomic_read(&apic->lapic_timer.pending))
21744ca88b3fSSean Christopherson 		goto out;
21754ca88b3fSSean Christopherson 
2176a749e247SPaolo Bonzini 	if (!start_hv_timer(apic))
2177a749e247SPaolo Bonzini 		start_sw_timer(apic);
21784ca88b3fSSean Christopherson out:
21791d518c68SWanpeng Li 	preempt_enable();
2180edf88417SAvi Kivity }
2181edf88417SAvi Kivity 
kvm_lapic_expired_hv_timer(struct kvm_vcpu * vcpu)21828003c9aeSWanpeng Li void kvm_lapic_expired_hv_timer(struct kvm_vcpu *vcpu)
21838003c9aeSWanpeng Li {
21848003c9aeSWanpeng Li 	struct kvm_lapic *apic = vcpu->arch.apic;
21858003c9aeSWanpeng Li 
21861d518c68SWanpeng Li 	preempt_disable();
21871d518c68SWanpeng Li 	/* If the preempt notifier has already run, it also called apic_timer_expired */
21881d518c68SWanpeng Li 	if (!apic->lapic_timer.hv_timer_in_use)
21891d518c68SWanpeng Li 		goto out;
2190d92a5d1cSSean Christopherson 	WARN_ON(kvm_vcpu_is_blocking(vcpu));
2191ae95f566SWanpeng Li 	apic_timer_expired(apic, false);
2192d981dd15SWanpeng Li 	cancel_hv_timer(apic);
21938003c9aeSWanpeng Li 
21948003c9aeSWanpeng Li 	if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
21958003c9aeSWanpeng Li 		advance_periodic_target_expiration(apic);
2196a749e247SPaolo Bonzini 		restart_apic_timer(apic);
21978003c9aeSWanpeng Li 	}
21981d518c68SWanpeng Li out:
21991d518c68SWanpeng Li 	preempt_enable();
22008003c9aeSWanpeng Li }
22018003c9aeSWanpeng Li EXPORT_SYMBOL_GPL(kvm_lapic_expired_hv_timer);
22028003c9aeSWanpeng Li 
kvm_lapic_switch_to_hv_timer(struct kvm_vcpu * vcpu)2203edf88417SAvi Kivity void kvm_lapic_switch_to_hv_timer(struct kvm_vcpu *vcpu)
2204edf88417SAvi Kivity {
2205a749e247SPaolo Bonzini 	restart_apic_timer(vcpu->arch.apic);
2206edf88417SAvi Kivity }
2207edf88417SAvi Kivity 
kvm_lapic_switch_to_sw_timer(struct kvm_vcpu * vcpu)2208edf88417SAvi Kivity void kvm_lapic_switch_to_sw_timer(struct kvm_vcpu *vcpu)
2209edf88417SAvi Kivity {
2210edf88417SAvi Kivity 	struct kvm_lapic *apic = vcpu->arch.apic;
2211edf88417SAvi Kivity 
22121d518c68SWanpeng Li 	preempt_disable();
2213edf88417SAvi Kivity 	/* Possibly the TSC deadline timer is not enabled yet */
2214a749e247SPaolo Bonzini 	if (apic->lapic_timer.hv_timer_in_use)
2215a749e247SPaolo Bonzini 		start_sw_timer(apic);
22161d518c68SWanpeng Li 	preempt_enable();
2217edf88417SAvi Kivity }
2218edf88417SAvi Kivity 
kvm_lapic_restart_hv_timer(struct kvm_vcpu * vcpu)2219a749e247SPaolo Bonzini void kvm_lapic_restart_hv_timer(struct kvm_vcpu *vcpu)
2220a749e247SPaolo Bonzini {
2221a749e247SPaolo Bonzini 	struct kvm_lapic *apic = vcpu->arch.apic;
2222a749e247SPaolo Bonzini 
2223a749e247SPaolo Bonzini 	WARN_ON(!apic->lapic_timer.hv_timer_in_use);
2224a749e247SPaolo Bonzini 	restart_apic_timer(apic);
2225a749e247SPaolo Bonzini }
2226a749e247SPaolo Bonzini 
__start_apic_timer(struct kvm_lapic * apic,u32 count_reg)222724647e0aSPeter Shier static void __start_apic_timer(struct kvm_lapic *apic, u32 count_reg)
2228edf88417SAvi Kivity {
2229edf88417SAvi Kivity 	atomic_set(&apic->lapic_timer.pending, 0);
2230edf88417SAvi Kivity 
2231a749e247SPaolo Bonzini 	if ((apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
223224647e0aSPeter Shier 	    && !set_target_expiration(apic, count_reg))
2233a749e247SPaolo Bonzini 		return;
2234a749e247SPaolo Bonzini 
2235a749e247SPaolo Bonzini 	restart_apic_timer(apic);
2236edf88417SAvi Kivity }
2237edf88417SAvi Kivity 
start_apic_timer(struct kvm_lapic * apic)223824647e0aSPeter Shier static void start_apic_timer(struct kvm_lapic *apic)
223924647e0aSPeter Shier {
224024647e0aSPeter Shier 	__start_apic_timer(apic, APIC_TMICT);
224124647e0aSPeter Shier }
224224647e0aSPeter Shier 
apic_manage_nmi_watchdog(struct kvm_lapic * apic,u32 lvt0_val)2243cc6e462cSJan Kiszka static void apic_manage_nmi_watchdog(struct kvm_lapic *apic, u32 lvt0_val)
2244cc6e462cSJan Kiszka {
224559fd1323SRadim Krčmář 	bool lvt0_in_nmi_mode = apic_lvt_nmi_mode(lvt0_val);
2246cc6e462cSJan Kiszka 
224759fd1323SRadim Krčmář 	if (apic->lvt0_in_nmi_mode != lvt0_in_nmi_mode) {
224859fd1323SRadim Krčmář 		apic->lvt0_in_nmi_mode = lvt0_in_nmi_mode;
224959fd1323SRadim Krčmář 		if (lvt0_in_nmi_mode) {
225042720138SRadim Krčmář 			atomic_inc(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
225159fd1323SRadim Krčmář 		} else
225242720138SRadim Krčmář 			atomic_dec(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
2253cc6e462cSJan Kiszka 	}
225459fd1323SRadim Krčmář }
2255cc6e462cSJan Kiszka 
get_lvt_index(u32 reg)22564b903561SJue Wang static int get_lvt_index(u32 reg)
22574b903561SJue Wang {
22584b903561SJue Wang 	if (reg == APIC_LVTCMCI)
22594b903561SJue Wang 		return LVT_CMCI;
22604b903561SJue Wang 	if (reg < APIC_LVTT || reg > APIC_LVTERR)
22614b903561SJue Wang 		return -1;
22624b903561SJue Wang 	return array_index_nospec(
22634b903561SJue Wang 			(reg - APIC_LVTT) >> 4, KVM_APIC_MAX_NR_LVT_ENTRIES);
22644b903561SJue Wang }
22654b903561SJue Wang 
kvm_lapic_reg_write(struct kvm_lapic * apic,u32 reg,u32 val)226670180052SSean Christopherson static int kvm_lapic_reg_write(struct kvm_lapic *apic, u32 reg, u32 val)
2267edf88417SAvi Kivity {
22680105d1a5SGleb Natapov 	int ret = 0;
2269edf88417SAvi Kivity 
22700105d1a5SGleb Natapov 	trace_kvm_apic_write(reg, val);
2271edf88417SAvi Kivity 
22720105d1a5SGleb Natapov 	switch (reg) {
2273edf88417SAvi Kivity 	case APIC_ID:		/* Local APIC ID */
22743743c2f0SMaxim Levitsky 		if (!apic_x2apic_mode(apic)) {
2275a92e2543SRadim Krčmář 			kvm_apic_set_xapic_id(apic, val >> 24);
22763743c2f0SMaxim Levitsky 		} else {
22770105d1a5SGleb Natapov 			ret = 1;
22783743c2f0SMaxim Levitsky 		}
2279edf88417SAvi Kivity 		break;
2280edf88417SAvi Kivity 
2281edf88417SAvi Kivity 	case APIC_TASKPRI:
2282b209749fSAvi Kivity 		report_tpr_access(apic, true);
2283edf88417SAvi Kivity 		apic_set_tpr(apic, val & 0xff);
2284edf88417SAvi Kivity 		break;
2285edf88417SAvi Kivity 
2286edf88417SAvi Kivity 	case APIC_EOI:
2287edf88417SAvi Kivity 		apic_set_eoi(apic);
2288edf88417SAvi Kivity 		break;
2289edf88417SAvi Kivity 
2290edf88417SAvi Kivity 	case APIC_LDR:
22910105d1a5SGleb Natapov 		if (!apic_x2apic_mode(apic))
22921e08ec4aSGleb Natapov 			kvm_apic_set_ldr(apic, val & APIC_LDR_MASK);
22930105d1a5SGleb Natapov 		else
22940105d1a5SGleb Natapov 			ret = 1;
2295edf88417SAvi Kivity 		break;
2296edf88417SAvi Kivity 
2297edf88417SAvi Kivity 	case APIC_DFR:
2298ae6f2496SWanpeng Li 		if (!apic_x2apic_mode(apic))
2299ae6f2496SWanpeng Li 			kvm_apic_set_dfr(apic, val | 0x0FFFFFFF);
2300ae6f2496SWanpeng Li 		else
23010105d1a5SGleb Natapov 			ret = 1;
2302edf88417SAvi Kivity 		break;
2303edf88417SAvi Kivity 
2304fc61b800SGleb Natapov 	case APIC_SPIV: {
2305fc61b800SGleb Natapov 		u32 mask = 0x3ff;
2306dfb95954SSuravee Suthikulpanit 		if (kvm_lapic_get_reg(apic, APIC_LVR) & APIC_LVR_DIRECTED_EOI)
2307fc61b800SGleb Natapov 			mask |= APIC_SPIV_DIRECTED_EOI;
2308f8c1ea10SGleb Natapov 		apic_set_spiv(apic, val & mask);
2309edf88417SAvi Kivity 		if (!(val & APIC_SPIV_APIC_ENABLED)) {
2310edf88417SAvi Kivity 			int i;
2311edf88417SAvi Kivity 
23124b903561SJue Wang 			for (i = 0; i < apic->nr_lvt_entries; i++) {
2313987f625eSJue Wang 				kvm_lapic_set_reg(apic, APIC_LVTx(i),
23144b903561SJue Wang 					kvm_lapic_get_reg(apic, APIC_LVTx(i)) | APIC_LVT_MASKED);
2315edf88417SAvi Kivity 			}
2316b6ac0695SRadim Krčmář 			apic_update_lvtt(apic);
2317d3c7b77dSMarcelo Tosatti 			atomic_set(&apic->lapic_timer.pending, 0);
2318edf88417SAvi Kivity 
2319edf88417SAvi Kivity 		}
2320edf88417SAvi Kivity 		break;
2321fc61b800SGleb Natapov 	}
2322edf88417SAvi Kivity 	case APIC_ICR:
2323a57a3168SSean Christopherson 		WARN_ON_ONCE(apic_x2apic_mode(apic));
2324a57a3168SSean Christopherson 
2325edf88417SAvi Kivity 		/* No delay here, so we always clear the pending bit */
2326bd17f417SSean Christopherson 		val &= ~APIC_ICR_BUSY;
2327d5361678SWanpeng Li 		kvm_apic_send_ipi(apic, val, kvm_lapic_get_reg(apic, APIC_ICR2));
23282b0911d1SWanpeng Li 		kvm_lapic_set_reg(apic, APIC_ICR, val);
2329edf88417SAvi Kivity 		break;
2330edf88417SAvi Kivity 	case APIC_ICR2:
2331a57a3168SSean Christopherson 		if (apic_x2apic_mode(apic))
2332a57a3168SSean Christopherson 			ret = 1;
2333a57a3168SSean Christopherson 		else
2334a57a3168SSean Christopherson 			kvm_lapic_set_reg(apic, APIC_ICR2, val & 0xff000000);
2335edf88417SAvi Kivity 		break;
2336edf88417SAvi Kivity 
233723930f95SJan Kiszka 	case APIC_LVT0:
2338cc6e462cSJan Kiszka 		apic_manage_nmi_watchdog(apic, val);
2339df561f66SGustavo A. R. Silva 		fallthrough;
2340edf88417SAvi Kivity 	case APIC_LVTTHMR:
2341edf88417SAvi Kivity 	case APIC_LVTPC:
2342edf88417SAvi Kivity 	case APIC_LVT1:
23434b903561SJue Wang 	case APIC_LVTERR:
23444b903561SJue Wang 	case APIC_LVTCMCI: {
23454b903561SJue Wang 		u32 index = get_lvt_index(reg);
23464b903561SJue Wang 		if (!kvm_lapic_lvt_supported(apic, index)) {
23474b903561SJue Wang 			ret = 1;
23484b903561SJue Wang 			break;
23494b903561SJue Wang 		}
2350c48f1496SGleb Natapov 		if (!kvm_apic_sw_enabled(apic))
2351edf88417SAvi Kivity 			val |= APIC_LVT_MASKED;
23524bf79cb0SMarios Pomonis 		val &= apic_lvt_mask[index];
23531e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, reg, val);
2354edf88417SAvi Kivity 		break;
23554bf79cb0SMarios Pomonis 	}
2356edf88417SAvi Kivity 
2357b6ac0695SRadim Krčmář 	case APIC_LVTT:
2358c48f1496SGleb Natapov 		if (!kvm_apic_sw_enabled(apic))
2359a3e06bbeSLiu, Jinsong 			val |= APIC_LVT_MASKED;
2360a3e06bbeSLiu, Jinsong 		val &= (apic_lvt_mask[0] | apic->lapic_timer.timer_mode_mask);
23611e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, APIC_LVTT, val);
2362b6ac0695SRadim Krčmář 		apic_update_lvtt(apic);
2363a3e06bbeSLiu, Jinsong 		break;
2364a3e06bbeSLiu, Jinsong 
2365edf88417SAvi Kivity 	case APIC_TMICT:
2366a3e06bbeSLiu, Jinsong 		if (apic_lvtt_tscdeadline(apic))
2367a3e06bbeSLiu, Jinsong 			break;
2368a3e06bbeSLiu, Jinsong 
2369e898da78SWanpeng Li 		cancel_apic_timer(apic);
23701e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, APIC_TMICT, val);
2371edf88417SAvi Kivity 		start_apic_timer(apic);
23720105d1a5SGleb Natapov 		break;
2373edf88417SAvi Kivity 
2374c301b909SWanpeng Li 	case APIC_TDCR: {
2375c301b909SWanpeng Li 		uint32_t old_divisor = apic->divide_count;
2376c301b909SWanpeng Li 
2377a445fc45SWanpeng Li 		kvm_lapic_set_reg(apic, APIC_TDCR, val & 0xb);
2378edf88417SAvi Kivity 		update_divide_count(apic);
2379c301b909SWanpeng Li 		if (apic->divide_count != old_divisor &&
2380c301b909SWanpeng Li 				apic->lapic_timer.period) {
2381c301b909SWanpeng Li 			hrtimer_cancel(&apic->lapic_timer.timer);
2382c301b909SWanpeng Li 			update_target_expiration(apic, old_divisor);
2383c301b909SWanpeng Li 			restart_apic_timer(apic);
2384c301b909SWanpeng Li 		}
2385edf88417SAvi Kivity 		break;
2386c301b909SWanpeng Li 	}
23870105d1a5SGleb Natapov 	case APIC_ESR:
23880d88800dSYi Wang 		if (apic_x2apic_mode(apic) && val != 0)
23890105d1a5SGleb Natapov 			ret = 1;
23900105d1a5SGleb Natapov 		break;
23910105d1a5SGleb Natapov 
23920105d1a5SGleb Natapov 	case APIC_SELF_IPI:
2393ba5838abSSean Christopherson 		/*
2394ba5838abSSean Christopherson 		 * Self-IPI exists only when x2APIC is enabled.  Bits 7:0 hold
2395ba5838abSSean Christopherson 		 * the vector, everything else is reserved.
2396ba5838abSSean Christopherson 		 */
2397ba5838abSSean Christopherson 		if (!apic_x2apic_mode(apic) || (val & ~APIC_VECTOR_MASK))
23980105d1a5SGleb Natapov 			ret = 1;
2399ba5838abSSean Christopherson 		else
2400ba5838abSSean Christopherson 			kvm_apic_send_ipi(apic, APIC_DEST_SELF | val, 0);
24010105d1a5SGleb Natapov 		break;
2402edf88417SAvi Kivity 	default:
24030105d1a5SGleb Natapov 		ret = 1;
2404edf88417SAvi Kivity 		break;
2405edf88417SAvi Kivity 	}
24060d88800dSYi Wang 
2407bd17f417SSean Christopherson 	/*
2408bd17f417SSean Christopherson 	 * Recalculate APIC maps if necessary, e.g. if the software enable bit
2409bd17f417SSean Christopherson 	 * was toggled, the APIC ID changed, etc...   The maps are marked dirty
2410bd17f417SSean Christopherson 	 * on relevant changes, i.e. this is a nop for most writes.
2411bd17f417SSean Christopherson 	 */
24124abaffceSWanpeng Li 	kvm_recalculate_apic_map(apic->vcpu->kvm);
24134abaffceSWanpeng Li 
24140105d1a5SGleb Natapov 	return ret;
24150105d1a5SGleb Natapov }
24160105d1a5SGleb Natapov 
apic_mmio_write(struct kvm_vcpu * vcpu,struct kvm_io_device * this,gpa_t address,int len,const void * data)2417e32edf4fSNikolay Nikolaev static int apic_mmio_write(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
24180105d1a5SGleb Natapov 			    gpa_t address, int len, const void *data)
24190105d1a5SGleb Natapov {
24200105d1a5SGleb Natapov 	struct kvm_lapic *apic = to_lapic(this);
24210105d1a5SGleb Natapov 	unsigned int offset = address - apic->base_address;
24220105d1a5SGleb Natapov 	u32 val;
24230105d1a5SGleb Natapov 
24240105d1a5SGleb Natapov 	if (!apic_mmio_in_range(apic, address))
24250105d1a5SGleb Natapov 		return -EOPNOTSUPP;
24260105d1a5SGleb Natapov 
2427d1766202SVitaly Kuznetsov 	if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
2428d1766202SVitaly Kuznetsov 		if (!kvm_check_has_quirk(vcpu->kvm,
2429d1766202SVitaly Kuznetsov 					 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
2430d1766202SVitaly Kuznetsov 			return -EOPNOTSUPP;
2431d1766202SVitaly Kuznetsov 
2432d1766202SVitaly Kuznetsov 		return 0;
2433d1766202SVitaly Kuznetsov 	}
2434d1766202SVitaly Kuznetsov 
24350105d1a5SGleb Natapov 	/*
24360105d1a5SGleb Natapov 	 * APIC register must be aligned on 128-bits boundary.
24370105d1a5SGleb Natapov 	 * 32/64/128 bits registers must be accessed thru 32 bits.
24380105d1a5SGleb Natapov 	 * Refer SDM 8.4.1
24390105d1a5SGleb Natapov 	 */
24400d88800dSYi Wang 	if (len != 4 || (offset & 0xf))
2441756975bbSSheng Yang 		return 0;
24420105d1a5SGleb Natapov 
24430105d1a5SGleb Natapov 	val = *(u32*)data;
24440105d1a5SGleb Natapov 
24450d88800dSYi Wang 	kvm_lapic_reg_write(apic, offset & 0xff0, val);
24460105d1a5SGleb Natapov 
2447bda9020eSMichael S. Tsirkin 	return 0;
2448edf88417SAvi Kivity }
2449edf88417SAvi Kivity 
kvm_lapic_set_eoi(struct kvm_vcpu * vcpu)245058fbbf26SKevin Tian void kvm_lapic_set_eoi(struct kvm_vcpu *vcpu)
245158fbbf26SKevin Tian {
24521e6e2755SSuravee Suthikulpanit 	kvm_lapic_reg_write(vcpu->arch.apic, APIC_EOI, 0);
245358fbbf26SKevin Tian }
245458fbbf26SKevin Tian EXPORT_SYMBOL_GPL(kvm_lapic_set_eoi);
245558fbbf26SKevin Tian 
2456d3323434SSean Christopherson #define X2APIC_ICR_RESERVED_BITS (GENMASK_ULL(31, 20) | GENMASK_ULL(17, 16) | BIT(13))
2457d3323434SSean Christopherson 
kvm_x2apic_icr_write(struct kvm_lapic * apic,u64 data)2458d3323434SSean Christopherson int kvm_x2apic_icr_write(struct kvm_lapic *apic, u64 data)
2459d3323434SSean Christopherson {
2460d3323434SSean Christopherson 	if (data & X2APIC_ICR_RESERVED_BITS)
2461d3323434SSean Christopherson 		return 1;
2462d3323434SSean Christopherson 
2463d3323434SSean Christopherson 	/*
2464d3323434SSean Christopherson 	 * The BUSY bit is reserved on both Intel and AMD in x2APIC mode, but
2465d3323434SSean Christopherson 	 * only AMD requires it to be zero, Intel essentially just ignores the
2466d3323434SSean Christopherson 	 * bit.  And if IPI virtualization (Intel) or x2AVIC (AMD) is enabled,
2467d3323434SSean Christopherson 	 * the CPU performs the reserved bits checks, i.e. the underlying CPU
2468d3323434SSean Christopherson 	 * behavior will "win".  Arbitrarily clear the BUSY bit, as there is no
2469d3323434SSean Christopherson 	 * sane way to provide consistent behavior with respect to hardware.
2470d3323434SSean Christopherson 	 */
2471d3323434SSean Christopherson 	data &= ~APIC_ICR_BUSY;
2472d3323434SSean Christopherson 
2473d3323434SSean Christopherson 	kvm_apic_send_ipi(apic, (u32)data, (u32)(data >> 32));
247473b42dc6SSean Christopherson 	if (kvm_x86_ops.x2apic_icr_is_split) {
247573b42dc6SSean Christopherson 		kvm_lapic_set_reg(apic, APIC_ICR, data);
247673b42dc6SSean Christopherson 		kvm_lapic_set_reg(apic, APIC_ICR2, data >> 32);
247773b42dc6SSean Christopherson 	} else {
2478d3323434SSean Christopherson 		kvm_lapic_set_reg64(apic, APIC_ICR, data);
247973b42dc6SSean Christopherson 	}
2480d3323434SSean Christopherson 	trace_kvm_apic_write(APIC_ICR, data);
2481d3323434SSean Christopherson 	return 0;
2482d3323434SSean Christopherson }
2483d3323434SSean Christopherson 
kvm_x2apic_icr_read(struct kvm_lapic * apic)248473b42dc6SSean Christopherson static u64 kvm_x2apic_icr_read(struct kvm_lapic *apic)
248573b42dc6SSean Christopherson {
248673b42dc6SSean Christopherson 	if (kvm_x86_ops.x2apic_icr_is_split)
248773b42dc6SSean Christopherson 		return (u64)kvm_lapic_get_reg(apic, APIC_ICR) |
248873b42dc6SSean Christopherson 		       (u64)kvm_lapic_get_reg(apic, APIC_ICR2) << 32;
248973b42dc6SSean Christopherson 
249073b42dc6SSean Christopherson 	return kvm_lapic_get_reg64(apic, APIC_ICR);
249173b42dc6SSean Christopherson }
249273b42dc6SSean Christopherson 
249383d4c286SYang Zhang /* emulate APIC access in a trap manner */
kvm_apic_write_nodecode(struct kvm_vcpu * vcpu,u32 offset)249483d4c286SYang Zhang void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset)
249583d4c286SYang Zhang {
24965413bcbaSZeng Guang 	struct kvm_lapic *apic = vcpu->arch.apic;
24975413bcbaSZeng Guang 
24981bd9dfecSSuravee Suthikulpanit 	/*
2499629d3698STao Su 	 * ICR is a single 64-bit register when x2APIC is enabled, all others
2500629d3698STao Su 	 * registers hold 32-bit values.  For legacy xAPIC, ICR writes need to
2501629d3698STao Su 	 * go down the common path to get the upper half from ICR2.
2502629d3698STao Su 	 *
2503629d3698STao Su 	 * Note, using the write helpers may incur an unnecessary write to the
2504629d3698STao Su 	 * virtual APIC state, but KVM needs to conditionally modify the value
2505629d3698STao Su 	 * in certain cases, e.g. to clear the ICR busy bit.  The cost of extra
2506629d3698STao Su 	 * conditional branches is likely a wash relative to the cost of the
2507629d3698STao Su 	 * maybe-unecessary write, and both are in the noise anyways.
25081bd9dfecSSuravee Suthikulpanit 	 */
2509629d3698STao Su 	if (apic_x2apic_mode(apic) && offset == APIC_ICR)
251073b42dc6SSean Christopherson 		WARN_ON_ONCE(kvm_x2apic_icr_write(apic, kvm_x2apic_icr_read(apic)));
2511629d3698STao Su 	else
2512629d3698STao Su 		kvm_lapic_reg_write(apic, offset, kvm_lapic_get_reg(apic, offset));
251383d4c286SYang Zhang }
251483d4c286SYang Zhang EXPORT_SYMBOL_GPL(kvm_apic_write_nodecode);
251583d4c286SYang Zhang 
kvm_free_lapic(struct kvm_vcpu * vcpu)2516edf88417SAvi Kivity void kvm_free_lapic(struct kvm_vcpu *vcpu)
2517edf88417SAvi Kivity {
2518f8c1ea10SGleb Natapov 	struct kvm_lapic *apic = vcpu->arch.apic;
2519f8c1ea10SGleb Natapov 
2520a78d9046SSean Christopherson 	if (!vcpu->arch.apic) {
2521a78d9046SSean Christopherson 		static_branch_dec(&kvm_has_noapic_vcpu);
2522edf88417SAvi Kivity 		return;
2523a78d9046SSean Christopherson 	}
2524edf88417SAvi Kivity 
2525f8c1ea10SGleb Natapov 	hrtimer_cancel(&apic->lapic_timer.timer);
2526edf88417SAvi Kivity 
2527c5cc421bSGleb Natapov 	if (!(vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE))
25286e4e3b4dSCun Li 		static_branch_slow_dec_deferred(&apic_hw_disabled);
2529c5cc421bSGleb Natapov 
2530e462755cSRadim Krčmář 	if (!apic->sw_enabled)
25316e4e3b4dSCun Li 		static_branch_slow_dec_deferred(&apic_sw_disabled);
2532edf88417SAvi Kivity 
2533f8c1ea10SGleb Natapov 	if (apic->regs)
2534f8c1ea10SGleb Natapov 		free_page((unsigned long)apic->regs);
2535f8c1ea10SGleb Natapov 
2536f8c1ea10SGleb Natapov 	kfree(apic);
2537edf88417SAvi Kivity }
2538edf88417SAvi Kivity 
2539edf88417SAvi Kivity /*
2540edf88417SAvi Kivity  *----------------------------------------------------------------------
2541edf88417SAvi Kivity  * LAPIC interface
2542edf88417SAvi Kivity  *----------------------------------------------------------------------
2543edf88417SAvi Kivity  */
kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu * vcpu)2544a3e06bbeSLiu, Jinsong u64 kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu)
2545a3e06bbeSLiu, Jinsong {
2546a3e06bbeSLiu, Jinsong 	struct kvm_lapic *apic = vcpu->arch.apic;
2547a3e06bbeSLiu, Jinsong 
2548a970e9b2SWanpeng Li 	if (!kvm_apic_present(vcpu) || !apic_lvtt_tscdeadline(apic))
2549a3e06bbeSLiu, Jinsong 		return 0;
2550a3e06bbeSLiu, Jinsong 
2551a3e06bbeSLiu, Jinsong 	return apic->lapic_timer.tscdeadline;
2552a3e06bbeSLiu, Jinsong }
2553a3e06bbeSLiu, Jinsong 
kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu * vcpu,u64 data)2554a3e06bbeSLiu, Jinsong void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data)
2555a3e06bbeSLiu, Jinsong {
2556a3e06bbeSLiu, Jinsong 	struct kvm_lapic *apic = vcpu->arch.apic;
2557a3e06bbeSLiu, Jinsong 
255827503833SWanpeng Li 	if (!kvm_apic_present(vcpu) || !apic_lvtt_tscdeadline(apic))
2559a3e06bbeSLiu, Jinsong 		return;
2560a3e06bbeSLiu, Jinsong 
2561a3e06bbeSLiu, Jinsong 	hrtimer_cancel(&apic->lapic_timer.timer);
2562a3e06bbeSLiu, Jinsong 	apic->lapic_timer.tscdeadline = data;
2563a3e06bbeSLiu, Jinsong 	start_apic_timer(apic);
2564a3e06bbeSLiu, Jinsong }
2565a3e06bbeSLiu, Jinsong 
kvm_lapic_set_tpr(struct kvm_vcpu * vcpu,unsigned long cr8)2566edf88417SAvi Kivity void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8)
2567edf88417SAvi Kivity {
2568f66af9f2SZhenzhong Duan 	apic_set_tpr(vcpu->arch.apic, (cr8 & 0x0f) << 4);
2569edf88417SAvi Kivity }
2570edf88417SAvi Kivity 
kvm_lapic_get_cr8(struct kvm_vcpu * vcpu)2571edf88417SAvi Kivity u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
2572edf88417SAvi Kivity {
2573edf88417SAvi Kivity 	u64 tpr;
2574edf88417SAvi Kivity 
2575dfb95954SSuravee Suthikulpanit 	tpr = (u64) kvm_lapic_get_reg(vcpu->arch.apic, APIC_TASKPRI);
2576edf88417SAvi Kivity 
2577edf88417SAvi Kivity 	return (tpr & 0xf0) >> 4;
2578edf88417SAvi Kivity }
2579edf88417SAvi Kivity 
kvm_lapic_set_base(struct kvm_vcpu * vcpu,u64 value)2580edf88417SAvi Kivity void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
2581edf88417SAvi Kivity {
25828d14695fSYang Zhang 	u64 old_value = vcpu->arch.apic_base;
2583edf88417SAvi Kivity 	struct kvm_lapic *apic = vcpu->arch.apic;
2584edf88417SAvi Kivity 
2585e66d2ae7SJan Kiszka 	vcpu->arch.apic_base = value;
2586e66d2ae7SJan Kiszka 
2587c7dd15b3SJim Mattson 	if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE)
2588aedbaf4fSXiaoyao Li 		kvm_update_cpuid_runtime(vcpu);
2589c7dd15b3SJim Mattson 
2590c7dd15b3SJim Mattson 	if (!apic)
2591c7dd15b3SJim Mattson 		return;
2592c7dd15b3SJim Mattson 
2593c5cc421bSGleb Natapov 	/* update jump label if enable bit changes */
25940dce7cd6SAndrew Jones 	if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE) {
259549bd29baSRadim Krčmář 		if (value & MSR_IA32_APICBASE_ENABLE) {
259649bd29baSRadim Krčmář 			kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
25976e4e3b4dSCun Li 			static_branch_slow_dec_deferred(&apic_hw_disabled);
25982f15d027SVitaly Kuznetsov 			/* Check if there are APF page ready requests pending */
25992f15d027SVitaly Kuznetsov 			kvm_make_request(KVM_REQ_APF_READY, vcpu);
2600187ca84bSWanpeng Li 		} else {
26016e4e3b4dSCun Li 			static_branch_inc(&apic_hw_disabled.key);
260244d52717SPaolo Bonzini 			atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
2603c5cc421bSGleb Natapov 		}
2604187ca84bSWanpeng Li 	}
2605c5cc421bSGleb Natapov 
2606052c3b99SEmanuele Giuseppe Esposito 	if ((old_value ^ value) & X2APIC_ENABLE) {
2607052c3b99SEmanuele Giuseppe Esposito 		if (value & X2APIC_ENABLE)
2608257b9a5fSRadim Krčmář 			kvm_apic_set_x2apic_id(apic, vcpu->vcpu_id);
2609052c3b99SEmanuele Giuseppe Esposito 		else if (value & MSR_IA32_APICBASE_ENABLE)
2610052c3b99SEmanuele Giuseppe Esposito 			kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2611052c3b99SEmanuele Giuseppe Esposito 	}
26128d860bbeSJim Mattson 
26138fc9c7a3SSuravee Suthikulpanit 	if ((old_value ^ value) & (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) {
26141459f5c6SSean Christopherson 		kvm_make_request(KVM_REQ_APICV_UPDATE, vcpu);
261589604647SWei Wang 		kvm_x86_call(set_virtual_apic_mode)(vcpu);
26168fc9c7a3SSuravee Suthikulpanit 	}
26178d14695fSYang Zhang 
2618edf88417SAvi Kivity 	apic->base_address = apic->vcpu->arch.apic_base &
2619edf88417SAvi Kivity 			     MSR_IA32_APICBASE_BASE;
2620edf88417SAvi Kivity 
2621db324fe6SNadav Amit 	if ((value & MSR_IA32_APICBASE_ENABLE) &&
26223743c2f0SMaxim Levitsky 	     apic->base_address != APIC_DEFAULT_PHYS_BASE) {
26233743c2f0SMaxim Levitsky 		kvm_set_apicv_inhibit(apic->vcpu->kvm,
26243743c2f0SMaxim Levitsky 				      APICV_INHIBIT_REASON_APIC_BASE_MODIFIED);
26253743c2f0SMaxim Levitsky 	}
2626edf88417SAvi Kivity }
2627edf88417SAvi Kivity 
kvm_apic_update_apicv(struct kvm_vcpu * vcpu)2628b26a695aSSuravee Suthikulpanit void kvm_apic_update_apicv(struct kvm_vcpu *vcpu)
2629b26a695aSSuravee Suthikulpanit {
2630b26a695aSSuravee Suthikulpanit 	struct kvm_lapic *apic = vcpu->arch.apic;
2631b26a695aSSuravee Suthikulpanit 
2632ce0a58f4SSean Christopherson 	if (apic->apicv_active) {
2633b26a695aSSuravee Suthikulpanit 		/* irr_pending is always true when apicv is activated. */
2634b26a695aSSuravee Suthikulpanit 		apic->irr_pending = true;
2635b26a695aSSuravee Suthikulpanit 		apic->isr_count = 1;
2636b26a695aSSuravee Suthikulpanit 	} else {
2637755c2bf8SMaxim Levitsky 		/*
2638755c2bf8SMaxim Levitsky 		 * Don't clear irr_pending, searching the IRR can race with
2639755c2bf8SMaxim Levitsky 		 * updates from the CPU as APICv is still active from hardware's
2640755c2bf8SMaxim Levitsky 		 * perspective.  The flag will be cleared as appropriate when
2641755c2bf8SMaxim Levitsky 		 * KVM injects the interrupt.
2642755c2bf8SMaxim Levitsky 		 */
2643b26a695aSSuravee Suthikulpanit 		apic->isr_count = count_vectors(apic->regs + APIC_ISR);
2644b26a695aSSuravee Suthikulpanit 	}
264597a71c44SSean Christopherson 	apic->highest_isr_cache = -1;
2646b26a695aSSuravee Suthikulpanit }
2647b26a695aSSuravee Suthikulpanit 
kvm_alloc_apic_access_page(struct kvm * kvm)2648c482f2ceSSean Christopherson int kvm_alloc_apic_access_page(struct kvm *kvm)
2649c482f2ceSSean Christopherson {
2650c482f2ceSSean Christopherson 	struct page *page;
2651c482f2ceSSean Christopherson 	void __user *hva;
2652c482f2ceSSean Christopherson 	int ret = 0;
2653c482f2ceSSean Christopherson 
2654c482f2ceSSean Christopherson 	mutex_lock(&kvm->slots_lock);
26552008fab3SSean Christopherson 	if (kvm->arch.apic_access_memslot_enabled ||
26562008fab3SSean Christopherson 	    kvm->arch.apic_access_memslot_inhibited)
2657c482f2ceSSean Christopherson 		goto out;
2658c482f2ceSSean Christopherson 
2659c482f2ceSSean Christopherson 	hva = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
2660c482f2ceSSean Christopherson 				      APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
2661c482f2ceSSean Christopherson 	if (IS_ERR(hva)) {
2662c482f2ceSSean Christopherson 		ret = PTR_ERR(hva);
2663c482f2ceSSean Christopherson 		goto out;
2664c482f2ceSSean Christopherson 	}
2665c482f2ceSSean Christopherson 
2666c482f2ceSSean Christopherson 	page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
2667c482f2ceSSean Christopherson 	if (is_error_page(page)) {
2668c482f2ceSSean Christopherson 		ret = -EFAULT;
2669c482f2ceSSean Christopherson 		goto out;
2670c482f2ceSSean Christopherson 	}
2671c482f2ceSSean Christopherson 
2672c482f2ceSSean Christopherson 	/*
2673c482f2ceSSean Christopherson 	 * Do not pin the page in memory, so that memory hot-unplug
2674c482f2ceSSean Christopherson 	 * is able to migrate it.
2675c482f2ceSSean Christopherson 	 */
2676c482f2ceSSean Christopherson 	put_page(page);
2677c482f2ceSSean Christopherson 	kvm->arch.apic_access_memslot_enabled = true;
2678c482f2ceSSean Christopherson out:
2679c482f2ceSSean Christopherson 	mutex_unlock(&kvm->slots_lock);
2680c482f2ceSSean Christopherson 	return ret;
2681c482f2ceSSean Christopherson }
2682c482f2ceSSean Christopherson EXPORT_SYMBOL_GPL(kvm_alloc_apic_access_page);
2683c482f2ceSSean Christopherson 
kvm_inhibit_apic_access_page(struct kvm_vcpu * vcpu)26842008fab3SSean Christopherson void kvm_inhibit_apic_access_page(struct kvm_vcpu *vcpu)
26852008fab3SSean Christopherson {
26862008fab3SSean Christopherson 	struct kvm *kvm = vcpu->kvm;
26872008fab3SSean Christopherson 
26882008fab3SSean Christopherson 	if (!kvm->arch.apic_access_memslot_enabled)
26892008fab3SSean Christopherson 		return;
26902008fab3SSean Christopherson 
26912008fab3SSean Christopherson 	kvm_vcpu_srcu_read_unlock(vcpu);
26922008fab3SSean Christopherson 
26932008fab3SSean Christopherson 	mutex_lock(&kvm->slots_lock);
26942008fab3SSean Christopherson 
26952008fab3SSean Christopherson 	if (kvm->arch.apic_access_memslot_enabled) {
26962008fab3SSean Christopherson 		__x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
26972008fab3SSean Christopherson 		/*
26982008fab3SSean Christopherson 		 * Clear "enabled" after the memslot is deleted so that a
26992008fab3SSean Christopherson 		 * different vCPU doesn't get a false negative when checking
27002008fab3SSean Christopherson 		 * the flag out of slots_lock.  No additional memory barrier is
27012008fab3SSean Christopherson 		 * needed as modifying memslots requires waiting other vCPUs to
27022008fab3SSean Christopherson 		 * drop SRCU (see above), and false positives are ok as the
27032008fab3SSean Christopherson 		 * flag is rechecked after acquiring slots_lock.
27042008fab3SSean Christopherson 		 */
27052008fab3SSean Christopherson 		kvm->arch.apic_access_memslot_enabled = false;
27062008fab3SSean Christopherson 
27072008fab3SSean Christopherson 		/*
27082008fab3SSean Christopherson 		 * Mark the memslot as inhibited to prevent reallocating the
27092008fab3SSean Christopherson 		 * memslot during vCPU creation, e.g. if a vCPU is hotplugged.
27102008fab3SSean Christopherson 		 */
27112008fab3SSean Christopherson 		kvm->arch.apic_access_memslot_inhibited = true;
27122008fab3SSean Christopherson 	}
27132008fab3SSean Christopherson 
27142008fab3SSean Christopherson 	mutex_unlock(&kvm->slots_lock);
27152008fab3SSean Christopherson 
27162008fab3SSean Christopherson 	kvm_vcpu_srcu_read_lock(vcpu);
2717edf88417SAvi Kivity }
2718edf88417SAvi Kivity 
kvm_lapic_reset(struct kvm_vcpu * vcpu,bool init_event)2719edf88417SAvi Kivity void kvm_lapic_reset(struct kvm_vcpu *vcpu, bool init_event)
2720edf88417SAvi Kivity {
2721edf88417SAvi Kivity 	struct kvm_lapic *apic = vcpu->arch.apic;
2722d28bc9ddSNadav Amit 	u64 msr_val;
2723edf88417SAvi Kivity 	int i;
2724b7e31be3SRadim Krčmář 
272589604647SWei Wang 	kvm_x86_call(apicv_pre_state_restore)(vcpu);
27269cfec6d0SHaitao Shan 
27274547700aSSean Christopherson 	if (!init_event) {
2728f7d8a19fSSean Christopherson 		msr_val = APIC_DEFAULT_PHYS_BASE | MSR_IA32_APICBASE_ENABLE;
27294547700aSSean Christopherson 		if (kvm_vcpu_is_reset_bsp(vcpu))
2730f7d8a19fSSean Christopherson 			msr_val |= MSR_IA32_APICBASE_BSP;
2731f7d8a19fSSean Christopherson 		kvm_lapic_set_base(vcpu, msr_val);
27324547700aSSean Christopherson 	}
27334547700aSSean Christopherson 
2734b7e31be3SRadim Krčmář 	if (!apic)
2735b7e31be3SRadim Krčmář 		return;
2736edf88417SAvi Kivity 
2737edf88417SAvi Kivity 	/* Stop the timer in case it's a reset to an active apic */
2738d3c7b77dSMarcelo Tosatti 	hrtimer_cancel(&apic->lapic_timer.timer);
2739edf88417SAvi Kivity 
2740f7d8a19fSSean Christopherson 	/* The xAPIC ID is set at RESET even if the APIC was already enabled. */
2741f7d8a19fSSean Christopherson 	if (!init_event)
2742a92e2543SRadim Krčmář 		kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2743fc61b800SGleb Natapov 	kvm_apic_set_version(apic->vcpu);
2744edf88417SAvi Kivity 
27454b903561SJue Wang 	for (i = 0; i < apic->nr_lvt_entries; i++)
2746987f625eSJue Wang 		kvm_lapic_set_reg(apic, APIC_LVTx(i), APIC_LVT_MASKED);
2747b6ac0695SRadim Krčmář 	apic_update_lvtt(apic);
274852b54190SJan H. Schönherr 	if (kvm_vcpu_is_reset_bsp(vcpu) &&
274952b54190SJan H. Schönherr 	    kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_LINT0_REENABLED))
27501e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, APIC_LVT0,
2751edf88417SAvi Kivity 			     SET_APIC_DELIVERY_MODE(0, APIC_MODE_EXTINT));
2752dfb95954SSuravee Suthikulpanit 	apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2753edf88417SAvi Kivity 
2754ae6f2496SWanpeng Li 	kvm_apic_set_dfr(apic, 0xffffffffU);
2755f8c1ea10SGleb Natapov 	apic_set_spiv(apic, 0xff);
27561e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_TASKPRI, 0);
2757c028dd6bSRadim Krčmář 	if (!apic_x2apic_mode(apic))
27581e08ec4aSGleb Natapov 		kvm_apic_set_ldr(apic, 0);
27591e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_ESR, 0);
2760a57a3168SSean Christopherson 	if (!apic_x2apic_mode(apic)) {
27611e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, APIC_ICR, 0);
27621e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, APIC_ICR2, 0);
2763a57a3168SSean Christopherson 	} else {
2764a57a3168SSean Christopherson 		kvm_lapic_set_reg64(apic, APIC_ICR, 0);
2765a57a3168SSean Christopherson 	}
27661e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_TDCR, 0);
27671e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_TMICT, 0);
2768edf88417SAvi Kivity 	for (i = 0; i < 8; i++) {
27691e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, APIC_IRR + 0x10 * i, 0);
27701e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, APIC_ISR + 0x10 * i, 0);
27711e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, APIC_TMR + 0x10 * i, 0);
2772edf88417SAvi Kivity 	}
2773b26a695aSSuravee Suthikulpanit 	kvm_apic_update_apicv(vcpu);
2774edf88417SAvi Kivity 	update_divide_count(apic);
2775d3c7b77dSMarcelo Tosatti 	atomic_set(&apic->lapic_timer.pending, 0);
2776549240e8SSean Christopherson 
2777ae7a2a3fSMichael S. Tsirkin 	vcpu->arch.pv_eoi.msr_val = 0;
2778edf88417SAvi Kivity 	apic_update_ppr(apic);
2779ce0a58f4SSean Christopherson 	if (apic->apicv_active) {
278089604647SWei Wang 		kvm_x86_call(apicv_post_state_restore)(vcpu);
278189604647SWei Wang 		kvm_x86_call(hwapic_irr_update)(vcpu, -1);
278289604647SWei Wang 		kvm_x86_call(hwapic_isr_update)(-1);
27834191db26SJan H. Schönherr 	}
2784edf88417SAvi Kivity 
2785e1035715SGleb Natapov 	vcpu->arch.apic_arb_prio = 0;
278641383771SGleb Natapov 	vcpu->arch.apic_attention = 0;
27874abaffceSWanpeng Li 
27884abaffceSWanpeng Li 	kvm_recalculate_apic_map(vcpu->kvm);
2789edf88417SAvi Kivity }
2790edf88417SAvi Kivity 
2791edf88417SAvi Kivity /*
2792edf88417SAvi Kivity  *----------------------------------------------------------------------
2793edf88417SAvi Kivity  * timer interface
2794edf88417SAvi Kivity  *----------------------------------------------------------------------
2795edf88417SAvi Kivity  */
2796edf88417SAvi Kivity 
lapic_is_periodic(struct kvm_lapic * apic)27972a6eac96SAvi Kivity static bool lapic_is_periodic(struct kvm_lapic *apic)
2798edf88417SAvi Kivity {
2799d3c7b77dSMarcelo Tosatti 	return apic_lvtt_period(apic);
2800edf88417SAvi Kivity }
2801edf88417SAvi Kivity 
apic_has_pending_timer(struct kvm_vcpu * vcpu)28023d80840dSMarcelo Tosatti int apic_has_pending_timer(struct kvm_vcpu *vcpu)
28033d80840dSMarcelo Tosatti {
280454e9818fSGleb Natapov 	struct kvm_lapic *apic = vcpu->arch.apic;
28053d80840dSMarcelo Tosatti 
28061e3161b4SPaolo Bonzini 	if (apic_enabled(apic) && apic_lvt_enabled(apic, APIC_LVTT))
280754e9818fSGleb Natapov 		return atomic_read(&apic->lapic_timer.pending);
28083d80840dSMarcelo Tosatti 
28093d80840dSMarcelo Tosatti 	return 0;
28103d80840dSMarcelo Tosatti }
28113d80840dSMarcelo Tosatti 
kvm_apic_local_deliver(struct kvm_lapic * apic,int lvt_type)281289342082SAvi Kivity int kvm_apic_local_deliver(struct kvm_lapic *apic, int lvt_type)
2813edf88417SAvi Kivity {
2814dfb95954SSuravee Suthikulpanit 	u32 reg = kvm_lapic_get_reg(apic, lvt_type);
281523930f95SJan Kiszka 	int vector, mode, trig_mode;
2816a16eb25bSJim Mattson 	int r;
2817edf88417SAvi Kivity 
2818c48f1496SGleb Natapov 	if (kvm_apic_hw_enabled(apic) && !(reg & APIC_LVT_MASKED)) {
281923930f95SJan Kiszka 		vector = reg & APIC_VECTOR_MASK;
282023930f95SJan Kiszka 		mode = reg & APIC_MODE_MASK;
282123930f95SJan Kiszka 		trig_mode = reg & APIC_LVT_LEVEL_TRIGGER;
2822a16eb25bSJim Mattson 
2823a16eb25bSJim Mattson 		r = __apic_accept_irq(apic, mode, vector, 1, trig_mode, NULL);
282449ff3b4aSSandipan Das 		if (r && lvt_type == APIC_LVTPC &&
282549ff3b4aSSandipan Das 		    guest_cpuid_is_intel_compatible(apic->vcpu))
2826a16eb25bSJim Mattson 			kvm_lapic_set_reg(apic, APIC_LVTPC, reg | APIC_LVT_MASKED);
2827a16eb25bSJim Mattson 		return r;
282823930f95SJan Kiszka 	}
282923930f95SJan Kiszka 	return 0;
283023930f95SJan Kiszka }
283123930f95SJan Kiszka 
kvm_apic_nmi_wd_deliver(struct kvm_vcpu * vcpu)28328fdb2351SJan Kiszka void kvm_apic_nmi_wd_deliver(struct kvm_vcpu *vcpu)
283323930f95SJan Kiszka {
28348fdb2351SJan Kiszka 	struct kvm_lapic *apic = vcpu->arch.apic;
28358fdb2351SJan Kiszka 
28368fdb2351SJan Kiszka 	if (apic)
28378fdb2351SJan Kiszka 		kvm_apic_local_deliver(apic, APIC_LVT0);
2838edf88417SAvi Kivity }
2839edf88417SAvi Kivity 
2840d76685c4SGregory Haskins static const struct kvm_io_device_ops apic_mmio_ops = {
2841d76685c4SGregory Haskins 	.read     = apic_mmio_read,
2842d76685c4SGregory Haskins 	.write    = apic_mmio_write,
2843d76685c4SGregory Haskins };
2844d76685c4SGregory Haskins 
apic_timer_fn(struct hrtimer * data)2845e9d90d47SAvi Kivity static enum hrtimer_restart apic_timer_fn(struct hrtimer *data)
2846e9d90d47SAvi Kivity {
2847e9d90d47SAvi Kivity 	struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
28482a6eac96SAvi Kivity 	struct kvm_lapic *apic = container_of(ktimer, struct kvm_lapic, lapic_timer);
2849e9d90d47SAvi Kivity 
2850ae95f566SWanpeng Li 	apic_timer_expired(apic, true);
2851e9d90d47SAvi Kivity 
28522a6eac96SAvi Kivity 	if (lapic_is_periodic(apic)) {
28538003c9aeSWanpeng Li 		advance_periodic_target_expiration(apic);
2854e9d90d47SAvi Kivity 		hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
2855e9d90d47SAvi Kivity 		return HRTIMER_RESTART;
2856e9d90d47SAvi Kivity 	} else
2857e9d90d47SAvi Kivity 		return HRTIMER_NORESTART;
2858e9d90d47SAvi Kivity }
2859e9d90d47SAvi Kivity 
kvm_create_lapic(struct kvm_vcpu * vcpu)286089a58812SSean Christopherson int kvm_create_lapic(struct kvm_vcpu *vcpu)
2861edf88417SAvi Kivity {
2862edf88417SAvi Kivity 	struct kvm_lapic *apic;
2863edf88417SAvi Kivity 
2864edf88417SAvi Kivity 	ASSERT(vcpu != NULL);
2865edf88417SAvi Kivity 
2866a78d9046SSean Christopherson 	if (!irqchip_in_kernel(vcpu->kvm)) {
2867a78d9046SSean Christopherson 		static_branch_inc(&kvm_has_noapic_vcpu);
2868a78d9046SSean Christopherson 		return 0;
2869a78d9046SSean Christopherson 	}
2870a78d9046SSean Christopherson 
2871254272ceSBen Gardon 	apic = kzalloc(sizeof(*apic), GFP_KERNEL_ACCOUNT);
2872edf88417SAvi Kivity 	if (!apic)
2873edf88417SAvi Kivity 		goto nomem;
2874edf88417SAvi Kivity 
2875edf88417SAvi Kivity 	vcpu->arch.apic = apic;
2876edf88417SAvi Kivity 
287775253db4SBrijesh Singh 	if (kvm_x86_ops.alloc_apic_backing_page)
287889604647SWei Wang 		apic->regs = kvm_x86_call(alloc_apic_backing_page)(vcpu);
287975253db4SBrijesh Singh 	else
2880254272ceSBen Gardon 		apic->regs = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
2881afc20184STakuya Yoshikawa 	if (!apic->regs) {
2882edf88417SAvi Kivity 		printk(KERN_ERR "malloc apic regs error for vcpu %x\n",
2883edf88417SAvi Kivity 		       vcpu->vcpu_id);
2884edf88417SAvi Kivity 		goto nomem_free_apic;
2885edf88417SAvi Kivity 	}
2886edf88417SAvi Kivity 	apic->vcpu = vcpu;
2887edf88417SAvi Kivity 
288803d84f96SSean Christopherson 	apic->nr_lvt_entries = kvm_apic_calc_nr_lvt_entries(vcpu);
288903d84f96SSean Christopherson 
2890d3c7b77dSMarcelo Tosatti 	hrtimer_init(&apic->lapic_timer.timer, CLOCK_MONOTONIC,
28912c0d278fSSebastian Andrzej Siewior 		     HRTIMER_MODE_ABS_HARD);
2892e9d90d47SAvi Kivity 	apic->lapic_timer.timer.function = apic_timer_fn;
289389a58812SSean Christopherson 	if (lapic_timer_advance)
2894a0f0037eSWanpeng Li 		apic->lapic_timer.timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
2895c3941d9eSSean Christopherson 
2896f7d8a19fSSean Christopherson 	/*
2897f7d8a19fSSean Christopherson 	 * Stuff the APIC ENABLE bit in lieu of temporarily incrementing
2898f7d8a19fSSean Christopherson 	 * apic_hw_disabled; the full RESET value is set by kvm_lapic_reset().
2899f7d8a19fSSean Christopherson 	 */
2900f7d8a19fSSean Christopherson 	vcpu->arch.apic_base = MSR_IA32_APICBASE_ENABLE;
29016e4e3b4dSCun Li 	static_branch_inc(&apic_sw_disabled.key); /* sw disabled at reset */
2902d76685c4SGregory Haskins 	kvm_iodevice_init(&apic->dev, &apic_mmio_ops);
2903edf88417SAvi Kivity 
2904a78d9046SSean Christopherson 	/*
2905a78d9046SSean Christopherson 	 * Defer evaluating inhibits until the vCPU is first run, as this vCPU
2906a78d9046SSean Christopherson 	 * will not get notified of any changes until this vCPU is visible to
2907a78d9046SSean Christopherson 	 * other vCPUs (marked online and added to the set of vCPUs).
2908a78d9046SSean Christopherson 	 *
2909a78d9046SSean Christopherson 	 * Opportunistically mark APICv active as VMX in particularly is highly
2910a78d9046SSean Christopherson 	 * unlikely to have inhibits.  Ignore the current per-VM APICv state so
2911a78d9046SSean Christopherson 	 * that vCPU creation is guaranteed to run with a deterministic value,
2912a78d9046SSean Christopherson 	 * the request will ensure the vCPU gets the correct state before VM-Entry.
2913a78d9046SSean Christopherson 	 */
2914a78d9046SSean Christopherson 	if (enable_apicv) {
2915a78d9046SSean Christopherson 		apic->apicv_active = true;
2916a78d9046SSean Christopherson 		kvm_make_request(KVM_REQ_APICV_UPDATE, vcpu);
2917a78d9046SSean Christopherson 	}
2918a78d9046SSean Christopherson 
2919edf88417SAvi Kivity 	return 0;
2920edf88417SAvi Kivity nomem_free_apic:
2921edf88417SAvi Kivity 	kfree(apic);
2922a251fb90SSaar Amar 	vcpu->arch.apic = NULL;
2923edf88417SAvi Kivity nomem:
2924edf88417SAvi Kivity 	return -ENOMEM;
2925edf88417SAvi Kivity }
2926edf88417SAvi Kivity 
kvm_apic_has_interrupt(struct kvm_vcpu * vcpu)2927edf88417SAvi Kivity int kvm_apic_has_interrupt(struct kvm_vcpu *vcpu)
2928edf88417SAvi Kivity {
2929edf88417SAvi Kivity 	struct kvm_lapic *apic = vcpu->arch.apic;
2930b3c045d3SPaolo Bonzini 	u32 ppr;
2931edf88417SAvi Kivity 
293272c3bcdcSPaolo Bonzini 	if (!kvm_apic_present(vcpu))
2933edf88417SAvi Kivity 		return -1;
2934edf88417SAvi Kivity 
2935b3c045d3SPaolo Bonzini 	__apic_update_ppr(apic, &ppr);
2936b3c045d3SPaolo Bonzini 	return apic_has_interrupt_for_ppr(apic, ppr);
2937edf88417SAvi Kivity }
293825bb2cf9SSean Christopherson EXPORT_SYMBOL_GPL(kvm_apic_has_interrupt);
2939edf88417SAvi Kivity 
kvm_apic_accept_pic_intr(struct kvm_vcpu * vcpu)2940edf88417SAvi Kivity int kvm_apic_accept_pic_intr(struct kvm_vcpu *vcpu)
2941edf88417SAvi Kivity {
2942dfb95954SSuravee Suthikulpanit 	u32 lvt0 = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVT0);
2943edf88417SAvi Kivity 
2944c48f1496SGleb Natapov 	if (!kvm_apic_hw_enabled(vcpu->arch.apic))
29453ce4dc17SMiaohe Lin 		return 1;
2946edf88417SAvi Kivity 	if ((lvt0 & APIC_LVT_MASKED) == 0 &&
2947edf88417SAvi Kivity 	    GET_APIC_DELIVERY_MODE(lvt0) == APIC_MODE_EXTINT)
29483ce4dc17SMiaohe Lin 		return 1;
29493ce4dc17SMiaohe Lin 	return 0;
2950edf88417SAvi Kivity }
2951edf88417SAvi Kivity 
kvm_inject_apic_timer_irqs(struct kvm_vcpu * vcpu)2952edf88417SAvi Kivity void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu)
2953edf88417SAvi Kivity {
2954edf88417SAvi Kivity 	struct kvm_lapic *apic = vcpu->arch.apic;
2955edf88417SAvi Kivity 
295654e9818fSGleb Natapov 	if (atomic_read(&apic->lapic_timer.pending) > 0) {
29570c5f81daSWanpeng Li 		kvm_apic_inject_pending_timer_irqs(apic);
2958f1ed0450SJan Kiszka 		atomic_set(&apic->lapic_timer.pending, 0);
2959edf88417SAvi Kivity 	}
2960edf88417SAvi Kivity }
2961edf88417SAvi Kivity 
kvm_apic_ack_interrupt(struct kvm_vcpu * vcpu,int vector)2962*a194a3a1SSean Christopherson void kvm_apic_ack_interrupt(struct kvm_vcpu *vcpu, int vector)
2963edf88417SAvi Kivity {
2964edf88417SAvi Kivity 	struct kvm_lapic *apic = vcpu->arch.apic;
29654d82d12bSPaolo Bonzini 	u32 ppr;
2966edf88417SAvi Kivity 
2967*a194a3a1SSean Christopherson 	if (WARN_ON_ONCE(vector < 0 || !apic))
2968*a194a3a1SSean Christopherson 		return;
2969edf88417SAvi Kivity 
297056cc2406SWanpeng Li 	/*
297156cc2406SWanpeng Li 	 * We get here even with APIC virtualization enabled, if doing
297256cc2406SWanpeng Li 	 * nested virtualization and L1 runs with the "acknowledge interrupt
297356cc2406SWanpeng Li 	 * on exit" mode.  Then we cannot inject the interrupt via RVI,
297456cc2406SWanpeng Li 	 * because the process would deliver it through the IDT.
297556cc2406SWanpeng Li 	 */
297656cc2406SWanpeng Li 
2977edf88417SAvi Kivity 	apic_clear_irr(vector, apic);
297816e880bfSVitaly Kuznetsov 	if (kvm_hv_synic_auto_eoi_set(vcpu, vector)) {
29794d82d12bSPaolo Bonzini 		/*
29804d82d12bSPaolo Bonzini 		 * For auto-EOI interrupts, there might be another pending
29814d82d12bSPaolo Bonzini 		 * interrupt above PPR, so check whether to raise another
29824d82d12bSPaolo Bonzini 		 * KVM_REQ_EVENT.
29834d82d12bSPaolo Bonzini 		 */
29845c919412SAndrey Smetanin 		apic_update_ppr(apic);
29854d82d12bSPaolo Bonzini 	} else {
29864d82d12bSPaolo Bonzini 		/*
29874d82d12bSPaolo Bonzini 		 * For normal interrupts, PPR has been raised and there cannot
29884d82d12bSPaolo Bonzini 		 * be a higher-priority pending interrupt---except if there was
29894d82d12bSPaolo Bonzini 		 * a concurrent interrupt injection, but that would have
29904d82d12bSPaolo Bonzini 		 * triggered KVM_REQ_EVENT already.
29914d82d12bSPaolo Bonzini 		 */
29924d82d12bSPaolo Bonzini 		apic_set_isr(vector, apic);
29934d82d12bSPaolo Bonzini 		__apic_update_ppr(apic, &ppr);
29945c919412SAndrey Smetanin 	}
29955c919412SAndrey Smetanin 
2996edf88417SAvi Kivity }
2997*a194a3a1SSean Christopherson EXPORT_SYMBOL_GPL(kvm_apic_ack_interrupt);
2998edf88417SAvi Kivity 
kvm_apic_state_fixup(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s,bool set)2999a92e2543SRadim Krčmář static int kvm_apic_state_fixup(struct kvm_vcpu *vcpu,
3000a92e2543SRadim Krčmář 		struct kvm_lapic_state *s, bool set)
3001a92e2543SRadim Krčmář {
3002a92e2543SRadim Krčmář 	if (apic_x2apic_mode(vcpu->arch.apic)) {
30034b7c3f6dSSean Christopherson 		u32 x2apic_id = kvm_x2apic_id(vcpu->arch.apic);
3004a92e2543SRadim Krčmář 		u32 *id = (u32 *)(s->regs + APIC_ID);
300512806ba9SDr. David Alan Gilbert 		u32 *ldr = (u32 *)(s->regs + APIC_LDR);
3006a57a3168SSean Christopherson 		u64 icr;
3007a92e2543SRadim Krčmář 
300837131313SRadim Krčmář 		if (vcpu->kvm->arch.x2apic_format) {
30094b7c3f6dSSean Christopherson 			if (*id != x2apic_id)
301037131313SRadim Krčmář 				return -EINVAL;
301137131313SRadim Krčmář 		} else {
30124b7c3f6dSSean Christopherson 			/*
30134b7c3f6dSSean Christopherson 			 * Ignore the userspace value when setting APIC state.
30144b7c3f6dSSean Christopherson 			 * KVM's model is that the x2APIC ID is readonly, e.g.
30154b7c3f6dSSean Christopherson 			 * KVM only supports delivering interrupts to KVM's
30164b7c3f6dSSean Christopherson 			 * version of the x2APIC ID.  However, for backwards
30174b7c3f6dSSean Christopherson 			 * compatibility, don't reject attempts to set a
30184b7c3f6dSSean Christopherson 			 * mismatched ID for userspace that hasn't opted into
30194b7c3f6dSSean Christopherson 			 * x2apic_format.
30204b7c3f6dSSean Christopherson 			 */
3021a92e2543SRadim Krčmář 			if (set)
30224b7c3f6dSSean Christopherson 				*id = x2apic_id;
3023a92e2543SRadim Krčmář 			else
30244b7c3f6dSSean Christopherson 				*id = x2apic_id << 24;
3025a92e2543SRadim Krčmář 		}
302612806ba9SDr. David Alan Gilbert 
3027a57a3168SSean Christopherson 		/*
3028a57a3168SSean Christopherson 		 * In x2APIC mode, the LDR is fixed and based on the id.  And
302973b42dc6SSean Christopherson 		 * if the ICR is _not_ split, ICR is internally a single 64-bit
303073b42dc6SSean Christopherson 		 * register, but needs to be split to ICR+ICR2 in userspace for
303173b42dc6SSean Christopherson 		 * backwards compatibility.
3032a57a3168SSean Christopherson 		 */
303373b42dc6SSean Christopherson 		if (set)
30344b7c3f6dSSean Christopherson 			*ldr = kvm_apic_calc_x2apic_ldr(x2apic_id);
3035a57a3168SSean Christopherson 
303673b42dc6SSean Christopherson 		if (!kvm_x86_ops.x2apic_icr_is_split) {
303773b42dc6SSean Christopherson 			if (set) {
3038a57a3168SSean Christopherson 				icr = __kvm_lapic_get_reg(s->regs, APIC_ICR) |
3039a57a3168SSean Christopherson 				      (u64)__kvm_lapic_get_reg(s->regs, APIC_ICR2) << 32;
3040a57a3168SSean Christopherson 				__kvm_lapic_set_reg64(s->regs, APIC_ICR, icr);
3041a57a3168SSean Christopherson 			} else {
3042a57a3168SSean Christopherson 				icr = __kvm_lapic_get_reg64(s->regs, APIC_ICR);
3043a57a3168SSean Christopherson 				__kvm_lapic_set_reg(s->regs, APIC_ICR2, icr >> 32);
3044a57a3168SSean Christopherson 			}
304537131313SRadim Krčmář 		}
304673b42dc6SSean Christopherson 	}
3047a92e2543SRadim Krčmář 
3048a92e2543SRadim Krčmář 	return 0;
3049a92e2543SRadim Krčmář }
3050a92e2543SRadim Krčmář 
kvm_apic_get_state(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)3051a92e2543SRadim Krčmář int kvm_apic_get_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
3052a92e2543SRadim Krčmář {
3053a92e2543SRadim Krčmář 	memcpy(s->regs, vcpu->arch.apic->regs, sizeof(*s));
305424647e0aSPeter Shier 
305524647e0aSPeter Shier 	/*
305624647e0aSPeter Shier 	 * Get calculated timer current count for remaining timer period (if
305724647e0aSPeter Shier 	 * any) and store it in the returned register set.
305824647e0aSPeter Shier 	 */
305924647e0aSPeter Shier 	__kvm_lapic_set_reg(s->regs, APIC_TMCCT,
306024647e0aSPeter Shier 			    __apic_read(vcpu->arch.apic, APIC_TMCCT));
306124647e0aSPeter Shier 
3062a92e2543SRadim Krčmář 	return kvm_apic_state_fixup(vcpu, s, false);
3063a92e2543SRadim Krčmář }
3064a92e2543SRadim Krčmář 
kvm_apic_set_state(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)3065a92e2543SRadim Krčmář int kvm_apic_set_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
3066edf88417SAvi Kivity {
3067edf88417SAvi Kivity 	struct kvm_lapic *apic = vcpu->arch.apic;
3068a92e2543SRadim Krčmář 	int r;
3069a92e2543SRadim Krčmář 
307089604647SWei Wang 	kvm_x86_call(apicv_pre_state_restore)(vcpu);
30719cfec6d0SHaitao Shan 
30725dbc8f3fSGleb Natapov 	kvm_lapic_set_base(vcpu, vcpu->arch.apic_base);
307364eb0620SGleb Natapov 	/* set SPIV separately to get count of SW disabled APICs right */
307464eb0620SGleb Natapov 	apic_set_spiv(apic, *((u32 *)(s->regs + APIC_SPIV)));
3075a92e2543SRadim Krčmář 
3076a92e2543SRadim Krčmář 	r = kvm_apic_state_fixup(vcpu, s, true);
30774abaffceSWanpeng Li 	if (r) {
30784abaffceSWanpeng Li 		kvm_recalculate_apic_map(vcpu->kvm);
3079a92e2543SRadim Krčmář 		return r;
30804abaffceSWanpeng Li 	}
30810e96f31eSJordan Borgner 	memcpy(vcpu->arch.apic->regs, s->regs, sizeof(*s));
3082a92e2543SRadim Krčmář 
308344d52717SPaolo Bonzini 	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
30844abaffceSWanpeng Li 	kvm_recalculate_apic_map(vcpu->kvm);
3085fc61b800SGleb Natapov 	kvm_apic_set_version(vcpu);
3086fc61b800SGleb Natapov 
3087edf88417SAvi Kivity 	apic_update_ppr(apic);
308835fe7cfbSWanpeng Li 	cancel_apic_timer(apic);
308935737d2dSWanpeng Li 	apic->lapic_timer.expired_tscdeadline = 0;
3090b6ac0695SRadim Krčmář 	apic_update_lvtt(apic);
3091dfb95954SSuravee Suthikulpanit 	apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
3092edf88417SAvi Kivity 	update_divide_count(apic);
309324647e0aSPeter Shier 	__start_apic_timer(apic, APIC_TMCCT);
30942735886cSWanpeng Li 	kvm_lapic_set_reg(apic, APIC_TMCCT, 0);
3095b26a695aSSuravee Suthikulpanit 	kvm_apic_update_apicv(vcpu);
3096ce0a58f4SSean Christopherson 	if (apic->apicv_active) {
309789604647SWei Wang 		kvm_x86_call(apicv_post_state_restore)(vcpu);
309889604647SWei Wang 		kvm_x86_call(hwapic_irr_update)(vcpu,
309989604647SWei Wang 						apic_find_highest_irr(apic));
310089604647SWei Wang 		kvm_x86_call(hwapic_isr_update)(apic_find_highest_isr(apic));
3101d62caabbSAndrey Smetanin 	}
31023842d135SAvi Kivity 	kvm_make_request(KVM_REQ_EVENT, vcpu);
310349df6397SSteve Rutherford 	if (ioapic_in_kernel(vcpu->kvm))
310410606919SYang Zhang 		kvm_rtc_eoi_tracking_restore_one(vcpu);
31050669a510SRadim Krčmář 
31060669a510SRadim Krčmář 	vcpu->arch.apic_arb_prio = 0;
3107a92e2543SRadim Krčmář 
3108a92e2543SRadim Krčmář 	return 0;
3109edf88417SAvi Kivity }
3110edf88417SAvi Kivity 
__kvm_migrate_apic_timer(struct kvm_vcpu * vcpu)31112f52d58cSAvi Kivity void __kvm_migrate_apic_timer(struct kvm_vcpu *vcpu)
3112edf88417SAvi Kivity {
3113edf88417SAvi Kivity 	struct hrtimer *timer;
3114edf88417SAvi Kivity 
31150c5f81daSWanpeng Li 	if (!lapic_in_kernel(vcpu) ||
31160c5f81daSWanpeng Li 		kvm_can_post_timer_interrupt(vcpu))
3117edf88417SAvi Kivity 		return;
3118edf88417SAvi Kivity 
311954e9818fSGleb Natapov 	timer = &vcpu->arch.apic->lapic_timer.timer;
3120edf88417SAvi Kivity 	if (hrtimer_cancel(timer))
31212c0d278fSSebastian Andrzej Siewior 		hrtimer_start_expires(timer, HRTIMER_MODE_ABS_HARD);
3122edf88417SAvi Kivity }
3123b93463aaSAvi Kivity 
3124ae7a2a3fSMichael S. Tsirkin /*
3125ae7a2a3fSMichael S. Tsirkin  * apic_sync_pv_eoi_from_guest - called on vmexit or cancel interrupt
3126ae7a2a3fSMichael S. Tsirkin  *
3127ae7a2a3fSMichael S. Tsirkin  * Detect whether guest triggered PV EOI since the
3128ae7a2a3fSMichael S. Tsirkin  * last entry. If yes, set EOI on guests's behalf.
3129ae7a2a3fSMichael S. Tsirkin  * Clear PV EOI in guest memory in any case.
3130ae7a2a3fSMichael S. Tsirkin  */
apic_sync_pv_eoi_from_guest(struct kvm_vcpu * vcpu,struct kvm_lapic * apic)3131ae7a2a3fSMichael S. Tsirkin static void apic_sync_pv_eoi_from_guest(struct kvm_vcpu *vcpu,
3132ae7a2a3fSMichael S. Tsirkin 					struct kvm_lapic *apic)
3133ae7a2a3fSMichael S. Tsirkin {
3134ae7a2a3fSMichael S. Tsirkin 	int vector;
3135ae7a2a3fSMichael S. Tsirkin 	/*
3136ae7a2a3fSMichael S. Tsirkin 	 * PV EOI state is derived from KVM_APIC_PV_EOI_PENDING in host
3137ae7a2a3fSMichael S. Tsirkin 	 * and KVM_PV_EOI_ENABLED in guest memory as follows:
3138ae7a2a3fSMichael S. Tsirkin 	 *
3139ae7a2a3fSMichael S. Tsirkin 	 * KVM_APIC_PV_EOI_PENDING is unset:
3140ae7a2a3fSMichael S. Tsirkin 	 * 	-> host disabled PV EOI.
3141ae7a2a3fSMichael S. Tsirkin 	 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is set:
3142ae7a2a3fSMichael S. Tsirkin 	 * 	-> host enabled PV EOI, guest did not execute EOI yet.
3143ae7a2a3fSMichael S. Tsirkin 	 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is unset:
3144ae7a2a3fSMichael S. Tsirkin 	 * 	-> host enabled PV EOI, guest executed EOI.
3145ae7a2a3fSMichael S. Tsirkin 	 */
3146ae7a2a3fSMichael S. Tsirkin 	BUG_ON(!pv_eoi_enabled(vcpu));
314751b1209cSLi RongQing 
314851b1209cSLi RongQing 	if (pv_eoi_test_and_clr_pending(vcpu))
3149ae7a2a3fSMichael S. Tsirkin 		return;
3150ae7a2a3fSMichael S. Tsirkin 	vector = apic_set_eoi(apic);
3151ae7a2a3fSMichael S. Tsirkin 	trace_kvm_pv_eoi(apic, vector);
3152ae7a2a3fSMichael S. Tsirkin }
3153ae7a2a3fSMichael S. Tsirkin 
kvm_lapic_sync_from_vapic(struct kvm_vcpu * vcpu)3154b93463aaSAvi Kivity void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
3155b93463aaSAvi Kivity {
3156b93463aaSAvi Kivity 	u32 data;
3157b93463aaSAvi Kivity 
3158ae7a2a3fSMichael S. Tsirkin 	if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
3159ae7a2a3fSMichael S. Tsirkin 		apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
3160ae7a2a3fSMichael S. Tsirkin 
316141383771SGleb Natapov 	if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
3162b93463aaSAvi Kivity 		return;
3163b93463aaSAvi Kivity 
31644e335d9eSPaolo Bonzini 	if (kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
3165603242a8SNicholas Krause 				  sizeof(u32)))
3166603242a8SNicholas Krause 		return;
3167b93463aaSAvi Kivity 
3168b93463aaSAvi Kivity 	apic_set_tpr(vcpu->arch.apic, data & 0xff);
3169b93463aaSAvi Kivity }
3170b93463aaSAvi Kivity 
3171ae7a2a3fSMichael S. Tsirkin /*
3172ae7a2a3fSMichael S. Tsirkin  * apic_sync_pv_eoi_to_guest - called before vmentry
3173ae7a2a3fSMichael S. Tsirkin  *
3174ae7a2a3fSMichael S. Tsirkin  * Detect whether it's safe to enable PV EOI and
3175ae7a2a3fSMichael S. Tsirkin  * if yes do so.
3176ae7a2a3fSMichael S. Tsirkin  */
apic_sync_pv_eoi_to_guest(struct kvm_vcpu * vcpu,struct kvm_lapic * apic)3177ae7a2a3fSMichael S. Tsirkin static void apic_sync_pv_eoi_to_guest(struct kvm_vcpu *vcpu,
3178ae7a2a3fSMichael S. Tsirkin 					struct kvm_lapic *apic)
3179ae7a2a3fSMichael S. Tsirkin {
3180ae7a2a3fSMichael S. Tsirkin 	if (!pv_eoi_enabled(vcpu) ||
3181ae7a2a3fSMichael S. Tsirkin 	    /* IRR set or many bits in ISR: could be nested. */
3182ae7a2a3fSMichael S. Tsirkin 	    apic->irr_pending ||
3183ae7a2a3fSMichael S. Tsirkin 	    /* Cache not set: could be safe but we don't bother. */
3184ae7a2a3fSMichael S. Tsirkin 	    apic->highest_isr_cache == -1 ||
3185ae7a2a3fSMichael S. Tsirkin 	    /* Need EOI to update ioapic. */
31863bb345f3SPaolo Bonzini 	    kvm_ioapic_handles_vector(apic, apic->highest_isr_cache)) {
3187ae7a2a3fSMichael S. Tsirkin 		/*
3188ae7a2a3fSMichael S. Tsirkin 		 * PV EOI was disabled by apic_sync_pv_eoi_from_guest
3189ae7a2a3fSMichael S. Tsirkin 		 * so we need not do anything here.
3190ae7a2a3fSMichael S. Tsirkin 		 */
3191ae7a2a3fSMichael S. Tsirkin 		return;
3192ae7a2a3fSMichael S. Tsirkin 	}
3193ae7a2a3fSMichael S. Tsirkin 
3194ae7a2a3fSMichael S. Tsirkin 	pv_eoi_set_pending(apic->vcpu);
3195ae7a2a3fSMichael S. Tsirkin }
3196ae7a2a3fSMichael S. Tsirkin 
kvm_lapic_sync_to_vapic(struct kvm_vcpu * vcpu)3197b93463aaSAvi Kivity void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
3198b93463aaSAvi Kivity {
3199b93463aaSAvi Kivity 	u32 data, tpr;
3200b93463aaSAvi Kivity 	int max_irr, max_isr;
3201ae7a2a3fSMichael S. Tsirkin 	struct kvm_lapic *apic = vcpu->arch.apic;
3202b93463aaSAvi Kivity 
3203ae7a2a3fSMichael S. Tsirkin 	apic_sync_pv_eoi_to_guest(vcpu, apic);
3204ae7a2a3fSMichael S. Tsirkin 
320541383771SGleb Natapov 	if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
3206b93463aaSAvi Kivity 		return;
3207b93463aaSAvi Kivity 
3208dfb95954SSuravee Suthikulpanit 	tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI) & 0xff;
3209b93463aaSAvi Kivity 	max_irr = apic_find_highest_irr(apic);
3210b93463aaSAvi Kivity 	if (max_irr < 0)
3211b93463aaSAvi Kivity 		max_irr = 0;
3212b93463aaSAvi Kivity 	max_isr = apic_find_highest_isr(apic);
3213b93463aaSAvi Kivity 	if (max_isr < 0)
3214b93463aaSAvi Kivity 		max_isr = 0;
3215b93463aaSAvi Kivity 	data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
3216b93463aaSAvi Kivity 
32174e335d9eSPaolo Bonzini 	kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
3218fda4e2e8SAndy Honig 				sizeof(u32));
3219b93463aaSAvi Kivity }
3220b93463aaSAvi Kivity 
kvm_lapic_set_vapic_addr(struct kvm_vcpu * vcpu,gpa_t vapic_addr)3221fda4e2e8SAndy Honig int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
3222b93463aaSAvi Kivity {
3223fda4e2e8SAndy Honig 	if (vapic_addr) {
32244e335d9eSPaolo Bonzini 		if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
3225fda4e2e8SAndy Honig 					&vcpu->arch.apic->vapic_cache,
3226fda4e2e8SAndy Honig 					vapic_addr, sizeof(u32)))
3227fda4e2e8SAndy Honig 			return -EINVAL;
322841383771SGleb Natapov 		__set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
3229fda4e2e8SAndy Honig 	} else {
323041383771SGleb Natapov 		__clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
3231b93463aaSAvi Kivity 	}
32320105d1a5SGleb Natapov 
3233fda4e2e8SAndy Honig 	vcpu->arch.apic->vapic_addr = vapic_addr;
3234fda4e2e8SAndy Honig 	return 0;
3235fda4e2e8SAndy Honig }
3236fda4e2e8SAndy Honig 
kvm_lapic_msr_read(struct kvm_lapic * apic,u32 reg,u64 * data)32375429478dSSean Christopherson static int kvm_lapic_msr_read(struct kvm_lapic *apic, u32 reg, u64 *data)
32385429478dSSean Christopherson {
3239a57a3168SSean Christopherson 	u32 low;
3240a57a3168SSean Christopherson 
3241a57a3168SSean Christopherson 	if (reg == APIC_ICR) {
324273b42dc6SSean Christopherson 		*data = kvm_x2apic_icr_read(apic);
3243a57a3168SSean Christopherson 		return 0;
3244a57a3168SSean Christopherson 	}
32455429478dSSean Christopherson 
32465429478dSSean Christopherson 	if (kvm_lapic_reg_read(apic, reg, 4, &low))
32475429478dSSean Christopherson 		return 1;
32485429478dSSean Christopherson 
3249a57a3168SSean Christopherson 	*data = low;
32505429478dSSean Christopherson 
32515429478dSSean Christopherson 	return 0;
32525429478dSSean Christopherson }
32535429478dSSean Christopherson 
kvm_lapic_msr_write(struct kvm_lapic * apic,u32 reg,u64 data)32545429478dSSean Christopherson static int kvm_lapic_msr_write(struct kvm_lapic *apic, u32 reg, u64 data)
32555429478dSSean Christopherson {
3256a57a3168SSean Christopherson 	/*
3257ab52be1bSSean Christopherson 	 * ICR is a 64-bit register in x2APIC mode (and Hyper-V PV vAPIC) and
3258a57a3168SSean Christopherson 	 * can be written as such, all other registers remain accessible only
3259a57a3168SSean Christopherson 	 * through 32-bit reads/writes.
3260a57a3168SSean Christopherson 	 */
32615429478dSSean Christopherson 	if (reg == APIC_ICR)
3262a57a3168SSean Christopherson 		return kvm_x2apic_icr_write(apic, data);
3263a57a3168SSean Christopherson 
3264ab52be1bSSean Christopherson 	/* Bits 63:32 are reserved in all other registers. */
3265ab52be1bSSean Christopherson 	if (data >> 32)
3266ab52be1bSSean Christopherson 		return 1;
3267ab52be1bSSean Christopherson 
32685429478dSSean Christopherson 	return kvm_lapic_reg_write(apic, reg, (u32)data);
32695429478dSSean Christopherson }
32705429478dSSean Christopherson 
kvm_x2apic_msr_write(struct kvm_vcpu * vcpu,u32 msr,u64 data)32710105d1a5SGleb Natapov int kvm_x2apic_msr_write(struct kvm_vcpu *vcpu, u32 msr, u64 data)
32720105d1a5SGleb Natapov {
32730105d1a5SGleb Natapov 	struct kvm_lapic *apic = vcpu->arch.apic;
32740105d1a5SGleb Natapov 	u32 reg = (msr - APIC_BASE_MSR) << 4;
32750105d1a5SGleb Natapov 
327635754c98SPaolo Bonzini 	if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
32770105d1a5SGleb Natapov 		return 1;
32780105d1a5SGleb Natapov 
32795429478dSSean Christopherson 	return kvm_lapic_msr_write(apic, reg, data);
32800105d1a5SGleb Natapov }
32810105d1a5SGleb Natapov 
kvm_x2apic_msr_read(struct kvm_vcpu * vcpu,u32 msr,u64 * data)32820105d1a5SGleb Natapov int kvm_x2apic_msr_read(struct kvm_vcpu *vcpu, u32 msr, u64 *data)
32830105d1a5SGleb Natapov {
32840105d1a5SGleb Natapov 	struct kvm_lapic *apic = vcpu->arch.apic;
32855429478dSSean Christopherson 	u32 reg = (msr - APIC_BASE_MSR) << 4;
32860105d1a5SGleb Natapov 
328735754c98SPaolo Bonzini 	if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
32880105d1a5SGleb Natapov 		return 1;
32890105d1a5SGleb Natapov 
32905429478dSSean Christopherson 	return kvm_lapic_msr_read(apic, reg, data);
32910105d1a5SGleb Natapov }
329210388a07SGleb Natapov 
kvm_hv_vapic_msr_write(struct kvm_vcpu * vcpu,u32 reg,u64 data)329310388a07SGleb Natapov int kvm_hv_vapic_msr_write(struct kvm_vcpu *vcpu, u32 reg, u64 data)
329410388a07SGleb Natapov {
3295bce87cceSPaolo Bonzini 	if (!lapic_in_kernel(vcpu))
329610388a07SGleb Natapov 		return 1;
329710388a07SGleb Natapov 
32985429478dSSean Christopherson 	return kvm_lapic_msr_write(vcpu->arch.apic, reg, data);
329910388a07SGleb Natapov }
330010388a07SGleb Natapov 
kvm_hv_vapic_msr_read(struct kvm_vcpu * vcpu,u32 reg,u64 * data)330110388a07SGleb Natapov int kvm_hv_vapic_msr_read(struct kvm_vcpu *vcpu, u32 reg, u64 *data)
330210388a07SGleb Natapov {
3303bce87cceSPaolo Bonzini 	if (!lapic_in_kernel(vcpu))
330410388a07SGleb Natapov 		return 1;
330510388a07SGleb Natapov 
33065429478dSSean Christopherson 	return kvm_lapic_msr_read(vcpu->arch.apic, reg, data);
330710388a07SGleb Natapov }
3308ae7a2a3fSMichael S. Tsirkin 
kvm_lapic_set_pv_eoi(struct kvm_vcpu * vcpu,u64 data,unsigned long len)330977c3323fSVitaly Kuznetsov int kvm_lapic_set_pv_eoi(struct kvm_vcpu *vcpu, u64 data, unsigned long len)
3310ae7a2a3fSMichael S. Tsirkin {
3311ae7a2a3fSMichael S. Tsirkin 	u64 addr = data & ~KVM_MSR_ENABLED;
3312a7c42bb6SVitaly Kuznetsov 	struct gfn_to_hva_cache *ghc = &vcpu->arch.pv_eoi.data;
3313a7c42bb6SVitaly Kuznetsov 	unsigned long new_len;
3314afd67ee3SVitaly Kuznetsov 	int ret;
3315a7c42bb6SVitaly Kuznetsov 
3316ae7a2a3fSMichael S. Tsirkin 	if (!IS_ALIGNED(addr, 4))
3317ae7a2a3fSMichael S. Tsirkin 		return 1;
3318ae7a2a3fSMichael S. Tsirkin 
3319afd67ee3SVitaly Kuznetsov 	if (data & KVM_MSR_ENABLED) {
3320a7c42bb6SVitaly Kuznetsov 		if (addr == ghc->gpa && len <= ghc->len)
3321a7c42bb6SVitaly Kuznetsov 			new_len = ghc->len;
3322a7c42bb6SVitaly Kuznetsov 		else
3323a7c42bb6SVitaly Kuznetsov 			new_len = len;
3324a7c42bb6SVitaly Kuznetsov 
3325afd67ee3SVitaly Kuznetsov 		ret = kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, addr, new_len);
3326afd67ee3SVitaly Kuznetsov 		if (ret)
3327afd67ee3SVitaly Kuznetsov 			return ret;
3328afd67ee3SVitaly Kuznetsov 	}
3329afd67ee3SVitaly Kuznetsov 
3330afd67ee3SVitaly Kuznetsov 	vcpu->arch.pv_eoi.msr_val = data;
3331afd67ee3SVitaly Kuznetsov 
3332afd67ee3SVitaly Kuznetsov 	return 0;
3333ae7a2a3fSMichael S. Tsirkin }
3334c5cc421bSGleb Natapov 
kvm_apic_accept_events(struct kvm_vcpu * vcpu)33354fe09bcfSJim Mattson int kvm_apic_accept_events(struct kvm_vcpu *vcpu)
333666450a21SJan Kiszka {
333766450a21SJan Kiszka 	struct kvm_lapic *apic = vcpu->arch.apic;
33382b4a273bSPaolo Bonzini 	u8 sipi_vector;
33391c96dcceSPaolo Bonzini 	int r;
334066450a21SJan Kiszka 
33411e17a6f8SSean Christopherson 	if (!kvm_apic_has_pending_init_or_sipi(vcpu))
33424fe09bcfSJim Mattson 		return 0;
33431c96dcceSPaolo Bonzini 
33441c96dcceSPaolo Bonzini 	if (is_guest_mode(vcpu)) {
3345cb6a32c2SSean Christopherson 		r = kvm_check_nested_events(vcpu);
33461c96dcceSPaolo Bonzini 		if (r < 0)
33474fe09bcfSJim Mattson 			return r == -EBUSY ? 0 : r;
33481c96dcceSPaolo Bonzini 		/*
33491e17a6f8SSean Christopherson 		 * Continue processing INIT/SIPI even if a nested VM-Exit
33501e17a6f8SSean Christopherson 		 * occurred, e.g. pending SIPIs should be dropped if INIT+SIPI
33511e17a6f8SSean Christopherson 		 * are blocked as a result of transitioning to VMX root mode.
33521c96dcceSPaolo Bonzini 		 */
33531c96dcceSPaolo Bonzini 	}
33541c96dcceSPaolo Bonzini 
33551c96dcceSPaolo Bonzini 	/*
33561e17a6f8SSean Christopherson 	 * INITs are blocked while CPU is in specific states (SMM, VMX root
33571e17a6f8SSean Christopherson 	 * mode, SVM with GIF=0), while SIPIs are dropped if the CPU isn't in
33581e17a6f8SSean Christopherson 	 * wait-for-SIPI (WFS).
3359cd7764feSPaolo Bonzini 	 */
33601b7a1b78SSean Christopherson 	if (!kvm_apic_init_sipi_allowed(vcpu)) {
3361cd7764feSPaolo Bonzini 		WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED);
3362cd7764feSPaolo Bonzini 		clear_bit(KVM_APIC_SIPI, &apic->pending_events);
33634fe09bcfSJim Mattson 		return 0;
3364cd7764feSPaolo Bonzini 	}
3365299018f4SGleb Natapov 
33661e17a6f8SSean Christopherson 	if (test_and_clear_bit(KVM_APIC_INIT, &apic->pending_events)) {
3367d28bc9ddSNadav Amit 		kvm_vcpu_reset(vcpu, true);
336866450a21SJan Kiszka 		if (kvm_vcpu_is_bsp(apic->vcpu))
336966450a21SJan Kiszka 			vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
337066450a21SJan Kiszka 		else
337166450a21SJan Kiszka 			vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
337266450a21SJan Kiszka 	}
33731e17a6f8SSean Christopherson 	if (test_and_clear_bit(KVM_APIC_SIPI, &apic->pending_events)) {
3374f57ad63aSMaxim Levitsky 		if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
337566450a21SJan Kiszka 			/* evaluate pending_events before reading the vector */
337666450a21SJan Kiszka 			smp_rmb();
337766450a21SJan Kiszka 			sipi_vector = apic->sipi_vector;
337889604647SWei Wang 			kvm_x86_call(vcpu_deliver_sipi_vector)(vcpu,
337989604647SWei Wang 							       sipi_vector);
338066450a21SJan Kiszka 			vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
338166450a21SJan Kiszka 		}
338266450a21SJan Kiszka 	}
33834fe09bcfSJim Mattson 	return 0;
3384f57ad63aSMaxim Levitsky }
338566450a21SJan Kiszka 
kvm_lapic_exit(void)3386cef84c30SDavid Matlack void kvm_lapic_exit(void)
3387cef84c30SDavid Matlack {
3388cef84c30SDavid Matlack 	static_key_deferred_flush(&apic_hw_disabled);
33899139a7a6SSean Christopherson 	WARN_ON(static_branch_unlikely(&apic_hw_disabled.key));
3390cef84c30SDavid Matlack 	static_key_deferred_flush(&apic_sw_disabled);
33919139a7a6SSean Christopherson 	WARN_ON(static_branch_unlikely(&apic_sw_disabled.key));
3392cef84c30SDavid Matlack }
3393