xref: /openbmc/linux/arch/x86/kvm/lapic.c (revision 360823a09426347ea8f232b0b0b5156d0aed0302)
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"
4428f71967SDavid 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 
62d0f5a86aSWanpeng Li static bool lapic_timer_advance_dynamic __read_mostly;
63a0f0037eSWanpeng Li #define LAPIC_TIMER_ADVANCE_ADJUST_MIN	100	/* clock cycles */
64a0f0037eSWanpeng Li #define LAPIC_TIMER_ADVANCE_ADJUST_MAX	10000	/* clock cycles */
65a0f0037eSWanpeng Li #define LAPIC_TIMER_ADVANCE_NS_INIT	1000
66a0f0037eSWanpeng Li #define LAPIC_TIMER_ADVANCE_NS_MAX     5000
673b8a5df6SWanpeng Li /* step-by-step approximation to mitigate fluctuation */
683b8a5df6SWanpeng Li #define LAPIC_TIMER_ADVANCE_ADJUST_STEP 8
695413bcbaSZeng Guang static int kvm_lapic_msr_read(struct kvm_lapic *apic, u32 reg, u64 *data);
701bd9dfecSSuravee Suthikulpanit static int kvm_lapic_msr_write(struct kvm_lapic *apic, u32 reg, u64 data);
713b8a5df6SWanpeng Li 
__kvm_lapic_set_reg(char * regs,int reg_off,u32 val)72b9964ee3SSean Christopherson static inline void __kvm_lapic_set_reg(char *regs, int reg_off, u32 val)
73b9964ee3SSean Christopherson {
74b9964ee3SSean Christopherson 	*((u32 *) (regs + reg_off)) = val;
75b9964ee3SSean Christopherson }
76b9964ee3SSean Christopherson 
kvm_lapic_set_reg(struct kvm_lapic * apic,int reg_off,u32 val)77b9964ee3SSean Christopherson static inline void kvm_lapic_set_reg(struct kvm_lapic *apic, int reg_off, u32 val)
78b9964ee3SSean Christopherson {
79b9964ee3SSean Christopherson 	__kvm_lapic_set_reg(apic->regs, reg_off, val);
80b9964ee3SSean Christopherson }
81b9964ee3SSean Christopherson 
__kvm_lapic_get_reg64(char * regs,int reg)82a57a3168SSean Christopherson static __always_inline u64 __kvm_lapic_get_reg64(char *regs, int reg)
83a57a3168SSean Christopherson {
84a57a3168SSean Christopherson 	BUILD_BUG_ON(reg != APIC_ICR);
85a57a3168SSean Christopherson 	return *((u64 *) (regs + reg));
86a57a3168SSean Christopherson }
87a57a3168SSean Christopherson 
kvm_lapic_get_reg64(struct kvm_lapic * apic,int reg)88a57a3168SSean Christopherson static __always_inline u64 kvm_lapic_get_reg64(struct kvm_lapic *apic, int reg)
89a57a3168SSean Christopherson {
90a57a3168SSean Christopherson 	return __kvm_lapic_get_reg64(apic->regs, reg);
91a57a3168SSean Christopherson }
92a57a3168SSean Christopherson 
__kvm_lapic_set_reg64(char * regs,int reg,u64 val)93a57a3168SSean Christopherson static __always_inline void __kvm_lapic_set_reg64(char *regs, int reg, u64 val)
94a57a3168SSean Christopherson {
95a57a3168SSean Christopherson 	BUILD_BUG_ON(reg != APIC_ICR);
96a57a3168SSean Christopherson 	*((u64 *) (regs + reg)) = val;
97a57a3168SSean Christopherson }
98a57a3168SSean Christopherson 
kvm_lapic_set_reg64(struct kvm_lapic * apic,int reg,u64 val)99a57a3168SSean Christopherson static __always_inline void kvm_lapic_set_reg64(struct kvm_lapic *apic,
100a57a3168SSean Christopherson 						int reg, u64 val)
101a57a3168SSean Christopherson {
102a57a3168SSean Christopherson 	__kvm_lapic_set_reg64(apic->regs, reg, val);
103a57a3168SSean Christopherson }
104a57a3168SSean Christopherson 
apic_test_vector(int vec,void * bitmap)105a0c9a822SMichael S. Tsirkin static inline int apic_test_vector(int vec, void *bitmap)
106a0c9a822SMichael S. Tsirkin {
107a0c9a822SMichael S. Tsirkin 	return test_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
108a0c9a822SMichael S. Tsirkin }
109a0c9a822SMichael S. Tsirkin 
kvm_apic_pending_eoi(struct kvm_vcpu * vcpu,int vector)11010606919SYang Zhang bool kvm_apic_pending_eoi(struct kvm_vcpu *vcpu, int vector)
11110606919SYang Zhang {
11210606919SYang Zhang 	struct kvm_lapic *apic = vcpu->arch.apic;
11310606919SYang Zhang 
11410606919SYang Zhang 	return apic_test_vector(vector, apic->regs + APIC_ISR) ||
11510606919SYang Zhang 		apic_test_vector(vector, apic->regs + APIC_IRR);
11610606919SYang Zhang }
11710606919SYang Zhang 
__apic_test_and_set_vector(int vec,void * bitmap)1188680b94bSMichael S. Tsirkin static inline int __apic_test_and_set_vector(int vec, void *bitmap)
1198680b94bSMichael S. Tsirkin {
1208680b94bSMichael S. Tsirkin 	return __test_and_set_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
1218680b94bSMichael S. Tsirkin }
1228680b94bSMichael S. Tsirkin 
__apic_test_and_clear_vector(int vec,void * bitmap)1238680b94bSMichael S. Tsirkin static inline int __apic_test_and_clear_vector(int vec, void *bitmap)
1248680b94bSMichael S. Tsirkin {
1258680b94bSMichael S. Tsirkin 	return __test_and_clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
1268680b94bSMichael S. Tsirkin }
1278680b94bSMichael S. Tsirkin 
1286e4e3b4dSCun Li __read_mostly DEFINE_STATIC_KEY_DEFERRED_FALSE(apic_hw_disabled, HZ);
1296e4e3b4dSCun Li __read_mostly DEFINE_STATIC_KEY_DEFERRED_FALSE(apic_sw_disabled, HZ);
130f8c1ea10SGleb Natapov 
apic_enabled(struct kvm_lapic * apic)131edf88417SAvi Kivity static inline int apic_enabled(struct kvm_lapic *apic)
132edf88417SAvi Kivity {
133c48f1496SGleb Natapov 	return kvm_apic_sw_enabled(apic) &&	kvm_apic_hw_enabled(apic);
13454e9818fSGleb Natapov }
13554e9818fSGleb Natapov 
136edf88417SAvi Kivity #define LVT_MASK	\
137edf88417SAvi Kivity 	(APIC_LVT_MASKED | APIC_SEND_PENDING | APIC_VECTOR_MASK)
138edf88417SAvi Kivity 
139edf88417SAvi Kivity #define LINT_MASK	\
140edf88417SAvi Kivity 	(LVT_MASK | APIC_MODE_MASK | APIC_INPUT_POLARITY | \
141edf88417SAvi Kivity 	 APIC_LVT_REMOTE_IRR | APIC_LVT_LEVEL_TRIGGER)
142edf88417SAvi Kivity 
kvm_x2apic_id(struct kvm_lapic * apic)1436e500439SRadim Krčmář static inline u32 kvm_x2apic_id(struct kvm_lapic *apic)
1446e500439SRadim Krčmář {
1456e500439SRadim Krčmář 	return apic->vcpu->vcpu_id;
1466e500439SRadim Krčmář }
1476e500439SRadim Krčmář 
kvm_can_post_timer_interrupt(struct kvm_vcpu * vcpu)148199a8b84SPaolo Bonzini static bool kvm_can_post_timer_interrupt(struct kvm_vcpu *vcpu)
1490c5f81daSWanpeng Li {
1501714a4ebSWanpeng Li 	return pi_inject_timer && kvm_vcpu_apicv_active(vcpu) &&
1511714a4ebSWanpeng Li 		(kvm_mwait_in_guest(vcpu->kvm) || kvm_hlt_in_guest(vcpu->kvm));
1520c5f81daSWanpeng Li }
153199a8b84SPaolo Bonzini 
kvm_can_use_hv_timer(struct kvm_vcpu * vcpu)154199a8b84SPaolo Bonzini bool kvm_can_use_hv_timer(struct kvm_vcpu *vcpu)
155199a8b84SPaolo Bonzini {
156199a8b84SPaolo Bonzini 	return kvm_x86_ops.set_hv_timer
157199a8b84SPaolo Bonzini 	       && !(kvm_mwait_in_guest(vcpu->kvm) ||
158199a8b84SPaolo Bonzini 		    kvm_can_post_timer_interrupt(vcpu));
159199a8b84SPaolo Bonzini }
1600c5f81daSWanpeng Li 
kvm_use_posted_timer_interrupt(struct kvm_vcpu * vcpu)1610c5f81daSWanpeng Li static bool kvm_use_posted_timer_interrupt(struct kvm_vcpu *vcpu)
1620c5f81daSWanpeng Li {
1630c5f81daSWanpeng Li 	return kvm_can_post_timer_interrupt(vcpu) && vcpu->mode == IN_GUEST_MODE;
1640c5f81daSWanpeng Li }
1650c5f81daSWanpeng Li 
kvm_apic_calc_x2apic_ldr(u32 id)16676e52750SSean Christopherson static inline u32 kvm_apic_calc_x2apic_ldr(u32 id)
16776e52750SSean Christopherson {
16876e52750SSean Christopherson 	return ((id >> 4) << 16) | (1 << (id & 0xf));
16976e52750SSean Christopherson }
17076e52750SSean Christopherson 
kvm_apic_map_get_logical_dest(struct kvm_apic_map * map,u32 dest_id,struct kvm_lapic *** cluster,u16 * mask)171e45115b6SRadim Krčmář static inline bool kvm_apic_map_get_logical_dest(struct kvm_apic_map *map,
172e45115b6SRadim Krčmář 		u32 dest_id, struct kvm_lapic ***cluster, u16 *mask) {
17335366901SSean Christopherson 	switch (map->logical_mode) {
17435366901SSean Christopherson 	case KVM_APIC_MODE_SW_DISABLED:
17535366901SSean Christopherson 		/* Arbitrarily use the flat map so that @cluster isn't NULL. */
17635366901SSean Christopherson 		*cluster = map->xapic_flat_map;
17735366901SSean Christopherson 		*mask = 0;
17835366901SSean Christopherson 		return true;
179e45115b6SRadim Krčmář 	case KVM_APIC_MODE_X2APIC: {
180e45115b6SRadim Krčmář 		u32 offset = (dest_id >> 16) * 16;
1810ca52e7bSRadim Krčmář 		u32 max_apic_id = map->max_apic_id;
182e45115b6SRadim Krčmář 
183e45115b6SRadim Krčmář 		if (offset <= max_apic_id) {
184e45115b6SRadim Krčmář 			u8 cluster_size = min(max_apic_id - offset + 1, 16U);
185e45115b6SRadim Krčmář 
1861d487e9bSPaolo Bonzini 			offset = array_index_nospec(offset, map->max_apic_id + 1);
187e45115b6SRadim Krčmář 			*cluster = &map->phys_map[offset];
188e45115b6SRadim Krčmář 			*mask = dest_id & (0xffff >> (16 - cluster_size));
189e45115b6SRadim Krčmář 		} else {
190e45115b6SRadim Krčmář 			*mask = 0;
1913548a259SRadim Krčmář 		}
1923548a259SRadim Krčmář 
193e45115b6SRadim Krčmář 		return true;
194e45115b6SRadim Krčmář 		}
195e45115b6SRadim Krčmář 	case KVM_APIC_MODE_XAPIC_FLAT:
196e45115b6SRadim Krčmář 		*cluster = map->xapic_flat_map;
197e45115b6SRadim Krčmář 		*mask = dest_id & 0xff;
198e45115b6SRadim Krčmář 		return true;
199e45115b6SRadim Krčmář 	case KVM_APIC_MODE_XAPIC_CLUSTER:
200444fdad8SRadim Krčmář 		*cluster = map->xapic_cluster_map[(dest_id >> 4) & 0xf];
201e45115b6SRadim Krčmář 		*mask = dest_id & 0xf;
202e45115b6SRadim Krčmář 		return true;
20335366901SSean Christopherson 	case KVM_APIC_MODE_MAP_DISABLED:
20435366901SSean Christopherson 		return false;
205e45115b6SRadim Krčmář 	default:
20635366901SSean Christopherson 		WARN_ON_ONCE(1);
207e45115b6SRadim Krčmář 		return false;
208e45115b6SRadim Krčmář 	}
2093b5a5ffaSRadim Krčmář }
2103b5a5ffaSRadim Krčmář 
kvm_apic_map_free(struct rcu_head * rcu)211af1bae54SRadim Krčmář static void kvm_apic_map_free(struct rcu_head *rcu)
212edf88417SAvi Kivity {
213af1bae54SRadim Krčmář 	struct kvm_apic_map *map = container_of(rcu, struct kvm_apic_map, rcu);
214edf88417SAvi Kivity 
215af1bae54SRadim Krčmář 	kvfree(map);
216edf88417SAvi Kivity }
217edf88417SAvi Kivity 
kvm_recalculate_phys_map(struct kvm_apic_map * new,struct kvm_vcpu * vcpu,bool * xapic_id_mismatch)21872c70ceeSSean Christopherson static int kvm_recalculate_phys_map(struct kvm_apic_map *new,
21972c70ceeSSean Christopherson 				    struct kvm_vcpu *vcpu,
22072c70ceeSSean Christopherson 				    bool *xapic_id_mismatch)
22172c70ceeSSean Christopherson {
22272c70ceeSSean Christopherson 	struct kvm_lapic *apic = vcpu->arch.apic;
22372c70ceeSSean Christopherson 	u32 x2apic_id = kvm_x2apic_id(apic);
22472c70ceeSSean Christopherson 	u32 xapic_id = kvm_xapic_id(apic);
22572c70ceeSSean Christopherson 	u32 physical_id;
22672c70ceeSSean Christopherson 
22772c70ceeSSean Christopherson 	/*
2284364b287SSean Christopherson 	 * For simplicity, KVM always allocates enough space for all possible
2294364b287SSean Christopherson 	 * xAPIC IDs.  Yell, but don't kill the VM, as KVM can continue on
2304364b287SSean Christopherson 	 * without the optimized map.
2314364b287SSean Christopherson 	 */
2324364b287SSean Christopherson 	if (WARN_ON_ONCE(xapic_id > new->max_apic_id))
2334364b287SSean Christopherson 		return -EINVAL;
2344364b287SSean Christopherson 
2354364b287SSean Christopherson 	/*
2364364b287SSean Christopherson 	 * Bail if a vCPU was added and/or enabled its APIC between allocating
2374364b287SSean Christopherson 	 * the map and doing the actual calculations for the map.  Note, KVM
2384364b287SSean Christopherson 	 * hardcodes the x2APIC ID to vcpu_id, i.e. there's no TOCTOU bug if
2394364b287SSean Christopherson 	 * the compiler decides to reload x2apic_id after this check.
2404364b287SSean Christopherson 	 */
2414364b287SSean Christopherson 	if (x2apic_id > new->max_apic_id)
2424364b287SSean Christopherson 		return -E2BIG;
2434364b287SSean Christopherson 
2444364b287SSean Christopherson 	/*
24572c70ceeSSean Christopherson 	 * Deliberately truncate the vCPU ID when detecting a mismatched APIC
24672c70ceeSSean Christopherson 	 * ID to avoid false positives if the vCPU ID, i.e. x2APIC ID, is a
24772c70ceeSSean Christopherson 	 * 32-bit value.  Any unwanted aliasing due to truncation results will
24872c70ceeSSean Christopherson 	 * be detected below.
24972c70ceeSSean Christopherson 	 */
25072c70ceeSSean Christopherson 	if (!apic_x2apic_mode(apic) && xapic_id != (u8)vcpu->vcpu_id)
25172c70ceeSSean Christopherson 		*xapic_id_mismatch = true;
25272c70ceeSSean Christopherson 
25372c70ceeSSean Christopherson 	/*
25472c70ceeSSean Christopherson 	 * Apply KVM's hotplug hack if userspace has enable 32-bit APIC IDs.
25572c70ceeSSean Christopherson 	 * Allow sending events to vCPUs by their x2APIC ID even if the target
25672c70ceeSSean Christopherson 	 * vCPU is in legacy xAPIC mode, and silently ignore aliased xAPIC IDs
25772c70ceeSSean Christopherson 	 * (the x2APIC ID is truncated to 8 bits, causing IDs > 0xff to wrap
25872c70ceeSSean Christopherson 	 * and collide).
25972c70ceeSSean Christopherson 	 *
26072c70ceeSSean Christopherson 	 * Honor the architectural (and KVM's non-optimized) behavior if
26172c70ceeSSean Christopherson 	 * userspace has not enabled 32-bit x2APIC IDs.  Each APIC is supposed
26272c70ceeSSean Christopherson 	 * to process messages independently.  If multiple vCPUs have the same
26372c70ceeSSean Christopherson 	 * effective APIC ID, e.g. due to the x2APIC wrap or because the guest
26472c70ceeSSean Christopherson 	 * manually modified its xAPIC IDs, events targeting that ID are
26572c70ceeSSean Christopherson 	 * supposed to be recognized by all vCPUs with said ID.
26672c70ceeSSean Christopherson 	 */
26772c70ceeSSean Christopherson 	if (vcpu->kvm->arch.x2apic_format) {
26872c70ceeSSean Christopherson 		/* See also kvm_apic_match_physical_addr(). */
2694364b287SSean Christopherson 		if (apic_x2apic_mode(apic) || x2apic_id > 0xff)
27072c70ceeSSean Christopherson 			new->phys_map[x2apic_id] = apic;
27172c70ceeSSean Christopherson 
27272c70ceeSSean Christopherson 		if (!apic_x2apic_mode(apic) && !new->phys_map[xapic_id])
27372c70ceeSSean Christopherson 			new->phys_map[xapic_id] = apic;
27472c70ceeSSean Christopherson 	} else {
27572c70ceeSSean Christopherson 		/*
27672c70ceeSSean Christopherson 		 * Disable the optimized map if the physical APIC ID is already
27772c70ceeSSean Christopherson 		 * mapped, i.e. is aliased to multiple vCPUs.  The optimized
27872c70ceeSSean Christopherson 		 * map requires a strict 1:1 mapping between IDs and vCPUs.
27972c70ceeSSean Christopherson 		 */
28072c70ceeSSean Christopherson 		if (apic_x2apic_mode(apic))
28172c70ceeSSean Christopherson 			physical_id = x2apic_id;
28272c70ceeSSean Christopherson 		else
28372c70ceeSSean Christopherson 			physical_id = xapic_id;
28472c70ceeSSean Christopherson 
28572c70ceeSSean Christopherson 		if (new->phys_map[physical_id])
28672c70ceeSSean Christopherson 			return -EINVAL;
28772c70ceeSSean Christopherson 
28872c70ceeSSean Christopherson 		new->phys_map[physical_id] = apic;
28972c70ceeSSean Christopherson 	}
29072c70ceeSSean Christopherson 
29172c70ceeSSean Christopherson 	return 0;
29272c70ceeSSean Christopherson }
29372c70ceeSSean Christopherson 
kvm_recalculate_logical_map(struct kvm_apic_map * new,struct kvm_vcpu * vcpu)29472c70ceeSSean Christopherson static void kvm_recalculate_logical_map(struct kvm_apic_map *new,
29572c70ceeSSean Christopherson 					struct kvm_vcpu *vcpu)
29672c70ceeSSean Christopherson {
29772c70ceeSSean Christopherson 	struct kvm_lapic *apic = vcpu->arch.apic;
29872c70ceeSSean Christopherson 	enum kvm_apic_logical_mode logical_mode;
29972c70ceeSSean Christopherson 	struct kvm_lapic **cluster;
30072c70ceeSSean Christopherson 	u16 mask;
30172c70ceeSSean Christopherson 	u32 ldr;
30272c70ceeSSean Christopherson 
30372c70ceeSSean Christopherson 	if (new->logical_mode == KVM_APIC_MODE_MAP_DISABLED)
30472c70ceeSSean Christopherson 		return;
30572c70ceeSSean Christopherson 
30672c70ceeSSean Christopherson 	if (!kvm_apic_sw_enabled(apic))
30772c70ceeSSean Christopherson 		return;
30872c70ceeSSean Christopherson 
30972c70ceeSSean Christopherson 	ldr = kvm_lapic_get_reg(apic, APIC_LDR);
31072c70ceeSSean Christopherson 	if (!ldr)
31172c70ceeSSean Christopherson 		return;
31272c70ceeSSean Christopherson 
31372c70ceeSSean Christopherson 	if (apic_x2apic_mode(apic)) {
31472c70ceeSSean Christopherson 		logical_mode = KVM_APIC_MODE_X2APIC;
31572c70ceeSSean Christopherson 	} else {
31672c70ceeSSean Christopherson 		ldr = GET_APIC_LOGICAL_ID(ldr);
31772c70ceeSSean Christopherson 		if (kvm_lapic_get_reg(apic, APIC_DFR) == APIC_DFR_FLAT)
31872c70ceeSSean Christopherson 			logical_mode = KVM_APIC_MODE_XAPIC_FLAT;
31972c70ceeSSean Christopherson 		else
32072c70ceeSSean Christopherson 			logical_mode = KVM_APIC_MODE_XAPIC_CLUSTER;
32172c70ceeSSean Christopherson 	}
32272c70ceeSSean Christopherson 
32372c70ceeSSean Christopherson 	/*
32472c70ceeSSean Christopherson 	 * To optimize logical mode delivery, all software-enabled APICs must
32572c70ceeSSean Christopherson 	 * be configured for the same mode.
32672c70ceeSSean Christopherson 	 */
32772c70ceeSSean Christopherson 	if (new->logical_mode == KVM_APIC_MODE_SW_DISABLED) {
32872c70ceeSSean Christopherson 		new->logical_mode = logical_mode;
32972c70ceeSSean Christopherson 	} else if (new->logical_mode != logical_mode) {
33072c70ceeSSean Christopherson 		new->logical_mode = KVM_APIC_MODE_MAP_DISABLED;
33172c70ceeSSean Christopherson 		return;
33272c70ceeSSean Christopherson 	}
33372c70ceeSSean Christopherson 
33472c70ceeSSean Christopherson 	/*
33572c70ceeSSean Christopherson 	 * In x2APIC mode, the LDR is read-only and derived directly from the
33672c70ceeSSean Christopherson 	 * x2APIC ID, thus is guaranteed to be addressable.  KVM reuses
33772c70ceeSSean Christopherson 	 * kvm_apic_map.phys_map to optimize logical mode x2APIC interrupts by
33872c70ceeSSean Christopherson 	 * reversing the LDR calculation to get cluster of APICs, i.e. no
33972c70ceeSSean Christopherson 	 * additional work is required.
34072c70ceeSSean Christopherson 	 */
3414fc0f9eaSSean Christopherson 	if (apic_x2apic_mode(apic))
34272c70ceeSSean Christopherson 		return;
34372c70ceeSSean Christopherson 
34472c70ceeSSean Christopherson 	if (WARN_ON_ONCE(!kvm_apic_map_get_logical_dest(new, ldr,
34572c70ceeSSean Christopherson 							&cluster, &mask))) {
34672c70ceeSSean Christopherson 		new->logical_mode = KVM_APIC_MODE_MAP_DISABLED;
34772c70ceeSSean Christopherson 		return;
34872c70ceeSSean Christopherson 	}
34972c70ceeSSean Christopherson 
35072c70ceeSSean Christopherson 	if (!mask)
35172c70ceeSSean Christopherson 		return;
35272c70ceeSSean Christopherson 
35372c70ceeSSean Christopherson 	ldr = ffs(mask) - 1;
35472c70ceeSSean Christopherson 	if (!is_power_of_2(mask) || cluster[ldr])
35572c70ceeSSean Christopherson 		new->logical_mode = KVM_APIC_MODE_MAP_DISABLED;
35672c70ceeSSean Christopherson 	else
35772c70ceeSSean Christopherson 		cluster[ldr] = apic;
35872c70ceeSSean Christopherson }
35972c70ceeSSean Christopherson 
36044d52717SPaolo Bonzini /*
36144d52717SPaolo Bonzini  * CLEAN -> DIRTY and UPDATE_IN_PROGRESS -> DIRTY changes happen without a lock.
36244d52717SPaolo Bonzini  *
36344d52717SPaolo Bonzini  * DIRTY -> UPDATE_IN_PROGRESS and UPDATE_IN_PROGRESS -> CLEAN happen with
36444d52717SPaolo Bonzini  * apic_map_lock_held.
36544d52717SPaolo Bonzini  */
36644d52717SPaolo Bonzini enum {
36744d52717SPaolo Bonzini 	CLEAN,
36844d52717SPaolo Bonzini 	UPDATE_IN_PROGRESS,
36944d52717SPaolo Bonzini 	DIRTY
37044d52717SPaolo Bonzini };
37144d52717SPaolo Bonzini 
kvm_recalculate_apic_map(struct kvm * kvm)3724abaffceSWanpeng Li void kvm_recalculate_apic_map(struct kvm *kvm)
3731e08ec4aSGleb Natapov {
3741e08ec4aSGleb Natapov 	struct kvm_apic_map *new, *old = NULL;
3751e08ec4aSGleb Natapov 	struct kvm_vcpu *vcpu;
37646808a4cSMarc Zyngier 	unsigned long i;
3776e500439SRadim Krčmář 	u32 max_id = 255; /* enough space for any xAPIC ID */
37841e90a69SSean Christopherson 	bool xapic_id_mismatch;
37941e90a69SSean Christopherson 	int r;
3801e08ec4aSGleb Natapov 
38144d52717SPaolo Bonzini 	/* Read kvm->arch.apic_map_dirty before kvm->arch.apic_map.  */
38244d52717SPaolo Bonzini 	if (atomic_read_acquire(&kvm->arch.apic_map_dirty) == CLEAN)
3834abaffceSWanpeng Li 		return;
3844abaffceSWanpeng Li 
385c2f79a65SSean Christopherson 	WARN_ONCE(!irqchip_in_kernel(kvm),
386c2f79a65SSean Christopherson 		  "Dirty APIC map without an in-kernel local APIC");
387c2f79a65SSean Christopherson 
3881e08ec4aSGleb Natapov 	mutex_lock(&kvm->arch.apic_map_lock);
38941e90a69SSean Christopherson 
39041e90a69SSean Christopherson retry:
39144d52717SPaolo Bonzini 	/*
39241e90a69SSean Christopherson 	 * Read kvm->arch.apic_map_dirty before kvm->arch.apic_map (if clean)
39341e90a69SSean Christopherson 	 * or the APIC registers (if dirty).  Note, on retry the map may have
39441e90a69SSean Christopherson 	 * not yet been marked dirty by whatever task changed a vCPU's x2APIC
39541e90a69SSean Christopherson 	 * ID, i.e. the map may still show up as in-progress.  In that case
39641e90a69SSean Christopherson 	 * this task still needs to retry and complete its calculation.
39744d52717SPaolo Bonzini 	 */
39844d52717SPaolo Bonzini 	if (atomic_cmpxchg_acquire(&kvm->arch.apic_map_dirty,
39944d52717SPaolo Bonzini 				   DIRTY, UPDATE_IN_PROGRESS) == CLEAN) {
4004abaffceSWanpeng Li 		/* Someone else has updated the map. */
4014abaffceSWanpeng Li 		mutex_unlock(&kvm->arch.apic_map_lock);
4024abaffceSWanpeng Li 		return;
4034abaffceSWanpeng Li 	}
4041e08ec4aSGleb Natapov 
40541e90a69SSean Christopherson 	/*
40641e90a69SSean Christopherson 	 * Reset the mismatch flag between attempts so that KVM does the right
40741e90a69SSean Christopherson 	 * thing if a vCPU changes its xAPIC ID, but do NOT reset max_id, i.e.
40841e90a69SSean Christopherson 	 * keep max_id strictly increasing.  Disallowing max_id from shrinking
40941e90a69SSean Christopherson 	 * ensures KVM won't get stuck in an infinite loop, e.g. if the vCPU
41041e90a69SSean Christopherson 	 * with the highest x2APIC ID is toggling its APIC on and off.
41141e90a69SSean Christopherson 	 */
41241e90a69SSean Christopherson 	xapic_id_mismatch = false;
41341e90a69SSean Christopherson 
4140ca52e7bSRadim Krčmář 	kvm_for_each_vcpu(i, vcpu, kvm)
4150ca52e7bSRadim Krčmář 		if (kvm_apic_present(vcpu))
4166e500439SRadim Krčmář 			max_id = max(max_id, kvm_x2apic_id(vcpu->arch.apic));
4170ca52e7bSRadim Krčmář 
418a7c3e901SMichal Hocko 	new = kvzalloc(sizeof(struct kvm_apic_map) +
419254272ceSBen Gardon 	                   sizeof(struct kvm_lapic *) * ((u64)max_id + 1),
420254272ceSBen Gardon 			   GFP_KERNEL_ACCOUNT);
4210ca52e7bSRadim Krčmář 
4221e08ec4aSGleb Natapov 	if (!new)
4231e08ec4aSGleb Natapov 		goto out;
4241e08ec4aSGleb Natapov 
4250ca52e7bSRadim Krčmář 	new->max_apic_id = max_id;
42635366901SSean Christopherson 	new->logical_mode = KVM_APIC_MODE_SW_DISABLED;
4270ca52e7bSRadim Krčmář 
428173beedcSNadav Amit 	kvm_for_each_vcpu(i, vcpu, kvm) {
429df04d1d1SRadim Krčmář 		if (!kvm_apic_present(vcpu))
430df04d1d1SRadim Krčmář 			continue;
431df04d1d1SRadim Krčmář 
43241e90a69SSean Christopherson 		r = kvm_recalculate_phys_map(new, vcpu, &xapic_id_mismatch);
43341e90a69SSean Christopherson 		if (r) {
4345b84b029SSean Christopherson 			kvfree(new);
4355b84b029SSean Christopherson 			new = NULL;
43641e90a69SSean Christopherson 			if (r == -E2BIG) {
43741e90a69SSean Christopherson 				cond_resched();
43841e90a69SSean Christopherson 				goto retry;
43941e90a69SSean Christopherson 			}
44041e90a69SSean Christopherson 
4415b84b029SSean Christopherson 			goto out;
4423b5a5ffaSRadim Krčmář 		}
4433b5a5ffaSRadim Krčmář 
44472c70ceeSSean Christopherson 		kvm_recalculate_logical_map(new, vcpu);
4451e08ec4aSGleb Natapov 	}
4461e08ec4aSGleb Natapov out:
4475063c41bSSean Christopherson 	/*
4485063c41bSSean Christopherson 	 * The optimized map is effectively KVM's internal version of APICv,
4495063c41bSSean Christopherson 	 * and all unwanted aliasing that results in disabling the optimized
4505063c41bSSean Christopherson 	 * map also applies to APICv.
4515063c41bSSean Christopherson 	 */
4525063c41bSSean Christopherson 	if (!new)
4535063c41bSSean Christopherson 		kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_PHYSICAL_ID_ALIASED);
4545063c41bSSean Christopherson 	else
4555063c41bSSean Christopherson 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_PHYSICAL_ID_ALIASED);
4565063c41bSSean Christopherson 
4579a364857SSean Christopherson 	if (!new || new->logical_mode == KVM_APIC_MODE_MAP_DISABLED)
4589a364857SSean Christopherson 		kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_LOGICAL_ID_ALIASED);
4599a364857SSean Christopherson 	else
4609a364857SSean Christopherson 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_LOGICAL_ID_ALIASED);
4619a364857SSean Christopherson 
462d471bd85SGreg Edwards 	if (xapic_id_mismatch)
463d471bd85SGreg Edwards 		kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_APIC_ID_MODIFIED);
464d471bd85SGreg Edwards 	else
465d471bd85SGreg Edwards 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_APIC_ID_MODIFIED);
466d471bd85SGreg Edwards 
4671e08ec4aSGleb Natapov 	old = rcu_dereference_protected(kvm->arch.apic_map,
4681e08ec4aSGleb Natapov 			lockdep_is_held(&kvm->arch.apic_map_lock));
4691e08ec4aSGleb Natapov 	rcu_assign_pointer(kvm->arch.apic_map, new);
4704abaffceSWanpeng Li 	/*
47144d52717SPaolo Bonzini 	 * Write kvm->arch.apic_map before clearing apic->apic_map_dirty.
47244d52717SPaolo Bonzini 	 * If another update has come in, leave it DIRTY.
4734abaffceSWanpeng Li 	 */
47444d52717SPaolo Bonzini 	atomic_cmpxchg_release(&kvm->arch.apic_map_dirty,
47544d52717SPaolo Bonzini 			       UPDATE_IN_PROGRESS, CLEAN);
4761e08ec4aSGleb Natapov 	mutex_unlock(&kvm->arch.apic_map_lock);
4771e08ec4aSGleb Natapov 
4781e08ec4aSGleb Natapov 	if (old)
479af1bae54SRadim Krčmář 		call_rcu(&old->rcu, kvm_apic_map_free);
480c7c9c56cSYang Zhang 
481b053b2aeSSteve Rutherford 	kvm_make_scan_ioapic_request(kvm);
4821e08ec4aSGleb Natapov }
4831e08ec4aSGleb Natapov 
apic_set_spiv(struct kvm_lapic * apic,u32 val)4841e1b6c26SNadav Amit static inline void apic_set_spiv(struct kvm_lapic *apic, u32 val)
4851e1b6c26SNadav Amit {
486e462755cSRadim Krčmář 	bool enabled = val & APIC_SPIV_APIC_ENABLED;
4871e1b6c26SNadav Amit 
4881e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_SPIV, val);
489e462755cSRadim Krčmář 
490e462755cSRadim Krčmář 	if (enabled != apic->sw_enabled) {
491e462755cSRadim Krčmář 		apic->sw_enabled = enabled;
492eb1ff0a9SPeng Hao 		if (enabled)
4936e4e3b4dSCun Li 			static_branch_slow_dec_deferred(&apic_sw_disabled);
494eb1ff0a9SPeng Hao 		else
4956e4e3b4dSCun Li 			static_branch_inc(&apic_sw_disabled.key);
496b14c876bSRadim Krcmar 
49744d52717SPaolo Bonzini 		atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
4981e1b6c26SNadav Amit 	}
4992f15d027SVitaly Kuznetsov 
5002f15d027SVitaly Kuznetsov 	/* Check if there are APF page ready requests pending */
50128f71967SDavid Woodhouse 	if (enabled) {
5022f15d027SVitaly Kuznetsov 		kvm_make_request(KVM_REQ_APF_READY, apic->vcpu);
50328f71967SDavid Woodhouse 		kvm_xen_sw_enable_lapic(apic->vcpu);
50428f71967SDavid Woodhouse 	}
5051e1b6c26SNadav Amit }
5061e1b6c26SNadav Amit 
kvm_apic_set_xapic_id(struct kvm_lapic * apic,u8 id)507a92e2543SRadim Krčmář static inline void kvm_apic_set_xapic_id(struct kvm_lapic *apic, u8 id)
5081e08ec4aSGleb Natapov {
5091e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_ID, id << 24);
51044d52717SPaolo Bonzini 	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
5111e08ec4aSGleb Natapov }
5121e08ec4aSGleb Natapov 
kvm_apic_set_ldr(struct kvm_lapic * apic,u32 id)5131e08ec4aSGleb Natapov static inline void kvm_apic_set_ldr(struct kvm_lapic *apic, u32 id)
5141e08ec4aSGleb Natapov {
5151e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_LDR, id);
51644d52717SPaolo Bonzini 	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
5171e08ec4aSGleb Natapov }
5181e08ec4aSGleb Natapov 
kvm_apic_set_dfr(struct kvm_lapic * apic,u32 val)519ae6f2496SWanpeng Li static inline void kvm_apic_set_dfr(struct kvm_lapic *apic, u32 val)
520ae6f2496SWanpeng Li {
521ae6f2496SWanpeng Li 	kvm_lapic_set_reg(apic, APIC_DFR, val);
522ae6f2496SWanpeng Li 	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
523ae6f2496SWanpeng Li }
524ae6f2496SWanpeng Li 
kvm_apic_set_x2apic_id(struct kvm_lapic * apic,u32 id)525a92e2543SRadim Krčmář static inline void kvm_apic_set_x2apic_id(struct kvm_lapic *apic, u32 id)
526257b9a5fSRadim Krčmář {
527e872fa94SDr. David Alan Gilbert 	u32 ldr = kvm_apic_calc_x2apic_ldr(id);
528257b9a5fSRadim Krčmář 
5296e500439SRadim Krčmář 	WARN_ON_ONCE(id != apic->vcpu->vcpu_id);
5306e500439SRadim Krčmář 
531a92e2543SRadim Krčmář 	kvm_lapic_set_reg(apic, APIC_ID, id);
5321e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_LDR, ldr);
53344d52717SPaolo Bonzini 	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
534257b9a5fSRadim Krčmář }
535257b9a5fSRadim Krčmář 
apic_lvt_enabled(struct kvm_lapic * apic,int lvt_type)536edf88417SAvi Kivity static inline int apic_lvt_enabled(struct kvm_lapic *apic, int lvt_type)
537edf88417SAvi Kivity {
538dfb95954SSuravee Suthikulpanit 	return !(kvm_lapic_get_reg(apic, lvt_type) & APIC_LVT_MASKED);
539edf88417SAvi Kivity }
540edf88417SAvi Kivity 
apic_lvtt_oneshot(struct kvm_lapic * apic)541a3e06bbeSLiu, Jinsong static inline int apic_lvtt_oneshot(struct kvm_lapic *apic)
542a3e06bbeSLiu, Jinsong {
543f30ebc31SRadim Krčmář 	return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_ONESHOT;
544a3e06bbeSLiu, Jinsong }
545a3e06bbeSLiu, Jinsong 
apic_lvtt_period(struct kvm_lapic * apic)546edf88417SAvi Kivity static inline int apic_lvtt_period(struct kvm_lapic *apic)
547edf88417SAvi Kivity {
548f30ebc31SRadim Krčmář 	return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_PERIODIC;
549a3e06bbeSLiu, Jinsong }
550a3e06bbeSLiu, Jinsong 
apic_lvtt_tscdeadline(struct kvm_lapic * apic)551a3e06bbeSLiu, Jinsong static inline int apic_lvtt_tscdeadline(struct kvm_lapic *apic)
552a3e06bbeSLiu, Jinsong {
553f30ebc31SRadim Krčmář 	return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_TSCDEADLINE;
554edf88417SAvi Kivity }
555edf88417SAvi Kivity 
apic_lvt_nmi_mode(u32 lvt_val)556cc6e462cSJan Kiszka static inline int apic_lvt_nmi_mode(u32 lvt_val)
557cc6e462cSJan Kiszka {
558cc6e462cSJan Kiszka 	return (lvt_val & (APIC_MODE_MASK | APIC_LVT_MASKED)) == APIC_DM_NMI;
559cc6e462cSJan Kiszka }
560cc6e462cSJan Kiszka 
kvm_lapic_lvt_supported(struct kvm_lapic * apic,int lvt_index)5614b903561SJue Wang static inline bool kvm_lapic_lvt_supported(struct kvm_lapic *apic, int lvt_index)
5624b903561SJue Wang {
5634b903561SJue Wang 	return apic->nr_lvt_entries > lvt_index;
5644b903561SJue Wang }
5654b903561SJue Wang 
kvm_apic_calc_nr_lvt_entries(struct kvm_vcpu * vcpu)56603d84f96SSean Christopherson static inline int kvm_apic_calc_nr_lvt_entries(struct kvm_vcpu *vcpu)
56703d84f96SSean Christopherson {
56803d84f96SSean Christopherson 	return KVM_APIC_MAX_NR_LVT_ENTRIES - !(vcpu->arch.mcg_cap & MCG_CMCI_P);
56903d84f96SSean Christopherson }
57003d84f96SSean Christopherson 
kvm_apic_set_version(struct kvm_vcpu * vcpu)571fc61b800SGleb Natapov void kvm_apic_set_version(struct kvm_vcpu *vcpu)
572fc61b800SGleb Natapov {
573fc61b800SGleb Natapov 	struct kvm_lapic *apic = vcpu->arch.apic;
5744b903561SJue Wang 	u32 v = 0;
575fc61b800SGleb Natapov 
576bce87cceSPaolo Bonzini 	if (!lapic_in_kernel(vcpu))
577fc61b800SGleb Natapov 		return;
578fc61b800SGleb Natapov 
5794b903561SJue Wang 	v = APIC_VERSION | ((apic->nr_lvt_entries - 1) << 16);
5804b903561SJue Wang 
5810bcc3fb9SVitaly Kuznetsov 	/*
5820bcc3fb9SVitaly Kuznetsov 	 * KVM emulates 82093AA datasheet (with in-kernel IOAPIC implementation)
5830bcc3fb9SVitaly Kuznetsov 	 * which doesn't have EOI register; Some buggy OSes (e.g. Windows with
5840bcc3fb9SVitaly Kuznetsov 	 * Hyper-V role) disable EOI broadcast in lapic not checking for IOAPIC
5850bcc3fb9SVitaly Kuznetsov 	 * version first and level-triggered interrupts never get EOIed in
5860bcc3fb9SVitaly Kuznetsov 	 * IOAPIC.
5870bcc3fb9SVitaly Kuznetsov 	 */
588565b7820SXiaoyao Li 	if (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) &&
5890bcc3fb9SVitaly Kuznetsov 	    !ioapic_in_kernel(vcpu->kvm))
590fc61b800SGleb Natapov 		v |= APIC_LVR_DIRECTED_EOI;
5911e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_LVR, v);
592fc61b800SGleb Natapov }
593fc61b800SGleb Natapov 
kvm_apic_after_set_mcg_cap(struct kvm_vcpu * vcpu)594f83894b2SSean Christopherson void kvm_apic_after_set_mcg_cap(struct kvm_vcpu *vcpu)
595f83894b2SSean Christopherson {
596f83894b2SSean Christopherson 	int nr_lvt_entries = kvm_apic_calc_nr_lvt_entries(vcpu);
597f83894b2SSean Christopherson 	struct kvm_lapic *apic = vcpu->arch.apic;
598f83894b2SSean Christopherson 	int i;
599f83894b2SSean Christopherson 
600f83894b2SSean Christopherson 	if (!lapic_in_kernel(vcpu) || nr_lvt_entries == apic->nr_lvt_entries)
601f83894b2SSean Christopherson 		return;
602f83894b2SSean Christopherson 
603f83894b2SSean Christopherson 	/* Initialize/mask any "new" LVT entries. */
604f83894b2SSean Christopherson 	for (i = apic->nr_lvt_entries; i < nr_lvt_entries; i++)
605f83894b2SSean Christopherson 		kvm_lapic_set_reg(apic, APIC_LVTx(i), APIC_LVT_MASKED);
606f83894b2SSean Christopherson 
607f83894b2SSean Christopherson 	apic->nr_lvt_entries = nr_lvt_entries;
608f83894b2SSean Christopherson 
609f83894b2SSean Christopherson 	/* The number of LVT entries is reflected in the version register. */
610f83894b2SSean Christopherson 	kvm_apic_set_version(vcpu);
611f83894b2SSean Christopherson }
612f83894b2SSean Christopherson 
6131d8c681fSJue Wang static const unsigned int apic_lvt_mask[KVM_APIC_MAX_NR_LVT_ENTRIES] = {
6141d8c681fSJue Wang 	[LVT_TIMER] = LVT_MASK,      /* timer mode mask added at runtime */
6151d8c681fSJue Wang 	[LVT_THERMAL_MONITOR] = LVT_MASK | APIC_MODE_MASK,
6161d8c681fSJue Wang 	[LVT_PERFORMANCE_COUNTER] = LVT_MASK | APIC_MODE_MASK,
6171d8c681fSJue Wang 	[LVT_LINT0] = LINT_MASK,
6181d8c681fSJue Wang 	[LVT_LINT1] = LINT_MASK,
6194b903561SJue Wang 	[LVT_ERROR] = LVT_MASK,
6204b903561SJue Wang 	[LVT_CMCI] = LVT_MASK | APIC_MODE_MASK
621edf88417SAvi Kivity };
622edf88417SAvi Kivity 
find_highest_vector(void * bitmap)623edf88417SAvi Kivity static int find_highest_vector(void *bitmap)
624edf88417SAvi Kivity {
625ecba9a52STakuya Yoshikawa 	int vec;
626ecba9a52STakuya Yoshikawa 	u32 *reg;
627edf88417SAvi Kivity 
628ecba9a52STakuya Yoshikawa 	for (vec = MAX_APIC_VECTOR - APIC_VECTORS_PER_REG;
629ecba9a52STakuya Yoshikawa 	     vec >= 0; vec -= APIC_VECTORS_PER_REG) {
630ecba9a52STakuya Yoshikawa 		reg = bitmap + REG_POS(vec);
631ecba9a52STakuya Yoshikawa 		if (*reg)
632810e6defSPaolo Bonzini 			return __fls(*reg) + vec;
633ecba9a52STakuya Yoshikawa 	}
634edf88417SAvi Kivity 
635edf88417SAvi Kivity 	return -1;
636edf88417SAvi Kivity }
637edf88417SAvi Kivity 
count_vectors(void * bitmap)6388680b94bSMichael S. Tsirkin static u8 count_vectors(void *bitmap)
6398680b94bSMichael S. Tsirkin {
640ecba9a52STakuya Yoshikawa 	int vec;
641ecba9a52STakuya Yoshikawa 	u32 *reg;
6428680b94bSMichael S. Tsirkin 	u8 count = 0;
643ecba9a52STakuya Yoshikawa 
644ecba9a52STakuya Yoshikawa 	for (vec = 0; vec < MAX_APIC_VECTOR; vec += APIC_VECTORS_PER_REG) {
645ecba9a52STakuya Yoshikawa 		reg = bitmap + REG_POS(vec);
646ecba9a52STakuya Yoshikawa 		count += hweight32(*reg);
647ecba9a52STakuya Yoshikawa 	}
648ecba9a52STakuya Yoshikawa 
6498680b94bSMichael S. Tsirkin 	return count;
6508680b94bSMichael S. Tsirkin }
6518680b94bSMichael S. Tsirkin 
__kvm_apic_update_irr(u32 * pir,void * regs,int * max_irr)652e7387b0eSLiran Alon bool __kvm_apic_update_irr(u32 *pir, void *regs, int *max_irr)
653a20ed54dSYang Zhang {
654810e6defSPaolo Bonzini 	u32 i, vec;
655e7387b0eSLiran Alon 	u32 pir_val, irr_val, prev_irr_val;
656e7387b0eSLiran Alon 	int max_updated_irr;
657e7387b0eSLiran Alon 
658e7387b0eSLiran Alon 	max_updated_irr = -1;
659e7387b0eSLiran Alon 	*max_irr = -1;
660a20ed54dSYang Zhang 
661810e6defSPaolo Bonzini 	for (i = vec = 0; i <= 7; i++, vec += 32) {
662514946d1SMaxim Levitsky 		u32 *p_irr = (u32 *)(regs + APIC_IRR + i * 0x10);
663514946d1SMaxim Levitsky 
664514946d1SMaxim Levitsky 		irr_val = *p_irr;
665ad361091SPaolo Bonzini 		pir_val = READ_ONCE(pir[i]);
666514946d1SMaxim Levitsky 
667ad361091SPaolo Bonzini 		if (pir_val) {
668514946d1SMaxim Levitsky 			pir_val = xchg(&pir[i], 0);
669514946d1SMaxim Levitsky 
670e7387b0eSLiran Alon 			prev_irr_val = irr_val;
671514946d1SMaxim Levitsky 			do {
672514946d1SMaxim Levitsky 				irr_val = prev_irr_val | pir_val;
673514946d1SMaxim Levitsky 			} while (prev_irr_val != irr_val &&
674514946d1SMaxim Levitsky 				 !try_cmpxchg(p_irr, &prev_irr_val, irr_val));
675514946d1SMaxim Levitsky 
676514946d1SMaxim Levitsky 			if (prev_irr_val != irr_val)
677514946d1SMaxim Levitsky 				max_updated_irr = __fls(irr_val ^ prev_irr_val) + vec;
678a20ed54dSYang Zhang 		}
679810e6defSPaolo Bonzini 		if (irr_val)
680e7387b0eSLiran Alon 			*max_irr = __fls(irr_val) + vec;
681a20ed54dSYang Zhang 	}
682810e6defSPaolo Bonzini 
683e7387b0eSLiran Alon 	return ((max_updated_irr != -1) &&
684e7387b0eSLiran Alon 		(max_updated_irr == *max_irr));
685ad361091SPaolo Bonzini }
686705699a1SWincy Van EXPORT_SYMBOL_GPL(__kvm_apic_update_irr);
687705699a1SWincy Van 
kvm_apic_update_irr(struct kvm_vcpu * vcpu,u32 * pir,int * max_irr)688e7387b0eSLiran Alon bool kvm_apic_update_irr(struct kvm_vcpu *vcpu, u32 *pir, int *max_irr)
689705699a1SWincy Van {
690705699a1SWincy Van 	struct kvm_lapic *apic = vcpu->arch.apic;
691cff540ebSMaxim Levitsky 	bool irr_updated = __kvm_apic_update_irr(pir, apic->regs, max_irr);
692705699a1SWincy Van 
693cff540ebSMaxim Levitsky 	if (unlikely(!apic->apicv_active && irr_updated))
694cff540ebSMaxim Levitsky 		apic->irr_pending = true;
695cff540ebSMaxim Levitsky 	return irr_updated;
696705699a1SWincy Van }
697a20ed54dSYang Zhang EXPORT_SYMBOL_GPL(kvm_apic_update_irr);
698a20ed54dSYang Zhang 
apic_search_irr(struct kvm_lapic * apic)69933e4c686SGleb Natapov static inline int apic_search_irr(struct kvm_lapic *apic)
700edf88417SAvi Kivity {
70133e4c686SGleb Natapov 	return find_highest_vector(apic->regs + APIC_IRR);
702edf88417SAvi Kivity }
703edf88417SAvi Kivity 
apic_find_highest_irr(struct kvm_lapic * apic)704edf88417SAvi Kivity static inline int apic_find_highest_irr(struct kvm_lapic *apic)
705edf88417SAvi Kivity {
706edf88417SAvi Kivity 	int result;
707edf88417SAvi Kivity 
708c7c9c56cSYang Zhang 	/*
709c7c9c56cSYang Zhang 	 * Note that irr_pending is just a hint. It will be always
710c7c9c56cSYang Zhang 	 * true with virtual interrupt delivery enabled.
711c7c9c56cSYang Zhang 	 */
71233e4c686SGleb Natapov 	if (!apic->irr_pending)
71333e4c686SGleb Natapov 		return -1;
71433e4c686SGleb Natapov 
71533e4c686SGleb Natapov 	result = apic_search_irr(apic);
716edf88417SAvi Kivity 	ASSERT(result == -1 || result >= 16);
717edf88417SAvi Kivity 
718edf88417SAvi Kivity 	return result;
719edf88417SAvi Kivity }
720edf88417SAvi Kivity 
apic_clear_irr(int vec,struct kvm_lapic * apic)72133e4c686SGleb Natapov static inline void apic_clear_irr(int vec, struct kvm_lapic *apic)
72233e4c686SGleb Natapov {
723ce0a58f4SSean Christopherson 	if (unlikely(apic->apicv_active)) {
724b95234c8SPaolo Bonzini 		/* need to update RVI */
725ee171d2fSWei Yang 		kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
726ce0a58f4SSean Christopherson 		static_call_cond(kvm_x86_hwapic_irr_update)(apic->vcpu,
727ce0a58f4SSean Christopherson 							    apic_find_highest_irr(apic));
728f210f757SNadav Amit 	} else {
729f210f757SNadav Amit 		apic->irr_pending = false;
730ee171d2fSWei Yang 		kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
731f210f757SNadav Amit 		if (apic_search_irr(apic) != -1)
732f210f757SNadav Amit 			apic->irr_pending = true;
73356cc2406SWanpeng Li 	}
73433e4c686SGleb Natapov }
73533e4c686SGleb Natapov 
kvm_apic_clear_irr(struct kvm_vcpu * vcpu,int vec)73625bb2cf9SSean Christopherson void kvm_apic_clear_irr(struct kvm_vcpu *vcpu, int vec)
73725bb2cf9SSean Christopherson {
73825bb2cf9SSean Christopherson 	apic_clear_irr(vec, vcpu->arch.apic);
73925bb2cf9SSean Christopherson }
74025bb2cf9SSean Christopherson EXPORT_SYMBOL_GPL(kvm_apic_clear_irr);
74125bb2cf9SSean Christopherson 
apic_set_isr(int vec,struct kvm_lapic * apic)7428680b94bSMichael S. Tsirkin static inline void apic_set_isr(int vec, struct kvm_lapic *apic)
7438680b94bSMichael S. Tsirkin {
74456cc2406SWanpeng Li 	if (__apic_test_and_set_vector(vec, apic->regs + APIC_ISR))
74556cc2406SWanpeng Li 		return;
74656cc2406SWanpeng Li 
74756cc2406SWanpeng Li 	/*
74856cc2406SWanpeng Li 	 * With APIC virtualization enabled, all caching is disabled
74956cc2406SWanpeng Li 	 * because the processor can modify ISR under the hood.  Instead
75056cc2406SWanpeng Li 	 * just set SVI.
75156cc2406SWanpeng Li 	 */
752ce0a58f4SSean Christopherson 	if (unlikely(apic->apicv_active))
753d39850f5SSean Christopherson 		static_call_cond(kvm_x86_hwapic_isr_update)(vec);
75456cc2406SWanpeng Li 	else {
7558680b94bSMichael S. Tsirkin 		++apic->isr_count;
7568680b94bSMichael S. Tsirkin 		BUG_ON(apic->isr_count > MAX_APIC_VECTOR);
7578680b94bSMichael S. Tsirkin 		/*
7588680b94bSMichael S. Tsirkin 		 * ISR (in service register) bit is set when injecting an interrupt.
7598680b94bSMichael S. Tsirkin 		 * The highest vector is injected. Thus the latest bit set matches
7608680b94bSMichael S. Tsirkin 		 * the highest bit in ISR.
7618680b94bSMichael S. Tsirkin 		 */
7628680b94bSMichael S. Tsirkin 		apic->highest_isr_cache = vec;
7638680b94bSMichael S. Tsirkin 	}
76456cc2406SWanpeng Li }
7658680b94bSMichael S. Tsirkin 
apic_find_highest_isr(struct kvm_lapic * apic)766fc57ac2cSPaolo Bonzini static inline int apic_find_highest_isr(struct kvm_lapic *apic)
767fc57ac2cSPaolo Bonzini {
768fc57ac2cSPaolo Bonzini 	int result;
769fc57ac2cSPaolo Bonzini 
770fc57ac2cSPaolo Bonzini 	/*
771fc57ac2cSPaolo Bonzini 	 * Note that isr_count is always 1, and highest_isr_cache
772fc57ac2cSPaolo Bonzini 	 * is always -1, with APIC virtualization enabled.
773fc57ac2cSPaolo Bonzini 	 */
774fc57ac2cSPaolo Bonzini 	if (!apic->isr_count)
775fc57ac2cSPaolo Bonzini 		return -1;
776fc57ac2cSPaolo Bonzini 	if (likely(apic->highest_isr_cache != -1))
777fc57ac2cSPaolo Bonzini 		return apic->highest_isr_cache;
778fc57ac2cSPaolo Bonzini 
779fc57ac2cSPaolo Bonzini 	result = find_highest_vector(apic->regs + APIC_ISR);
780fc57ac2cSPaolo Bonzini 	ASSERT(result == -1 || result >= 16);
781fc57ac2cSPaolo Bonzini 
782fc57ac2cSPaolo Bonzini 	return result;
783fc57ac2cSPaolo Bonzini }
784fc57ac2cSPaolo Bonzini 
apic_clear_isr(int vec,struct kvm_lapic * apic)7858680b94bSMichael S. Tsirkin static inline void apic_clear_isr(int vec, struct kvm_lapic *apic)
7868680b94bSMichael S. Tsirkin {
787fc57ac2cSPaolo Bonzini 	if (!__apic_test_and_clear_vector(vec, apic->regs + APIC_ISR))
788fc57ac2cSPaolo Bonzini 		return;
789fc57ac2cSPaolo Bonzini 
790fc57ac2cSPaolo Bonzini 	/*
791fc57ac2cSPaolo Bonzini 	 * We do get here for APIC virtualization enabled if the guest
792fc57ac2cSPaolo Bonzini 	 * uses the Hyper-V APIC enlightenment.  In this case we may need
793fc57ac2cSPaolo Bonzini 	 * to trigger a new interrupt delivery by writing the SVI field;
794fc57ac2cSPaolo Bonzini 	 * on the other hand isr_count and highest_isr_cache are unused
795fc57ac2cSPaolo Bonzini 	 * and must be left alone.
796fc57ac2cSPaolo Bonzini 	 */
797ce0a58f4SSean Christopherson 	if (unlikely(apic->apicv_active))
798d39850f5SSean Christopherson 		static_call_cond(kvm_x86_hwapic_isr_update)(apic_find_highest_isr(apic));
799fc57ac2cSPaolo Bonzini 	else {
8008680b94bSMichael S. Tsirkin 		--apic->isr_count;
8018680b94bSMichael S. Tsirkin 		BUG_ON(apic->isr_count < 0);
8028680b94bSMichael S. Tsirkin 		apic->highest_isr_cache = -1;
8038680b94bSMichael S. Tsirkin 	}
804fc57ac2cSPaolo Bonzini }
8058680b94bSMichael S. Tsirkin 
kvm_lapic_find_highest_irr(struct kvm_vcpu * vcpu)806edf88417SAvi Kivity int kvm_lapic_find_highest_irr(struct kvm_vcpu *vcpu)
807edf88417SAvi Kivity {
80833e4c686SGleb Natapov 	/* This may race with setting of irr in __apic_accept_irq() and
80933e4c686SGleb Natapov 	 * value returned may be wrong, but kvm_vcpu_kick() in __apic_accept_irq
81033e4c686SGleb Natapov 	 * will cause vmexit immediately and the value will be recalculated
81133e4c686SGleb Natapov 	 * on the next vmentry.
81233e4c686SGleb Natapov 	 */
813f8543d6aSPaolo Bonzini 	return apic_find_highest_irr(vcpu->arch.apic);
814edf88417SAvi Kivity }
81576dfafd5SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_lapic_find_highest_irr);
816edf88417SAvi Kivity 
8176da7e3f6SGleb Natapov static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
818b4f2225cSYang Zhang 			     int vector, int level, int trig_mode,
8199e4aabe2SJoerg Roedel 			     struct dest_map *dest_map);
8206da7e3f6SGleb Natapov 
kvm_apic_set_irq(struct kvm_vcpu * vcpu,struct kvm_lapic_irq * irq,struct dest_map * dest_map)821b4f2225cSYang Zhang int kvm_apic_set_irq(struct kvm_vcpu *vcpu, struct kvm_lapic_irq *irq,
8229e4aabe2SJoerg Roedel 		     struct dest_map *dest_map)
823edf88417SAvi Kivity {
824edf88417SAvi Kivity 	struct kvm_lapic *apic = vcpu->arch.apic;
825edf88417SAvi Kivity 
82658c2dde1SGleb Natapov 	return __apic_accept_irq(apic, irq->delivery_mode, irq->vector,
827b4f2225cSYang Zhang 			irq->level, irq->trig_mode, dest_map);
828edf88417SAvi Kivity }
829edf88417SAvi Kivity 
__pv_send_ipi(unsigned long * ipi_bitmap,struct kvm_apic_map * map,struct kvm_lapic_irq * irq,u32 min)8301a686237SMiaohe Lin static int __pv_send_ipi(unsigned long *ipi_bitmap, struct kvm_apic_map *map,
8311a686237SMiaohe Lin 			 struct kvm_lapic_irq *irq, u32 min)
8321a686237SMiaohe Lin {
8331a686237SMiaohe Lin 	int i, count = 0;
8341a686237SMiaohe Lin 	struct kvm_vcpu *vcpu;
8351a686237SMiaohe Lin 
8361a686237SMiaohe Lin 	if (min > map->max_apic_id)
8371a686237SMiaohe Lin 		return 0;
8381a686237SMiaohe Lin 
8391a686237SMiaohe Lin 	for_each_set_bit(i, ipi_bitmap,
8401a686237SMiaohe Lin 		min((u32)BITS_PER_LONG, (map->max_apic_id - min + 1))) {
8411a686237SMiaohe Lin 		if (map->phys_map[min + i]) {
8421a686237SMiaohe Lin 			vcpu = map->phys_map[min + i]->vcpu;
8431a686237SMiaohe Lin 			count += kvm_apic_set_irq(vcpu, irq, NULL);
8441a686237SMiaohe Lin 		}
8451a686237SMiaohe Lin 	}
8461a686237SMiaohe Lin 
8471a686237SMiaohe Lin 	return count;
8481a686237SMiaohe Lin }
8491a686237SMiaohe 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)8504180bf1bSWanpeng Li int kvm_pv_send_ipi(struct kvm *kvm, unsigned long ipi_bitmap_low,
851bdf7ffc8SWanpeng Li 		    unsigned long ipi_bitmap_high, u32 min,
8524180bf1bSWanpeng Li 		    unsigned long icr, int op_64_bit)
8534180bf1bSWanpeng Li {
8544180bf1bSWanpeng Li 	struct kvm_apic_map *map;
8554180bf1bSWanpeng Li 	struct kvm_lapic_irq irq = {0};
8564180bf1bSWanpeng Li 	int cluster_size = op_64_bit ? 64 : 32;
8571a686237SMiaohe Lin 	int count;
8581a686237SMiaohe Lin 
8591a686237SMiaohe Lin 	if (icr & (APIC_DEST_MASK | APIC_SHORT_MASK))
8601a686237SMiaohe Lin 		return -KVM_EINVAL;
8614180bf1bSWanpeng Li 
8624180bf1bSWanpeng Li 	irq.vector = icr & APIC_VECTOR_MASK;
8634180bf1bSWanpeng Li 	irq.delivery_mode = icr & APIC_MODE_MASK;
8644180bf1bSWanpeng Li 	irq.level = (icr & APIC_INT_ASSERT) != 0;
8654180bf1bSWanpeng Li 	irq.trig_mode = icr & APIC_INT_LEVELTRIG;
8664180bf1bSWanpeng Li 
8674180bf1bSWanpeng Li 	rcu_read_lock();
8684180bf1bSWanpeng Li 	map = rcu_dereference(kvm->arch.apic_map);
8694180bf1bSWanpeng Li 
87038ab012fSWanpeng Li 	count = -EOPNOTSUPP;
8711a686237SMiaohe Lin 	if (likely(map)) {
8721a686237SMiaohe Lin 		count = __pv_send_ipi(&ipi_bitmap_low, map, &irq, min);
8734180bf1bSWanpeng Li 		min += cluster_size;
8741a686237SMiaohe Lin 		count += __pv_send_ipi(&ipi_bitmap_high, map, &irq, min);
875bdf7ffc8SWanpeng Li 	}
8764180bf1bSWanpeng Li 
8774180bf1bSWanpeng Li 	rcu_read_unlock();
8784180bf1bSWanpeng Li 	return count;
8794180bf1bSWanpeng Li }
8804180bf1bSWanpeng Li 
pv_eoi_put_user(struct kvm_vcpu * vcpu,u8 val)881ae7a2a3fSMichael S. Tsirkin static int pv_eoi_put_user(struct kvm_vcpu *vcpu, u8 val)
882ae7a2a3fSMichael S. Tsirkin {
8834e335d9eSPaolo Bonzini 
8844e335d9eSPaolo Bonzini 	return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, &val,
885ae7a2a3fSMichael S. Tsirkin 				      sizeof(val));
886ae7a2a3fSMichael S. Tsirkin }
887ae7a2a3fSMichael S. Tsirkin 
pv_eoi_get_user(struct kvm_vcpu * vcpu,u8 * val)888ae7a2a3fSMichael S. Tsirkin static int pv_eoi_get_user(struct kvm_vcpu *vcpu, u8 *val)
889ae7a2a3fSMichael S. Tsirkin {
8904e335d9eSPaolo Bonzini 
8914e335d9eSPaolo Bonzini 	return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, val,
892ae7a2a3fSMichael S. Tsirkin 				      sizeof(*val));
893ae7a2a3fSMichael S. Tsirkin }
894ae7a2a3fSMichael S. Tsirkin 
pv_eoi_enabled(struct kvm_vcpu * vcpu)895ae7a2a3fSMichael S. Tsirkin static inline bool pv_eoi_enabled(struct kvm_vcpu *vcpu)
896ae7a2a3fSMichael S. Tsirkin {
897ae7a2a3fSMichael S. Tsirkin 	return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
898ae7a2a3fSMichael S. Tsirkin }
899ae7a2a3fSMichael S. Tsirkin 
pv_eoi_set_pending(struct kvm_vcpu * vcpu)900ae7a2a3fSMichael S. Tsirkin static void pv_eoi_set_pending(struct kvm_vcpu *vcpu)
901ae7a2a3fSMichael S. Tsirkin {
902ce5977b1SLi RongQing 	if (pv_eoi_put_user(vcpu, KVM_PV_EOI_ENABLED) < 0)
903ae7a2a3fSMichael S. Tsirkin 		return;
904ce5977b1SLi RongQing 
905ae7a2a3fSMichael S. Tsirkin 	__set_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
906ae7a2a3fSMichael S. Tsirkin }
907ae7a2a3fSMichael S. Tsirkin 
pv_eoi_test_and_clr_pending(struct kvm_vcpu * vcpu)90851b1209cSLi RongQing static bool pv_eoi_test_and_clr_pending(struct kvm_vcpu *vcpu)
909ae7a2a3fSMichael S. Tsirkin {
91051b1209cSLi RongQing 	u8 val;
911ce5977b1SLi RongQing 
91251b1209cSLi RongQing 	if (pv_eoi_get_user(vcpu, &val) < 0)
91351b1209cSLi RongQing 		return false;
91451b1209cSLi RongQing 
91551b1209cSLi RongQing 	val &= KVM_PV_EOI_ENABLED;
91651b1209cSLi RongQing 
91751b1209cSLi RongQing 	if (val && pv_eoi_put_user(vcpu, KVM_PV_EOI_DISABLED) < 0)
91851b1209cSLi RongQing 		return false;
91951b1209cSLi RongQing 
92051b1209cSLi RongQing 	/*
92151b1209cSLi RongQing 	 * Clear pending bit in any case: it will be set again on vmentry.
92251b1209cSLi RongQing 	 * While this might not be ideal from performance point of view,
92351b1209cSLi RongQing 	 * this makes sure pv eoi is only enabled when we know it's safe.
92451b1209cSLi RongQing 	 */
925ae7a2a3fSMichael S. Tsirkin 	__clear_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
92651b1209cSLi RongQing 
92751b1209cSLi RongQing 	return val;
928ae7a2a3fSMichael S. Tsirkin }
929ae7a2a3fSMichael S. Tsirkin 
apic_has_interrupt_for_ppr(struct kvm_lapic * apic,u32 ppr)930b3c045d3SPaolo Bonzini static int apic_has_interrupt_for_ppr(struct kvm_lapic *apic, u32 ppr)
931b3c045d3SPaolo Bonzini {
9323d92789fSPaolo Bonzini 	int highest_irr;
93337c4dbf3SPaolo Bonzini 	if (kvm_x86_ops.sync_pir_to_irr)
934b3646477SJason Baron 		highest_irr = static_call(kvm_x86_sync_pir_to_irr)(apic->vcpu);
93576dfafd5SPaolo Bonzini 	else
9363d92789fSPaolo Bonzini 		highest_irr = apic_find_highest_irr(apic);
937b3c045d3SPaolo Bonzini 	if (highest_irr == -1 || (highest_irr & 0xF0) <= ppr)
938b3c045d3SPaolo Bonzini 		return -1;
939b3c045d3SPaolo Bonzini 	return highest_irr;
940b3c045d3SPaolo Bonzini }
941b3c045d3SPaolo Bonzini 
__apic_update_ppr(struct kvm_lapic * apic,u32 * new_ppr)942b3c045d3SPaolo Bonzini static bool __apic_update_ppr(struct kvm_lapic *apic, u32 *new_ppr)
943edf88417SAvi Kivity {
9443842d135SAvi Kivity 	u32 tpr, isrv, ppr, old_ppr;
945edf88417SAvi Kivity 	int isr;
946edf88417SAvi Kivity 
947dfb95954SSuravee Suthikulpanit 	old_ppr = kvm_lapic_get_reg(apic, APIC_PROCPRI);
948dfb95954SSuravee Suthikulpanit 	tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI);
949edf88417SAvi Kivity 	isr = apic_find_highest_isr(apic);
950edf88417SAvi Kivity 	isrv = (isr != -1) ? isr : 0;
951edf88417SAvi Kivity 
952edf88417SAvi Kivity 	if ((tpr & 0xf0) >= (isrv & 0xf0))
953edf88417SAvi Kivity 		ppr = tpr & 0xff;
954edf88417SAvi Kivity 	else
955edf88417SAvi Kivity 		ppr = isrv & 0xf0;
956edf88417SAvi Kivity 
957b3c045d3SPaolo Bonzini 	*new_ppr = ppr;
958b3c045d3SPaolo Bonzini 	if (old_ppr != ppr)
9591e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, APIC_PROCPRI, ppr);
960b3c045d3SPaolo Bonzini 
961b3c045d3SPaolo Bonzini 	return ppr < old_ppr;
9623842d135SAvi Kivity }
963b3c045d3SPaolo Bonzini 
apic_update_ppr(struct kvm_lapic * apic)964b3c045d3SPaolo Bonzini static void apic_update_ppr(struct kvm_lapic *apic)
965b3c045d3SPaolo Bonzini {
966b3c045d3SPaolo Bonzini 	u32 ppr;
967b3c045d3SPaolo Bonzini 
96826fbbee5SPaolo Bonzini 	if (__apic_update_ppr(apic, &ppr) &&
96926fbbee5SPaolo Bonzini 	    apic_has_interrupt_for_ppr(apic, ppr) != -1)
970b3c045d3SPaolo Bonzini 		kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
971edf88417SAvi Kivity }
972edf88417SAvi Kivity 
kvm_apic_update_ppr(struct kvm_vcpu * vcpu)973eb90f341SPaolo Bonzini void kvm_apic_update_ppr(struct kvm_vcpu *vcpu)
974eb90f341SPaolo Bonzini {
975eb90f341SPaolo Bonzini 	apic_update_ppr(vcpu->arch.apic);
976eb90f341SPaolo Bonzini }
977eb90f341SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_apic_update_ppr);
978eb90f341SPaolo Bonzini 
apic_set_tpr(struct kvm_lapic * apic,u32 tpr)979edf88417SAvi Kivity static void apic_set_tpr(struct kvm_lapic *apic, u32 tpr)
980edf88417SAvi Kivity {
9811e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_TASKPRI, tpr);
982edf88417SAvi Kivity 	apic_update_ppr(apic);
983edf88417SAvi Kivity }
984edf88417SAvi Kivity 
kvm_apic_broadcast(struct kvm_lapic * apic,u32 mda)98503d2249eSRadim Krčmář static bool kvm_apic_broadcast(struct kvm_lapic *apic, u32 mda)
986edf88417SAvi Kivity {
987b4535b58SRadim Krčmář 	return mda == (apic_x2apic_mode(apic) ?
988b4535b58SRadim Krčmář 			X2APIC_BROADCAST : APIC_BROADCAST);
989edf88417SAvi Kivity }
990edf88417SAvi Kivity 
kvm_apic_match_physical_addr(struct kvm_lapic * apic,u32 mda)99103d2249eSRadim Krčmář static bool kvm_apic_match_physical_addr(struct kvm_lapic *apic, u32 mda)
992394457a9SNadav Amit {
99303d2249eSRadim Krčmář 	if (kvm_apic_broadcast(apic, mda))
99403d2249eSRadim Krčmář 		return true;
99503d2249eSRadim Krčmář 
9965bd5db38SRadim Krčmář 	/*
9978031d87aSSean Christopherson 	 * Hotplug hack: Accept interrupts for vCPUs in xAPIC mode as if they
9988031d87aSSean Christopherson 	 * were in x2APIC mode if the target APIC ID can't be encoded as an
9998031d87aSSean Christopherson 	 * xAPIC ID.  This allows unique addressing of hotplugged vCPUs (which
10008031d87aSSean Christopherson 	 * start in xAPIC mode) with an APIC ID that is unaddressable in xAPIC
10018031d87aSSean Christopherson 	 * mode.  Match the x2APIC ID if and only if the target APIC ID can't
10028031d87aSSean Christopherson 	 * be encoded in xAPIC to avoid spurious matches against a vCPU that
10038031d87aSSean Christopherson 	 * changed its (addressable) xAPIC ID (which is writable).
10045bd5db38SRadim Krčmář 	 */
10058031d87aSSean Christopherson 	if (apic_x2apic_mode(apic) || mda > 0xff)
10068031d87aSSean Christopherson 		return mda == kvm_x2apic_id(apic);
10075bd5db38SRadim Krčmář 
1008b4535b58SRadim Krčmář 	return mda == kvm_xapic_id(apic);
1009394457a9SNadav Amit }
1010394457a9SNadav Amit 
kvm_apic_match_logical_addr(struct kvm_lapic * apic,u32 mda)101152c233a4SRadim Krčmář static bool kvm_apic_match_logical_addr(struct kvm_lapic *apic, u32 mda)
1012edf88417SAvi Kivity {
10130105d1a5SGleb Natapov 	u32 logical_id;
10140105d1a5SGleb Natapov 
1015394457a9SNadav Amit 	if (kvm_apic_broadcast(apic, mda))
10169368b567SRadim Krčmář 		return true;
1017394457a9SNadav Amit 
1018dfb95954SSuravee Suthikulpanit 	logical_id = kvm_lapic_get_reg(apic, APIC_LDR);
1019edf88417SAvi Kivity 
10209368b567SRadim Krčmář 	if (apic_x2apic_mode(apic))
10218a395363SRadim Krčmář 		return ((logical_id >> 16) == (mda >> 16))
10228a395363SRadim Krčmář 		       && (logical_id & mda & 0xffff) != 0;
10239368b567SRadim Krčmář 
10249368b567SRadim Krčmář 	logical_id = GET_APIC_LOGICAL_ID(logical_id);
1025edf88417SAvi Kivity 
1026dfb95954SSuravee Suthikulpanit 	switch (kvm_lapic_get_reg(apic, APIC_DFR)) {
1027edf88417SAvi Kivity 	case APIC_DFR_FLAT:
10289368b567SRadim Krčmář 		return (logical_id & mda) != 0;
1029edf88417SAvi Kivity 	case APIC_DFR_CLUSTER:
10309368b567SRadim Krčmář 		return ((logical_id >> 4) == (mda >> 4))
10319368b567SRadim Krčmář 		       && (logical_id & mda & 0xf) != 0;
1032edf88417SAvi Kivity 	default:
10339368b567SRadim Krčmář 		return false;
1034edf88417SAvi Kivity 	}
1035edf88417SAvi Kivity }
1036edf88417SAvi Kivity 
1037c519265fSRadim Krčmář /* The KVM local APIC implementation has two quirks:
1038c519265fSRadim Krčmář  *
1039b4535b58SRadim Krčmář  *  - Real hardware delivers interrupts destined to x2APIC ID > 0xff to LAPICs
1040b4535b58SRadim Krčmář  *    in xAPIC mode if the "destination & 0xff" matches its xAPIC ID.
1041b4535b58SRadim Krčmář  *    KVM doesn't do that aliasing.
1042c519265fSRadim Krčmář  *
1043c519265fSRadim Krčmář  *  - in-kernel IOAPIC messages have to be delivered directly to
1044c519265fSRadim Krčmář  *    x2APIC, because the kernel does not support interrupt remapping.
1045c519265fSRadim Krčmář  *    In order to support broadcast without interrupt remapping, x2APIC
1046c519265fSRadim Krčmář  *    rewrites the destination of non-IPI messages from APIC_BROADCAST
1047c519265fSRadim Krčmář  *    to X2APIC_BROADCAST.
1048c519265fSRadim Krčmář  *
1049c519265fSRadim Krčmář  * The broadcast quirk can be disabled with KVM_CAP_X2APIC_API.  This is
1050c519265fSRadim Krčmář  * important when userspace wants to use x2APIC-format MSIs, because
1051c519265fSRadim Krčmář  * APIC_BROADCAST (0xff) is a legal route for "cluster 0, CPUs 0-7".
105203d2249eSRadim Krčmář  */
kvm_apic_mda(struct kvm_vcpu * vcpu,unsigned int dest_id,struct kvm_lapic * source,struct kvm_lapic * target)1053c519265fSRadim Krčmář static u32 kvm_apic_mda(struct kvm_vcpu *vcpu, unsigned int dest_id,
1054c519265fSRadim Krčmář 		struct kvm_lapic *source, struct kvm_lapic *target)
105503d2249eSRadim Krčmář {
105603d2249eSRadim Krčmář 	bool ipi = source != NULL;
105703d2249eSRadim Krčmář 
1058c519265fSRadim Krčmář 	if (!vcpu->kvm->arch.x2apic_broadcast_quirk_disabled &&
1059b4535b58SRadim Krčmář 	    !ipi && dest_id == APIC_BROADCAST && apic_x2apic_mode(target))
106003d2249eSRadim Krčmář 		return X2APIC_BROADCAST;
106103d2249eSRadim Krčmář 
1062b4535b58SRadim Krčmář 	return dest_id;
106303d2249eSRadim Krčmář }
106403d2249eSRadim Krčmář 
kvm_apic_match_dest(struct kvm_vcpu * vcpu,struct kvm_lapic * source,int shorthand,unsigned int dest,int dest_mode)106552c233a4SRadim Krčmář bool kvm_apic_match_dest(struct kvm_vcpu *vcpu, struct kvm_lapic *source,
10665c69d5c1SPeter Xu 			   int shorthand, unsigned int dest, int dest_mode)
1067edf88417SAvi Kivity {
1068edf88417SAvi Kivity 	struct kvm_lapic *target = vcpu->arch.apic;
1069c519265fSRadim Krčmář 	u32 mda = kvm_apic_mda(vcpu, dest, source, target);
1070edf88417SAvi Kivity 
1071bd371396SZachary Amsden 	ASSERT(target);
10725c69d5c1SPeter Xu 	switch (shorthand) {
1073edf88417SAvi Kivity 	case APIC_DEST_NOSHORT:
10743697f302SRadim Krčmář 		if (dest_mode == APIC_DEST_PHYSICAL)
107503d2249eSRadim Krčmář 			return kvm_apic_match_physical_addr(target, mda);
1076343f94feSGleb Natapov 		else
107703d2249eSRadim Krčmář 			return kvm_apic_match_logical_addr(target, mda);
1078edf88417SAvi Kivity 	case APIC_DEST_SELF:
10799368b567SRadim Krčmář 		return target == source;
1080edf88417SAvi Kivity 	case APIC_DEST_ALLINC:
10819368b567SRadim Krčmář 		return true;
1082edf88417SAvi Kivity 	case APIC_DEST_ALLBUT:
10839368b567SRadim Krčmář 		return target != source;
1084edf88417SAvi Kivity 	default:
10859368b567SRadim Krčmář 		return false;
1086edf88417SAvi Kivity 	}
1087edf88417SAvi Kivity }
10881e6e2755SSuravee Suthikulpanit EXPORT_SYMBOL_GPL(kvm_apic_match_dest);
1089edf88417SAvi Kivity 
kvm_vector_to_index(u32 vector,u32 dest_vcpus,const unsigned long * bitmap,u32 bitmap_size)109052004014SFeng Wu int kvm_vector_to_index(u32 vector, u32 dest_vcpus,
109152004014SFeng Wu 		       const unsigned long *bitmap, u32 bitmap_size)
109252004014SFeng Wu {
109352004014SFeng Wu 	u32 mod;
109452004014SFeng Wu 	int i, idx = -1;
109552004014SFeng Wu 
109652004014SFeng Wu 	mod = vector % dest_vcpus;
109752004014SFeng Wu 
109852004014SFeng Wu 	for (i = 0; i <= mod; i++) {
109952004014SFeng Wu 		idx = find_next_bit(bitmap, bitmap_size, idx + 1);
110052004014SFeng Wu 		BUG_ON(idx == bitmap_size);
110152004014SFeng Wu 	}
110252004014SFeng Wu 
110352004014SFeng Wu 	return idx;
110452004014SFeng Wu }
110552004014SFeng Wu 
kvm_apic_disabled_lapic_found(struct kvm * kvm)11064efd805fSRadim Krčmář static void kvm_apic_disabled_lapic_found(struct kvm *kvm)
11074efd805fSRadim Krčmář {
11084efd805fSRadim Krčmář 	if (!kvm->arch.disabled_lapic_found) {
11094efd805fSRadim Krčmář 		kvm->arch.disabled_lapic_found = true;
11108d20bd63SSean Christopherson 		pr_info("Disabled LAPIC found during irq injection\n");
11114efd805fSRadim Krčmář 	}
11124efd805fSRadim Krčmář }
11134efd805fSRadim Krčmář 
kvm_apic_is_broadcast_dest(struct kvm * kvm,struct kvm_lapic ** src,struct kvm_lapic_irq * irq,struct kvm_apic_map * map)1114c519265fSRadim Krčmář static bool kvm_apic_is_broadcast_dest(struct kvm *kvm, struct kvm_lapic **src,
1115c519265fSRadim Krčmář 		struct kvm_lapic_irq *irq, struct kvm_apic_map *map)
1116c519265fSRadim Krčmář {
1117c519265fSRadim Krčmář 	if (kvm->arch.x2apic_broadcast_quirk_disabled) {
1118c519265fSRadim Krčmář 		if ((irq->dest_id == APIC_BROADCAST &&
111935366901SSean Christopherson 		     map->logical_mode != KVM_APIC_MODE_X2APIC))
1120c519265fSRadim Krčmář 			return true;
1121c519265fSRadim Krčmář 		if (irq->dest_id == X2APIC_BROADCAST)
1122c519265fSRadim Krčmář 			return true;
1123c519265fSRadim Krčmář 	} else {
1124c519265fSRadim Krčmář 		bool x2apic_ipi = src && *src && apic_x2apic_mode(*src);
1125c519265fSRadim Krčmář 		if (irq->dest_id == (x2apic_ipi ?
1126c519265fSRadim Krčmář 		                     X2APIC_BROADCAST : APIC_BROADCAST))
1127c519265fSRadim Krčmář 			return true;
1128c519265fSRadim Krčmář 	}
1129c519265fSRadim Krčmář 
1130c519265fSRadim Krčmář 	return false;
1131c519265fSRadim Krčmář }
1132c519265fSRadim Krčmář 
113364aa47bfSRadim Krčmář /* Return true if the interrupt can be handled by using *bitmap as index mask
113464aa47bfSRadim Krčmář  * for valid destinations in *dst array.
113564aa47bfSRadim Krčmář  * Return false if kvm_apic_map_get_dest_lapic did nothing useful.
113664aa47bfSRadim Krčmář  * Note: we may have zero kvm_lapic destinations when we return true, which
113764aa47bfSRadim Krčmář  * means that the interrupt should be dropped.  In this case, *bitmap would be
113864aa47bfSRadim Krčmář  * zero and *dst undefined.
113964aa47bfSRadim 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)114064aa47bfSRadim Krčmář static inline bool kvm_apic_map_get_dest_lapic(struct kvm *kvm,
114164aa47bfSRadim Krčmář 		struct kvm_lapic **src, struct kvm_lapic_irq *irq,
114264aa47bfSRadim Krčmář 		struct kvm_apic_map *map, struct kvm_lapic ***dst,
114364aa47bfSRadim Krčmář 		unsigned long *bitmap)
114464aa47bfSRadim Krčmář {
114564aa47bfSRadim Krčmář 	int i, lowest;
114664aa47bfSRadim Krčmář 
114764aa47bfSRadim Krčmář 	if (irq->shorthand == APIC_DEST_SELF && src) {
114864aa47bfSRadim Krčmář 		*dst = src;
114964aa47bfSRadim Krčmář 		*bitmap = 1;
115064aa47bfSRadim Krčmář 		return true;
115164aa47bfSRadim Krčmář 	} else if (irq->shorthand)
115264aa47bfSRadim Krčmář 		return false;
115364aa47bfSRadim Krčmář 
1154c519265fSRadim Krčmář 	if (!map || kvm_apic_is_broadcast_dest(kvm, src, irq, map))
115564aa47bfSRadim Krčmář 		return false;
115664aa47bfSRadim Krčmář 
115764aa47bfSRadim Krčmář 	if (irq->dest_mode == APIC_DEST_PHYSICAL) {
11580ca52e7bSRadim Krčmář 		if (irq->dest_id > map->max_apic_id) {
115964aa47bfSRadim Krčmář 			*bitmap = 0;
116064aa47bfSRadim Krčmář 		} else {
11611d487e9bSPaolo Bonzini 			u32 dest_id = array_index_nospec(irq->dest_id, map->max_apic_id + 1);
11621d487e9bSPaolo Bonzini 			*dst = &map->phys_map[dest_id];
116364aa47bfSRadim Krčmář 			*bitmap = 1;
116464aa47bfSRadim Krčmář 		}
116564aa47bfSRadim Krčmář 		return true;
116664aa47bfSRadim Krčmář 	}
116764aa47bfSRadim Krčmář 
116864aa47bfSRadim Krčmář 	*bitmap = 0;
1169e45115b6SRadim Krčmář 	if (!kvm_apic_map_get_logical_dest(map, irq->dest_id, dst,
1170e45115b6SRadim Krčmář 				(u16 *)bitmap))
1171e45115b6SRadim Krčmář 		return false;
117264aa47bfSRadim Krčmář 
117364aa47bfSRadim Krčmář 	if (!kvm_lowest_prio_delivery(irq))
117464aa47bfSRadim Krčmář 		return true;
117564aa47bfSRadim Krčmář 
117664aa47bfSRadim Krčmář 	if (!kvm_vector_hashing_enabled()) {
117764aa47bfSRadim Krčmář 		lowest = -1;
117864aa47bfSRadim Krčmář 		for_each_set_bit(i, bitmap, 16) {
117964aa47bfSRadim Krčmář 			if (!(*dst)[i])
118064aa47bfSRadim Krčmář 				continue;
118164aa47bfSRadim Krčmář 			if (lowest < 0)
118264aa47bfSRadim Krčmář 				lowest = i;
118364aa47bfSRadim Krčmář 			else if (kvm_apic_compare_prio((*dst)[i]->vcpu,
118464aa47bfSRadim Krčmář 						(*dst)[lowest]->vcpu) < 0)
118564aa47bfSRadim Krčmář 				lowest = i;
118664aa47bfSRadim Krčmář 		}
118764aa47bfSRadim Krčmář 	} else {
118864aa47bfSRadim Krčmář 		if (!*bitmap)
118964aa47bfSRadim Krčmář 			return true;
119064aa47bfSRadim Krčmář 
119164aa47bfSRadim Krčmář 		lowest = kvm_vector_to_index(irq->vector, hweight16(*bitmap),
119264aa47bfSRadim Krčmář 				bitmap, 16);
119364aa47bfSRadim Krčmář 
119464aa47bfSRadim Krčmář 		if (!(*dst)[lowest]) {
119564aa47bfSRadim Krčmář 			kvm_apic_disabled_lapic_found(kvm);
119664aa47bfSRadim Krčmář 			*bitmap = 0;
119764aa47bfSRadim Krčmář 			return true;
119864aa47bfSRadim Krčmář 		}
119964aa47bfSRadim Krčmář 	}
120064aa47bfSRadim Krčmář 
120164aa47bfSRadim Krčmář 	*bitmap = (lowest >= 0) ? 1 << lowest : 0;
120264aa47bfSRadim Krčmář 
120364aa47bfSRadim Krčmář 	return true;
120464aa47bfSRadim Krčmář }
120564aa47bfSRadim 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)12061e08ec4aSGleb Natapov bool kvm_irq_delivery_to_apic_fast(struct kvm *kvm, struct kvm_lapic *src,
12079e4aabe2SJoerg Roedel 		struct kvm_lapic_irq *irq, int *r, struct dest_map *dest_map)
12081e08ec4aSGleb Natapov {
12091e08ec4aSGleb Natapov 	struct kvm_apic_map *map;
121064aa47bfSRadim Krčmář 	unsigned long bitmap;
121164aa47bfSRadim Krčmář 	struct kvm_lapic **dst = NULL;
12121e08ec4aSGleb Natapov 	int i;
121364aa47bfSRadim Krčmář 	bool ret;
12141e08ec4aSGleb Natapov 
12151e08ec4aSGleb Natapov 	*r = -1;
12161e08ec4aSGleb Natapov 
12171e08ec4aSGleb Natapov 	if (irq->shorthand == APIC_DEST_SELF) {
121800b5f371SVitaly Kuznetsov 		if (KVM_BUG_ON(!src, kvm)) {
121900b5f371SVitaly Kuznetsov 			*r = 0;
122000b5f371SVitaly Kuznetsov 			return true;
122100b5f371SVitaly Kuznetsov 		}
1222b4f2225cSYang Zhang 		*r = kvm_apic_set_irq(src->vcpu, irq, dest_map);
12231e08ec4aSGleb Natapov 		return true;
12241e08ec4aSGleb Natapov 	}
12251e08ec4aSGleb Natapov 
12261e08ec4aSGleb Natapov 	rcu_read_lock();
12271e08ec4aSGleb Natapov 	map = rcu_dereference(kvm->arch.apic_map);
12281e08ec4aSGleb Natapov 
122964aa47bfSRadim Krčmář 	ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dst, &bitmap);
12300624fca9SPaolo Bonzini 	if (ret) {
12310624fca9SPaolo Bonzini 		*r = 0;
12321e08ec4aSGleb Natapov 		for_each_set_bit(i, &bitmap, 16) {
12331e08ec4aSGleb Natapov 			if (!dst[i])
12341e08ec4aSGleb Natapov 				continue;
1235b4f2225cSYang Zhang 			*r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map);
12361e08ec4aSGleb Natapov 		}
12370624fca9SPaolo Bonzini 	}
123864aa47bfSRadim Krčmář 
12391e08ec4aSGleb Natapov 	rcu_read_unlock();
12401e08ec4aSGleb Natapov 	return ret;
12411e08ec4aSGleb Natapov }
12421e08ec4aSGleb Natapov 
12436228a0daSFeng Wu /*
124400116795SMiaohe Lin  * This routine tries to handle interrupts in posted mode, here is how
12456228a0daSFeng Wu  * it deals with different cases:
12466228a0daSFeng Wu  * - For single-destination interrupts, handle it in posted mode
12476228a0daSFeng Wu  * - Else if vector hashing is enabled and it is a lowest-priority
12486228a0daSFeng Wu  *   interrupt, handle it in posted mode and use the following mechanism
124967b0ae43SMiaohe Lin  *   to find the destination vCPU.
12506228a0daSFeng Wu  *	1. For lowest-priority interrupts, store all the possible
12516228a0daSFeng Wu  *	   destination vCPUs in an array.
12526228a0daSFeng Wu  *	2. Use "guest vector % max number of destination vCPUs" to find
12536228a0daSFeng Wu  *	   the right destination vCPU in the array for the lowest-priority
12546228a0daSFeng Wu  *	   interrupt.
12556228a0daSFeng Wu  * - Otherwise, use remapped mode to inject the interrupt.
12566228a0daSFeng Wu  */
kvm_intr_is_single_vcpu_fast(struct kvm * kvm,struct kvm_lapic_irq * irq,struct kvm_vcpu ** dest_vcpu)12578feb4a04SFeng Wu bool kvm_intr_is_single_vcpu_fast(struct kvm *kvm, struct kvm_lapic_irq *irq,
12588feb4a04SFeng Wu 			struct kvm_vcpu **dest_vcpu)
12598feb4a04SFeng Wu {
12608feb4a04SFeng Wu 	struct kvm_apic_map *map;
126164aa47bfSRadim Krčmář 	unsigned long bitmap;
126264aa47bfSRadim Krčmář 	struct kvm_lapic **dst = NULL;
12638feb4a04SFeng Wu 	bool ret = false;
12648feb4a04SFeng Wu 
12658feb4a04SFeng Wu 	if (irq->shorthand)
12668feb4a04SFeng Wu 		return false;
12678feb4a04SFeng Wu 
12688feb4a04SFeng Wu 	rcu_read_lock();
12698feb4a04SFeng Wu 	map = rcu_dereference(kvm->arch.apic_map);
12708feb4a04SFeng Wu 
127164aa47bfSRadim Krčmář 	if (kvm_apic_map_get_dest_lapic(kvm, NULL, irq, map, &dst, &bitmap) &&
127264aa47bfSRadim Krčmář 			hweight16(bitmap) == 1) {
127364aa47bfSRadim Krčmář 		unsigned long i = find_first_bit(&bitmap, 16);
12748feb4a04SFeng Wu 
127564aa47bfSRadim Krčmář 		if (dst[i]) {
127664aa47bfSRadim Krčmář 			*dest_vcpu = dst[i]->vcpu;
12778feb4a04SFeng Wu 			ret = true;
127864aa47bfSRadim Krčmář 		}
127964aa47bfSRadim Krčmář 	}
128064aa47bfSRadim Krčmář 
12818feb4a04SFeng Wu 	rcu_read_unlock();
12828feb4a04SFeng Wu 	return ret;
12838feb4a04SFeng Wu }
12848feb4a04SFeng Wu 
1285edf88417SAvi Kivity /*
1286edf88417SAvi Kivity  * Add a pending IRQ into lapic.
1287edf88417SAvi Kivity  * Return 1 if successfully added and 0 if discarded.
1288edf88417SAvi Kivity  */
__apic_accept_irq(struct kvm_lapic * apic,int delivery_mode,int vector,int level,int trig_mode,struct dest_map * dest_map)1289edf88417SAvi Kivity static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
1290b4f2225cSYang Zhang 			     int vector, int level, int trig_mode,
12919e4aabe2SJoerg Roedel 			     struct dest_map *dest_map)
1292edf88417SAvi Kivity {
12936da7e3f6SGleb Natapov 	int result = 0;
1294edf88417SAvi Kivity 	struct kvm_vcpu *vcpu = apic->vcpu;
1295edf88417SAvi Kivity 
1296a183b638SPaolo Bonzini 	trace_kvm_apic_accept_irq(vcpu->vcpu_id, delivery_mode,
1297a183b638SPaolo Bonzini 				  trig_mode, vector);
1298edf88417SAvi Kivity 	switch (delivery_mode) {
1299edf88417SAvi Kivity 	case APIC_DM_LOWEST:
1300e1035715SGleb Natapov 		vcpu->arch.apic_arb_prio++;
1301df561f66SGustavo A. R. Silva 		fallthrough;
1302e1035715SGleb Natapov 	case APIC_DM_FIXED:
1303bdaffe1dSPaolo Bonzini 		if (unlikely(trig_mode && !level))
1304bdaffe1dSPaolo Bonzini 			break;
1305bdaffe1dSPaolo Bonzini 
1306edf88417SAvi Kivity 		/* FIXME add logic for vcpu on reset */
1307edf88417SAvi Kivity 		if (unlikely(!apic_enabled(apic)))
1308edf88417SAvi Kivity 			break;
1309edf88417SAvi Kivity 
131011f5cc05SJan Kiszka 		result = 1;
131111f5cc05SJan Kiszka 
13129daa5007SJoerg Roedel 		if (dest_map) {
13139e4aabe2SJoerg Roedel 			__set_bit(vcpu->vcpu_id, dest_map->map);
13149daa5007SJoerg Roedel 			dest_map->vectors[vcpu->vcpu_id] = vector;
13159daa5007SJoerg Roedel 		}
1316a5d36f82SAvi Kivity 
1317bdaffe1dSPaolo Bonzini 		if (apic_test_vector(vector, apic->regs + APIC_TMR) != !!trig_mode) {
1318bdaffe1dSPaolo Bonzini 			if (trig_mode)
1319ee171d2fSWei Yang 				kvm_lapic_set_vector(vector,
1320ee171d2fSWei Yang 						     apic->regs + APIC_TMR);
1321bdaffe1dSPaolo Bonzini 			else
1322ee171d2fSWei Yang 				kvm_lapic_clear_vector(vector,
1323ee171d2fSWei Yang 						       apic->regs + APIC_TMR);
1324bdaffe1dSPaolo Bonzini 		}
1325bdaffe1dSPaolo Bonzini 
132657dfd7b5SSean Christopherson 		static_call(kvm_x86_deliver_interrupt)(apic, delivery_mode,
13278e819d75SMaxim Levitsky 						       trig_mode, vector);
1328edf88417SAvi Kivity 		break;
1329edf88417SAvi Kivity 
1330edf88417SAvi Kivity 	case APIC_DM_REMRD:
133124d2166bSRaghavendra K T 		result = 1;
133224d2166bSRaghavendra K T 		vcpu->arch.pv.pv_unhalted = 1;
133324d2166bSRaghavendra K T 		kvm_make_request(KVM_REQ_EVENT, vcpu);
133424d2166bSRaghavendra K T 		kvm_vcpu_kick(vcpu);
1335edf88417SAvi Kivity 		break;
1336edf88417SAvi Kivity 
1337edf88417SAvi Kivity 	case APIC_DM_SMI:
1338b0b42197SPaolo Bonzini 		if (!kvm_inject_smi(vcpu)) {
133964d60670SPaolo Bonzini 			kvm_vcpu_kick(vcpu);
1340b0b42197SPaolo Bonzini 			result = 1;
1341b0b42197SPaolo Bonzini 		}
1342edf88417SAvi Kivity 		break;
13433419ffc8SSheng Yang 
1344edf88417SAvi Kivity 	case APIC_DM_NMI:
13456da7e3f6SGleb Natapov 		result = 1;
13463419ffc8SSheng Yang 		kvm_inject_nmi(vcpu);
134726df99c6SJan Kiszka 		kvm_vcpu_kick(vcpu);
1348edf88417SAvi Kivity 		break;
1349edf88417SAvi Kivity 
1350edf88417SAvi Kivity 	case APIC_DM_INIT:
1351a52315e1SJulian Stecklina 		if (!trig_mode || level) {
13526da7e3f6SGleb Natapov 			result = 1;
135366450a21SJan Kiszka 			/* assumes that there are only KVM_APIC_INIT/SIPI */
135466450a21SJan Kiszka 			apic->pending_events = (1UL << KVM_APIC_INIT);
13553842d135SAvi Kivity 			kvm_make_request(KVM_REQ_EVENT, vcpu);
1356edf88417SAvi Kivity 			kvm_vcpu_kick(vcpu);
1357edf88417SAvi Kivity 		}
1358edf88417SAvi Kivity 		break;
1359edf88417SAvi Kivity 
1360edf88417SAvi Kivity 	case APIC_DM_STARTUP:
13616da7e3f6SGleb Natapov 		result = 1;
136266450a21SJan Kiszka 		apic->sipi_vector = vector;
136366450a21SJan Kiszka 		/* make sure sipi_vector is visible for the receiver */
136466450a21SJan Kiszka 		smp_wmb();
136566450a21SJan Kiszka 		set_bit(KVM_APIC_SIPI, &apic->pending_events);
13663842d135SAvi Kivity 		kvm_make_request(KVM_REQ_EVENT, vcpu);
1367d7690175SMarcelo Tosatti 		kvm_vcpu_kick(vcpu);
1368edf88417SAvi Kivity 		break;
1369edf88417SAvi Kivity 
137023930f95SJan Kiszka 	case APIC_DM_EXTINT:
137123930f95SJan Kiszka 		/*
137223930f95SJan Kiszka 		 * Should only be called by kvm_apic_local_deliver() with LVT0,
137323930f95SJan Kiszka 		 * before NMI watchdog was enabled. Already handled by
137423930f95SJan Kiszka 		 * kvm_apic_accept_pic_intr().
137523930f95SJan Kiszka 		 */
137623930f95SJan Kiszka 		break;
137723930f95SJan Kiszka 
1378edf88417SAvi Kivity 	default:
1379edf88417SAvi Kivity 		printk(KERN_ERR "TODO: unsupported delivery mode %x\n",
1380edf88417SAvi Kivity 		       delivery_mode);
1381edf88417SAvi Kivity 		break;
1382edf88417SAvi Kivity 	}
1383edf88417SAvi Kivity 	return result;
1384edf88417SAvi Kivity }
1385edf88417SAvi Kivity 
13867ee30bc1SNitesh Narayan Lal /*
13877ee30bc1SNitesh Narayan Lal  * This routine identifies the destination vcpus mask meant to receive the
13887ee30bc1SNitesh Narayan Lal  * IOAPIC interrupts. It either uses kvm_apic_map_get_dest_lapic() to find
13897ee30bc1SNitesh Narayan Lal  * out the destination vcpus array and set the bitmap or it traverses to
13907ee30bc1SNitesh Narayan Lal  * each available vcpu to identify the same.
13917ee30bc1SNitesh Narayan Lal  */
kvm_bitmap_or_dest_vcpus(struct kvm * kvm,struct kvm_lapic_irq * irq,unsigned long * vcpu_bitmap)13927ee30bc1SNitesh Narayan Lal void kvm_bitmap_or_dest_vcpus(struct kvm *kvm, struct kvm_lapic_irq *irq,
13937ee30bc1SNitesh Narayan Lal 			      unsigned long *vcpu_bitmap)
13947ee30bc1SNitesh Narayan Lal {
13957ee30bc1SNitesh Narayan Lal 	struct kvm_lapic **dest_vcpu = NULL;
13967ee30bc1SNitesh Narayan Lal 	struct kvm_lapic *src = NULL;
13977ee30bc1SNitesh Narayan Lal 	struct kvm_apic_map *map;
13987ee30bc1SNitesh Narayan Lal 	struct kvm_vcpu *vcpu;
139946808a4cSMarc Zyngier 	unsigned long bitmap, i;
140046808a4cSMarc Zyngier 	int vcpu_idx;
14017ee30bc1SNitesh Narayan Lal 	bool ret;
14027ee30bc1SNitesh Narayan Lal 
14037ee30bc1SNitesh Narayan Lal 	rcu_read_lock();
14047ee30bc1SNitesh Narayan Lal 	map = rcu_dereference(kvm->arch.apic_map);
14057ee30bc1SNitesh Narayan Lal 
14067ee30bc1SNitesh Narayan Lal 	ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dest_vcpu,
14077ee30bc1SNitesh Narayan Lal 					  &bitmap);
14087ee30bc1SNitesh Narayan Lal 	if (ret) {
14097ee30bc1SNitesh Narayan Lal 		for_each_set_bit(i, &bitmap, 16) {
14107ee30bc1SNitesh Narayan Lal 			if (!dest_vcpu[i])
14117ee30bc1SNitesh Narayan Lal 				continue;
14127ee30bc1SNitesh Narayan Lal 			vcpu_idx = dest_vcpu[i]->vcpu->vcpu_idx;
14137ee30bc1SNitesh Narayan Lal 			__set_bit(vcpu_idx, vcpu_bitmap);
14147ee30bc1SNitesh Narayan Lal 		}
14157ee30bc1SNitesh Narayan Lal 	} else {
14167ee30bc1SNitesh Narayan Lal 		kvm_for_each_vcpu(i, vcpu, kvm) {
14177ee30bc1SNitesh Narayan Lal 			if (!kvm_apic_present(vcpu))
14187ee30bc1SNitesh Narayan Lal 				continue;
14197ee30bc1SNitesh Narayan Lal 			if (!kvm_apic_match_dest(vcpu, NULL,
1420b4b29636SPeter Xu 						 irq->shorthand,
14217ee30bc1SNitesh Narayan Lal 						 irq->dest_id,
14227ee30bc1SNitesh Narayan Lal 						 irq->dest_mode))
14237ee30bc1SNitesh Narayan Lal 				continue;
14247ee30bc1SNitesh Narayan Lal 			__set_bit(i, vcpu_bitmap);
14257ee30bc1SNitesh Narayan Lal 		}
14267ee30bc1SNitesh Narayan Lal 	}
14277ee30bc1SNitesh Narayan Lal 	rcu_read_unlock();
14287ee30bc1SNitesh Narayan Lal }
14297ee30bc1SNitesh Narayan Lal 
kvm_apic_compare_prio(struct kvm_vcpu * vcpu1,struct kvm_vcpu * vcpu2)1430e1035715SGleb Natapov int kvm_apic_compare_prio(struct kvm_vcpu *vcpu1, struct kvm_vcpu *vcpu2)
1431edf88417SAvi Kivity {
1432e1035715SGleb Natapov 	return vcpu1->arch.apic_arb_prio - vcpu2->arch.apic_arb_prio;
1433edf88417SAvi Kivity }
1434edf88417SAvi Kivity 
kvm_ioapic_handles_vector(struct kvm_lapic * apic,int vector)14353bb345f3SPaolo Bonzini static bool kvm_ioapic_handles_vector(struct kvm_lapic *apic, int vector)
14363bb345f3SPaolo Bonzini {
14376308630bSAndrey Smetanin 	return test_bit(vector, apic->vcpu->arch.ioapic_handled_vectors);
14383bb345f3SPaolo Bonzini }
14393bb345f3SPaolo Bonzini 
kvm_ioapic_send_eoi(struct kvm_lapic * apic,int vector)1440c7c9c56cSYang Zhang static void kvm_ioapic_send_eoi(struct kvm_lapic *apic, int vector)
1441c7c9c56cSYang Zhang {
1442c7c9c56cSYang Zhang 	int trigger_mode;
14437543a635SSteve Rutherford 
14447543a635SSteve Rutherford 	/* Eoi the ioapic only if the ioapic doesn't own the vector. */
14457543a635SSteve Rutherford 	if (!kvm_ioapic_handles_vector(apic, vector))
14467543a635SSteve Rutherford 		return;
14477543a635SSteve Rutherford 
14487543a635SSteve Rutherford 	/* Request a KVM exit to inform the userspace IOAPIC. */
14497543a635SSteve Rutherford 	if (irqchip_split(apic->vcpu->kvm)) {
14507543a635SSteve Rutherford 		apic->vcpu->arch.pending_ioapic_eoi = vector;
14517543a635SSteve Rutherford 		kvm_make_request(KVM_REQ_IOAPIC_EOI_EXIT, apic->vcpu);
14527543a635SSteve Rutherford 		return;
14537543a635SSteve Rutherford 	}
14547543a635SSteve Rutherford 
1455c7c9c56cSYang Zhang 	if (apic_test_vector(vector, apic->regs + APIC_TMR))
1456c7c9c56cSYang Zhang 		trigger_mode = IOAPIC_LEVEL_TRIG;
1457c7c9c56cSYang Zhang 	else
1458c7c9c56cSYang Zhang 		trigger_mode = IOAPIC_EDGE_TRIG;
14593bb345f3SPaolo Bonzini 
14601fcc7890SYang Zhang 	kvm_ioapic_update_eoi(apic->vcpu, vector, trigger_mode);
1461c7c9c56cSYang Zhang }
1462c7c9c56cSYang Zhang 
apic_set_eoi(struct kvm_lapic * apic)1463ae7a2a3fSMichael S. Tsirkin static int apic_set_eoi(struct kvm_lapic *apic)
1464edf88417SAvi Kivity {
1465edf88417SAvi Kivity 	int vector = apic_find_highest_isr(apic);
1466ae7a2a3fSMichael S. Tsirkin 
1467ae7a2a3fSMichael S. Tsirkin 	trace_kvm_eoi(apic, vector);
1468ae7a2a3fSMichael S. Tsirkin 
1469edf88417SAvi Kivity 	/*
1470edf88417SAvi Kivity 	 * Not every write EOI will has corresponding ISR,
1471edf88417SAvi Kivity 	 * one example is when Kernel check timer on setup_IO_APIC
1472edf88417SAvi Kivity 	 */
1473edf88417SAvi Kivity 	if (vector == -1)
1474ae7a2a3fSMichael S. Tsirkin 		return vector;
1475edf88417SAvi Kivity 
14768680b94bSMichael S. Tsirkin 	apic_clear_isr(vector, apic);
1477edf88417SAvi Kivity 	apic_update_ppr(apic);
1478edf88417SAvi Kivity 
1479f2bc14b6SVitaly Kuznetsov 	if (to_hv_vcpu(apic->vcpu) &&
1480f2bc14b6SVitaly Kuznetsov 	    test_bit(vector, to_hv_synic(apic->vcpu)->vec_bitmap))
14815c919412SAndrey Smetanin 		kvm_hv_synic_send_eoi(apic->vcpu, vector);
14825c919412SAndrey Smetanin 
1483c7c9c56cSYang Zhang 	kvm_ioapic_send_eoi(apic, vector);
14843842d135SAvi Kivity 	kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1485ae7a2a3fSMichael S. Tsirkin 	return vector;
1486fc61b800SGleb Natapov }
1487edf88417SAvi Kivity 
1488c7c9c56cSYang Zhang /*
1489c7c9c56cSYang Zhang  * this interface assumes a trap-like exit, which has already finished
1490c7c9c56cSYang Zhang  * desired side effect including vISR and vPPR update.
1491c7c9c56cSYang Zhang  */
kvm_apic_set_eoi_accelerated(struct kvm_vcpu * vcpu,int vector)1492c7c9c56cSYang Zhang void kvm_apic_set_eoi_accelerated(struct kvm_vcpu *vcpu, int vector)
1493c7c9c56cSYang Zhang {
1494c7c9c56cSYang Zhang 	struct kvm_lapic *apic = vcpu->arch.apic;
1495c7c9c56cSYang Zhang 
1496c7c9c56cSYang Zhang 	trace_kvm_eoi(apic, vector);
1497c7c9c56cSYang Zhang 
1498c7c9c56cSYang Zhang 	kvm_ioapic_send_eoi(apic, vector);
1499c7c9c56cSYang Zhang 	kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1500c7c9c56cSYang Zhang }
1501c7c9c56cSYang Zhang EXPORT_SYMBOL_GPL(kvm_apic_set_eoi_accelerated);
1502c7c9c56cSYang Zhang 
kvm_apic_send_ipi(struct kvm_lapic * apic,u32 icr_low,u32 icr_high)1503d5361678SWanpeng Li void kvm_apic_send_ipi(struct kvm_lapic *apic, u32 icr_low, u32 icr_high)
1504edf88417SAvi Kivity {
150558c2dde1SGleb Natapov 	struct kvm_lapic_irq irq;
1506edf88417SAvi Kivity 
1507bd17f417SSean Christopherson 	/* KVM has no delay and should always clear the BUSY/PENDING flag. */
1508bd17f417SSean Christopherson 	WARN_ON_ONCE(icr_low & APIC_ICR_BUSY);
1509bd17f417SSean Christopherson 
151058c2dde1SGleb Natapov 	irq.vector = icr_low & APIC_VECTOR_MASK;
151158c2dde1SGleb Natapov 	irq.delivery_mode = icr_low & APIC_MODE_MASK;
151258c2dde1SGleb Natapov 	irq.dest_mode = icr_low & APIC_DEST_MASK;
1513b7cb2231SPaolo Bonzini 	irq.level = (icr_low & APIC_INT_ASSERT) != 0;
151458c2dde1SGleb Natapov 	irq.trig_mode = icr_low & APIC_INT_LEVELTRIG;
151558c2dde1SGleb Natapov 	irq.shorthand = icr_low & APIC_SHORT_MASK;
151693bbf0b8SJames Sullivan 	irq.msi_redir_hint = false;
15170105d1a5SGleb Natapov 	if (apic_x2apic_mode(apic))
15180105d1a5SGleb Natapov 		irq.dest_id = icr_high;
15190105d1a5SGleb Natapov 	else
1520bf348f66SSuravee Suthikulpanit 		irq.dest_id = GET_XAPIC_DEST_FIELD(icr_high);
1521edf88417SAvi Kivity 
15221000ff8dSGleb Natapov 	trace_kvm_apic_ipi(icr_low, irq.dest_id);
15231000ff8dSGleb Natapov 
1524b4f2225cSYang Zhang 	kvm_irq_delivery_to_apic(apic->vcpu->kvm, apic, &irq, NULL);
1525edf88417SAvi Kivity }
1526b51818afSSean Christopherson EXPORT_SYMBOL_GPL(kvm_apic_send_ipi);
1527edf88417SAvi Kivity 
apic_get_tmcct(struct kvm_lapic * apic)1528edf88417SAvi Kivity static u32 apic_get_tmcct(struct kvm_lapic *apic)
1529edf88417SAvi Kivity {
15308003c9aeSWanpeng Li 	ktime_t remaining, now;
1531b682b814SMarcelo Tosatti 	s64 ns;
1532edf88417SAvi Kivity 
1533edf88417SAvi Kivity 	ASSERT(apic != NULL);
1534edf88417SAvi Kivity 
1535edf88417SAvi Kivity 	/* if initial count is 0, current count should also be 0 */
1536dfb95954SSuravee Suthikulpanit 	if (kvm_lapic_get_reg(apic, APIC_TMICT) == 0 ||
1537b963a22eSAndy Honig 		apic->lapic_timer.period == 0)
1538edf88417SAvi Kivity 		return 0;
1539edf88417SAvi Kivity 
15405587859fSPaolo Bonzini 	now = ktime_get();
15418003c9aeSWanpeng Li 	remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1542b682b814SMarcelo Tosatti 	if (ktime_to_ns(remaining) < 0)
15438b0e1953SThomas Gleixner 		remaining = 0;
1544edf88417SAvi Kivity 
1545d3c7b77dSMarcelo Tosatti 	ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
154685e64d09Szhang songyi 	return div64_u64(ns, (APIC_BUS_CYCLE_NS * apic->divide_count));
1547edf88417SAvi Kivity }
1548edf88417SAvi Kivity 
__report_tpr_access(struct kvm_lapic * apic,bool write)1549b209749fSAvi Kivity static void __report_tpr_access(struct kvm_lapic *apic, bool write)
1550b209749fSAvi Kivity {
1551b209749fSAvi Kivity 	struct kvm_vcpu *vcpu = apic->vcpu;
1552b209749fSAvi Kivity 	struct kvm_run *run = vcpu->run;
1553b209749fSAvi Kivity 
1554a8eeb04aSAvi Kivity 	kvm_make_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu);
15555fdbf976SMarcelo Tosatti 	run->tpr_access.rip = kvm_rip_read(vcpu);
1556b209749fSAvi Kivity 	run->tpr_access.is_write = write;
1557b209749fSAvi Kivity }
1558b209749fSAvi Kivity 
report_tpr_access(struct kvm_lapic * apic,bool write)1559b209749fSAvi Kivity static inline void report_tpr_access(struct kvm_lapic *apic, bool write)
1560b209749fSAvi Kivity {
1561b209749fSAvi Kivity 	if (apic->vcpu->arch.tpr_access_reporting)
1562b209749fSAvi Kivity 		__report_tpr_access(apic, write);
1563b209749fSAvi Kivity }
1564b209749fSAvi Kivity 
__apic_read(struct kvm_lapic * apic,unsigned int offset)1565edf88417SAvi Kivity static u32 __apic_read(struct kvm_lapic *apic, unsigned int offset)
1566edf88417SAvi Kivity {
1567edf88417SAvi Kivity 	u32 val = 0;
1568edf88417SAvi Kivity 
1569edf88417SAvi Kivity 	if (offset >= LAPIC_MMIO_LENGTH)
1570edf88417SAvi Kivity 		return 0;
1571edf88417SAvi Kivity 
1572edf88417SAvi Kivity 	switch (offset) {
1573edf88417SAvi Kivity 	case APIC_ARBPRI:
1574edf88417SAvi Kivity 		break;
1575edf88417SAvi Kivity 
1576edf88417SAvi Kivity 	case APIC_TMCCT:	/* Timer CCR */
1577a3e06bbeSLiu, Jinsong 		if (apic_lvtt_tscdeadline(apic))
1578a3e06bbeSLiu, Jinsong 			return 0;
1579a3e06bbeSLiu, Jinsong 
1580edf88417SAvi Kivity 		val = apic_get_tmcct(apic);
1581edf88417SAvi Kivity 		break;
15824a4541a4SAvi Kivity 	case APIC_PROCPRI:
15834a4541a4SAvi Kivity 		apic_update_ppr(apic);
1584dfb95954SSuravee Suthikulpanit 		val = kvm_lapic_get_reg(apic, offset);
15854a4541a4SAvi Kivity 		break;
1586b209749fSAvi Kivity 	case APIC_TASKPRI:
1587b209749fSAvi Kivity 		report_tpr_access(apic, false);
1588df561f66SGustavo A. R. Silva 		fallthrough;
1589edf88417SAvi Kivity 	default:
1590dfb95954SSuravee Suthikulpanit 		val = kvm_lapic_get_reg(apic, offset);
1591edf88417SAvi Kivity 		break;
1592edf88417SAvi Kivity 	}
1593edf88417SAvi Kivity 
1594edf88417SAvi Kivity 	return val;
1595edf88417SAvi Kivity }
1596edf88417SAvi Kivity 
to_lapic(struct kvm_io_device * dev)1597d76685c4SGregory Haskins static inline struct kvm_lapic *to_lapic(struct kvm_io_device *dev)
1598d76685c4SGregory Haskins {
1599d76685c4SGregory Haskins 	return container_of(dev, struct kvm_lapic, dev);
1600d76685c4SGregory Haskins }
1601d76685c4SGregory Haskins 
160201402cf8SPaolo Bonzini #define APIC_REG_MASK(reg)	(1ull << ((reg) >> 4))
160301402cf8SPaolo Bonzini #define APIC_REGS_MASK(first, count) \
160401402cf8SPaolo Bonzini 	(APIC_REG_MASK(first) * ((1ull << (count)) - 1))
160501402cf8SPaolo Bonzini 
kvm_lapic_readable_reg_mask(struct kvm_lapic * apic)1606b5fcc59bSSean Christopherson u64 kvm_lapic_readable_reg_mask(struct kvm_lapic *apic)
1607bda9020eSMichael S. Tsirkin {
1608b5fcc59bSSean Christopherson 	/* Leave bits '0' for reserved and write-only registers. */
160901402cf8SPaolo Bonzini 	u64 valid_reg_mask =
161001402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_ID) |
161101402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_LVR) |
161201402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_TASKPRI) |
161301402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_PROCPRI) |
161401402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_LDR) |
161501402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_SPIV) |
161601402cf8SPaolo Bonzini 		APIC_REGS_MASK(APIC_ISR, APIC_ISR_NR) |
161701402cf8SPaolo Bonzini 		APIC_REGS_MASK(APIC_TMR, APIC_ISR_NR) |
161801402cf8SPaolo Bonzini 		APIC_REGS_MASK(APIC_IRR, APIC_ISR_NR) |
161901402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_ESR) |
162001402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_ICR) |
162101402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_LVTT) |
162201402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_LVTTHMR) |
162301402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_LVTPC) |
162401402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_LVT0) |
162501402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_LVT1) |
162601402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_LVTERR) |
162701402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_TMICT) |
162801402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_TMCCT) |
162901402cf8SPaolo Bonzini 		APIC_REG_MASK(APIC_TDCR);
1630edf88417SAvi Kivity 
16314b903561SJue Wang 	if (kvm_lapic_lvt_supported(apic, LVT_CMCI))
16324b903561SJue Wang 		valid_reg_mask |= APIC_REG_MASK(APIC_LVTCMCI);
16334b903561SJue Wang 
1634b5fcc59bSSean Christopherson 	/* ARBPRI, DFR, and ICR2 are not valid in x2APIC mode. */
163501402cf8SPaolo Bonzini 	if (!apic_x2apic_mode(apic))
1636a57a3168SSean Christopherson 		valid_reg_mask |= APIC_REG_MASK(APIC_ARBPRI) |
1637b2236495SSean Christopherson 				  APIC_REG_MASK(APIC_DFR) |
1638a57a3168SSean Christopherson 				  APIC_REG_MASK(APIC_ICR2);
1639b5fcc59bSSean Christopherson 
1640b5fcc59bSSean Christopherson 	return valid_reg_mask;
1641b5fcc59bSSean Christopherson }
1642b5fcc59bSSean Christopherson EXPORT_SYMBOL_GPL(kvm_lapic_readable_reg_mask);
1643b5fcc59bSSean Christopherson 
kvm_lapic_reg_read(struct kvm_lapic * apic,u32 offset,int len,void * data)1644b5fcc59bSSean Christopherson static int kvm_lapic_reg_read(struct kvm_lapic *apic, u32 offset, int len,
1645b5fcc59bSSean Christopherson 			      void *data)
1646b5fcc59bSSean Christopherson {
1647b5fcc59bSSean Christopherson 	unsigned char alignment = offset & 0xf;
1648b5fcc59bSSean Christopherson 	u32 result;
1649b5fcc59bSSean Christopherson 
1650b5fcc59bSSean Christopherson 	/*
1651b5fcc59bSSean Christopherson 	 * WARN if KVM reads ICR in x2APIC mode, as it's an 8-byte register in
1652b5fcc59bSSean Christopherson 	 * x2APIC and needs to be manually handled by the caller.
1653b5fcc59bSSean Christopherson 	 */
1654b5fcc59bSSean Christopherson 	WARN_ON_ONCE(apic_x2apic_mode(apic) && offset == APIC_ICR);
16550105d1a5SGleb Natapov 
1656218bf772SJim Mattson 	if (alignment + len > 4)
1657218bf772SJim Mattson 		return 1;
1658218bf772SJim Mattson 
1659b5fcc59bSSean Christopherson 	if (offset > 0x3f0 ||
1660b5fcc59bSSean Christopherson 	    !(kvm_lapic_readable_reg_mask(apic) & APIC_REG_MASK(offset)))
16610105d1a5SGleb Natapov 		return 1;
16620105d1a5SGleb Natapov 
1663edf88417SAvi Kivity 	result = __apic_read(apic, offset & ~0xf);
1664edf88417SAvi Kivity 
1665229456fcSMarcelo Tosatti 	trace_kvm_apic_read(offset, result);
1666229456fcSMarcelo Tosatti 
1667edf88417SAvi Kivity 	switch (len) {
1668edf88417SAvi Kivity 	case 1:
1669edf88417SAvi Kivity 	case 2:
1670edf88417SAvi Kivity 	case 4:
1671edf88417SAvi Kivity 		memcpy(data, (char *)&result + alignment, len);
1672edf88417SAvi Kivity 		break;
1673edf88417SAvi Kivity 	default:
1674edf88417SAvi Kivity 		printk(KERN_ERR "Local APIC read with len = %x, "
1675edf88417SAvi Kivity 		       "should be 1,2, or 4 instead\n", len);
1676edf88417SAvi Kivity 		break;
1677edf88417SAvi Kivity 	}
1678bda9020eSMichael S. Tsirkin 	return 0;
1679edf88417SAvi Kivity }
1680edf88417SAvi Kivity 
apic_mmio_in_range(struct kvm_lapic * apic,gpa_t addr)16810105d1a5SGleb Natapov static int apic_mmio_in_range(struct kvm_lapic *apic, gpa_t addr)
16820105d1a5SGleb Natapov {
1683d1766202SVitaly Kuznetsov 	return addr >= apic->base_address &&
16840105d1a5SGleb Natapov 		addr < apic->base_address + LAPIC_MMIO_LENGTH;
16850105d1a5SGleb Natapov }
16860105d1a5SGleb Natapov 
apic_mmio_read(struct kvm_vcpu * vcpu,struct kvm_io_device * this,gpa_t address,int len,void * data)1687e32edf4fSNikolay Nikolaev static int apic_mmio_read(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
16880105d1a5SGleb Natapov 			   gpa_t address, int len, void *data)
16890105d1a5SGleb Natapov {
16900105d1a5SGleb Natapov 	struct kvm_lapic *apic = to_lapic(this);
16910105d1a5SGleb Natapov 	u32 offset = address - apic->base_address;
16920105d1a5SGleb Natapov 
16930105d1a5SGleb Natapov 	if (!apic_mmio_in_range(apic, address))
16940105d1a5SGleb Natapov 		return -EOPNOTSUPP;
16950105d1a5SGleb Natapov 
1696d1766202SVitaly Kuznetsov 	if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
1697d1766202SVitaly Kuznetsov 		if (!kvm_check_has_quirk(vcpu->kvm,
1698d1766202SVitaly Kuznetsov 					 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
1699d1766202SVitaly Kuznetsov 			return -EOPNOTSUPP;
1700d1766202SVitaly Kuznetsov 
1701d1766202SVitaly Kuznetsov 		memset(data, 0xff, len);
1702d1766202SVitaly Kuznetsov 		return 0;
1703d1766202SVitaly Kuznetsov 	}
1704d1766202SVitaly Kuznetsov 
17051e6e2755SSuravee Suthikulpanit 	kvm_lapic_reg_read(apic, offset, len, data);
17060105d1a5SGleb Natapov 
17070105d1a5SGleb Natapov 	return 0;
17080105d1a5SGleb Natapov }
17090105d1a5SGleb Natapov 
update_divide_count(struct kvm_lapic * apic)1710edf88417SAvi Kivity static void update_divide_count(struct kvm_lapic *apic)
1711edf88417SAvi Kivity {
1712edf88417SAvi Kivity 	u32 tmp1, tmp2, tdcr;
1713edf88417SAvi Kivity 
1714dfb95954SSuravee Suthikulpanit 	tdcr = kvm_lapic_get_reg(apic, APIC_TDCR);
1715edf88417SAvi Kivity 	tmp1 = tdcr & 0xf;
1716edf88417SAvi Kivity 	tmp2 = ((tmp1 & 0x3) | ((tmp1 & 0x8) >> 1)) + 1;
1717d3c7b77dSMarcelo Tosatti 	apic->divide_count = 0x1 << (tmp2 & 0x7);
1718edf88417SAvi Kivity }
1719edf88417SAvi Kivity 
limit_periodic_timer_frequency(struct kvm_lapic * apic)1720ccbfa1d3SWanpeng Li static void limit_periodic_timer_frequency(struct kvm_lapic *apic)
1721ccbfa1d3SWanpeng Li {
1722ccbfa1d3SWanpeng Li 	/*
1723ccbfa1d3SWanpeng Li 	 * Do not allow the guest to program periodic timers with small
1724ccbfa1d3SWanpeng Li 	 * interval, since the hrtimers are not throttled by the host
1725ccbfa1d3SWanpeng Li 	 * scheduler.
1726ccbfa1d3SWanpeng Li 	 */
1727dedf9c5eSWanpeng Li 	if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
1728ccbfa1d3SWanpeng Li 		s64 min_period = min_timer_period_us * 1000LL;
1729ccbfa1d3SWanpeng Li 
1730ccbfa1d3SWanpeng Li 		if (apic->lapic_timer.period < min_period) {
1731ccbfa1d3SWanpeng Li 			pr_info_ratelimited(
17328d20bd63SSean Christopherson 			    "vcpu %i: requested %lld ns "
1733ccbfa1d3SWanpeng Li 			    "lapic timer period limited to %lld ns\n",
1734ccbfa1d3SWanpeng Li 			    apic->vcpu->vcpu_id,
1735ccbfa1d3SWanpeng Li 			    apic->lapic_timer.period, min_period);
1736ccbfa1d3SWanpeng Li 			apic->lapic_timer.period = min_period;
1737ccbfa1d3SWanpeng Li 		}
1738ccbfa1d3SWanpeng Li 	}
1739ccbfa1d3SWanpeng Li }
1740ccbfa1d3SWanpeng Li 
174194be4b85SWanpeng Li static void cancel_hv_timer(struct kvm_lapic *apic);
174294be4b85SWanpeng Li 
cancel_apic_timer(struct kvm_lapic * apic)1743e898da78SWanpeng Li static void cancel_apic_timer(struct kvm_lapic *apic)
1744e898da78SWanpeng Li {
1745e898da78SWanpeng Li 	hrtimer_cancel(&apic->lapic_timer.timer);
1746e898da78SWanpeng Li 	preempt_disable();
1747e898da78SWanpeng Li 	if (apic->lapic_timer.hv_timer_in_use)
1748e898da78SWanpeng Li 		cancel_hv_timer(apic);
1749e898da78SWanpeng Li 	preempt_enable();
1750619f51daSWanpeng Li 	atomic_set(&apic->lapic_timer.pending, 0);
1751e898da78SWanpeng Li }
1752e898da78SWanpeng Li 
apic_update_lvtt(struct kvm_lapic * apic)1753b6ac0695SRadim Krčmář static void apic_update_lvtt(struct kvm_lapic *apic)
1754b6ac0695SRadim Krčmář {
1755dfb95954SSuravee Suthikulpanit 	u32 timer_mode = kvm_lapic_get_reg(apic, APIC_LVTT) &
1756b6ac0695SRadim Krčmář 			apic->lapic_timer.timer_mode_mask;
1757b6ac0695SRadim Krčmář 
1758b6ac0695SRadim Krčmář 	if (apic->lapic_timer.timer_mode != timer_mode) {
1759c69518c8SWanpeng Li 		if (apic_lvtt_tscdeadline(apic) != (timer_mode ==
1760dedf9c5eSWanpeng Li 				APIC_LVT_TIMER_TSCDEADLINE)) {
1761e898da78SWanpeng Li 			cancel_apic_timer(apic);
176244275932SRadim Krčmář 			kvm_lapic_set_reg(apic, APIC_TMICT, 0);
176344275932SRadim Krčmář 			apic->lapic_timer.period = 0;
176444275932SRadim Krčmář 			apic->lapic_timer.tscdeadline = 0;
1765b6ac0695SRadim Krčmář 		}
1766dedf9c5eSWanpeng Li 		apic->lapic_timer.timer_mode = timer_mode;
1767dedf9c5eSWanpeng Li 		limit_periodic_timer_frequency(apic);
1768b6ac0695SRadim Krčmář 	}
1769b6ac0695SRadim Krčmář }
1770b6ac0695SRadim Krčmář 
1771d0659d94SMarcelo Tosatti /*
1772d0659d94SMarcelo Tosatti  * On APICv, this test will cause a busy wait
1773d0659d94SMarcelo Tosatti  * during a higher-priority task.
1774d0659d94SMarcelo Tosatti  */
1775d0659d94SMarcelo Tosatti 
lapic_timer_int_injected(struct kvm_vcpu * vcpu)1776d0659d94SMarcelo Tosatti static bool lapic_timer_int_injected(struct kvm_vcpu *vcpu)
1777d0659d94SMarcelo Tosatti {
1778d0659d94SMarcelo Tosatti 	struct kvm_lapic *apic = vcpu->arch.apic;
1779dfb95954SSuravee Suthikulpanit 	u32 reg = kvm_lapic_get_reg(apic, APIC_LVTT);
1780d0659d94SMarcelo Tosatti 
1781d0659d94SMarcelo Tosatti 	if (kvm_apic_hw_enabled(apic)) {
1782d0659d94SMarcelo Tosatti 		int vec = reg & APIC_VECTOR_MASK;
1783f9339860SMarcelo Tosatti 		void *bitmap = apic->regs + APIC_ISR;
1784d0659d94SMarcelo Tosatti 
1785ce0a58f4SSean Christopherson 		if (apic->apicv_active)
1786f9339860SMarcelo Tosatti 			bitmap = apic->regs + APIC_IRR;
1787f9339860SMarcelo Tosatti 
1788f9339860SMarcelo Tosatti 		if (apic_test_vector(vec, bitmap))
1789d0659d94SMarcelo Tosatti 			return true;
1790d0659d94SMarcelo Tosatti 	}
1791d0659d94SMarcelo Tosatti 	return false;
1792d0659d94SMarcelo Tosatti }
1793d0659d94SMarcelo Tosatti 
__wait_lapic_expire(struct kvm_vcpu * vcpu,u64 guest_cycles)1794b6aa57c6SSean Christopherson static inline void __wait_lapic_expire(struct kvm_vcpu *vcpu, u64 guest_cycles)
1795b6aa57c6SSean Christopherson {
1796b6aa57c6SSean Christopherson 	u64 timer_advance_ns = vcpu->arch.apic->lapic_timer.timer_advance_ns;
1797b6aa57c6SSean Christopherson 
1798b6aa57c6SSean Christopherson 	/*
1799b6aa57c6SSean Christopherson 	 * If the guest TSC is running at a different ratio than the host, then
1800b6aa57c6SSean Christopherson 	 * convert the delay to nanoseconds to achieve an accurate delay.  Note
1801b6aa57c6SSean Christopherson 	 * that __delay() uses delay_tsc whenever the hardware has TSC, thus
1802b6aa57c6SSean Christopherson 	 * always for VMX enabled hardware.
1803b6aa57c6SSean Christopherson 	 */
1804938c8745SSean Christopherson 	if (vcpu->arch.tsc_scaling_ratio == kvm_caps.default_tsc_scaling_ratio) {
1805b6aa57c6SSean Christopherson 		__delay(min(guest_cycles,
1806b6aa57c6SSean Christopherson 			nsec_to_cycles(vcpu, timer_advance_ns)));
1807b6aa57c6SSean Christopherson 	} else {
1808b6aa57c6SSean Christopherson 		u64 delay_ns = guest_cycles * 1000000ULL;
1809b6aa57c6SSean Christopherson 		do_div(delay_ns, vcpu->arch.virtual_tsc_khz);
1810b6aa57c6SSean Christopherson 		ndelay(min_t(u32, delay_ns, timer_advance_ns));
1811b6aa57c6SSean Christopherson 	}
1812b6aa57c6SSean Christopherson }
1813b6aa57c6SSean Christopherson 
adjust_lapic_timer_advance(struct kvm_vcpu * vcpu,s64 advance_expire_delta)181484ea3acaSWanpeng Li static inline void adjust_lapic_timer_advance(struct kvm_vcpu *vcpu,
1815ec0671d5SWanpeng Li 					      s64 advance_expire_delta)
1816d0659d94SMarcelo Tosatti {
1817d0659d94SMarcelo Tosatti 	struct kvm_lapic *apic = vcpu->arch.apic;
181839497d76SSean Christopherson 	u32 timer_advance_ns = apic->lapic_timer.timer_advance_ns;
181984ea3acaSWanpeng Li 	u64 ns;
182084ea3acaSWanpeng Li 
1821d0f5a86aSWanpeng Li 	/* Do not adjust for tiny fluctuations or large random spikes. */
1822d0f5a86aSWanpeng Li 	if (abs(advance_expire_delta) > LAPIC_TIMER_ADVANCE_ADJUST_MAX ||
1823d0f5a86aSWanpeng Li 	    abs(advance_expire_delta) < LAPIC_TIMER_ADVANCE_ADJUST_MIN)
1824d0f5a86aSWanpeng Li 		return;
1825d0f5a86aSWanpeng Li 
182684ea3acaSWanpeng Li 	/* too early */
1827ec0671d5SWanpeng Li 	if (advance_expire_delta < 0) {
1828ec0671d5SWanpeng Li 		ns = -advance_expire_delta * 1000000ULL;
182984ea3acaSWanpeng Li 		do_div(ns, vcpu->arch.virtual_tsc_khz);
1830d0f5a86aSWanpeng Li 		timer_advance_ns -= ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
183184ea3acaSWanpeng Li 	} else {
183284ea3acaSWanpeng Li 	/* too late */
1833ec0671d5SWanpeng Li 		ns = advance_expire_delta * 1000000ULL;
183484ea3acaSWanpeng Li 		do_div(ns, vcpu->arch.virtual_tsc_khz);
1835d0f5a86aSWanpeng Li 		timer_advance_ns += ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
183684ea3acaSWanpeng Li 	}
183784ea3acaSWanpeng Li 
1838a0f0037eSWanpeng Li 	if (unlikely(timer_advance_ns > LAPIC_TIMER_ADVANCE_NS_MAX))
1839a0f0037eSWanpeng Li 		timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
184084ea3acaSWanpeng Li 	apic->lapic_timer.timer_advance_ns = timer_advance_ns;
184184ea3acaSWanpeng Li }
184284ea3acaSWanpeng Li 
__kvm_wait_lapic_expire(struct kvm_vcpu * vcpu)18430c5f81daSWanpeng Li static void __kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
184484ea3acaSWanpeng Li {
184584ea3acaSWanpeng Li 	struct kvm_lapic *apic = vcpu->arch.apic;
184684ea3acaSWanpeng Li 	u64 guest_tsc, tsc_deadline;
1847d0659d94SMarcelo Tosatti 
1848d0659d94SMarcelo Tosatti 	tsc_deadline = apic->lapic_timer.expired_tscdeadline;
1849d0659d94SMarcelo Tosatti 	apic->lapic_timer.expired_tscdeadline = 0;
18504ba76538SHaozhong Zhang 	guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1851e0ac5351SWanpeng Li 	trace_kvm_wait_lapic_expire(vcpu->vcpu_id, guest_tsc - tsc_deadline);
1852d0659d94SMarcelo Tosatti 
18539805cf03SWanpeng Li 	if (lapic_timer_advance_dynamic) {
1854e0ac5351SWanpeng Li 		adjust_lapic_timer_advance(vcpu, guest_tsc - tsc_deadline);
18559805cf03SWanpeng Li 		/*
18569805cf03SWanpeng Li 		 * If the timer fired early, reread the TSC to account for the
18579805cf03SWanpeng Li 		 * overhead of the above adjustment to avoid waiting longer
18589805cf03SWanpeng Li 		 * than is necessary.
18599805cf03SWanpeng Li 		 */
18609805cf03SWanpeng Li 		if (guest_tsc < tsc_deadline)
18619805cf03SWanpeng Li 			guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
18629805cf03SWanpeng Li 	}
18639805cf03SWanpeng Li 
1864d0659d94SMarcelo Tosatti 	if (guest_tsc < tsc_deadline)
1865b6aa57c6SSean Christopherson 		__wait_lapic_expire(vcpu, tsc_deadline - guest_tsc);
18663b8a5df6SWanpeng Li }
18670c5f81daSWanpeng Li 
kvm_wait_lapic_expire(struct kvm_vcpu * vcpu)18680c5f81daSWanpeng Li void kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
18690c5f81daSWanpeng Li {
1870010fd37fSWanpeng Li 	if (lapic_in_kernel(vcpu) &&
1871010fd37fSWanpeng Li 	    vcpu->arch.apic->lapic_timer.expired_tscdeadline &&
1872010fd37fSWanpeng Li 	    vcpu->arch.apic->lapic_timer.timer_advance_ns &&
1873010fd37fSWanpeng Li 	    lapic_timer_int_injected(vcpu))
18740c5f81daSWanpeng Li 		__kvm_wait_lapic_expire(vcpu);
18750c5f81daSWanpeng Li }
1876b6c4bc65SWanpeng Li EXPORT_SYMBOL_GPL(kvm_wait_lapic_expire);
18775d87db71SRadim Krčmář 
kvm_apic_inject_pending_timer_irqs(struct kvm_lapic * apic)18780c5f81daSWanpeng Li static void kvm_apic_inject_pending_timer_irqs(struct kvm_lapic *apic)
18790c5f81daSWanpeng Li {
18800c5f81daSWanpeng Li 	struct kvm_timer *ktimer = &apic->lapic_timer;
18810c5f81daSWanpeng Li 
18820c5f81daSWanpeng Li 	kvm_apic_local_deliver(apic, APIC_LVTT);
188317ac43a8SHaiwei Li 	if (apic_lvtt_tscdeadline(apic)) {
18840c5f81daSWanpeng Li 		ktimer->tscdeadline = 0;
188517ac43a8SHaiwei Li 	} else if (apic_lvtt_oneshot(apic)) {
18860c5f81daSWanpeng Li 		ktimer->tscdeadline = 0;
18870c5f81daSWanpeng Li 		ktimer->target_expiration = 0;
18880c5f81daSWanpeng Li 	}
18890c5f81daSWanpeng Li }
18900c5f81daSWanpeng Li 
apic_timer_expired(struct kvm_lapic * apic,bool from_timer_fn)1891ae95f566SWanpeng Li static void apic_timer_expired(struct kvm_lapic *apic, bool from_timer_fn)
18920c5f81daSWanpeng Li {
18930c5f81daSWanpeng Li 	struct kvm_vcpu *vcpu = apic->vcpu;
18940c5f81daSWanpeng Li 	struct kvm_timer *ktimer = &apic->lapic_timer;
18950c5f81daSWanpeng Li 
18960c5f81daSWanpeng Li 	if (atomic_read(&apic->lapic_timer.pending))
18970c5f81daSWanpeng Li 		return;
18980c5f81daSWanpeng Li 
18990c5f81daSWanpeng Li 	if (apic_lvtt_tscdeadline(apic) || ktimer->hv_timer_in_use)
19000c5f81daSWanpeng Li 		ktimer->expired_tscdeadline = ktimer->tscdeadline;
19010c5f81daSWanpeng Li 
1902ce0a58f4SSean Christopherson 	if (!from_timer_fn && apic->apicv_active) {
1903ae95f566SWanpeng Li 		WARN_ON(kvm_get_running_vcpu() != vcpu);
1904ae95f566SWanpeng Li 		kvm_apic_inject_pending_timer_irqs(apic);
1905ae95f566SWanpeng Li 		return;
1906ae95f566SWanpeng Li 	}
1907ae95f566SWanpeng Li 
19080c5f81daSWanpeng Li 	if (kvm_use_posted_timer_interrupt(apic->vcpu)) {
1909beda4301SSean Christopherson 		/*
1910beda4301SSean Christopherson 		 * Ensure the guest's timer has truly expired before posting an
1911beda4301SSean Christopherson 		 * interrupt.  Open code the relevant checks to avoid querying
1912beda4301SSean Christopherson 		 * lapic_timer_int_injected(), which will be false since the
1913beda4301SSean Christopherson 		 * interrupt isn't yet injected.  Waiting until after injecting
1914beda4301SSean Christopherson 		 * is not an option since that won't help a posted interrupt.
1915beda4301SSean Christopherson 		 */
1916beda4301SSean Christopherson 		if (vcpu->arch.apic->lapic_timer.expired_tscdeadline &&
1917beda4301SSean Christopherson 		    vcpu->arch.apic->lapic_timer.timer_advance_ns)
1918beda4301SSean Christopherson 			__kvm_wait_lapic_expire(vcpu);
19190c5f81daSWanpeng Li 		kvm_apic_inject_pending_timer_irqs(apic);
19200c5f81daSWanpeng Li 		return;
19210c5f81daSWanpeng Li 	}
19220c5f81daSWanpeng Li 
19230c5f81daSWanpeng Li 	atomic_inc(&apic->lapic_timer.pending);
1924084071d5SMarcelo Tosatti 	kvm_make_request(KVM_REQ_UNBLOCK, vcpu);
192568ca7663SWanpeng Li 	if (from_timer_fn)
192668ca7663SWanpeng Li 		kvm_vcpu_kick(vcpu);
19270c5f81daSWanpeng Li }
19280c5f81daSWanpeng Li 
start_sw_tscdeadline(struct kvm_lapic * apic)192953f9eedfSYunhong Jiang static void start_sw_tscdeadline(struct kvm_lapic *apic)
193053f9eedfSYunhong Jiang {
193139497d76SSean Christopherson 	struct kvm_timer *ktimer = &apic->lapic_timer;
193239497d76SSean Christopherson 	u64 guest_tsc, tscdeadline = ktimer->tscdeadline;
193353f9eedfSYunhong Jiang 	u64 ns = 0;
193453f9eedfSYunhong Jiang 	ktime_t expire;
193553f9eedfSYunhong Jiang 	struct kvm_vcpu *vcpu = apic->vcpu;
193653f9eedfSYunhong Jiang 	unsigned long this_tsc_khz = vcpu->arch.virtual_tsc_khz;
193753f9eedfSYunhong Jiang 	unsigned long flags;
193853f9eedfSYunhong Jiang 	ktime_t now;
193953f9eedfSYunhong Jiang 
194053f9eedfSYunhong Jiang 	if (unlikely(!tscdeadline || !this_tsc_khz))
194153f9eedfSYunhong Jiang 		return;
194253f9eedfSYunhong Jiang 
194353f9eedfSYunhong Jiang 	local_irq_save(flags);
194453f9eedfSYunhong Jiang 
19455587859fSPaolo Bonzini 	now = ktime_get();
194653f9eedfSYunhong Jiang 	guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1947c09d65d9SLiran Alon 
194853f9eedfSYunhong Jiang 	ns = (tscdeadline - guest_tsc) * 1000000ULL;
194953f9eedfSYunhong Jiang 	do_div(ns, this_tsc_khz);
1950c09d65d9SLiran Alon 
1951c09d65d9SLiran Alon 	if (likely(tscdeadline > guest_tsc) &&
195239497d76SSean Christopherson 	    likely(ns > apic->lapic_timer.timer_advance_ns)) {
195353f9eedfSYunhong Jiang 		expire = ktime_add_ns(now, ns);
195439497d76SSean Christopherson 		expire = ktime_sub_ns(expire, ktimer->timer_advance_ns);
19552c0d278fSSebastian Andrzej Siewior 		hrtimer_start(&ktimer->timer, expire, HRTIMER_MODE_ABS_HARD);
195653f9eedfSYunhong Jiang 	} else
1957ae95f566SWanpeng Li 		apic_timer_expired(apic, false);
195853f9eedfSYunhong Jiang 
195953f9eedfSYunhong Jiang 	local_irq_restore(flags);
196053f9eedfSYunhong Jiang }
196153f9eedfSYunhong Jiang 
tmict_to_ns(struct kvm_lapic * apic,u32 tmict)196224647e0aSPeter Shier static inline u64 tmict_to_ns(struct kvm_lapic *apic, u32 tmict)
196324647e0aSPeter Shier {
196424647e0aSPeter Shier 	return (u64)tmict * APIC_BUS_CYCLE_NS * (u64)apic->divide_count;
196524647e0aSPeter Shier }
196624647e0aSPeter Shier 
update_target_expiration(struct kvm_lapic * apic,uint32_t old_divisor)1967c301b909SWanpeng Li static void update_target_expiration(struct kvm_lapic *apic, uint32_t old_divisor)
1968c301b909SWanpeng Li {
1969c301b909SWanpeng Li 	ktime_t now, remaining;
1970c301b909SWanpeng Li 	u64 ns_remaining_old, ns_remaining_new;
1971c301b909SWanpeng Li 
197224647e0aSPeter Shier 	apic->lapic_timer.period =
197324647e0aSPeter Shier 			tmict_to_ns(apic, kvm_lapic_get_reg(apic, APIC_TMICT));
1974c301b909SWanpeng Li 	limit_periodic_timer_frequency(apic);
1975c301b909SWanpeng Li 
1976c301b909SWanpeng Li 	now = ktime_get();
1977c301b909SWanpeng Li 	remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1978c301b909SWanpeng Li 	if (ktime_to_ns(remaining) < 0)
1979c301b909SWanpeng Li 		remaining = 0;
1980c301b909SWanpeng Li 
1981c301b909SWanpeng Li 	ns_remaining_old = ktime_to_ns(remaining);
1982c301b909SWanpeng Li 	ns_remaining_new = mul_u64_u32_div(ns_remaining_old,
1983c301b909SWanpeng Li 	                                   apic->divide_count, old_divisor);
1984c301b909SWanpeng Li 
1985c301b909SWanpeng Li 	apic->lapic_timer.tscdeadline +=
1986c301b909SWanpeng Li 		nsec_to_cycles(apic->vcpu, ns_remaining_new) -
1987c301b909SWanpeng Li 		nsec_to_cycles(apic->vcpu, ns_remaining_old);
1988c301b909SWanpeng Li 	apic->lapic_timer.target_expiration = ktime_add_ns(now, ns_remaining_new);
1989c301b909SWanpeng Li }
1990c301b909SWanpeng Li 
set_target_expiration(struct kvm_lapic * apic,u32 count_reg)199124647e0aSPeter Shier static bool set_target_expiration(struct kvm_lapic *apic, u32 count_reg)
1992edf88417SAvi Kivity {
1993a3e06bbeSLiu, Jinsong 	ktime_t now;
19948003c9aeSWanpeng Li 	u64 tscl = rdtsc();
199524647e0aSPeter Shier 	s64 deadline;
1996d0659d94SMarcelo Tosatti 
19975587859fSPaolo Bonzini 	now = ktime_get();
199824647e0aSPeter Shier 	apic->lapic_timer.period =
199924647e0aSPeter Shier 			tmict_to_ns(apic, kvm_lapic_get_reg(apic, APIC_TMICT));
2000a3e06bbeSLiu, Jinsong 
20015d74a699SRadim Krčmář 	if (!apic->lapic_timer.period) {
20025d74a699SRadim Krčmář 		apic->lapic_timer.tscdeadline = 0;
20038003c9aeSWanpeng Li 		return false;
20049bc5791dSJan Kiszka 	}
20051444885aSMarcelo Tosatti 
2006ccbfa1d3SWanpeng Li 	limit_periodic_timer_frequency(apic);
200724647e0aSPeter Shier 	deadline = apic->lapic_timer.period;
200824647e0aSPeter Shier 
200924647e0aSPeter Shier 	if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic)) {
201024647e0aSPeter Shier 		if (unlikely(count_reg != APIC_TMICT)) {
201124647e0aSPeter Shier 			deadline = tmict_to_ns(apic,
201224647e0aSPeter Shier 				     kvm_lapic_get_reg(apic, count_reg));
20138e6ed96cSLi RongQing 			if (unlikely(deadline <= 0)) {
20148e6ed96cSLi RongQing 				if (apic_lvtt_period(apic))
201524647e0aSPeter Shier 					deadline = apic->lapic_timer.period;
20168e6ed96cSLi RongQing 				else
20178e6ed96cSLi RongQing 					deadline = 0;
20188e6ed96cSLi RongQing 			}
201924647e0aSPeter Shier 			else if (unlikely(deadline > apic->lapic_timer.period)) {
202024647e0aSPeter Shier 				pr_info_ratelimited(
20218d20bd63SSean Christopherson 				    "vcpu %i: requested lapic timer restore with "
202224647e0aSPeter Shier 				    "starting count register %#x=%u (%lld ns) > initial count (%lld ns). "
202324647e0aSPeter Shier 				    "Using initial count to start timer.\n",
202424647e0aSPeter Shier 				    apic->vcpu->vcpu_id,
202524647e0aSPeter Shier 				    count_reg,
202624647e0aSPeter Shier 				    kvm_lapic_get_reg(apic, count_reg),
202724647e0aSPeter Shier 				    deadline, apic->lapic_timer.period);
202824647e0aSPeter Shier 				kvm_lapic_set_reg(apic, count_reg, 0);
202924647e0aSPeter Shier 				deadline = apic->lapic_timer.period;
203024647e0aSPeter Shier 			}
203124647e0aSPeter Shier 		}
203224647e0aSPeter Shier 	}
20330b975a3cSAvi Kivity 
20348003c9aeSWanpeng Li 	apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
203524647e0aSPeter Shier 		nsec_to_cycles(apic->vcpu, deadline);
203624647e0aSPeter Shier 	apic->lapic_timer.target_expiration = ktime_add_ns(now, deadline);
20378003c9aeSWanpeng Li 
20388003c9aeSWanpeng Li 	return true;
20398003c9aeSWanpeng Li }
20408003c9aeSWanpeng Li 
advance_periodic_target_expiration(struct kvm_lapic * apic)20418003c9aeSWanpeng Li static void advance_periodic_target_expiration(struct kvm_lapic *apic)
20428003c9aeSWanpeng Li {
2043d8f2f498SDavid Vrabel 	ktime_t now = ktime_get();
2044d8f2f498SDavid Vrabel 	u64 tscl = rdtsc();
2045d8f2f498SDavid Vrabel 	ktime_t delta;
2046d8f2f498SDavid Vrabel 
2047d8f2f498SDavid Vrabel 	/*
2048d8f2f498SDavid Vrabel 	 * Synchronize both deadlines to the same time source or
2049d8f2f498SDavid Vrabel 	 * differences in the periods (caused by differences in the
2050d8f2f498SDavid Vrabel 	 * underlying clocks or numerical approximation errors) will
2051d8f2f498SDavid Vrabel 	 * cause the two to drift apart over time as the errors
2052d8f2f498SDavid Vrabel 	 * accumulate.
2053d8f2f498SDavid Vrabel 	 */
20548003c9aeSWanpeng Li 	apic->lapic_timer.target_expiration =
20558003c9aeSWanpeng Li 		ktime_add_ns(apic->lapic_timer.target_expiration,
20568003c9aeSWanpeng Li 				apic->lapic_timer.period);
2057d8f2f498SDavid Vrabel 	delta = ktime_sub(apic->lapic_timer.target_expiration, now);
2058d8f2f498SDavid Vrabel 	apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
2059d8f2f498SDavid Vrabel 		nsec_to_cycles(apic->vcpu, delta);
20607d7f7da2SWanpeng Li }
20617d7f7da2SWanpeng Li 
start_sw_period(struct kvm_lapic * apic)2062ecf08dadSAnthoine Bourgeois static void start_sw_period(struct kvm_lapic *apic)
2063ecf08dadSAnthoine Bourgeois {
2064ecf08dadSAnthoine Bourgeois 	if (!apic->lapic_timer.period)
2065ecf08dadSAnthoine Bourgeois 		return;
2066ecf08dadSAnthoine Bourgeois 
2067ecf08dadSAnthoine Bourgeois 	if (ktime_after(ktime_get(),
2068ecf08dadSAnthoine Bourgeois 			apic->lapic_timer.target_expiration)) {
2069ae95f566SWanpeng Li 		apic_timer_expired(apic, false);
2070ecf08dadSAnthoine Bourgeois 
2071ecf08dadSAnthoine Bourgeois 		if (apic_lvtt_oneshot(apic))
2072ecf08dadSAnthoine Bourgeois 			return;
2073ecf08dadSAnthoine Bourgeois 
2074ecf08dadSAnthoine Bourgeois 		advance_periodic_target_expiration(apic);
2075ecf08dadSAnthoine Bourgeois 	}
2076ecf08dadSAnthoine Bourgeois 
2077ecf08dadSAnthoine Bourgeois 	hrtimer_start(&apic->lapic_timer.timer,
2078ecf08dadSAnthoine Bourgeois 		apic->lapic_timer.target_expiration,
2079edec6e01SHe Zhe 		HRTIMER_MODE_ABS_HARD);
2080ecf08dadSAnthoine Bourgeois }
2081ecf08dadSAnthoine Bourgeois 
kvm_lapic_hv_timer_in_use(struct kvm_vcpu * vcpu)2082edf88417SAvi Kivity bool kvm_lapic_hv_timer_in_use(struct kvm_vcpu *vcpu)
2083edf88417SAvi Kivity {
2084edf88417SAvi Kivity 	if (!lapic_in_kernel(vcpu))
2085edf88417SAvi Kivity 		return false;
2086edf88417SAvi Kivity 
2087edf88417SAvi Kivity 	return vcpu->arch.apic->lapic_timer.hv_timer_in_use;
2088edf88417SAvi Kivity }
2089edf88417SAvi Kivity 
cancel_hv_timer(struct kvm_lapic * apic)20907e810a38SWanpeng Li static void cancel_hv_timer(struct kvm_lapic *apic)
2091edf88417SAvi Kivity {
20921d518c68SWanpeng Li 	WARN_ON(preemptible());
2093a749e247SPaolo Bonzini 	WARN_ON(!apic->lapic_timer.hv_timer_in_use);
2094b3646477SJason Baron 	static_call(kvm_x86_cancel_hv_timer)(apic->vcpu);
2095edf88417SAvi Kivity 	apic->lapic_timer.hv_timer_in_use = false;
2096edf88417SAvi Kivity }
2097edf88417SAvi Kivity 
start_hv_timer(struct kvm_lapic * apic)2098a749e247SPaolo Bonzini static bool start_hv_timer(struct kvm_lapic *apic)
209935ee9e48SPaolo Bonzini {
210035ee9e48SPaolo Bonzini 	struct kvm_timer *ktimer = &apic->lapic_timer;
2101f9927982SSean Christopherson 	struct kvm_vcpu *vcpu = apic->vcpu;
2102f9927982SSean Christopherson 	bool expired;
210335ee9e48SPaolo Bonzini 
21041d518c68SWanpeng Li 	WARN_ON(preemptible());
2105199a8b84SPaolo Bonzini 	if (!kvm_can_use_hv_timer(vcpu))
2106a749e247SPaolo Bonzini 		return false;
2107a749e247SPaolo Bonzini 
210886bbc1e6SRadim Krčmář 	if (!ktimer->tscdeadline)
210986bbc1e6SRadim Krčmář 		return false;
211086bbc1e6SRadim Krčmář 
2111b3646477SJason Baron 	if (static_call(kvm_x86_set_hv_timer)(vcpu, ktimer->tscdeadline, &expired))
211235ee9e48SPaolo Bonzini 		return false;
211335ee9e48SPaolo Bonzini 
211435ee9e48SPaolo Bonzini 	ktimer->hv_timer_in_use = true;
211535ee9e48SPaolo Bonzini 	hrtimer_cancel(&ktimer->timer);
211635ee9e48SPaolo Bonzini 
211735ee9e48SPaolo Bonzini 	/*
2118f1ba5cfbSSean Christopherson 	 * To simplify handling the periodic timer, leave the hv timer running
2119f1ba5cfbSSean Christopherson 	 * even if the deadline timer has expired, i.e. rely on the resulting
2120f1ba5cfbSSean Christopherson 	 * VM-Exit to recompute the periodic timer's target expiration.
212135ee9e48SPaolo Bonzini 	 */
2122f1ba5cfbSSean Christopherson 	if (!apic_lvtt_period(apic)) {
2123f1ba5cfbSSean Christopherson 		/*
2124f1ba5cfbSSean Christopherson 		 * Cancel the hv timer if the sw timer fired while the hv timer
2125f1ba5cfbSSean Christopherson 		 * was being programmed, or if the hv timer itself expired.
2126f1ba5cfbSSean Christopherson 		 */
2127f1ba5cfbSSean Christopherson 		if (atomic_read(&ktimer->pending)) {
2128f1ba5cfbSSean Christopherson 			cancel_hv_timer(apic);
2129f9927982SSean Christopherson 		} else if (expired) {
2130ae95f566SWanpeng Li 			apic_timer_expired(apic, false);
2131f1ba5cfbSSean Christopherson 			cancel_hv_timer(apic);
2132f1ba5cfbSSean Christopherson 		}
2133c8533544SWanpeng Li 	}
2134a749e247SPaolo Bonzini 
2135f9927982SSean Christopherson 	trace_kvm_hv_timer_state(vcpu->vcpu_id, ktimer->hv_timer_in_use);
2136f1ba5cfbSSean Christopherson 
213735ee9e48SPaolo Bonzini 	return true;
213835ee9e48SPaolo Bonzini }
213935ee9e48SPaolo Bonzini 
start_sw_timer(struct kvm_lapic * apic)2140a749e247SPaolo Bonzini static void start_sw_timer(struct kvm_lapic *apic)
2141edf88417SAvi Kivity {
2142a749e247SPaolo Bonzini 	struct kvm_timer *ktimer = &apic->lapic_timer;
21431d518c68SWanpeng Li 
21441d518c68SWanpeng Li 	WARN_ON(preemptible());
2145edf88417SAvi Kivity 	if (apic->lapic_timer.hv_timer_in_use)
21467e810a38SWanpeng Li 		cancel_hv_timer(apic);
2147a749e247SPaolo Bonzini 	if (!apic_lvtt_period(apic) && atomic_read(&ktimer->pending))
2148a749e247SPaolo Bonzini 		return;
2149a749e247SPaolo Bonzini 
2150a749e247SPaolo Bonzini 	if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
2151a749e247SPaolo Bonzini 		start_sw_period(apic);
2152a749e247SPaolo Bonzini 	else if (apic_lvtt_tscdeadline(apic))
2153a749e247SPaolo Bonzini 		start_sw_tscdeadline(apic);
2154a749e247SPaolo Bonzini 	trace_kvm_hv_timer_state(apic->vcpu->vcpu_id, false);
2155edf88417SAvi Kivity }
215635ee9e48SPaolo Bonzini 
restart_apic_timer(struct kvm_lapic * apic)2157a749e247SPaolo Bonzini static void restart_apic_timer(struct kvm_lapic *apic)
2158a749e247SPaolo Bonzini {
21591d518c68SWanpeng Li 	preempt_disable();
21604ca88b3fSSean Christopherson 
21614ca88b3fSSean Christopherson 	if (!apic_lvtt_period(apic) && atomic_read(&apic->lapic_timer.pending))
21624ca88b3fSSean Christopherson 		goto out;
21634ca88b3fSSean Christopherson 
2164a749e247SPaolo Bonzini 	if (!start_hv_timer(apic))
2165a749e247SPaolo Bonzini 		start_sw_timer(apic);
21664ca88b3fSSean Christopherson out:
21671d518c68SWanpeng Li 	preempt_enable();
2168edf88417SAvi Kivity }
2169edf88417SAvi Kivity 
kvm_lapic_expired_hv_timer(struct kvm_vcpu * vcpu)21708003c9aeSWanpeng Li void kvm_lapic_expired_hv_timer(struct kvm_vcpu *vcpu)
21718003c9aeSWanpeng Li {
21728003c9aeSWanpeng Li 	struct kvm_lapic *apic = vcpu->arch.apic;
21738003c9aeSWanpeng Li 
21741d518c68SWanpeng Li 	preempt_disable();
21751d518c68SWanpeng Li 	/* If the preempt notifier has already run, it also called apic_timer_expired */
21761d518c68SWanpeng Li 	if (!apic->lapic_timer.hv_timer_in_use)
21771d518c68SWanpeng Li 		goto out;
2178d92a5d1cSSean Christopherson 	WARN_ON(kvm_vcpu_is_blocking(vcpu));
2179ae95f566SWanpeng Li 	apic_timer_expired(apic, false);
2180d981dd15SWanpeng Li 	cancel_hv_timer(apic);
21818003c9aeSWanpeng Li 
21828003c9aeSWanpeng Li 	if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
21838003c9aeSWanpeng Li 		advance_periodic_target_expiration(apic);
2184a749e247SPaolo Bonzini 		restart_apic_timer(apic);
21858003c9aeSWanpeng Li 	}
21861d518c68SWanpeng Li out:
21871d518c68SWanpeng Li 	preempt_enable();
21888003c9aeSWanpeng Li }
21898003c9aeSWanpeng Li EXPORT_SYMBOL_GPL(kvm_lapic_expired_hv_timer);
21908003c9aeSWanpeng Li 
kvm_lapic_switch_to_hv_timer(struct kvm_vcpu * vcpu)2191edf88417SAvi Kivity void kvm_lapic_switch_to_hv_timer(struct kvm_vcpu *vcpu)
2192edf88417SAvi Kivity {
2193a749e247SPaolo Bonzini 	restart_apic_timer(vcpu->arch.apic);
2194edf88417SAvi Kivity }
2195edf88417SAvi Kivity 
kvm_lapic_switch_to_sw_timer(struct kvm_vcpu * vcpu)2196edf88417SAvi Kivity void kvm_lapic_switch_to_sw_timer(struct kvm_vcpu *vcpu)
2197edf88417SAvi Kivity {
2198edf88417SAvi Kivity 	struct kvm_lapic *apic = vcpu->arch.apic;
2199edf88417SAvi Kivity 
22001d518c68SWanpeng Li 	preempt_disable();
2201edf88417SAvi Kivity 	/* Possibly the TSC deadline timer is not enabled yet */
2202a749e247SPaolo Bonzini 	if (apic->lapic_timer.hv_timer_in_use)
2203a749e247SPaolo Bonzini 		start_sw_timer(apic);
22041d518c68SWanpeng Li 	preempt_enable();
2205edf88417SAvi Kivity }
2206edf88417SAvi Kivity 
kvm_lapic_restart_hv_timer(struct kvm_vcpu * vcpu)2207a749e247SPaolo Bonzini void kvm_lapic_restart_hv_timer(struct kvm_vcpu *vcpu)
2208a749e247SPaolo Bonzini {
2209a749e247SPaolo Bonzini 	struct kvm_lapic *apic = vcpu->arch.apic;
2210a749e247SPaolo Bonzini 
2211a749e247SPaolo Bonzini 	WARN_ON(!apic->lapic_timer.hv_timer_in_use);
2212a749e247SPaolo Bonzini 	restart_apic_timer(apic);
2213a749e247SPaolo Bonzini }
2214a749e247SPaolo Bonzini 
__start_apic_timer(struct kvm_lapic * apic,u32 count_reg)221524647e0aSPeter Shier static void __start_apic_timer(struct kvm_lapic *apic, u32 count_reg)
2216edf88417SAvi Kivity {
2217edf88417SAvi Kivity 	atomic_set(&apic->lapic_timer.pending, 0);
2218edf88417SAvi Kivity 
2219a749e247SPaolo Bonzini 	if ((apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
222024647e0aSPeter Shier 	    && !set_target_expiration(apic, count_reg))
2221a749e247SPaolo Bonzini 		return;
2222a749e247SPaolo Bonzini 
2223a749e247SPaolo Bonzini 	restart_apic_timer(apic);
2224edf88417SAvi Kivity }
2225edf88417SAvi Kivity 
start_apic_timer(struct kvm_lapic * apic)222624647e0aSPeter Shier static void start_apic_timer(struct kvm_lapic *apic)
222724647e0aSPeter Shier {
222824647e0aSPeter Shier 	__start_apic_timer(apic, APIC_TMICT);
222924647e0aSPeter Shier }
223024647e0aSPeter Shier 
apic_manage_nmi_watchdog(struct kvm_lapic * apic,u32 lvt0_val)2231cc6e462cSJan Kiszka static void apic_manage_nmi_watchdog(struct kvm_lapic *apic, u32 lvt0_val)
2232cc6e462cSJan Kiszka {
223359fd1323SRadim Krčmář 	bool lvt0_in_nmi_mode = apic_lvt_nmi_mode(lvt0_val);
2234cc6e462cSJan Kiszka 
223559fd1323SRadim Krčmář 	if (apic->lvt0_in_nmi_mode != lvt0_in_nmi_mode) {
223659fd1323SRadim Krčmář 		apic->lvt0_in_nmi_mode = lvt0_in_nmi_mode;
223759fd1323SRadim Krčmář 		if (lvt0_in_nmi_mode) {
223842720138SRadim Krčmář 			atomic_inc(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
223959fd1323SRadim Krčmář 		} else
224042720138SRadim Krčmář 			atomic_dec(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
2241cc6e462cSJan Kiszka 	}
224259fd1323SRadim Krčmář }
2243cc6e462cSJan Kiszka 
get_lvt_index(u32 reg)22444b903561SJue Wang static int get_lvt_index(u32 reg)
22454b903561SJue Wang {
22464b903561SJue Wang 	if (reg == APIC_LVTCMCI)
22474b903561SJue Wang 		return LVT_CMCI;
22484b903561SJue Wang 	if (reg < APIC_LVTT || reg > APIC_LVTERR)
22494b903561SJue Wang 		return -1;
22504b903561SJue Wang 	return array_index_nospec(
22514b903561SJue Wang 			(reg - APIC_LVTT) >> 4, KVM_APIC_MAX_NR_LVT_ENTRIES);
22524b903561SJue Wang }
22534b903561SJue Wang 
kvm_lapic_reg_write(struct kvm_lapic * apic,u32 reg,u32 val)225470180052SSean Christopherson static int kvm_lapic_reg_write(struct kvm_lapic *apic, u32 reg, u32 val)
2255edf88417SAvi Kivity {
22560105d1a5SGleb Natapov 	int ret = 0;
2257edf88417SAvi Kivity 
22580105d1a5SGleb Natapov 	trace_kvm_apic_write(reg, val);
2259edf88417SAvi Kivity 
22600105d1a5SGleb Natapov 	switch (reg) {
2261edf88417SAvi Kivity 	case APIC_ID:		/* Local APIC ID */
22623743c2f0SMaxim Levitsky 		if (!apic_x2apic_mode(apic)) {
2263a92e2543SRadim Krčmář 			kvm_apic_set_xapic_id(apic, val >> 24);
22643743c2f0SMaxim Levitsky 		} else {
22650105d1a5SGleb Natapov 			ret = 1;
22663743c2f0SMaxim Levitsky 		}
2267edf88417SAvi Kivity 		break;
2268edf88417SAvi Kivity 
2269edf88417SAvi Kivity 	case APIC_TASKPRI:
2270b209749fSAvi Kivity 		report_tpr_access(apic, true);
2271edf88417SAvi Kivity 		apic_set_tpr(apic, val & 0xff);
2272edf88417SAvi Kivity 		break;
2273edf88417SAvi Kivity 
2274edf88417SAvi Kivity 	case APIC_EOI:
2275edf88417SAvi Kivity 		apic_set_eoi(apic);
2276edf88417SAvi Kivity 		break;
2277edf88417SAvi Kivity 
2278edf88417SAvi Kivity 	case APIC_LDR:
22790105d1a5SGleb Natapov 		if (!apic_x2apic_mode(apic))
22801e08ec4aSGleb Natapov 			kvm_apic_set_ldr(apic, val & APIC_LDR_MASK);
22810105d1a5SGleb Natapov 		else
22820105d1a5SGleb Natapov 			ret = 1;
2283edf88417SAvi Kivity 		break;
2284edf88417SAvi Kivity 
2285edf88417SAvi Kivity 	case APIC_DFR:
2286ae6f2496SWanpeng Li 		if (!apic_x2apic_mode(apic))
2287ae6f2496SWanpeng Li 			kvm_apic_set_dfr(apic, val | 0x0FFFFFFF);
2288ae6f2496SWanpeng Li 		else
22890105d1a5SGleb Natapov 			ret = 1;
2290edf88417SAvi Kivity 		break;
2291edf88417SAvi Kivity 
2292fc61b800SGleb Natapov 	case APIC_SPIV: {
2293fc61b800SGleb Natapov 		u32 mask = 0x3ff;
2294dfb95954SSuravee Suthikulpanit 		if (kvm_lapic_get_reg(apic, APIC_LVR) & APIC_LVR_DIRECTED_EOI)
2295fc61b800SGleb Natapov 			mask |= APIC_SPIV_DIRECTED_EOI;
2296f8c1ea10SGleb Natapov 		apic_set_spiv(apic, val & mask);
2297edf88417SAvi Kivity 		if (!(val & APIC_SPIV_APIC_ENABLED)) {
2298edf88417SAvi Kivity 			int i;
2299edf88417SAvi Kivity 
23004b903561SJue Wang 			for (i = 0; i < apic->nr_lvt_entries; i++) {
2301987f625eSJue Wang 				kvm_lapic_set_reg(apic, APIC_LVTx(i),
23024b903561SJue Wang 					kvm_lapic_get_reg(apic, APIC_LVTx(i)) | APIC_LVT_MASKED);
2303edf88417SAvi Kivity 			}
2304b6ac0695SRadim Krčmář 			apic_update_lvtt(apic);
2305d3c7b77dSMarcelo Tosatti 			atomic_set(&apic->lapic_timer.pending, 0);
2306edf88417SAvi Kivity 
2307edf88417SAvi Kivity 		}
2308edf88417SAvi Kivity 		break;
2309fc61b800SGleb Natapov 	}
2310edf88417SAvi Kivity 	case APIC_ICR:
2311a57a3168SSean Christopherson 		WARN_ON_ONCE(apic_x2apic_mode(apic));
2312a57a3168SSean Christopherson 
2313edf88417SAvi Kivity 		/* No delay here, so we always clear the pending bit */
2314bd17f417SSean Christopherson 		val &= ~APIC_ICR_BUSY;
2315d5361678SWanpeng Li 		kvm_apic_send_ipi(apic, val, kvm_lapic_get_reg(apic, APIC_ICR2));
23162b0911d1SWanpeng Li 		kvm_lapic_set_reg(apic, APIC_ICR, val);
2317edf88417SAvi Kivity 		break;
2318edf88417SAvi Kivity 	case APIC_ICR2:
2319a57a3168SSean Christopherson 		if (apic_x2apic_mode(apic))
2320a57a3168SSean Christopherson 			ret = 1;
2321a57a3168SSean Christopherson 		else
2322a57a3168SSean Christopherson 			kvm_lapic_set_reg(apic, APIC_ICR2, val & 0xff000000);
2323edf88417SAvi Kivity 		break;
2324edf88417SAvi Kivity 
232523930f95SJan Kiszka 	case APIC_LVT0:
2326cc6e462cSJan Kiszka 		apic_manage_nmi_watchdog(apic, val);
2327df561f66SGustavo A. R. Silva 		fallthrough;
2328edf88417SAvi Kivity 	case APIC_LVTTHMR:
2329edf88417SAvi Kivity 	case APIC_LVTPC:
2330edf88417SAvi Kivity 	case APIC_LVT1:
23314b903561SJue Wang 	case APIC_LVTERR:
23324b903561SJue Wang 	case APIC_LVTCMCI: {
23334b903561SJue Wang 		u32 index = get_lvt_index(reg);
23344b903561SJue Wang 		if (!kvm_lapic_lvt_supported(apic, index)) {
23354b903561SJue Wang 			ret = 1;
23364b903561SJue Wang 			break;
23374b903561SJue Wang 		}
2338c48f1496SGleb Natapov 		if (!kvm_apic_sw_enabled(apic))
2339edf88417SAvi Kivity 			val |= APIC_LVT_MASKED;
23404bf79cb0SMarios Pomonis 		val &= apic_lvt_mask[index];
23411e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, reg, val);
2342edf88417SAvi Kivity 		break;
23434bf79cb0SMarios Pomonis 	}
2344edf88417SAvi Kivity 
2345b6ac0695SRadim Krčmář 	case APIC_LVTT:
2346c48f1496SGleb Natapov 		if (!kvm_apic_sw_enabled(apic))
2347a3e06bbeSLiu, Jinsong 			val |= APIC_LVT_MASKED;
2348a3e06bbeSLiu, Jinsong 		val &= (apic_lvt_mask[0] | apic->lapic_timer.timer_mode_mask);
23491e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, APIC_LVTT, val);
2350b6ac0695SRadim Krčmář 		apic_update_lvtt(apic);
2351a3e06bbeSLiu, Jinsong 		break;
2352a3e06bbeSLiu, Jinsong 
2353edf88417SAvi Kivity 	case APIC_TMICT:
2354a3e06bbeSLiu, Jinsong 		if (apic_lvtt_tscdeadline(apic))
2355a3e06bbeSLiu, Jinsong 			break;
2356a3e06bbeSLiu, Jinsong 
2357e898da78SWanpeng Li 		cancel_apic_timer(apic);
23581e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, APIC_TMICT, val);
2359edf88417SAvi Kivity 		start_apic_timer(apic);
23600105d1a5SGleb Natapov 		break;
2361edf88417SAvi Kivity 
2362c301b909SWanpeng Li 	case APIC_TDCR: {
2363c301b909SWanpeng Li 		uint32_t old_divisor = apic->divide_count;
2364c301b909SWanpeng Li 
2365a445fc45SWanpeng Li 		kvm_lapic_set_reg(apic, APIC_TDCR, val & 0xb);
2366edf88417SAvi Kivity 		update_divide_count(apic);
2367c301b909SWanpeng Li 		if (apic->divide_count != old_divisor &&
2368c301b909SWanpeng Li 				apic->lapic_timer.period) {
2369c301b909SWanpeng Li 			hrtimer_cancel(&apic->lapic_timer.timer);
2370c301b909SWanpeng Li 			update_target_expiration(apic, old_divisor);
2371c301b909SWanpeng Li 			restart_apic_timer(apic);
2372c301b909SWanpeng Li 		}
2373edf88417SAvi Kivity 		break;
2374c301b909SWanpeng Li 	}
23750105d1a5SGleb Natapov 	case APIC_ESR:
23760d88800dSYi Wang 		if (apic_x2apic_mode(apic) && val != 0)
23770105d1a5SGleb Natapov 			ret = 1;
23780105d1a5SGleb Natapov 		break;
23790105d1a5SGleb Natapov 
23800105d1a5SGleb Natapov 	case APIC_SELF_IPI:
2381ba5838abSSean Christopherson 		/*
2382ba5838abSSean Christopherson 		 * Self-IPI exists only when x2APIC is enabled.  Bits 7:0 hold
2383ba5838abSSean Christopherson 		 * the vector, everything else is reserved.
2384ba5838abSSean Christopherson 		 */
2385ba5838abSSean Christopherson 		if (!apic_x2apic_mode(apic) || (val & ~APIC_VECTOR_MASK))
23860105d1a5SGleb Natapov 			ret = 1;
2387ba5838abSSean Christopherson 		else
2388ba5838abSSean Christopherson 			kvm_apic_send_ipi(apic, APIC_DEST_SELF | val, 0);
23890105d1a5SGleb Natapov 		break;
2390edf88417SAvi Kivity 	default:
23910105d1a5SGleb Natapov 		ret = 1;
2392edf88417SAvi Kivity 		break;
2393edf88417SAvi Kivity 	}
23940d88800dSYi Wang 
2395bd17f417SSean Christopherson 	/*
2396bd17f417SSean Christopherson 	 * Recalculate APIC maps if necessary, e.g. if the software enable bit
2397bd17f417SSean Christopherson 	 * was toggled, the APIC ID changed, etc...   The maps are marked dirty
2398bd17f417SSean Christopherson 	 * on relevant changes, i.e. this is a nop for most writes.
2399bd17f417SSean Christopherson 	 */
24004abaffceSWanpeng Li 	kvm_recalculate_apic_map(apic->vcpu->kvm);
24014abaffceSWanpeng Li 
24020105d1a5SGleb Natapov 	return ret;
24030105d1a5SGleb Natapov }
24040105d1a5SGleb Natapov 
apic_mmio_write(struct kvm_vcpu * vcpu,struct kvm_io_device * this,gpa_t address,int len,const void * data)2405e32edf4fSNikolay Nikolaev static int apic_mmio_write(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
24060105d1a5SGleb Natapov 			    gpa_t address, int len, const void *data)
24070105d1a5SGleb Natapov {
24080105d1a5SGleb Natapov 	struct kvm_lapic *apic = to_lapic(this);
24090105d1a5SGleb Natapov 	unsigned int offset = address - apic->base_address;
24100105d1a5SGleb Natapov 	u32 val;
24110105d1a5SGleb Natapov 
24120105d1a5SGleb Natapov 	if (!apic_mmio_in_range(apic, address))
24130105d1a5SGleb Natapov 		return -EOPNOTSUPP;
24140105d1a5SGleb Natapov 
2415d1766202SVitaly Kuznetsov 	if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
2416d1766202SVitaly Kuznetsov 		if (!kvm_check_has_quirk(vcpu->kvm,
2417d1766202SVitaly Kuznetsov 					 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
2418d1766202SVitaly Kuznetsov 			return -EOPNOTSUPP;
2419d1766202SVitaly Kuznetsov 
2420d1766202SVitaly Kuznetsov 		return 0;
2421d1766202SVitaly Kuznetsov 	}
2422d1766202SVitaly Kuznetsov 
24230105d1a5SGleb Natapov 	/*
24240105d1a5SGleb Natapov 	 * APIC register must be aligned on 128-bits boundary.
24250105d1a5SGleb Natapov 	 * 32/64/128 bits registers must be accessed thru 32 bits.
24260105d1a5SGleb Natapov 	 * Refer SDM 8.4.1
24270105d1a5SGleb Natapov 	 */
24280d88800dSYi Wang 	if (len != 4 || (offset & 0xf))
2429756975bbSSheng Yang 		return 0;
24300105d1a5SGleb Natapov 
24310105d1a5SGleb Natapov 	val = *(u32*)data;
24320105d1a5SGleb Natapov 
24330d88800dSYi Wang 	kvm_lapic_reg_write(apic, offset & 0xff0, val);
24340105d1a5SGleb Natapov 
2435bda9020eSMichael S. Tsirkin 	return 0;
2436edf88417SAvi Kivity }
2437edf88417SAvi Kivity 
kvm_lapic_set_eoi(struct kvm_vcpu * vcpu)243858fbbf26SKevin Tian void kvm_lapic_set_eoi(struct kvm_vcpu *vcpu)
243958fbbf26SKevin Tian {
24401e6e2755SSuravee Suthikulpanit 	kvm_lapic_reg_write(vcpu->arch.apic, APIC_EOI, 0);
244158fbbf26SKevin Tian }
244258fbbf26SKevin Tian EXPORT_SYMBOL_GPL(kvm_lapic_set_eoi);
244358fbbf26SKevin Tian 
2444beef3353SSean Christopherson #define X2APIC_ICR_RESERVED_BITS (GENMASK_ULL(31, 20) | GENMASK_ULL(17, 16) | BIT(13))
2445beef3353SSean Christopherson 
kvm_x2apic_icr_write(struct kvm_lapic * apic,u64 data)2446beef3353SSean Christopherson int kvm_x2apic_icr_write(struct kvm_lapic *apic, u64 data)
2447beef3353SSean Christopherson {
2448beef3353SSean Christopherson 	if (data & X2APIC_ICR_RESERVED_BITS)
2449beef3353SSean Christopherson 		return 1;
2450beef3353SSean Christopherson 
2451beef3353SSean Christopherson 	/*
2452beef3353SSean Christopherson 	 * The BUSY bit is reserved on both Intel and AMD in x2APIC mode, but
2453beef3353SSean Christopherson 	 * only AMD requires it to be zero, Intel essentially just ignores the
2454beef3353SSean Christopherson 	 * bit.  And if IPI virtualization (Intel) or x2AVIC (AMD) is enabled,
2455beef3353SSean Christopherson 	 * the CPU performs the reserved bits checks, i.e. the underlying CPU
2456beef3353SSean Christopherson 	 * behavior will "win".  Arbitrarily clear the BUSY bit, as there is no
2457beef3353SSean Christopherson 	 * sane way to provide consistent behavior with respect to hardware.
2458beef3353SSean Christopherson 	 */
2459beef3353SSean Christopherson 	data &= ~APIC_ICR_BUSY;
2460beef3353SSean Christopherson 
2461beef3353SSean Christopherson 	kvm_apic_send_ipi(apic, (u32)data, (u32)(data >> 32));
2462*e8ad068cSSean Christopherson 	if (kvm_x86_ops.x2apic_icr_is_split) {
2463*e8ad068cSSean Christopherson 		kvm_lapic_set_reg(apic, APIC_ICR, data);
2464*e8ad068cSSean Christopherson 		kvm_lapic_set_reg(apic, APIC_ICR2, data >> 32);
2465*e8ad068cSSean Christopherson 	} else {
2466beef3353SSean Christopherson 		kvm_lapic_set_reg64(apic, APIC_ICR, data);
2467*e8ad068cSSean Christopherson 	}
2468beef3353SSean Christopherson 	trace_kvm_apic_write(APIC_ICR, data);
2469beef3353SSean Christopherson 	return 0;
2470beef3353SSean Christopherson }
2471beef3353SSean Christopherson 
kvm_x2apic_icr_read(struct kvm_lapic * apic)2472*e8ad068cSSean Christopherson static u64 kvm_x2apic_icr_read(struct kvm_lapic *apic)
2473*e8ad068cSSean Christopherson {
2474*e8ad068cSSean Christopherson 	if (kvm_x86_ops.x2apic_icr_is_split)
2475*e8ad068cSSean Christopherson 		return (u64)kvm_lapic_get_reg(apic, APIC_ICR) |
2476*e8ad068cSSean Christopherson 		       (u64)kvm_lapic_get_reg(apic, APIC_ICR2) << 32;
2477*e8ad068cSSean Christopherson 
2478*e8ad068cSSean Christopherson 	return kvm_lapic_get_reg64(apic, APIC_ICR);
2479*e8ad068cSSean Christopherson }
2480*e8ad068cSSean Christopherson 
248183d4c286SYang Zhang /* emulate APIC access in a trap manner */
kvm_apic_write_nodecode(struct kvm_vcpu * vcpu,u32 offset)248283d4c286SYang Zhang void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset)
248383d4c286SYang Zhang {
24845413bcbaSZeng Guang 	struct kvm_lapic *apic = vcpu->arch.apic;
24855413bcbaSZeng Guang 
24861bd9dfecSSuravee Suthikulpanit 	/*
2487fb05c7b9STao Su 	 * ICR is a single 64-bit register when x2APIC is enabled, all others
2488fb05c7b9STao Su 	 * registers hold 32-bit values.  For legacy xAPIC, ICR writes need to
2489fb05c7b9STao Su 	 * go down the common path to get the upper half from ICR2.
2490fb05c7b9STao Su 	 *
2491fb05c7b9STao Su 	 * Note, using the write helpers may incur an unnecessary write to the
2492fb05c7b9STao Su 	 * virtual APIC state, but KVM needs to conditionally modify the value
2493fb05c7b9STao Su 	 * in certain cases, e.g. to clear the ICR busy bit.  The cost of extra
2494fb05c7b9STao Su 	 * conditional branches is likely a wash relative to the cost of the
2495fb05c7b9STao Su 	 * maybe-unecessary write, and both are in the noise anyways.
24961bd9dfecSSuravee Suthikulpanit 	 */
2497fb05c7b9STao Su 	if (apic_x2apic_mode(apic) && offset == APIC_ICR)
2498*e8ad068cSSean Christopherson 		WARN_ON_ONCE(kvm_x2apic_icr_write(apic, kvm_x2apic_icr_read(apic)));
2499fb05c7b9STao Su 	else
2500fb05c7b9STao Su 		kvm_lapic_reg_write(apic, offset, kvm_lapic_get_reg(apic, offset));
250183d4c286SYang Zhang }
250283d4c286SYang Zhang EXPORT_SYMBOL_GPL(kvm_apic_write_nodecode);
250383d4c286SYang Zhang 
kvm_free_lapic(struct kvm_vcpu * vcpu)2504edf88417SAvi Kivity void kvm_free_lapic(struct kvm_vcpu *vcpu)
2505edf88417SAvi Kivity {
2506f8c1ea10SGleb Natapov 	struct kvm_lapic *apic = vcpu->arch.apic;
2507f8c1ea10SGleb Natapov 
2508edf88417SAvi Kivity 	if (!vcpu->arch.apic)
2509edf88417SAvi Kivity 		return;
2510edf88417SAvi Kivity 
2511f8c1ea10SGleb Natapov 	hrtimer_cancel(&apic->lapic_timer.timer);
2512edf88417SAvi Kivity 
2513c5cc421bSGleb Natapov 	if (!(vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE))
25146e4e3b4dSCun Li 		static_branch_slow_dec_deferred(&apic_hw_disabled);
2515c5cc421bSGleb Natapov 
2516e462755cSRadim Krčmář 	if (!apic->sw_enabled)
25176e4e3b4dSCun Li 		static_branch_slow_dec_deferred(&apic_sw_disabled);
2518edf88417SAvi Kivity 
2519f8c1ea10SGleb Natapov 	if (apic->regs)
2520f8c1ea10SGleb Natapov 		free_page((unsigned long)apic->regs);
2521f8c1ea10SGleb Natapov 
2522f8c1ea10SGleb Natapov 	kfree(apic);
2523edf88417SAvi Kivity }
2524edf88417SAvi Kivity 
2525edf88417SAvi Kivity /*
2526edf88417SAvi Kivity  *----------------------------------------------------------------------
2527edf88417SAvi Kivity  * LAPIC interface
2528edf88417SAvi Kivity  *----------------------------------------------------------------------
2529edf88417SAvi Kivity  */
kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu * vcpu)2530a3e06bbeSLiu, Jinsong u64 kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu)
2531a3e06bbeSLiu, Jinsong {
2532a3e06bbeSLiu, Jinsong 	struct kvm_lapic *apic = vcpu->arch.apic;
2533a3e06bbeSLiu, Jinsong 
2534a970e9b2SWanpeng Li 	if (!kvm_apic_present(vcpu) || !apic_lvtt_tscdeadline(apic))
2535a3e06bbeSLiu, Jinsong 		return 0;
2536a3e06bbeSLiu, Jinsong 
2537a3e06bbeSLiu, Jinsong 	return apic->lapic_timer.tscdeadline;
2538a3e06bbeSLiu, Jinsong }
2539a3e06bbeSLiu, Jinsong 
kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu * vcpu,u64 data)2540a3e06bbeSLiu, Jinsong void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data)
2541a3e06bbeSLiu, Jinsong {
2542a3e06bbeSLiu, Jinsong 	struct kvm_lapic *apic = vcpu->arch.apic;
2543a3e06bbeSLiu, Jinsong 
254427503833SWanpeng Li 	if (!kvm_apic_present(vcpu) || !apic_lvtt_tscdeadline(apic))
2545a3e06bbeSLiu, Jinsong 		return;
2546a3e06bbeSLiu, Jinsong 
2547a3e06bbeSLiu, Jinsong 	hrtimer_cancel(&apic->lapic_timer.timer);
2548a3e06bbeSLiu, Jinsong 	apic->lapic_timer.tscdeadline = data;
2549a3e06bbeSLiu, Jinsong 	start_apic_timer(apic);
2550a3e06bbeSLiu, Jinsong }
2551a3e06bbeSLiu, Jinsong 
kvm_lapic_set_tpr(struct kvm_vcpu * vcpu,unsigned long cr8)2552edf88417SAvi Kivity void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8)
2553edf88417SAvi Kivity {
2554f66af9f2SZhenzhong Duan 	apic_set_tpr(vcpu->arch.apic, (cr8 & 0x0f) << 4);
2555edf88417SAvi Kivity }
2556edf88417SAvi Kivity 
kvm_lapic_get_cr8(struct kvm_vcpu * vcpu)2557edf88417SAvi Kivity u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
2558edf88417SAvi Kivity {
2559edf88417SAvi Kivity 	u64 tpr;
2560edf88417SAvi Kivity 
2561dfb95954SSuravee Suthikulpanit 	tpr = (u64) kvm_lapic_get_reg(vcpu->arch.apic, APIC_TASKPRI);
2562edf88417SAvi Kivity 
2563edf88417SAvi Kivity 	return (tpr & 0xf0) >> 4;
2564edf88417SAvi Kivity }
2565edf88417SAvi Kivity 
kvm_lapic_set_base(struct kvm_vcpu * vcpu,u64 value)2566edf88417SAvi Kivity void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
2567edf88417SAvi Kivity {
25688d14695fSYang Zhang 	u64 old_value = vcpu->arch.apic_base;
2569edf88417SAvi Kivity 	struct kvm_lapic *apic = vcpu->arch.apic;
2570edf88417SAvi Kivity 
2571e66d2ae7SJan Kiszka 	vcpu->arch.apic_base = value;
2572e66d2ae7SJan Kiszka 
2573c7dd15b3SJim Mattson 	if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE)
2574aedbaf4fSXiaoyao Li 		kvm_update_cpuid_runtime(vcpu);
2575c7dd15b3SJim Mattson 
2576c7dd15b3SJim Mattson 	if (!apic)
2577c7dd15b3SJim Mattson 		return;
2578c7dd15b3SJim Mattson 
2579c5cc421bSGleb Natapov 	/* update jump label if enable bit changes */
25800dce7cd6SAndrew Jones 	if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE) {
258149bd29baSRadim Krčmář 		if (value & MSR_IA32_APICBASE_ENABLE) {
258249bd29baSRadim Krčmář 			kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
25836e4e3b4dSCun Li 			static_branch_slow_dec_deferred(&apic_hw_disabled);
25842f15d027SVitaly Kuznetsov 			/* Check if there are APF page ready requests pending */
25852f15d027SVitaly Kuznetsov 			kvm_make_request(KVM_REQ_APF_READY, vcpu);
2586187ca84bSWanpeng Li 		} else {
25876e4e3b4dSCun Li 			static_branch_inc(&apic_hw_disabled.key);
258844d52717SPaolo Bonzini 			atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
2589c5cc421bSGleb Natapov 		}
2590187ca84bSWanpeng Li 	}
2591c5cc421bSGleb Natapov 
2592052c3b99SEmanuele Giuseppe Esposito 	if ((old_value ^ value) & X2APIC_ENABLE) {
2593052c3b99SEmanuele Giuseppe Esposito 		if (value & X2APIC_ENABLE)
2594257b9a5fSRadim Krčmář 			kvm_apic_set_x2apic_id(apic, vcpu->vcpu_id);
2595052c3b99SEmanuele Giuseppe Esposito 		else if (value & MSR_IA32_APICBASE_ENABLE)
2596052c3b99SEmanuele Giuseppe Esposito 			kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2597052c3b99SEmanuele Giuseppe Esposito 	}
25988d860bbeSJim Mattson 
25998fc9c7a3SSuravee Suthikulpanit 	if ((old_value ^ value) & (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) {
26001459f5c6SSean Christopherson 		kvm_make_request(KVM_REQ_APICV_UPDATE, vcpu);
2601abb6d479SPaolo Bonzini 		static_call_cond(kvm_x86_set_virtual_apic_mode)(vcpu);
26028fc9c7a3SSuravee Suthikulpanit 	}
26038d14695fSYang Zhang 
2604edf88417SAvi Kivity 	apic->base_address = apic->vcpu->arch.apic_base &
2605edf88417SAvi Kivity 			     MSR_IA32_APICBASE_BASE;
2606edf88417SAvi Kivity 
2607db324fe6SNadav Amit 	if ((value & MSR_IA32_APICBASE_ENABLE) &&
26083743c2f0SMaxim Levitsky 	     apic->base_address != APIC_DEFAULT_PHYS_BASE) {
26093743c2f0SMaxim Levitsky 		kvm_set_apicv_inhibit(apic->vcpu->kvm,
26103743c2f0SMaxim Levitsky 				      APICV_INHIBIT_REASON_APIC_BASE_MODIFIED);
26113743c2f0SMaxim Levitsky 	}
2612edf88417SAvi Kivity }
2613edf88417SAvi Kivity 
kvm_apic_update_apicv(struct kvm_vcpu * vcpu)2614b26a695aSSuravee Suthikulpanit void kvm_apic_update_apicv(struct kvm_vcpu *vcpu)
2615b26a695aSSuravee Suthikulpanit {
2616b26a695aSSuravee Suthikulpanit 	struct kvm_lapic *apic = vcpu->arch.apic;
2617b26a695aSSuravee Suthikulpanit 
2618755c2bf8SMaxim Levitsky 	/*
26194b7522b0SSean Christopherson 	 * When APICv is enabled, KVM must always search the IRR for a pending
26204b7522b0SSean Christopherson 	 * IRQ, as other vCPUs and devices can set IRR bits even if the vCPU
26214b7522b0SSean Christopherson 	 * isn't running.  If APICv is disabled, KVM _should_ search the IRR
26224b7522b0SSean Christopherson 	 * for a pending IRQ.  But KVM currently doesn't ensure *all* hardware,
26234b7522b0SSean Christopherson 	 * e.g. CPUs and IOMMUs, has seen the change in state, i.e. searching
26244b7522b0SSean Christopherson 	 * the IRR at this time could race with IRQ delivery from hardware that
26254b7522b0SSean Christopherson 	 * still sees APICv as being enabled.
26264b7522b0SSean Christopherson 	 *
26274b7522b0SSean Christopherson 	 * FIXME: Ensure other vCPUs and devices observe the change in APICv
26284b7522b0SSean Christopherson 	 *        state prior to updating KVM's metadata caches, so that KVM
26294b7522b0SSean Christopherson 	 *        can safely search the IRR and set irr_pending accordingly.
2630755c2bf8SMaxim Levitsky 	 */
26314b7522b0SSean Christopherson 	apic->irr_pending = true;
26324b7522b0SSean Christopherson 
26334b7522b0SSean Christopherson 	if (apic->apicv_active)
26344b7522b0SSean Christopherson 		apic->isr_count = 1;
26354b7522b0SSean Christopherson 	else
2636b26a695aSSuravee Suthikulpanit 		apic->isr_count = count_vectors(apic->regs + APIC_ISR);
26374b7522b0SSean Christopherson 
263897a71c44SSean Christopherson 	apic->highest_isr_cache = -1;
2639b26a695aSSuravee Suthikulpanit }
2640b26a695aSSuravee Suthikulpanit 
kvm_alloc_apic_access_page(struct kvm * kvm)2641c482f2ceSSean Christopherson int kvm_alloc_apic_access_page(struct kvm *kvm)
2642c482f2ceSSean Christopherson {
2643c482f2ceSSean Christopherson 	struct page *page;
2644c482f2ceSSean Christopherson 	void __user *hva;
2645c482f2ceSSean Christopherson 	int ret = 0;
2646c482f2ceSSean Christopherson 
2647c482f2ceSSean Christopherson 	mutex_lock(&kvm->slots_lock);
26482008fab3SSean Christopherson 	if (kvm->arch.apic_access_memslot_enabled ||
26492008fab3SSean Christopherson 	    kvm->arch.apic_access_memslot_inhibited)
2650c482f2ceSSean Christopherson 		goto out;
2651c482f2ceSSean Christopherson 
2652c482f2ceSSean Christopherson 	hva = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
2653c482f2ceSSean Christopherson 				      APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
2654c482f2ceSSean Christopherson 	if (IS_ERR(hva)) {
2655c482f2ceSSean Christopherson 		ret = PTR_ERR(hva);
2656c482f2ceSSean Christopherson 		goto out;
2657c482f2ceSSean Christopherson 	}
2658c482f2ceSSean Christopherson 
2659c482f2ceSSean Christopherson 	page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
2660c482f2ceSSean Christopherson 	if (is_error_page(page)) {
2661c482f2ceSSean Christopherson 		ret = -EFAULT;
2662c482f2ceSSean Christopherson 		goto out;
2663c482f2ceSSean Christopherson 	}
2664c482f2ceSSean Christopherson 
2665c482f2ceSSean Christopherson 	/*
2666c482f2ceSSean Christopherson 	 * Do not pin the page in memory, so that memory hot-unplug
2667c482f2ceSSean Christopherson 	 * is able to migrate it.
2668c482f2ceSSean Christopherson 	 */
2669c482f2ceSSean Christopherson 	put_page(page);
2670c482f2ceSSean Christopherson 	kvm->arch.apic_access_memslot_enabled = true;
2671c482f2ceSSean Christopherson out:
2672c482f2ceSSean Christopherson 	mutex_unlock(&kvm->slots_lock);
2673c482f2ceSSean Christopherson 	return ret;
2674c482f2ceSSean Christopherson }
2675c482f2ceSSean Christopherson EXPORT_SYMBOL_GPL(kvm_alloc_apic_access_page);
2676c482f2ceSSean Christopherson 
kvm_inhibit_apic_access_page(struct kvm_vcpu * vcpu)26772008fab3SSean Christopherson void kvm_inhibit_apic_access_page(struct kvm_vcpu *vcpu)
26782008fab3SSean Christopherson {
26792008fab3SSean Christopherson 	struct kvm *kvm = vcpu->kvm;
26802008fab3SSean Christopherson 
26812008fab3SSean Christopherson 	if (!kvm->arch.apic_access_memslot_enabled)
26822008fab3SSean Christopherson 		return;
26832008fab3SSean Christopherson 
26842008fab3SSean Christopherson 	kvm_vcpu_srcu_read_unlock(vcpu);
26852008fab3SSean Christopherson 
26862008fab3SSean Christopherson 	mutex_lock(&kvm->slots_lock);
26872008fab3SSean Christopherson 
26882008fab3SSean Christopherson 	if (kvm->arch.apic_access_memslot_enabled) {
26892008fab3SSean Christopherson 		__x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
26902008fab3SSean Christopherson 		/*
26912008fab3SSean Christopherson 		 * Clear "enabled" after the memslot is deleted so that a
26922008fab3SSean Christopherson 		 * different vCPU doesn't get a false negative when checking
26932008fab3SSean Christopherson 		 * the flag out of slots_lock.  No additional memory barrier is
26942008fab3SSean Christopherson 		 * needed as modifying memslots requires waiting other vCPUs to
26952008fab3SSean Christopherson 		 * drop SRCU (see above), and false positives are ok as the
26962008fab3SSean Christopherson 		 * flag is rechecked after acquiring slots_lock.
26972008fab3SSean Christopherson 		 */
26982008fab3SSean Christopherson 		kvm->arch.apic_access_memslot_enabled = false;
26992008fab3SSean Christopherson 
27002008fab3SSean Christopherson 		/*
27012008fab3SSean Christopherson 		 * Mark the memslot as inhibited to prevent reallocating the
27022008fab3SSean Christopherson 		 * memslot during vCPU creation, e.g. if a vCPU is hotplugged.
27032008fab3SSean Christopherson 		 */
27042008fab3SSean Christopherson 		kvm->arch.apic_access_memslot_inhibited = true;
27052008fab3SSean Christopherson 	}
27062008fab3SSean Christopherson 
27072008fab3SSean Christopherson 	mutex_unlock(&kvm->slots_lock);
27082008fab3SSean Christopherson 
27092008fab3SSean Christopherson 	kvm_vcpu_srcu_read_lock(vcpu);
2710edf88417SAvi Kivity }
2711edf88417SAvi Kivity 
kvm_lapic_reset(struct kvm_vcpu * vcpu,bool init_event)2712edf88417SAvi Kivity void kvm_lapic_reset(struct kvm_vcpu *vcpu, bool init_event)
2713edf88417SAvi Kivity {
2714edf88417SAvi Kivity 	struct kvm_lapic *apic = vcpu->arch.apic;
2715d28bc9ddSNadav Amit 	u64 msr_val;
2716edf88417SAvi Kivity 	int i;
2717b7e31be3SRadim Krčmář 
27187de33b0fSHaitao Shan 	static_call_cond(kvm_x86_apicv_pre_state_restore)(vcpu);
27197de33b0fSHaitao Shan 
27204547700aSSean Christopherson 	if (!init_event) {
2721f7d8a19fSSean Christopherson 		msr_val = APIC_DEFAULT_PHYS_BASE | MSR_IA32_APICBASE_ENABLE;
27224547700aSSean Christopherson 		if (kvm_vcpu_is_reset_bsp(vcpu))
2723f7d8a19fSSean Christopherson 			msr_val |= MSR_IA32_APICBASE_BSP;
2724f7d8a19fSSean Christopherson 		kvm_lapic_set_base(vcpu, msr_val);
27254547700aSSean Christopherson 	}
27264547700aSSean Christopherson 
2727b7e31be3SRadim Krčmář 	if (!apic)
2728b7e31be3SRadim Krčmář 		return;
2729edf88417SAvi Kivity 
2730edf88417SAvi Kivity 	/* Stop the timer in case it's a reset to an active apic */
2731d3c7b77dSMarcelo Tosatti 	hrtimer_cancel(&apic->lapic_timer.timer);
2732edf88417SAvi Kivity 
2733f7d8a19fSSean Christopherson 	/* The xAPIC ID is set at RESET even if the APIC was already enabled. */
2734f7d8a19fSSean Christopherson 	if (!init_event)
2735a92e2543SRadim Krčmář 		kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2736fc61b800SGleb Natapov 	kvm_apic_set_version(apic->vcpu);
2737edf88417SAvi Kivity 
27384b903561SJue Wang 	for (i = 0; i < apic->nr_lvt_entries; i++)
2739987f625eSJue Wang 		kvm_lapic_set_reg(apic, APIC_LVTx(i), APIC_LVT_MASKED);
2740b6ac0695SRadim Krčmář 	apic_update_lvtt(apic);
274152b54190SJan H. Schönherr 	if (kvm_vcpu_is_reset_bsp(vcpu) &&
274252b54190SJan H. Schönherr 	    kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_LINT0_REENABLED))
27431e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, APIC_LVT0,
2744edf88417SAvi Kivity 			     SET_APIC_DELIVERY_MODE(0, APIC_MODE_EXTINT));
2745dfb95954SSuravee Suthikulpanit 	apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2746edf88417SAvi Kivity 
2747ae6f2496SWanpeng Li 	kvm_apic_set_dfr(apic, 0xffffffffU);
2748f8c1ea10SGleb Natapov 	apic_set_spiv(apic, 0xff);
27491e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_TASKPRI, 0);
2750c028dd6bSRadim Krčmář 	if (!apic_x2apic_mode(apic))
27511e08ec4aSGleb Natapov 		kvm_apic_set_ldr(apic, 0);
27521e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_ESR, 0);
2753a57a3168SSean Christopherson 	if (!apic_x2apic_mode(apic)) {
27541e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, APIC_ICR, 0);
27551e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, APIC_ICR2, 0);
2756a57a3168SSean Christopherson 	} else {
2757a57a3168SSean Christopherson 		kvm_lapic_set_reg64(apic, APIC_ICR, 0);
2758a57a3168SSean Christopherson 	}
27591e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_TDCR, 0);
27601e6e2755SSuravee Suthikulpanit 	kvm_lapic_set_reg(apic, APIC_TMICT, 0);
2761edf88417SAvi Kivity 	for (i = 0; i < 8; i++) {
27621e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, APIC_IRR + 0x10 * i, 0);
27631e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, APIC_ISR + 0x10 * i, 0);
27641e6e2755SSuravee Suthikulpanit 		kvm_lapic_set_reg(apic, APIC_TMR + 0x10 * i, 0);
2765edf88417SAvi Kivity 	}
2766b26a695aSSuravee Suthikulpanit 	kvm_apic_update_apicv(vcpu);
2767edf88417SAvi Kivity 	update_divide_count(apic);
2768d3c7b77dSMarcelo Tosatti 	atomic_set(&apic->lapic_timer.pending, 0);
2769549240e8SSean Christopherson 
2770ae7a2a3fSMichael S. Tsirkin 	vcpu->arch.pv_eoi.msr_val = 0;
2771edf88417SAvi Kivity 	apic_update_ppr(apic);
2772ce0a58f4SSean Christopherson 	if (apic->apicv_active) {
2773abb6d479SPaolo Bonzini 		static_call_cond(kvm_x86_apicv_post_state_restore)(vcpu);
2774abb6d479SPaolo Bonzini 		static_call_cond(kvm_x86_hwapic_irr_update)(vcpu, -1);
2775d39850f5SSean Christopherson 		static_call_cond(kvm_x86_hwapic_isr_update)(-1);
27764191db26SJan H. Schönherr 	}
2777edf88417SAvi Kivity 
2778e1035715SGleb Natapov 	vcpu->arch.apic_arb_prio = 0;
277941383771SGleb Natapov 	vcpu->arch.apic_attention = 0;
27804abaffceSWanpeng Li 
27814abaffceSWanpeng Li 	kvm_recalculate_apic_map(vcpu->kvm);
2782edf88417SAvi Kivity }
2783edf88417SAvi Kivity 
2784edf88417SAvi Kivity /*
2785edf88417SAvi Kivity  *----------------------------------------------------------------------
2786edf88417SAvi Kivity  * timer interface
2787edf88417SAvi Kivity  *----------------------------------------------------------------------
2788edf88417SAvi Kivity  */
2789edf88417SAvi Kivity 
lapic_is_periodic(struct kvm_lapic * apic)27902a6eac96SAvi Kivity static bool lapic_is_periodic(struct kvm_lapic *apic)
2791edf88417SAvi Kivity {
2792d3c7b77dSMarcelo Tosatti 	return apic_lvtt_period(apic);
2793edf88417SAvi Kivity }
2794edf88417SAvi Kivity 
apic_has_pending_timer(struct kvm_vcpu * vcpu)27953d80840dSMarcelo Tosatti int apic_has_pending_timer(struct kvm_vcpu *vcpu)
27963d80840dSMarcelo Tosatti {
279754e9818fSGleb Natapov 	struct kvm_lapic *apic = vcpu->arch.apic;
27983d80840dSMarcelo Tosatti 
27991e3161b4SPaolo Bonzini 	if (apic_enabled(apic) && apic_lvt_enabled(apic, APIC_LVTT))
280054e9818fSGleb Natapov 		return atomic_read(&apic->lapic_timer.pending);
28013d80840dSMarcelo Tosatti 
28023d80840dSMarcelo Tosatti 	return 0;
28033d80840dSMarcelo Tosatti }
28043d80840dSMarcelo Tosatti 
kvm_apic_local_deliver(struct kvm_lapic * apic,int lvt_type)280589342082SAvi Kivity int kvm_apic_local_deliver(struct kvm_lapic *apic, int lvt_type)
2806edf88417SAvi Kivity {
2807dfb95954SSuravee Suthikulpanit 	u32 reg = kvm_lapic_get_reg(apic, lvt_type);
280823930f95SJan Kiszka 	int vector, mode, trig_mode;
2809a16eb25bSJim Mattson 	int r;
2810edf88417SAvi Kivity 
2811c48f1496SGleb Natapov 	if (kvm_apic_hw_enabled(apic) && !(reg & APIC_LVT_MASKED)) {
281223930f95SJan Kiszka 		vector = reg & APIC_VECTOR_MASK;
281323930f95SJan Kiszka 		mode = reg & APIC_MODE_MASK;
281423930f95SJan Kiszka 		trig_mode = reg & APIC_LVT_LEVEL_TRIGGER;
2815a16eb25bSJim Mattson 
2816a16eb25bSJim Mattson 		r = __apic_accept_irq(apic, mode, vector, 1, trig_mode, NULL);
2817947d518eSSandipan Das 		if (r && lvt_type == APIC_LVTPC &&
2818947d518eSSandipan Das 		    guest_cpuid_is_intel_compatible(apic->vcpu))
2819a16eb25bSJim Mattson 			kvm_lapic_set_reg(apic, APIC_LVTPC, reg | APIC_LVT_MASKED);
2820a16eb25bSJim Mattson 		return r;
282123930f95SJan Kiszka 	}
282223930f95SJan Kiszka 	return 0;
282323930f95SJan Kiszka }
282423930f95SJan Kiszka 
kvm_apic_nmi_wd_deliver(struct kvm_vcpu * vcpu)28258fdb2351SJan Kiszka void kvm_apic_nmi_wd_deliver(struct kvm_vcpu *vcpu)
282623930f95SJan Kiszka {
28278fdb2351SJan Kiszka 	struct kvm_lapic *apic = vcpu->arch.apic;
28288fdb2351SJan Kiszka 
28298fdb2351SJan Kiszka 	if (apic)
28308fdb2351SJan Kiszka 		kvm_apic_local_deliver(apic, APIC_LVT0);
2831edf88417SAvi Kivity }
2832edf88417SAvi Kivity 
2833d76685c4SGregory Haskins static const struct kvm_io_device_ops apic_mmio_ops = {
2834d76685c4SGregory Haskins 	.read     = apic_mmio_read,
2835d76685c4SGregory Haskins 	.write    = apic_mmio_write,
2836d76685c4SGregory Haskins };
2837d76685c4SGregory Haskins 
apic_timer_fn(struct hrtimer * data)2838e9d90d47SAvi Kivity static enum hrtimer_restart apic_timer_fn(struct hrtimer *data)
2839e9d90d47SAvi Kivity {
2840e9d90d47SAvi Kivity 	struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
28412a6eac96SAvi Kivity 	struct kvm_lapic *apic = container_of(ktimer, struct kvm_lapic, lapic_timer);
2842e9d90d47SAvi Kivity 
2843ae95f566SWanpeng Li 	apic_timer_expired(apic, true);
2844e9d90d47SAvi Kivity 
28452a6eac96SAvi Kivity 	if (lapic_is_periodic(apic)) {
28468003c9aeSWanpeng Li 		advance_periodic_target_expiration(apic);
2847e9d90d47SAvi Kivity 		hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
2848e9d90d47SAvi Kivity 		return HRTIMER_RESTART;
2849e9d90d47SAvi Kivity 	} else
2850e9d90d47SAvi Kivity 		return HRTIMER_NORESTART;
2851e9d90d47SAvi Kivity }
2852e9d90d47SAvi Kivity 
kvm_create_lapic(struct kvm_vcpu * vcpu,int timer_advance_ns)2853c3941d9eSSean Christopherson int kvm_create_lapic(struct kvm_vcpu *vcpu, int timer_advance_ns)
2854edf88417SAvi Kivity {
2855edf88417SAvi Kivity 	struct kvm_lapic *apic;
2856edf88417SAvi Kivity 
2857edf88417SAvi Kivity 	ASSERT(vcpu != NULL);
2858edf88417SAvi Kivity 
2859254272ceSBen Gardon 	apic = kzalloc(sizeof(*apic), GFP_KERNEL_ACCOUNT);
2860edf88417SAvi Kivity 	if (!apic)
2861edf88417SAvi Kivity 		goto nomem;
2862edf88417SAvi Kivity 
2863edf88417SAvi Kivity 	vcpu->arch.apic = apic;
2864edf88417SAvi Kivity 
2865254272ceSBen Gardon 	apic->regs = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
2866afc20184STakuya Yoshikawa 	if (!apic->regs) {
2867edf88417SAvi Kivity 		printk(KERN_ERR "malloc apic regs error for vcpu %x\n",
2868edf88417SAvi Kivity 		       vcpu->vcpu_id);
2869edf88417SAvi Kivity 		goto nomem_free_apic;
2870edf88417SAvi Kivity 	}
2871edf88417SAvi Kivity 	apic->vcpu = vcpu;
2872edf88417SAvi Kivity 
287303d84f96SSean Christopherson 	apic->nr_lvt_entries = kvm_apic_calc_nr_lvt_entries(vcpu);
287403d84f96SSean Christopherson 
2875d3c7b77dSMarcelo Tosatti 	hrtimer_init(&apic->lapic_timer.timer, CLOCK_MONOTONIC,
28762c0d278fSSebastian Andrzej Siewior 		     HRTIMER_MODE_ABS_HARD);
2877e9d90d47SAvi Kivity 	apic->lapic_timer.timer.function = apic_timer_fn;
2878c3941d9eSSean Christopherson 	if (timer_advance_ns == -1) {
2879a0f0037eSWanpeng Li 		apic->lapic_timer.timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
2880d0f5a86aSWanpeng Li 		lapic_timer_advance_dynamic = true;
2881c3941d9eSSean Christopherson 	} else {
288239497d76SSean Christopherson 		apic->lapic_timer.timer_advance_ns = timer_advance_ns;
2883d0f5a86aSWanpeng Li 		lapic_timer_advance_dynamic = false;
2884c3941d9eSSean Christopherson 	}
2885c3941d9eSSean Christopherson 
2886f7d8a19fSSean Christopherson 	/*
2887f7d8a19fSSean Christopherson 	 * Stuff the APIC ENABLE bit in lieu of temporarily incrementing
2888f7d8a19fSSean Christopherson 	 * apic_hw_disabled; the full RESET value is set by kvm_lapic_reset().
2889f7d8a19fSSean Christopherson 	 */
2890f7d8a19fSSean Christopherson 	vcpu->arch.apic_base = MSR_IA32_APICBASE_ENABLE;
28916e4e3b4dSCun Li 	static_branch_inc(&apic_sw_disabled.key); /* sw disabled at reset */
2892d76685c4SGregory Haskins 	kvm_iodevice_init(&apic->dev, &apic_mmio_ops);
2893edf88417SAvi Kivity 
2894edf88417SAvi Kivity 	return 0;
2895edf88417SAvi Kivity nomem_free_apic:
2896edf88417SAvi Kivity 	kfree(apic);
2897a251fb90SSaar Amar 	vcpu->arch.apic = NULL;
2898edf88417SAvi Kivity nomem:
2899edf88417SAvi Kivity 	return -ENOMEM;
2900edf88417SAvi Kivity }
2901edf88417SAvi Kivity 
kvm_apic_has_interrupt(struct kvm_vcpu * vcpu)2902edf88417SAvi Kivity int kvm_apic_has_interrupt(struct kvm_vcpu *vcpu)
2903edf88417SAvi Kivity {
2904edf88417SAvi Kivity 	struct kvm_lapic *apic = vcpu->arch.apic;
2905b3c045d3SPaolo Bonzini 	u32 ppr;
2906edf88417SAvi Kivity 
290772c3bcdcSPaolo Bonzini 	if (!kvm_apic_present(vcpu))
2908edf88417SAvi Kivity 		return -1;
2909edf88417SAvi Kivity 
2910b3c045d3SPaolo Bonzini 	__apic_update_ppr(apic, &ppr);
2911b3c045d3SPaolo Bonzini 	return apic_has_interrupt_for_ppr(apic, ppr);
2912edf88417SAvi Kivity }
291325bb2cf9SSean Christopherson EXPORT_SYMBOL_GPL(kvm_apic_has_interrupt);
2914edf88417SAvi Kivity 
kvm_apic_accept_pic_intr(struct kvm_vcpu * vcpu)2915edf88417SAvi Kivity int kvm_apic_accept_pic_intr(struct kvm_vcpu *vcpu)
2916edf88417SAvi Kivity {
2917dfb95954SSuravee Suthikulpanit 	u32 lvt0 = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVT0);
2918edf88417SAvi Kivity 
2919c48f1496SGleb Natapov 	if (!kvm_apic_hw_enabled(vcpu->arch.apic))
29203ce4dc17SMiaohe Lin 		return 1;
2921edf88417SAvi Kivity 	if ((lvt0 & APIC_LVT_MASKED) == 0 &&
2922edf88417SAvi Kivity 	    GET_APIC_DELIVERY_MODE(lvt0) == APIC_MODE_EXTINT)
29233ce4dc17SMiaohe Lin 		return 1;
29243ce4dc17SMiaohe Lin 	return 0;
2925edf88417SAvi Kivity }
2926edf88417SAvi Kivity 
kvm_inject_apic_timer_irqs(struct kvm_vcpu * vcpu)2927edf88417SAvi Kivity void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu)
2928edf88417SAvi Kivity {
2929edf88417SAvi Kivity 	struct kvm_lapic *apic = vcpu->arch.apic;
2930edf88417SAvi Kivity 
293154e9818fSGleb Natapov 	if (atomic_read(&apic->lapic_timer.pending) > 0) {
29320c5f81daSWanpeng Li 		kvm_apic_inject_pending_timer_irqs(apic);
2933f1ed0450SJan Kiszka 		atomic_set(&apic->lapic_timer.pending, 0);
2934edf88417SAvi Kivity 	}
2935edf88417SAvi Kivity }
2936edf88417SAvi Kivity 
kvm_get_apic_interrupt(struct kvm_vcpu * vcpu)2937edf88417SAvi Kivity int kvm_get_apic_interrupt(struct kvm_vcpu *vcpu)
2938edf88417SAvi Kivity {
2939edf88417SAvi Kivity 	int vector = kvm_apic_has_interrupt(vcpu);
2940edf88417SAvi Kivity 	struct kvm_lapic *apic = vcpu->arch.apic;
29414d82d12bSPaolo Bonzini 	u32 ppr;
2942edf88417SAvi Kivity 
2943edf88417SAvi Kivity 	if (vector == -1)
2944edf88417SAvi Kivity 		return -1;
2945edf88417SAvi Kivity 
294656cc2406SWanpeng Li 	/*
294756cc2406SWanpeng Li 	 * We get here even with APIC virtualization enabled, if doing
294856cc2406SWanpeng Li 	 * nested virtualization and L1 runs with the "acknowledge interrupt
294956cc2406SWanpeng Li 	 * on exit" mode.  Then we cannot inject the interrupt via RVI,
295056cc2406SWanpeng Li 	 * because the process would deliver it through the IDT.
295156cc2406SWanpeng Li 	 */
295256cc2406SWanpeng Li 
2953edf88417SAvi Kivity 	apic_clear_irr(vector, apic);
2954f2bc14b6SVitaly Kuznetsov 	if (to_hv_vcpu(vcpu) && test_bit(vector, to_hv_synic(vcpu)->auto_eoi_bitmap)) {
29554d82d12bSPaolo Bonzini 		/*
29564d82d12bSPaolo Bonzini 		 * For auto-EOI interrupts, there might be another pending
29574d82d12bSPaolo Bonzini 		 * interrupt above PPR, so check whether to raise another
29584d82d12bSPaolo Bonzini 		 * KVM_REQ_EVENT.
29594d82d12bSPaolo Bonzini 		 */
29605c919412SAndrey Smetanin 		apic_update_ppr(apic);
29614d82d12bSPaolo Bonzini 	} else {
29624d82d12bSPaolo Bonzini 		/*
29634d82d12bSPaolo Bonzini 		 * For normal interrupts, PPR has been raised and there cannot
29644d82d12bSPaolo Bonzini 		 * be a higher-priority pending interrupt---except if there was
29654d82d12bSPaolo Bonzini 		 * a concurrent interrupt injection, but that would have
29664d82d12bSPaolo Bonzini 		 * triggered KVM_REQ_EVENT already.
29674d82d12bSPaolo Bonzini 		 */
29684d82d12bSPaolo Bonzini 		apic_set_isr(vector, apic);
29694d82d12bSPaolo Bonzini 		__apic_update_ppr(apic, &ppr);
29705c919412SAndrey Smetanin 	}
29715c919412SAndrey Smetanin 
2972edf88417SAvi Kivity 	return vector;
2973edf88417SAvi Kivity }
2974edf88417SAvi Kivity 
kvm_apic_state_fixup(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s,bool set)2975a92e2543SRadim Krčmář static int kvm_apic_state_fixup(struct kvm_vcpu *vcpu,
2976a92e2543SRadim Krčmář 		struct kvm_lapic_state *s, bool set)
2977a92e2543SRadim Krčmář {
2978a92e2543SRadim Krčmář 	if (apic_x2apic_mode(vcpu->arch.apic)) {
29794fc0f9eaSSean Christopherson 		u32 x2apic_id = kvm_x2apic_id(vcpu->arch.apic);
2980a92e2543SRadim Krčmář 		u32 *id = (u32 *)(s->regs + APIC_ID);
298112806ba9SDr. David Alan Gilbert 		u32 *ldr = (u32 *)(s->regs + APIC_LDR);
2982a57a3168SSean Christopherson 		u64 icr;
2983a92e2543SRadim Krčmář 
298437131313SRadim Krčmář 		if (vcpu->kvm->arch.x2apic_format) {
29854fc0f9eaSSean Christopherson 			if (*id != x2apic_id)
298637131313SRadim Krčmář 				return -EINVAL;
298737131313SRadim Krčmář 		} else {
29884fc0f9eaSSean Christopherson 			/*
29894fc0f9eaSSean Christopherson 			 * Ignore the userspace value when setting APIC state.
29904fc0f9eaSSean Christopherson 			 * KVM's model is that the x2APIC ID is readonly, e.g.
29914fc0f9eaSSean Christopherson 			 * KVM only supports delivering interrupts to KVM's
29924fc0f9eaSSean Christopherson 			 * version of the x2APIC ID.  However, for backwards
29934fc0f9eaSSean Christopherson 			 * compatibility, don't reject attempts to set a
29944fc0f9eaSSean Christopherson 			 * mismatched ID for userspace that hasn't opted into
29954fc0f9eaSSean Christopherson 			 * x2apic_format.
29964fc0f9eaSSean Christopherson 			 */
2997a92e2543SRadim Krčmář 			if (set)
29984fc0f9eaSSean Christopherson 				*id = x2apic_id;
2999a92e2543SRadim Krčmář 			else
30004fc0f9eaSSean Christopherson 				*id = x2apic_id << 24;
3001a92e2543SRadim Krčmář 		}
300212806ba9SDr. David Alan Gilbert 
3003a57a3168SSean Christopherson 		/*
3004a57a3168SSean Christopherson 		 * In x2APIC mode, the LDR is fixed and based on the id.  And
3005*e8ad068cSSean Christopherson 		 * if the ICR is _not_ split, ICR is internally a single 64-bit
3006*e8ad068cSSean Christopherson 		 * register, but needs to be split to ICR+ICR2 in userspace for
3007*e8ad068cSSean Christopherson 		 * backwards compatibility.
3008a57a3168SSean Christopherson 		 */
3009*e8ad068cSSean Christopherson 		if (set)
30104fc0f9eaSSean Christopherson 			*ldr = kvm_apic_calc_x2apic_ldr(x2apic_id);
3011a57a3168SSean Christopherson 
3012*e8ad068cSSean Christopherson 		if (!kvm_x86_ops.x2apic_icr_is_split) {
3013*e8ad068cSSean Christopherson 			if (set) {
3014a57a3168SSean Christopherson 				icr = __kvm_lapic_get_reg(s->regs, APIC_ICR) |
3015a57a3168SSean Christopherson 				      (u64)__kvm_lapic_get_reg(s->regs, APIC_ICR2) << 32;
3016a57a3168SSean Christopherson 				__kvm_lapic_set_reg64(s->regs, APIC_ICR, icr);
3017a57a3168SSean Christopherson 			} else {
3018a57a3168SSean Christopherson 				icr = __kvm_lapic_get_reg64(s->regs, APIC_ICR);
3019a57a3168SSean Christopherson 				__kvm_lapic_set_reg(s->regs, APIC_ICR2, icr >> 32);
3020a57a3168SSean Christopherson 			}
302137131313SRadim Krčmář 		}
3022*e8ad068cSSean Christopherson 	}
3023a92e2543SRadim Krčmář 
3024a92e2543SRadim Krčmář 	return 0;
3025a92e2543SRadim Krčmář }
3026a92e2543SRadim Krčmář 
kvm_apic_get_state(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)3027a92e2543SRadim Krčmář int kvm_apic_get_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
3028a92e2543SRadim Krčmář {
3029a92e2543SRadim Krčmář 	memcpy(s->regs, vcpu->arch.apic->regs, sizeof(*s));
303024647e0aSPeter Shier 
303124647e0aSPeter Shier 	/*
303224647e0aSPeter Shier 	 * Get calculated timer current count for remaining timer period (if
303324647e0aSPeter Shier 	 * any) and store it in the returned register set.
303424647e0aSPeter Shier 	 */
303524647e0aSPeter Shier 	__kvm_lapic_set_reg(s->regs, APIC_TMCCT,
303624647e0aSPeter Shier 			    __apic_read(vcpu->arch.apic, APIC_TMCCT));
303724647e0aSPeter Shier 
3038a92e2543SRadim Krčmář 	return kvm_apic_state_fixup(vcpu, s, false);
3039a92e2543SRadim Krčmář }
3040a92e2543SRadim Krčmář 
kvm_apic_set_state(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)3041a92e2543SRadim Krčmář int kvm_apic_set_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
3042edf88417SAvi Kivity {
3043edf88417SAvi Kivity 	struct kvm_lapic *apic = vcpu->arch.apic;
3044a92e2543SRadim Krčmář 	int r;
3045a92e2543SRadim Krčmář 
30467de33b0fSHaitao Shan 	static_call_cond(kvm_x86_apicv_pre_state_restore)(vcpu);
30477de33b0fSHaitao Shan 
30485dbc8f3fSGleb Natapov 	kvm_lapic_set_base(vcpu, vcpu->arch.apic_base);
304964eb0620SGleb Natapov 	/* set SPIV separately to get count of SW disabled APICs right */
305064eb0620SGleb Natapov 	apic_set_spiv(apic, *((u32 *)(s->regs + APIC_SPIV)));
3051a92e2543SRadim Krčmář 
3052a92e2543SRadim Krčmář 	r = kvm_apic_state_fixup(vcpu, s, true);
30534abaffceSWanpeng Li 	if (r) {
30544abaffceSWanpeng Li 		kvm_recalculate_apic_map(vcpu->kvm);
3055a92e2543SRadim Krčmář 		return r;
30564abaffceSWanpeng Li 	}
30570e96f31eSJordan Borgner 	memcpy(vcpu->arch.apic->regs, s->regs, sizeof(*s));
3058a92e2543SRadim Krčmář 
305944d52717SPaolo Bonzini 	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
30604abaffceSWanpeng Li 	kvm_recalculate_apic_map(vcpu->kvm);
3061fc61b800SGleb Natapov 	kvm_apic_set_version(vcpu);
3062fc61b800SGleb Natapov 
3063edf88417SAvi Kivity 	apic_update_ppr(apic);
306435fe7cfbSWanpeng Li 	cancel_apic_timer(apic);
306535737d2dSWanpeng Li 	apic->lapic_timer.expired_tscdeadline = 0;
3066b6ac0695SRadim Krčmář 	apic_update_lvtt(apic);
3067dfb95954SSuravee Suthikulpanit 	apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
3068edf88417SAvi Kivity 	update_divide_count(apic);
306924647e0aSPeter Shier 	__start_apic_timer(apic, APIC_TMCCT);
30702735886cSWanpeng Li 	kvm_lapic_set_reg(apic, APIC_TMCCT, 0);
3071b26a695aSSuravee Suthikulpanit 	kvm_apic_update_apicv(vcpu);
3072ce0a58f4SSean Christopherson 	if (apic->apicv_active) {
3073abb6d479SPaolo Bonzini 		static_call_cond(kvm_x86_apicv_post_state_restore)(vcpu);
3074abb6d479SPaolo Bonzini 		static_call_cond(kvm_x86_hwapic_irr_update)(vcpu, apic_find_highest_irr(apic));
3075d39850f5SSean Christopherson 		static_call_cond(kvm_x86_hwapic_isr_update)(apic_find_highest_isr(apic));
3076d62caabbSAndrey Smetanin 	}
30773842d135SAvi Kivity 	kvm_make_request(KVM_REQ_EVENT, vcpu);
307849df6397SSteve Rutherford 	if (ioapic_in_kernel(vcpu->kvm))
307910606919SYang Zhang 		kvm_rtc_eoi_tracking_restore_one(vcpu);
30800669a510SRadim Krčmář 
30810669a510SRadim Krčmář 	vcpu->arch.apic_arb_prio = 0;
3082a92e2543SRadim Krčmář 
3083a92e2543SRadim Krčmář 	return 0;
3084edf88417SAvi Kivity }
3085edf88417SAvi Kivity 
__kvm_migrate_apic_timer(struct kvm_vcpu * vcpu)30862f52d58cSAvi Kivity void __kvm_migrate_apic_timer(struct kvm_vcpu *vcpu)
3087edf88417SAvi Kivity {
3088edf88417SAvi Kivity 	struct hrtimer *timer;
3089edf88417SAvi Kivity 
30900c5f81daSWanpeng Li 	if (!lapic_in_kernel(vcpu) ||
30910c5f81daSWanpeng Li 		kvm_can_post_timer_interrupt(vcpu))
3092edf88417SAvi Kivity 		return;
3093edf88417SAvi Kivity 
309454e9818fSGleb Natapov 	timer = &vcpu->arch.apic->lapic_timer.timer;
3095edf88417SAvi Kivity 	if (hrtimer_cancel(timer))
30962c0d278fSSebastian Andrzej Siewior 		hrtimer_start_expires(timer, HRTIMER_MODE_ABS_HARD);
3097edf88417SAvi Kivity }
3098b93463aaSAvi Kivity 
3099ae7a2a3fSMichael S. Tsirkin /*
3100ae7a2a3fSMichael S. Tsirkin  * apic_sync_pv_eoi_from_guest - called on vmexit or cancel interrupt
3101ae7a2a3fSMichael S. Tsirkin  *
3102ae7a2a3fSMichael S. Tsirkin  * Detect whether guest triggered PV EOI since the
3103ae7a2a3fSMichael S. Tsirkin  * last entry. If yes, set EOI on guests's behalf.
3104ae7a2a3fSMichael S. Tsirkin  * Clear PV EOI in guest memory in any case.
3105ae7a2a3fSMichael S. Tsirkin  */
apic_sync_pv_eoi_from_guest(struct kvm_vcpu * vcpu,struct kvm_lapic * apic)3106ae7a2a3fSMichael S. Tsirkin static void apic_sync_pv_eoi_from_guest(struct kvm_vcpu *vcpu,
3107ae7a2a3fSMichael S. Tsirkin 					struct kvm_lapic *apic)
3108ae7a2a3fSMichael S. Tsirkin {
3109ae7a2a3fSMichael S. Tsirkin 	int vector;
3110ae7a2a3fSMichael S. Tsirkin 	/*
3111ae7a2a3fSMichael S. Tsirkin 	 * PV EOI state is derived from KVM_APIC_PV_EOI_PENDING in host
3112ae7a2a3fSMichael S. Tsirkin 	 * and KVM_PV_EOI_ENABLED in guest memory as follows:
3113ae7a2a3fSMichael S. Tsirkin 	 *
3114ae7a2a3fSMichael S. Tsirkin 	 * KVM_APIC_PV_EOI_PENDING is unset:
3115ae7a2a3fSMichael S. Tsirkin 	 * 	-> host disabled PV EOI.
3116ae7a2a3fSMichael S. Tsirkin 	 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is set:
3117ae7a2a3fSMichael S. Tsirkin 	 * 	-> host enabled PV EOI, guest did not execute EOI yet.
3118ae7a2a3fSMichael S. Tsirkin 	 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is unset:
3119ae7a2a3fSMichael S. Tsirkin 	 * 	-> host enabled PV EOI, guest executed EOI.
3120ae7a2a3fSMichael S. Tsirkin 	 */
3121ae7a2a3fSMichael S. Tsirkin 	BUG_ON(!pv_eoi_enabled(vcpu));
312251b1209cSLi RongQing 
312351b1209cSLi RongQing 	if (pv_eoi_test_and_clr_pending(vcpu))
3124ae7a2a3fSMichael S. Tsirkin 		return;
3125ae7a2a3fSMichael S. Tsirkin 	vector = apic_set_eoi(apic);
3126ae7a2a3fSMichael S. Tsirkin 	trace_kvm_pv_eoi(apic, vector);
3127ae7a2a3fSMichael S. Tsirkin }
3128ae7a2a3fSMichael S. Tsirkin 
kvm_lapic_sync_from_vapic(struct kvm_vcpu * vcpu)3129b93463aaSAvi Kivity void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
3130b93463aaSAvi Kivity {
3131b93463aaSAvi Kivity 	u32 data;
3132b93463aaSAvi Kivity 
3133ae7a2a3fSMichael S. Tsirkin 	if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
3134ae7a2a3fSMichael S. Tsirkin 		apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
3135ae7a2a3fSMichael S. Tsirkin 
313641383771SGleb Natapov 	if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
3137b93463aaSAvi Kivity 		return;
3138b93463aaSAvi Kivity 
31394e335d9eSPaolo Bonzini 	if (kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
3140603242a8SNicholas Krause 				  sizeof(u32)))
3141603242a8SNicholas Krause 		return;
3142b93463aaSAvi Kivity 
3143b93463aaSAvi Kivity 	apic_set_tpr(vcpu->arch.apic, data & 0xff);
3144b93463aaSAvi Kivity }
3145b93463aaSAvi Kivity 
3146ae7a2a3fSMichael S. Tsirkin /*
3147ae7a2a3fSMichael S. Tsirkin  * apic_sync_pv_eoi_to_guest - called before vmentry
3148ae7a2a3fSMichael S. Tsirkin  *
3149ae7a2a3fSMichael S. Tsirkin  * Detect whether it's safe to enable PV EOI and
3150ae7a2a3fSMichael S. Tsirkin  * if yes do so.
3151ae7a2a3fSMichael S. Tsirkin  */
apic_sync_pv_eoi_to_guest(struct kvm_vcpu * vcpu,struct kvm_lapic * apic)3152ae7a2a3fSMichael S. Tsirkin static void apic_sync_pv_eoi_to_guest(struct kvm_vcpu *vcpu,
3153ae7a2a3fSMichael S. Tsirkin 					struct kvm_lapic *apic)
3154ae7a2a3fSMichael S. Tsirkin {
3155ae7a2a3fSMichael S. Tsirkin 	if (!pv_eoi_enabled(vcpu) ||
3156ae7a2a3fSMichael S. Tsirkin 	    /* IRR set or many bits in ISR: could be nested. */
3157ae7a2a3fSMichael S. Tsirkin 	    apic->irr_pending ||
3158ae7a2a3fSMichael S. Tsirkin 	    /* Cache not set: could be safe but we don't bother. */
3159ae7a2a3fSMichael S. Tsirkin 	    apic->highest_isr_cache == -1 ||
3160ae7a2a3fSMichael S. Tsirkin 	    /* Need EOI to update ioapic. */
31613bb345f3SPaolo Bonzini 	    kvm_ioapic_handles_vector(apic, apic->highest_isr_cache)) {
3162ae7a2a3fSMichael S. Tsirkin 		/*
3163ae7a2a3fSMichael S. Tsirkin 		 * PV EOI was disabled by apic_sync_pv_eoi_from_guest
3164ae7a2a3fSMichael S. Tsirkin 		 * so we need not do anything here.
3165ae7a2a3fSMichael S. Tsirkin 		 */
3166ae7a2a3fSMichael S. Tsirkin 		return;
3167ae7a2a3fSMichael S. Tsirkin 	}
3168ae7a2a3fSMichael S. Tsirkin 
3169ae7a2a3fSMichael S. Tsirkin 	pv_eoi_set_pending(apic->vcpu);
3170ae7a2a3fSMichael S. Tsirkin }
3171ae7a2a3fSMichael S. Tsirkin 
kvm_lapic_sync_to_vapic(struct kvm_vcpu * vcpu)3172b93463aaSAvi Kivity void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
3173b93463aaSAvi Kivity {
3174b93463aaSAvi Kivity 	u32 data, tpr;
3175b93463aaSAvi Kivity 	int max_irr, max_isr;
3176ae7a2a3fSMichael S. Tsirkin 	struct kvm_lapic *apic = vcpu->arch.apic;
3177b93463aaSAvi Kivity 
3178ae7a2a3fSMichael S. Tsirkin 	apic_sync_pv_eoi_to_guest(vcpu, apic);
3179ae7a2a3fSMichael S. Tsirkin 
318041383771SGleb Natapov 	if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
3181b93463aaSAvi Kivity 		return;
3182b93463aaSAvi Kivity 
3183dfb95954SSuravee Suthikulpanit 	tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI) & 0xff;
3184b93463aaSAvi Kivity 	max_irr = apic_find_highest_irr(apic);
3185b93463aaSAvi Kivity 	if (max_irr < 0)
3186b93463aaSAvi Kivity 		max_irr = 0;
3187b93463aaSAvi Kivity 	max_isr = apic_find_highest_isr(apic);
3188b93463aaSAvi Kivity 	if (max_isr < 0)
3189b93463aaSAvi Kivity 		max_isr = 0;
3190b93463aaSAvi Kivity 	data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
3191b93463aaSAvi Kivity 
31924e335d9eSPaolo Bonzini 	kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
3193fda4e2e8SAndy Honig 				sizeof(u32));
3194b93463aaSAvi Kivity }
3195b93463aaSAvi Kivity 
kvm_lapic_set_vapic_addr(struct kvm_vcpu * vcpu,gpa_t vapic_addr)3196fda4e2e8SAndy Honig int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
3197b93463aaSAvi Kivity {
3198fda4e2e8SAndy Honig 	if (vapic_addr) {
31994e335d9eSPaolo Bonzini 		if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
3200fda4e2e8SAndy Honig 					&vcpu->arch.apic->vapic_cache,
3201fda4e2e8SAndy Honig 					vapic_addr, sizeof(u32)))
3202fda4e2e8SAndy Honig 			return -EINVAL;
320341383771SGleb Natapov 		__set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
3204fda4e2e8SAndy Honig 	} else {
320541383771SGleb Natapov 		__clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
3206b93463aaSAvi Kivity 	}
32070105d1a5SGleb Natapov 
3208fda4e2e8SAndy Honig 	vcpu->arch.apic->vapic_addr = vapic_addr;
3209fda4e2e8SAndy Honig 	return 0;
3210fda4e2e8SAndy Honig }
3211fda4e2e8SAndy Honig 
kvm_lapic_msr_read(struct kvm_lapic * apic,u32 reg,u64 * data)32125429478dSSean Christopherson static int kvm_lapic_msr_read(struct kvm_lapic *apic, u32 reg, u64 *data)
32135429478dSSean Christopherson {
3214a57a3168SSean Christopherson 	u32 low;
3215a57a3168SSean Christopherson 
3216a57a3168SSean Christopherson 	if (reg == APIC_ICR) {
3217*e8ad068cSSean Christopherson 		*data = kvm_x2apic_icr_read(apic);
3218a57a3168SSean Christopherson 		return 0;
3219a57a3168SSean Christopherson 	}
32205429478dSSean Christopherson 
32215429478dSSean Christopherson 	if (kvm_lapic_reg_read(apic, reg, 4, &low))
32225429478dSSean Christopherson 		return 1;
32235429478dSSean Christopherson 
3224a57a3168SSean Christopherson 	*data = low;
32255429478dSSean Christopherson 
32265429478dSSean Christopherson 	return 0;
32275429478dSSean Christopherson }
32285429478dSSean Christopherson 
kvm_lapic_msr_write(struct kvm_lapic * apic,u32 reg,u64 data)32295429478dSSean Christopherson static int kvm_lapic_msr_write(struct kvm_lapic *apic, u32 reg, u64 data)
32305429478dSSean Christopherson {
3231a57a3168SSean Christopherson 	/*
3232ab52be1bSSean Christopherson 	 * ICR is a 64-bit register in x2APIC mode (and Hyper-V PV vAPIC) and
3233a57a3168SSean Christopherson 	 * can be written as such, all other registers remain accessible only
3234a57a3168SSean Christopherson 	 * through 32-bit reads/writes.
3235a57a3168SSean Christopherson 	 */
32365429478dSSean Christopherson 	if (reg == APIC_ICR)
3237a57a3168SSean Christopherson 		return kvm_x2apic_icr_write(apic, data);
3238a57a3168SSean Christopherson 
3239ab52be1bSSean Christopherson 	/* Bits 63:32 are reserved in all other registers. */
3240ab52be1bSSean Christopherson 	if (data >> 32)
3241ab52be1bSSean Christopherson 		return 1;
3242ab52be1bSSean Christopherson 
32435429478dSSean Christopherson 	return kvm_lapic_reg_write(apic, reg, (u32)data);
32445429478dSSean Christopherson }
32455429478dSSean Christopherson 
kvm_x2apic_msr_write(struct kvm_vcpu * vcpu,u32 msr,u64 data)32460105d1a5SGleb Natapov int kvm_x2apic_msr_write(struct kvm_vcpu *vcpu, u32 msr, u64 data)
32470105d1a5SGleb Natapov {
32480105d1a5SGleb Natapov 	struct kvm_lapic *apic = vcpu->arch.apic;
32490105d1a5SGleb Natapov 	u32 reg = (msr - APIC_BASE_MSR) << 4;
32500105d1a5SGleb Natapov 
325135754c98SPaolo Bonzini 	if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
32520105d1a5SGleb Natapov 		return 1;
32530105d1a5SGleb Natapov 
32545429478dSSean Christopherson 	return kvm_lapic_msr_write(apic, reg, data);
32550105d1a5SGleb Natapov }
32560105d1a5SGleb Natapov 
kvm_x2apic_msr_read(struct kvm_vcpu * vcpu,u32 msr,u64 * data)32570105d1a5SGleb Natapov int kvm_x2apic_msr_read(struct kvm_vcpu *vcpu, u32 msr, u64 *data)
32580105d1a5SGleb Natapov {
32590105d1a5SGleb Natapov 	struct kvm_lapic *apic = vcpu->arch.apic;
32605429478dSSean Christopherson 	u32 reg = (msr - APIC_BASE_MSR) << 4;
32610105d1a5SGleb Natapov 
326235754c98SPaolo Bonzini 	if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
32630105d1a5SGleb Natapov 		return 1;
32640105d1a5SGleb Natapov 
32655429478dSSean Christopherson 	return kvm_lapic_msr_read(apic, reg, data);
32660105d1a5SGleb Natapov }
326710388a07SGleb Natapov 
kvm_hv_vapic_msr_write(struct kvm_vcpu * vcpu,u32 reg,u64 data)326810388a07SGleb Natapov int kvm_hv_vapic_msr_write(struct kvm_vcpu *vcpu, u32 reg, u64 data)
326910388a07SGleb Natapov {
3270bce87cceSPaolo Bonzini 	if (!lapic_in_kernel(vcpu))
327110388a07SGleb Natapov 		return 1;
327210388a07SGleb Natapov 
32735429478dSSean Christopherson 	return kvm_lapic_msr_write(vcpu->arch.apic, reg, data);
327410388a07SGleb Natapov }
327510388a07SGleb Natapov 
kvm_hv_vapic_msr_read(struct kvm_vcpu * vcpu,u32 reg,u64 * data)327610388a07SGleb Natapov int kvm_hv_vapic_msr_read(struct kvm_vcpu *vcpu, u32 reg, u64 *data)
327710388a07SGleb Natapov {
3278bce87cceSPaolo Bonzini 	if (!lapic_in_kernel(vcpu))
327910388a07SGleb Natapov 		return 1;
328010388a07SGleb Natapov 
32815429478dSSean Christopherson 	return kvm_lapic_msr_read(vcpu->arch.apic, reg, data);
328210388a07SGleb Natapov }
3283ae7a2a3fSMichael S. Tsirkin 
kvm_lapic_set_pv_eoi(struct kvm_vcpu * vcpu,u64 data,unsigned long len)328477c3323fSVitaly Kuznetsov int kvm_lapic_set_pv_eoi(struct kvm_vcpu *vcpu, u64 data, unsigned long len)
3285ae7a2a3fSMichael S. Tsirkin {
3286ae7a2a3fSMichael S. Tsirkin 	u64 addr = data & ~KVM_MSR_ENABLED;
3287a7c42bb6SVitaly Kuznetsov 	struct gfn_to_hva_cache *ghc = &vcpu->arch.pv_eoi.data;
3288a7c42bb6SVitaly Kuznetsov 	unsigned long new_len;
3289afd67ee3SVitaly Kuznetsov 	int ret;
3290a7c42bb6SVitaly Kuznetsov 
3291ae7a2a3fSMichael S. Tsirkin 	if (!IS_ALIGNED(addr, 4))
3292ae7a2a3fSMichael S. Tsirkin 		return 1;
3293ae7a2a3fSMichael S. Tsirkin 
3294afd67ee3SVitaly Kuznetsov 	if (data & KVM_MSR_ENABLED) {
3295a7c42bb6SVitaly Kuznetsov 		if (addr == ghc->gpa && len <= ghc->len)
3296a7c42bb6SVitaly Kuznetsov 			new_len = ghc->len;
3297a7c42bb6SVitaly Kuznetsov 		else
3298a7c42bb6SVitaly Kuznetsov 			new_len = len;
3299a7c42bb6SVitaly Kuznetsov 
3300afd67ee3SVitaly Kuznetsov 		ret = kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, addr, new_len);
3301afd67ee3SVitaly Kuznetsov 		if (ret)
3302afd67ee3SVitaly Kuznetsov 			return ret;
3303afd67ee3SVitaly Kuznetsov 	}
3304afd67ee3SVitaly Kuznetsov 
3305afd67ee3SVitaly Kuznetsov 	vcpu->arch.pv_eoi.msr_val = data;
3306afd67ee3SVitaly Kuznetsov 
3307afd67ee3SVitaly Kuznetsov 	return 0;
3308ae7a2a3fSMichael S. Tsirkin }
3309c5cc421bSGleb Natapov 
kvm_apic_accept_events(struct kvm_vcpu * vcpu)33104fe09bcfSJim Mattson int kvm_apic_accept_events(struct kvm_vcpu *vcpu)
331166450a21SJan Kiszka {
331266450a21SJan Kiszka 	struct kvm_lapic *apic = vcpu->arch.apic;
33132b4a273bSPaolo Bonzini 	u8 sipi_vector;
33141c96dcceSPaolo Bonzini 	int r;
331566450a21SJan Kiszka 
33161e17a6f8SSean Christopherson 	if (!kvm_apic_has_pending_init_or_sipi(vcpu))
33174fe09bcfSJim Mattson 		return 0;
33181c96dcceSPaolo Bonzini 
33191c96dcceSPaolo Bonzini 	if (is_guest_mode(vcpu)) {
3320cb6a32c2SSean Christopherson 		r = kvm_check_nested_events(vcpu);
33211c96dcceSPaolo Bonzini 		if (r < 0)
33224fe09bcfSJim Mattson 			return r == -EBUSY ? 0 : r;
33231c96dcceSPaolo Bonzini 		/*
33241e17a6f8SSean Christopherson 		 * Continue processing INIT/SIPI even if a nested VM-Exit
33251e17a6f8SSean Christopherson 		 * occurred, e.g. pending SIPIs should be dropped if INIT+SIPI
33261e17a6f8SSean Christopherson 		 * are blocked as a result of transitioning to VMX root mode.
33271c96dcceSPaolo Bonzini 		 */
33281c96dcceSPaolo Bonzini 	}
33291c96dcceSPaolo Bonzini 
33301c96dcceSPaolo Bonzini 	/*
33311e17a6f8SSean Christopherson 	 * INITs are blocked while CPU is in specific states (SMM, VMX root
33321e17a6f8SSean Christopherson 	 * mode, SVM with GIF=0), while SIPIs are dropped if the CPU isn't in
33331e17a6f8SSean Christopherson 	 * wait-for-SIPI (WFS).
3334cd7764feSPaolo Bonzini 	 */
33351b7a1b78SSean Christopherson 	if (!kvm_apic_init_sipi_allowed(vcpu)) {
3336cd7764feSPaolo Bonzini 		WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED);
3337cd7764feSPaolo Bonzini 		clear_bit(KVM_APIC_SIPI, &apic->pending_events);
33384fe09bcfSJim Mattson 		return 0;
3339cd7764feSPaolo Bonzini 	}
3340299018f4SGleb Natapov 
33411e17a6f8SSean Christopherson 	if (test_and_clear_bit(KVM_APIC_INIT, &apic->pending_events)) {
3342d28bc9ddSNadav Amit 		kvm_vcpu_reset(vcpu, true);
334366450a21SJan Kiszka 		if (kvm_vcpu_is_bsp(apic->vcpu))
334466450a21SJan Kiszka 			vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
334566450a21SJan Kiszka 		else
334666450a21SJan Kiszka 			vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
334766450a21SJan Kiszka 	}
33481e17a6f8SSean Christopherson 	if (test_and_clear_bit(KVM_APIC_SIPI, &apic->pending_events)) {
3349f57ad63aSMaxim Levitsky 		if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
335066450a21SJan Kiszka 			/* evaluate pending_events before reading the vector */
335166450a21SJan Kiszka 			smp_rmb();
335266450a21SJan Kiszka 			sipi_vector = apic->sipi_vector;
3353a0941a64SSean Christopherson 			static_call(kvm_x86_vcpu_deliver_sipi_vector)(vcpu, sipi_vector);
335466450a21SJan Kiszka 			vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
335566450a21SJan Kiszka 		}
335666450a21SJan Kiszka 	}
33574fe09bcfSJim Mattson 	return 0;
3358f57ad63aSMaxim Levitsky }
335966450a21SJan Kiszka 
kvm_lapic_exit(void)3360cef84c30SDavid Matlack void kvm_lapic_exit(void)
3361cef84c30SDavid Matlack {
3362cef84c30SDavid Matlack 	static_key_deferred_flush(&apic_hw_disabled);
33639139a7a6SSean Christopherson 	WARN_ON(static_branch_unlikely(&apic_hw_disabled.key));
3364cef84c30SDavid Matlack 	static_key_deferred_flush(&apic_sw_disabled);
33659139a7a6SSean Christopherson 	WARN_ON(static_branch_unlikely(&apic_sw_disabled.key));
3366cef84c30SDavid Matlack }
3367