xref: /openbmc/linux/arch/x86/kvm/lapic.c (revision 2d99a7ec)
1 // SPDX-License-Identifier: GPL-2.0-only
2 
3 /*
4  * Local APIC virtualization
5  *
6  * Copyright (C) 2006 Qumranet, Inc.
7  * Copyright (C) 2007 Novell
8  * Copyright (C) 2007 Intel
9  * Copyright 2009 Red Hat, Inc. and/or its affiliates.
10  *
11  * Authors:
12  *   Dor Laor <dor.laor@qumranet.com>
13  *   Gregory Haskins <ghaskins@novell.com>
14  *   Yaozu (Eddie) Dong <eddie.dong@intel.com>
15  *
16  * Based on Xen 3.1 code, Copyright (c) 2004, Intel Corporation.
17  */
18 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
19 
20 #include <linux/kvm_host.h>
21 #include <linux/kvm.h>
22 #include <linux/mm.h>
23 #include <linux/highmem.h>
24 #include <linux/smp.h>
25 #include <linux/hrtimer.h>
26 #include <linux/io.h>
27 #include <linux/export.h>
28 #include <linux/math64.h>
29 #include <linux/slab.h>
30 #include <asm/processor.h>
31 #include <asm/mce.h>
32 #include <asm/msr.h>
33 #include <asm/page.h>
34 #include <asm/current.h>
35 #include <asm/apicdef.h>
36 #include <asm/delay.h>
37 #include <linux/atomic.h>
38 #include <linux/jump_label.h>
39 #include "kvm_cache_regs.h"
40 #include "irq.h"
41 #include "ioapic.h"
42 #include "trace.h"
43 #include "x86.h"
44 #include "cpuid.h"
45 #include "hyperv.h"
46 #include "smm.h"
47 
48 #ifndef CONFIG_X86_64
49 #define mod_64(x, y) ((x) - (y) * div64_u64(x, y))
50 #else
51 #define mod_64(x, y) ((x) % (y))
52 #endif
53 
54 #define PRId64 "d"
55 #define PRIx64 "llx"
56 #define PRIu64 "u"
57 #define PRIo64 "o"
58 
59 /* 14 is the version for Xeon and Pentium 8.4.8*/
60 #define APIC_VERSION			0x14UL
61 #define LAPIC_MMIO_LENGTH		(1 << 12)
62 /* followed define is not in apicdef.h */
63 #define MAX_APIC_VECTOR			256
64 #define APIC_VECTORS_PER_REG		32
65 
66 static bool lapic_timer_advance_dynamic __read_mostly;
67 #define LAPIC_TIMER_ADVANCE_ADJUST_MIN	100	/* clock cycles */
68 #define LAPIC_TIMER_ADVANCE_ADJUST_MAX	10000	/* clock cycles */
69 #define LAPIC_TIMER_ADVANCE_NS_INIT	1000
70 #define LAPIC_TIMER_ADVANCE_NS_MAX     5000
71 /* step-by-step approximation to mitigate fluctuation */
72 #define LAPIC_TIMER_ADVANCE_ADJUST_STEP 8
73 static int kvm_lapic_msr_read(struct kvm_lapic *apic, u32 reg, u64 *data);
74 static int kvm_lapic_msr_write(struct kvm_lapic *apic, u32 reg, u64 data);
75 
76 static inline void __kvm_lapic_set_reg(char *regs, int reg_off, u32 val)
77 {
78 	*((u32 *) (regs + reg_off)) = val;
79 }
80 
81 static inline void kvm_lapic_set_reg(struct kvm_lapic *apic, int reg_off, u32 val)
82 {
83 	__kvm_lapic_set_reg(apic->regs, reg_off, val);
84 }
85 
86 static __always_inline u64 __kvm_lapic_get_reg64(char *regs, int reg)
87 {
88 	BUILD_BUG_ON(reg != APIC_ICR);
89 	return *((u64 *) (regs + reg));
90 }
91 
92 static __always_inline u64 kvm_lapic_get_reg64(struct kvm_lapic *apic, int reg)
93 {
94 	return __kvm_lapic_get_reg64(apic->regs, reg);
95 }
96 
97 static __always_inline void __kvm_lapic_set_reg64(char *regs, int reg, u64 val)
98 {
99 	BUILD_BUG_ON(reg != APIC_ICR);
100 	*((u64 *) (regs + reg)) = val;
101 }
102 
103 static __always_inline void kvm_lapic_set_reg64(struct kvm_lapic *apic,
104 						int reg, u64 val)
105 {
106 	__kvm_lapic_set_reg64(apic->regs, reg, val);
107 }
108 
109 static inline int apic_test_vector(int vec, void *bitmap)
110 {
111 	return test_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
112 }
113 
114 bool kvm_apic_pending_eoi(struct kvm_vcpu *vcpu, int vector)
115 {
116 	struct kvm_lapic *apic = vcpu->arch.apic;
117 
118 	return apic_test_vector(vector, apic->regs + APIC_ISR) ||
119 		apic_test_vector(vector, apic->regs + APIC_IRR);
120 }
121 
122 static inline int __apic_test_and_set_vector(int vec, void *bitmap)
123 {
124 	return __test_and_set_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
125 }
126 
127 static inline int __apic_test_and_clear_vector(int vec, void *bitmap)
128 {
129 	return __test_and_clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
130 }
131 
132 __read_mostly DEFINE_STATIC_KEY_DEFERRED_FALSE(apic_hw_disabled, HZ);
133 __read_mostly DEFINE_STATIC_KEY_DEFERRED_FALSE(apic_sw_disabled, HZ);
134 
135 static inline int apic_enabled(struct kvm_lapic *apic)
136 {
137 	return kvm_apic_sw_enabled(apic) &&	kvm_apic_hw_enabled(apic);
138 }
139 
140 #define LVT_MASK	\
141 	(APIC_LVT_MASKED | APIC_SEND_PENDING | APIC_VECTOR_MASK)
142 
143 #define LINT_MASK	\
144 	(LVT_MASK | APIC_MODE_MASK | APIC_INPUT_POLARITY | \
145 	 APIC_LVT_REMOTE_IRR | APIC_LVT_LEVEL_TRIGGER)
146 
147 static inline u32 kvm_x2apic_id(struct kvm_lapic *apic)
148 {
149 	return apic->vcpu->vcpu_id;
150 }
151 
152 static bool kvm_can_post_timer_interrupt(struct kvm_vcpu *vcpu)
153 {
154 	return pi_inject_timer && kvm_vcpu_apicv_active(vcpu) &&
155 		(kvm_mwait_in_guest(vcpu->kvm) || kvm_hlt_in_guest(vcpu->kvm));
156 }
157 
158 bool kvm_can_use_hv_timer(struct kvm_vcpu *vcpu)
159 {
160 	return kvm_x86_ops.set_hv_timer
161 	       && !(kvm_mwait_in_guest(vcpu->kvm) ||
162 		    kvm_can_post_timer_interrupt(vcpu));
163 }
164 
165 static bool kvm_use_posted_timer_interrupt(struct kvm_vcpu *vcpu)
166 {
167 	return kvm_can_post_timer_interrupt(vcpu) && vcpu->mode == IN_GUEST_MODE;
168 }
169 
170 static inline u32 kvm_apic_calc_x2apic_ldr(u32 id)
171 {
172 	return ((id >> 4) << 16) | (1 << (id & 0xf));
173 }
174 
175 static inline bool kvm_apic_map_get_logical_dest(struct kvm_apic_map *map,
176 		u32 dest_id, struct kvm_lapic ***cluster, u16 *mask) {
177 	switch (map->logical_mode) {
178 	case KVM_APIC_MODE_SW_DISABLED:
179 		/* Arbitrarily use the flat map so that @cluster isn't NULL. */
180 		*cluster = map->xapic_flat_map;
181 		*mask = 0;
182 		return true;
183 	case KVM_APIC_MODE_X2APIC: {
184 		u32 offset = (dest_id >> 16) * 16;
185 		u32 max_apic_id = map->max_apic_id;
186 
187 		if (offset <= max_apic_id) {
188 			u8 cluster_size = min(max_apic_id - offset + 1, 16U);
189 
190 			offset = array_index_nospec(offset, map->max_apic_id + 1);
191 			*cluster = &map->phys_map[offset];
192 			*mask = dest_id & (0xffff >> (16 - cluster_size));
193 		} else {
194 			*mask = 0;
195 		}
196 
197 		return true;
198 		}
199 	case KVM_APIC_MODE_XAPIC_FLAT:
200 		*cluster = map->xapic_flat_map;
201 		*mask = dest_id & 0xff;
202 		return true;
203 	case KVM_APIC_MODE_XAPIC_CLUSTER:
204 		*cluster = map->xapic_cluster_map[(dest_id >> 4) & 0xf];
205 		*mask = dest_id & 0xf;
206 		return true;
207 	case KVM_APIC_MODE_MAP_DISABLED:
208 		return false;
209 	default:
210 		WARN_ON_ONCE(1);
211 		return false;
212 	}
213 }
214 
215 static void kvm_apic_map_free(struct rcu_head *rcu)
216 {
217 	struct kvm_apic_map *map = container_of(rcu, struct kvm_apic_map, rcu);
218 
219 	kvfree(map);
220 }
221 
222 static int kvm_recalculate_phys_map(struct kvm_apic_map *new,
223 				    struct kvm_vcpu *vcpu,
224 				    bool *xapic_id_mismatch)
225 {
226 	struct kvm_lapic *apic = vcpu->arch.apic;
227 	u32 x2apic_id = kvm_x2apic_id(apic);
228 	u32 xapic_id = kvm_xapic_id(apic);
229 	u32 physical_id;
230 
231 	/*
232 	 * Deliberately truncate the vCPU ID when detecting a mismatched APIC
233 	 * ID to avoid false positives if the vCPU ID, i.e. x2APIC ID, is a
234 	 * 32-bit value.  Any unwanted aliasing due to truncation results will
235 	 * be detected below.
236 	 */
237 	if (!apic_x2apic_mode(apic) && xapic_id != (u8)vcpu->vcpu_id)
238 		*xapic_id_mismatch = true;
239 
240 	/*
241 	 * Apply KVM's hotplug hack if userspace has enable 32-bit APIC IDs.
242 	 * Allow sending events to vCPUs by their x2APIC ID even if the target
243 	 * vCPU is in legacy xAPIC mode, and silently ignore aliased xAPIC IDs
244 	 * (the x2APIC ID is truncated to 8 bits, causing IDs > 0xff to wrap
245 	 * and collide).
246 	 *
247 	 * Honor the architectural (and KVM's non-optimized) behavior if
248 	 * userspace has not enabled 32-bit x2APIC IDs.  Each APIC is supposed
249 	 * to process messages independently.  If multiple vCPUs have the same
250 	 * effective APIC ID, e.g. due to the x2APIC wrap or because the guest
251 	 * manually modified its xAPIC IDs, events targeting that ID are
252 	 * supposed to be recognized by all vCPUs with said ID.
253 	 */
254 	if (vcpu->kvm->arch.x2apic_format) {
255 		/* See also kvm_apic_match_physical_addr(). */
256 		if ((apic_x2apic_mode(apic) || x2apic_id > 0xff) &&
257 			x2apic_id <= new->max_apic_id)
258 			new->phys_map[x2apic_id] = apic;
259 
260 		if (!apic_x2apic_mode(apic) && !new->phys_map[xapic_id])
261 			new->phys_map[xapic_id] = apic;
262 	} else {
263 		/*
264 		 * Disable the optimized map if the physical APIC ID is already
265 		 * mapped, i.e. is aliased to multiple vCPUs.  The optimized
266 		 * map requires a strict 1:1 mapping between IDs and vCPUs.
267 		 */
268 		if (apic_x2apic_mode(apic))
269 			physical_id = x2apic_id;
270 		else
271 			physical_id = xapic_id;
272 
273 		if (new->phys_map[physical_id])
274 			return -EINVAL;
275 
276 		new->phys_map[physical_id] = apic;
277 	}
278 
279 	return 0;
280 }
281 
282 static void kvm_recalculate_logical_map(struct kvm_apic_map *new,
283 					struct kvm_vcpu *vcpu)
284 {
285 	struct kvm_lapic *apic = vcpu->arch.apic;
286 	enum kvm_apic_logical_mode logical_mode;
287 	struct kvm_lapic **cluster;
288 	u16 mask;
289 	u32 ldr;
290 
291 	if (new->logical_mode == KVM_APIC_MODE_MAP_DISABLED)
292 		return;
293 
294 	if (!kvm_apic_sw_enabled(apic))
295 		return;
296 
297 	ldr = kvm_lapic_get_reg(apic, APIC_LDR);
298 	if (!ldr)
299 		return;
300 
301 	if (apic_x2apic_mode(apic)) {
302 		logical_mode = KVM_APIC_MODE_X2APIC;
303 	} else {
304 		ldr = GET_APIC_LOGICAL_ID(ldr);
305 		if (kvm_lapic_get_reg(apic, APIC_DFR) == APIC_DFR_FLAT)
306 			logical_mode = KVM_APIC_MODE_XAPIC_FLAT;
307 		else
308 			logical_mode = KVM_APIC_MODE_XAPIC_CLUSTER;
309 	}
310 
311 	/*
312 	 * To optimize logical mode delivery, all software-enabled APICs must
313 	 * be configured for the same mode.
314 	 */
315 	if (new->logical_mode == KVM_APIC_MODE_SW_DISABLED) {
316 		new->logical_mode = logical_mode;
317 	} else if (new->logical_mode != logical_mode) {
318 		new->logical_mode = KVM_APIC_MODE_MAP_DISABLED;
319 		return;
320 	}
321 
322 	/*
323 	 * In x2APIC mode, the LDR is read-only and derived directly from the
324 	 * x2APIC ID, thus is guaranteed to be addressable.  KVM reuses
325 	 * kvm_apic_map.phys_map to optimize logical mode x2APIC interrupts by
326 	 * reversing the LDR calculation to get cluster of APICs, i.e. no
327 	 * additional work is required.
328 	 */
329 	if (apic_x2apic_mode(apic)) {
330 		WARN_ON_ONCE(ldr != kvm_apic_calc_x2apic_ldr(kvm_x2apic_id(apic)));
331 		return;
332 	}
333 
334 	if (WARN_ON_ONCE(!kvm_apic_map_get_logical_dest(new, ldr,
335 							&cluster, &mask))) {
336 		new->logical_mode = KVM_APIC_MODE_MAP_DISABLED;
337 		return;
338 	}
339 
340 	if (!mask)
341 		return;
342 
343 	ldr = ffs(mask) - 1;
344 	if (!is_power_of_2(mask) || cluster[ldr])
345 		new->logical_mode = KVM_APIC_MODE_MAP_DISABLED;
346 	else
347 		cluster[ldr] = apic;
348 }
349 
350 /*
351  * CLEAN -> DIRTY and UPDATE_IN_PROGRESS -> DIRTY changes happen without a lock.
352  *
353  * DIRTY -> UPDATE_IN_PROGRESS and UPDATE_IN_PROGRESS -> CLEAN happen with
354  * apic_map_lock_held.
355  */
356 enum {
357 	CLEAN,
358 	UPDATE_IN_PROGRESS,
359 	DIRTY
360 };
361 
362 void kvm_recalculate_apic_map(struct kvm *kvm)
363 {
364 	struct kvm_apic_map *new, *old = NULL;
365 	struct kvm_vcpu *vcpu;
366 	unsigned long i;
367 	u32 max_id = 255; /* enough space for any xAPIC ID */
368 	bool xapic_id_mismatch = false;
369 
370 	/* Read kvm->arch.apic_map_dirty before kvm->arch.apic_map.  */
371 	if (atomic_read_acquire(&kvm->arch.apic_map_dirty) == CLEAN)
372 		return;
373 
374 	WARN_ONCE(!irqchip_in_kernel(kvm),
375 		  "Dirty APIC map without an in-kernel local APIC");
376 
377 	mutex_lock(&kvm->arch.apic_map_lock);
378 	/*
379 	 * Read kvm->arch.apic_map_dirty before kvm->arch.apic_map
380 	 * (if clean) or the APIC registers (if dirty).
381 	 */
382 	if (atomic_cmpxchg_acquire(&kvm->arch.apic_map_dirty,
383 				   DIRTY, UPDATE_IN_PROGRESS) == CLEAN) {
384 		/* Someone else has updated the map. */
385 		mutex_unlock(&kvm->arch.apic_map_lock);
386 		return;
387 	}
388 
389 	kvm_for_each_vcpu(i, vcpu, kvm)
390 		if (kvm_apic_present(vcpu))
391 			max_id = max(max_id, kvm_x2apic_id(vcpu->arch.apic));
392 
393 	new = kvzalloc(sizeof(struct kvm_apic_map) +
394 	                   sizeof(struct kvm_lapic *) * ((u64)max_id + 1),
395 			   GFP_KERNEL_ACCOUNT);
396 
397 	if (!new)
398 		goto out;
399 
400 	new->max_apic_id = max_id;
401 	new->logical_mode = KVM_APIC_MODE_SW_DISABLED;
402 
403 	kvm_for_each_vcpu(i, vcpu, kvm) {
404 		if (!kvm_apic_present(vcpu))
405 			continue;
406 
407 		if (kvm_recalculate_phys_map(new, vcpu, &xapic_id_mismatch)) {
408 			kvfree(new);
409 			new = NULL;
410 			goto out;
411 		}
412 
413 		kvm_recalculate_logical_map(new, vcpu);
414 	}
415 out:
416 	/*
417 	 * The optimized map is effectively KVM's internal version of APICv,
418 	 * and all unwanted aliasing that results in disabling the optimized
419 	 * map also applies to APICv.
420 	 */
421 	if (!new)
422 		kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_PHYSICAL_ID_ALIASED);
423 	else
424 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_PHYSICAL_ID_ALIASED);
425 
426 	if (!new || new->logical_mode == KVM_APIC_MODE_MAP_DISABLED)
427 		kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_LOGICAL_ID_ALIASED);
428 	else
429 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_LOGICAL_ID_ALIASED);
430 
431 	if (xapic_id_mismatch)
432 		kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_APIC_ID_MODIFIED);
433 	else
434 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_APIC_ID_MODIFIED);
435 
436 	old = rcu_dereference_protected(kvm->arch.apic_map,
437 			lockdep_is_held(&kvm->arch.apic_map_lock));
438 	rcu_assign_pointer(kvm->arch.apic_map, new);
439 	/*
440 	 * Write kvm->arch.apic_map before clearing apic->apic_map_dirty.
441 	 * If another update has come in, leave it DIRTY.
442 	 */
443 	atomic_cmpxchg_release(&kvm->arch.apic_map_dirty,
444 			       UPDATE_IN_PROGRESS, CLEAN);
445 	mutex_unlock(&kvm->arch.apic_map_lock);
446 
447 	if (old)
448 		call_rcu(&old->rcu, kvm_apic_map_free);
449 
450 	kvm_make_scan_ioapic_request(kvm);
451 }
452 
453 static inline void apic_set_spiv(struct kvm_lapic *apic, u32 val)
454 {
455 	bool enabled = val & APIC_SPIV_APIC_ENABLED;
456 
457 	kvm_lapic_set_reg(apic, APIC_SPIV, val);
458 
459 	if (enabled != apic->sw_enabled) {
460 		apic->sw_enabled = enabled;
461 		if (enabled)
462 			static_branch_slow_dec_deferred(&apic_sw_disabled);
463 		else
464 			static_branch_inc(&apic_sw_disabled.key);
465 
466 		atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
467 	}
468 
469 	/* Check if there are APF page ready requests pending */
470 	if (enabled)
471 		kvm_make_request(KVM_REQ_APF_READY, apic->vcpu);
472 }
473 
474 static inline void kvm_apic_set_xapic_id(struct kvm_lapic *apic, u8 id)
475 {
476 	kvm_lapic_set_reg(apic, APIC_ID, id << 24);
477 	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
478 }
479 
480 static inline void kvm_apic_set_ldr(struct kvm_lapic *apic, u32 id)
481 {
482 	kvm_lapic_set_reg(apic, APIC_LDR, id);
483 	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
484 }
485 
486 static inline void kvm_apic_set_dfr(struct kvm_lapic *apic, u32 val)
487 {
488 	kvm_lapic_set_reg(apic, APIC_DFR, val);
489 	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
490 }
491 
492 static inline void kvm_apic_set_x2apic_id(struct kvm_lapic *apic, u32 id)
493 {
494 	u32 ldr = kvm_apic_calc_x2apic_ldr(id);
495 
496 	WARN_ON_ONCE(id != apic->vcpu->vcpu_id);
497 
498 	kvm_lapic_set_reg(apic, APIC_ID, id);
499 	kvm_lapic_set_reg(apic, APIC_LDR, ldr);
500 	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
501 }
502 
503 static inline int apic_lvt_enabled(struct kvm_lapic *apic, int lvt_type)
504 {
505 	return !(kvm_lapic_get_reg(apic, lvt_type) & APIC_LVT_MASKED);
506 }
507 
508 static inline int apic_lvtt_oneshot(struct kvm_lapic *apic)
509 {
510 	return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_ONESHOT;
511 }
512 
513 static inline int apic_lvtt_period(struct kvm_lapic *apic)
514 {
515 	return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_PERIODIC;
516 }
517 
518 static inline int apic_lvtt_tscdeadline(struct kvm_lapic *apic)
519 {
520 	return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_TSCDEADLINE;
521 }
522 
523 static inline int apic_lvt_nmi_mode(u32 lvt_val)
524 {
525 	return (lvt_val & (APIC_MODE_MASK | APIC_LVT_MASKED)) == APIC_DM_NMI;
526 }
527 
528 static inline bool kvm_lapic_lvt_supported(struct kvm_lapic *apic, int lvt_index)
529 {
530 	return apic->nr_lvt_entries > lvt_index;
531 }
532 
533 static inline int kvm_apic_calc_nr_lvt_entries(struct kvm_vcpu *vcpu)
534 {
535 	return KVM_APIC_MAX_NR_LVT_ENTRIES - !(vcpu->arch.mcg_cap & MCG_CMCI_P);
536 }
537 
538 void kvm_apic_set_version(struct kvm_vcpu *vcpu)
539 {
540 	struct kvm_lapic *apic = vcpu->arch.apic;
541 	u32 v = 0;
542 
543 	if (!lapic_in_kernel(vcpu))
544 		return;
545 
546 	v = APIC_VERSION | ((apic->nr_lvt_entries - 1) << 16);
547 
548 	/*
549 	 * KVM emulates 82093AA datasheet (with in-kernel IOAPIC implementation)
550 	 * which doesn't have EOI register; Some buggy OSes (e.g. Windows with
551 	 * Hyper-V role) disable EOI broadcast in lapic not checking for IOAPIC
552 	 * version first and level-triggered interrupts never get EOIed in
553 	 * IOAPIC.
554 	 */
555 	if (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) &&
556 	    !ioapic_in_kernel(vcpu->kvm))
557 		v |= APIC_LVR_DIRECTED_EOI;
558 	kvm_lapic_set_reg(apic, APIC_LVR, v);
559 }
560 
561 void kvm_apic_after_set_mcg_cap(struct kvm_vcpu *vcpu)
562 {
563 	int nr_lvt_entries = kvm_apic_calc_nr_lvt_entries(vcpu);
564 	struct kvm_lapic *apic = vcpu->arch.apic;
565 	int i;
566 
567 	if (!lapic_in_kernel(vcpu) || nr_lvt_entries == apic->nr_lvt_entries)
568 		return;
569 
570 	/* Initialize/mask any "new" LVT entries. */
571 	for (i = apic->nr_lvt_entries; i < nr_lvt_entries; i++)
572 		kvm_lapic_set_reg(apic, APIC_LVTx(i), APIC_LVT_MASKED);
573 
574 	apic->nr_lvt_entries = nr_lvt_entries;
575 
576 	/* The number of LVT entries is reflected in the version register. */
577 	kvm_apic_set_version(vcpu);
578 }
579 
580 static const unsigned int apic_lvt_mask[KVM_APIC_MAX_NR_LVT_ENTRIES] = {
581 	[LVT_TIMER] = LVT_MASK,      /* timer mode mask added at runtime */
582 	[LVT_THERMAL_MONITOR] = LVT_MASK | APIC_MODE_MASK,
583 	[LVT_PERFORMANCE_COUNTER] = LVT_MASK | APIC_MODE_MASK,
584 	[LVT_LINT0] = LINT_MASK,
585 	[LVT_LINT1] = LINT_MASK,
586 	[LVT_ERROR] = LVT_MASK,
587 	[LVT_CMCI] = LVT_MASK | APIC_MODE_MASK
588 };
589 
590 static int find_highest_vector(void *bitmap)
591 {
592 	int vec;
593 	u32 *reg;
594 
595 	for (vec = MAX_APIC_VECTOR - APIC_VECTORS_PER_REG;
596 	     vec >= 0; vec -= APIC_VECTORS_PER_REG) {
597 		reg = bitmap + REG_POS(vec);
598 		if (*reg)
599 			return __fls(*reg) + vec;
600 	}
601 
602 	return -1;
603 }
604 
605 static u8 count_vectors(void *bitmap)
606 {
607 	int vec;
608 	u32 *reg;
609 	u8 count = 0;
610 
611 	for (vec = 0; vec < MAX_APIC_VECTOR; vec += APIC_VECTORS_PER_REG) {
612 		reg = bitmap + REG_POS(vec);
613 		count += hweight32(*reg);
614 	}
615 
616 	return count;
617 }
618 
619 bool __kvm_apic_update_irr(u32 *pir, void *regs, int *max_irr)
620 {
621 	u32 i, vec;
622 	u32 pir_val, irr_val, prev_irr_val;
623 	int max_updated_irr;
624 
625 	max_updated_irr = -1;
626 	*max_irr = -1;
627 
628 	for (i = vec = 0; i <= 7; i++, vec += 32) {
629 		pir_val = READ_ONCE(pir[i]);
630 		irr_val = *((u32 *)(regs + APIC_IRR + i * 0x10));
631 		if (pir_val) {
632 			prev_irr_val = irr_val;
633 			irr_val |= xchg(&pir[i], 0);
634 			*((u32 *)(regs + APIC_IRR + i * 0x10)) = irr_val;
635 			if (prev_irr_val != irr_val) {
636 				max_updated_irr =
637 					__fls(irr_val ^ prev_irr_val) + vec;
638 			}
639 		}
640 		if (irr_val)
641 			*max_irr = __fls(irr_val) + vec;
642 	}
643 
644 	return ((max_updated_irr != -1) &&
645 		(max_updated_irr == *max_irr));
646 }
647 EXPORT_SYMBOL_GPL(__kvm_apic_update_irr);
648 
649 bool kvm_apic_update_irr(struct kvm_vcpu *vcpu, u32 *pir, int *max_irr)
650 {
651 	struct kvm_lapic *apic = vcpu->arch.apic;
652 
653 	return __kvm_apic_update_irr(pir, apic->regs, max_irr);
654 }
655 EXPORT_SYMBOL_GPL(kvm_apic_update_irr);
656 
657 static inline int apic_search_irr(struct kvm_lapic *apic)
658 {
659 	return find_highest_vector(apic->regs + APIC_IRR);
660 }
661 
662 static inline int apic_find_highest_irr(struct kvm_lapic *apic)
663 {
664 	int result;
665 
666 	/*
667 	 * Note that irr_pending is just a hint. It will be always
668 	 * true with virtual interrupt delivery enabled.
669 	 */
670 	if (!apic->irr_pending)
671 		return -1;
672 
673 	result = apic_search_irr(apic);
674 	ASSERT(result == -1 || result >= 16);
675 
676 	return result;
677 }
678 
679 static inline void apic_clear_irr(int vec, struct kvm_lapic *apic)
680 {
681 	if (unlikely(apic->apicv_active)) {
682 		/* need to update RVI */
683 		kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
684 		static_call_cond(kvm_x86_hwapic_irr_update)(apic->vcpu,
685 							    apic_find_highest_irr(apic));
686 	} else {
687 		apic->irr_pending = false;
688 		kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
689 		if (apic_search_irr(apic) != -1)
690 			apic->irr_pending = true;
691 	}
692 }
693 
694 void kvm_apic_clear_irr(struct kvm_vcpu *vcpu, int vec)
695 {
696 	apic_clear_irr(vec, vcpu->arch.apic);
697 }
698 EXPORT_SYMBOL_GPL(kvm_apic_clear_irr);
699 
700 static inline void apic_set_isr(int vec, struct kvm_lapic *apic)
701 {
702 	if (__apic_test_and_set_vector(vec, apic->regs + APIC_ISR))
703 		return;
704 
705 	/*
706 	 * With APIC virtualization enabled, all caching is disabled
707 	 * because the processor can modify ISR under the hood.  Instead
708 	 * just set SVI.
709 	 */
710 	if (unlikely(apic->apicv_active))
711 		static_call_cond(kvm_x86_hwapic_isr_update)(vec);
712 	else {
713 		++apic->isr_count;
714 		BUG_ON(apic->isr_count > MAX_APIC_VECTOR);
715 		/*
716 		 * ISR (in service register) bit is set when injecting an interrupt.
717 		 * The highest vector is injected. Thus the latest bit set matches
718 		 * the highest bit in ISR.
719 		 */
720 		apic->highest_isr_cache = vec;
721 	}
722 }
723 
724 static inline int apic_find_highest_isr(struct kvm_lapic *apic)
725 {
726 	int result;
727 
728 	/*
729 	 * Note that isr_count is always 1, and highest_isr_cache
730 	 * is always -1, with APIC virtualization enabled.
731 	 */
732 	if (!apic->isr_count)
733 		return -1;
734 	if (likely(apic->highest_isr_cache != -1))
735 		return apic->highest_isr_cache;
736 
737 	result = find_highest_vector(apic->regs + APIC_ISR);
738 	ASSERT(result == -1 || result >= 16);
739 
740 	return result;
741 }
742 
743 static inline void apic_clear_isr(int vec, struct kvm_lapic *apic)
744 {
745 	if (!__apic_test_and_clear_vector(vec, apic->regs + APIC_ISR))
746 		return;
747 
748 	/*
749 	 * We do get here for APIC virtualization enabled if the guest
750 	 * uses the Hyper-V APIC enlightenment.  In this case we may need
751 	 * to trigger a new interrupt delivery by writing the SVI field;
752 	 * on the other hand isr_count and highest_isr_cache are unused
753 	 * and must be left alone.
754 	 */
755 	if (unlikely(apic->apicv_active))
756 		static_call_cond(kvm_x86_hwapic_isr_update)(apic_find_highest_isr(apic));
757 	else {
758 		--apic->isr_count;
759 		BUG_ON(apic->isr_count < 0);
760 		apic->highest_isr_cache = -1;
761 	}
762 }
763 
764 int kvm_lapic_find_highest_irr(struct kvm_vcpu *vcpu)
765 {
766 	/* This may race with setting of irr in __apic_accept_irq() and
767 	 * value returned may be wrong, but kvm_vcpu_kick() in __apic_accept_irq
768 	 * will cause vmexit immediately and the value will be recalculated
769 	 * on the next vmentry.
770 	 */
771 	return apic_find_highest_irr(vcpu->arch.apic);
772 }
773 EXPORT_SYMBOL_GPL(kvm_lapic_find_highest_irr);
774 
775 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
776 			     int vector, int level, int trig_mode,
777 			     struct dest_map *dest_map);
778 
779 int kvm_apic_set_irq(struct kvm_vcpu *vcpu, struct kvm_lapic_irq *irq,
780 		     struct dest_map *dest_map)
781 {
782 	struct kvm_lapic *apic = vcpu->arch.apic;
783 
784 	return __apic_accept_irq(apic, irq->delivery_mode, irq->vector,
785 			irq->level, irq->trig_mode, dest_map);
786 }
787 
788 static int __pv_send_ipi(unsigned long *ipi_bitmap, struct kvm_apic_map *map,
789 			 struct kvm_lapic_irq *irq, u32 min)
790 {
791 	int i, count = 0;
792 	struct kvm_vcpu *vcpu;
793 
794 	if (min > map->max_apic_id)
795 		return 0;
796 
797 	for_each_set_bit(i, ipi_bitmap,
798 		min((u32)BITS_PER_LONG, (map->max_apic_id - min + 1))) {
799 		if (map->phys_map[min + i]) {
800 			vcpu = map->phys_map[min + i]->vcpu;
801 			count += kvm_apic_set_irq(vcpu, irq, NULL);
802 		}
803 	}
804 
805 	return count;
806 }
807 
808 int kvm_pv_send_ipi(struct kvm *kvm, unsigned long ipi_bitmap_low,
809 		    unsigned long ipi_bitmap_high, u32 min,
810 		    unsigned long icr, int op_64_bit)
811 {
812 	struct kvm_apic_map *map;
813 	struct kvm_lapic_irq irq = {0};
814 	int cluster_size = op_64_bit ? 64 : 32;
815 	int count;
816 
817 	if (icr & (APIC_DEST_MASK | APIC_SHORT_MASK))
818 		return -KVM_EINVAL;
819 
820 	irq.vector = icr & APIC_VECTOR_MASK;
821 	irq.delivery_mode = icr & APIC_MODE_MASK;
822 	irq.level = (icr & APIC_INT_ASSERT) != 0;
823 	irq.trig_mode = icr & APIC_INT_LEVELTRIG;
824 
825 	rcu_read_lock();
826 	map = rcu_dereference(kvm->arch.apic_map);
827 
828 	count = -EOPNOTSUPP;
829 	if (likely(map)) {
830 		count = __pv_send_ipi(&ipi_bitmap_low, map, &irq, min);
831 		min += cluster_size;
832 		count += __pv_send_ipi(&ipi_bitmap_high, map, &irq, min);
833 	}
834 
835 	rcu_read_unlock();
836 	return count;
837 }
838 
839 static int pv_eoi_put_user(struct kvm_vcpu *vcpu, u8 val)
840 {
841 
842 	return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, &val,
843 				      sizeof(val));
844 }
845 
846 static int pv_eoi_get_user(struct kvm_vcpu *vcpu, u8 *val)
847 {
848 
849 	return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, val,
850 				      sizeof(*val));
851 }
852 
853 static inline bool pv_eoi_enabled(struct kvm_vcpu *vcpu)
854 {
855 	return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
856 }
857 
858 static void pv_eoi_set_pending(struct kvm_vcpu *vcpu)
859 {
860 	if (pv_eoi_put_user(vcpu, KVM_PV_EOI_ENABLED) < 0)
861 		return;
862 
863 	__set_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
864 }
865 
866 static bool pv_eoi_test_and_clr_pending(struct kvm_vcpu *vcpu)
867 {
868 	u8 val;
869 
870 	if (pv_eoi_get_user(vcpu, &val) < 0)
871 		return false;
872 
873 	val &= KVM_PV_EOI_ENABLED;
874 
875 	if (val && pv_eoi_put_user(vcpu, KVM_PV_EOI_DISABLED) < 0)
876 		return false;
877 
878 	/*
879 	 * Clear pending bit in any case: it will be set again on vmentry.
880 	 * While this might not be ideal from performance point of view,
881 	 * this makes sure pv eoi is only enabled when we know it's safe.
882 	 */
883 	__clear_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
884 
885 	return val;
886 }
887 
888 static int apic_has_interrupt_for_ppr(struct kvm_lapic *apic, u32 ppr)
889 {
890 	int highest_irr;
891 	if (kvm_x86_ops.sync_pir_to_irr)
892 		highest_irr = static_call(kvm_x86_sync_pir_to_irr)(apic->vcpu);
893 	else
894 		highest_irr = apic_find_highest_irr(apic);
895 	if (highest_irr == -1 || (highest_irr & 0xF0) <= ppr)
896 		return -1;
897 	return highest_irr;
898 }
899 
900 static bool __apic_update_ppr(struct kvm_lapic *apic, u32 *new_ppr)
901 {
902 	u32 tpr, isrv, ppr, old_ppr;
903 	int isr;
904 
905 	old_ppr = kvm_lapic_get_reg(apic, APIC_PROCPRI);
906 	tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI);
907 	isr = apic_find_highest_isr(apic);
908 	isrv = (isr != -1) ? isr : 0;
909 
910 	if ((tpr & 0xf0) >= (isrv & 0xf0))
911 		ppr = tpr & 0xff;
912 	else
913 		ppr = isrv & 0xf0;
914 
915 	*new_ppr = ppr;
916 	if (old_ppr != ppr)
917 		kvm_lapic_set_reg(apic, APIC_PROCPRI, ppr);
918 
919 	return ppr < old_ppr;
920 }
921 
922 static void apic_update_ppr(struct kvm_lapic *apic)
923 {
924 	u32 ppr;
925 
926 	if (__apic_update_ppr(apic, &ppr) &&
927 	    apic_has_interrupt_for_ppr(apic, ppr) != -1)
928 		kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
929 }
930 
931 void kvm_apic_update_ppr(struct kvm_vcpu *vcpu)
932 {
933 	apic_update_ppr(vcpu->arch.apic);
934 }
935 EXPORT_SYMBOL_GPL(kvm_apic_update_ppr);
936 
937 static void apic_set_tpr(struct kvm_lapic *apic, u32 tpr)
938 {
939 	kvm_lapic_set_reg(apic, APIC_TASKPRI, tpr);
940 	apic_update_ppr(apic);
941 }
942 
943 static bool kvm_apic_broadcast(struct kvm_lapic *apic, u32 mda)
944 {
945 	return mda == (apic_x2apic_mode(apic) ?
946 			X2APIC_BROADCAST : APIC_BROADCAST);
947 }
948 
949 static bool kvm_apic_match_physical_addr(struct kvm_lapic *apic, u32 mda)
950 {
951 	if (kvm_apic_broadcast(apic, mda))
952 		return true;
953 
954 	/*
955 	 * Hotplug hack: Accept interrupts for vCPUs in xAPIC mode as if they
956 	 * were in x2APIC mode if the target APIC ID can't be encoded as an
957 	 * xAPIC ID.  This allows unique addressing of hotplugged vCPUs (which
958 	 * start in xAPIC mode) with an APIC ID that is unaddressable in xAPIC
959 	 * mode.  Match the x2APIC ID if and only if the target APIC ID can't
960 	 * be encoded in xAPIC to avoid spurious matches against a vCPU that
961 	 * changed its (addressable) xAPIC ID (which is writable).
962 	 */
963 	if (apic_x2apic_mode(apic) || mda > 0xff)
964 		return mda == kvm_x2apic_id(apic);
965 
966 	return mda == kvm_xapic_id(apic);
967 }
968 
969 static bool kvm_apic_match_logical_addr(struct kvm_lapic *apic, u32 mda)
970 {
971 	u32 logical_id;
972 
973 	if (kvm_apic_broadcast(apic, mda))
974 		return true;
975 
976 	logical_id = kvm_lapic_get_reg(apic, APIC_LDR);
977 
978 	if (apic_x2apic_mode(apic))
979 		return ((logical_id >> 16) == (mda >> 16))
980 		       && (logical_id & mda & 0xffff) != 0;
981 
982 	logical_id = GET_APIC_LOGICAL_ID(logical_id);
983 
984 	switch (kvm_lapic_get_reg(apic, APIC_DFR)) {
985 	case APIC_DFR_FLAT:
986 		return (logical_id & mda) != 0;
987 	case APIC_DFR_CLUSTER:
988 		return ((logical_id >> 4) == (mda >> 4))
989 		       && (logical_id & mda & 0xf) != 0;
990 	default:
991 		return false;
992 	}
993 }
994 
995 /* The KVM local APIC implementation has two quirks:
996  *
997  *  - Real hardware delivers interrupts destined to x2APIC ID > 0xff to LAPICs
998  *    in xAPIC mode if the "destination & 0xff" matches its xAPIC ID.
999  *    KVM doesn't do that aliasing.
1000  *
1001  *  - in-kernel IOAPIC messages have to be delivered directly to
1002  *    x2APIC, because the kernel does not support interrupt remapping.
1003  *    In order to support broadcast without interrupt remapping, x2APIC
1004  *    rewrites the destination of non-IPI messages from APIC_BROADCAST
1005  *    to X2APIC_BROADCAST.
1006  *
1007  * The broadcast quirk can be disabled with KVM_CAP_X2APIC_API.  This is
1008  * important when userspace wants to use x2APIC-format MSIs, because
1009  * APIC_BROADCAST (0xff) is a legal route for "cluster 0, CPUs 0-7".
1010  */
1011 static u32 kvm_apic_mda(struct kvm_vcpu *vcpu, unsigned int dest_id,
1012 		struct kvm_lapic *source, struct kvm_lapic *target)
1013 {
1014 	bool ipi = source != NULL;
1015 
1016 	if (!vcpu->kvm->arch.x2apic_broadcast_quirk_disabled &&
1017 	    !ipi && dest_id == APIC_BROADCAST && apic_x2apic_mode(target))
1018 		return X2APIC_BROADCAST;
1019 
1020 	return dest_id;
1021 }
1022 
1023 bool kvm_apic_match_dest(struct kvm_vcpu *vcpu, struct kvm_lapic *source,
1024 			   int shorthand, unsigned int dest, int dest_mode)
1025 {
1026 	struct kvm_lapic *target = vcpu->arch.apic;
1027 	u32 mda = kvm_apic_mda(vcpu, dest, source, target);
1028 
1029 	ASSERT(target);
1030 	switch (shorthand) {
1031 	case APIC_DEST_NOSHORT:
1032 		if (dest_mode == APIC_DEST_PHYSICAL)
1033 			return kvm_apic_match_physical_addr(target, mda);
1034 		else
1035 			return kvm_apic_match_logical_addr(target, mda);
1036 	case APIC_DEST_SELF:
1037 		return target == source;
1038 	case APIC_DEST_ALLINC:
1039 		return true;
1040 	case APIC_DEST_ALLBUT:
1041 		return target != source;
1042 	default:
1043 		return false;
1044 	}
1045 }
1046 EXPORT_SYMBOL_GPL(kvm_apic_match_dest);
1047 
1048 int kvm_vector_to_index(u32 vector, u32 dest_vcpus,
1049 		       const unsigned long *bitmap, u32 bitmap_size)
1050 {
1051 	u32 mod;
1052 	int i, idx = -1;
1053 
1054 	mod = vector % dest_vcpus;
1055 
1056 	for (i = 0; i <= mod; i++) {
1057 		idx = find_next_bit(bitmap, bitmap_size, idx + 1);
1058 		BUG_ON(idx == bitmap_size);
1059 	}
1060 
1061 	return idx;
1062 }
1063 
1064 static void kvm_apic_disabled_lapic_found(struct kvm *kvm)
1065 {
1066 	if (!kvm->arch.disabled_lapic_found) {
1067 		kvm->arch.disabled_lapic_found = true;
1068 		pr_info("Disabled LAPIC found during irq injection\n");
1069 	}
1070 }
1071 
1072 static bool kvm_apic_is_broadcast_dest(struct kvm *kvm, struct kvm_lapic **src,
1073 		struct kvm_lapic_irq *irq, struct kvm_apic_map *map)
1074 {
1075 	if (kvm->arch.x2apic_broadcast_quirk_disabled) {
1076 		if ((irq->dest_id == APIC_BROADCAST &&
1077 		     map->logical_mode != KVM_APIC_MODE_X2APIC))
1078 			return true;
1079 		if (irq->dest_id == X2APIC_BROADCAST)
1080 			return true;
1081 	} else {
1082 		bool x2apic_ipi = src && *src && apic_x2apic_mode(*src);
1083 		if (irq->dest_id == (x2apic_ipi ?
1084 		                     X2APIC_BROADCAST : APIC_BROADCAST))
1085 			return true;
1086 	}
1087 
1088 	return false;
1089 }
1090 
1091 /* Return true if the interrupt can be handled by using *bitmap as index mask
1092  * for valid destinations in *dst array.
1093  * Return false if kvm_apic_map_get_dest_lapic did nothing useful.
1094  * Note: we may have zero kvm_lapic destinations when we return true, which
1095  * means that the interrupt should be dropped.  In this case, *bitmap would be
1096  * zero and *dst undefined.
1097  */
1098 static inline bool kvm_apic_map_get_dest_lapic(struct kvm *kvm,
1099 		struct kvm_lapic **src, struct kvm_lapic_irq *irq,
1100 		struct kvm_apic_map *map, struct kvm_lapic ***dst,
1101 		unsigned long *bitmap)
1102 {
1103 	int i, lowest;
1104 
1105 	if (irq->shorthand == APIC_DEST_SELF && src) {
1106 		*dst = src;
1107 		*bitmap = 1;
1108 		return true;
1109 	} else if (irq->shorthand)
1110 		return false;
1111 
1112 	if (!map || kvm_apic_is_broadcast_dest(kvm, src, irq, map))
1113 		return false;
1114 
1115 	if (irq->dest_mode == APIC_DEST_PHYSICAL) {
1116 		if (irq->dest_id > map->max_apic_id) {
1117 			*bitmap = 0;
1118 		} else {
1119 			u32 dest_id = array_index_nospec(irq->dest_id, map->max_apic_id + 1);
1120 			*dst = &map->phys_map[dest_id];
1121 			*bitmap = 1;
1122 		}
1123 		return true;
1124 	}
1125 
1126 	*bitmap = 0;
1127 	if (!kvm_apic_map_get_logical_dest(map, irq->dest_id, dst,
1128 				(u16 *)bitmap))
1129 		return false;
1130 
1131 	if (!kvm_lowest_prio_delivery(irq))
1132 		return true;
1133 
1134 	if (!kvm_vector_hashing_enabled()) {
1135 		lowest = -1;
1136 		for_each_set_bit(i, bitmap, 16) {
1137 			if (!(*dst)[i])
1138 				continue;
1139 			if (lowest < 0)
1140 				lowest = i;
1141 			else if (kvm_apic_compare_prio((*dst)[i]->vcpu,
1142 						(*dst)[lowest]->vcpu) < 0)
1143 				lowest = i;
1144 		}
1145 	} else {
1146 		if (!*bitmap)
1147 			return true;
1148 
1149 		lowest = kvm_vector_to_index(irq->vector, hweight16(*bitmap),
1150 				bitmap, 16);
1151 
1152 		if (!(*dst)[lowest]) {
1153 			kvm_apic_disabled_lapic_found(kvm);
1154 			*bitmap = 0;
1155 			return true;
1156 		}
1157 	}
1158 
1159 	*bitmap = (lowest >= 0) ? 1 << lowest : 0;
1160 
1161 	return true;
1162 }
1163 
1164 bool kvm_irq_delivery_to_apic_fast(struct kvm *kvm, struct kvm_lapic *src,
1165 		struct kvm_lapic_irq *irq, int *r, struct dest_map *dest_map)
1166 {
1167 	struct kvm_apic_map *map;
1168 	unsigned long bitmap;
1169 	struct kvm_lapic **dst = NULL;
1170 	int i;
1171 	bool ret;
1172 
1173 	*r = -1;
1174 
1175 	if (irq->shorthand == APIC_DEST_SELF) {
1176 		if (KVM_BUG_ON(!src, kvm)) {
1177 			*r = 0;
1178 			return true;
1179 		}
1180 		*r = kvm_apic_set_irq(src->vcpu, irq, dest_map);
1181 		return true;
1182 	}
1183 
1184 	rcu_read_lock();
1185 	map = rcu_dereference(kvm->arch.apic_map);
1186 
1187 	ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dst, &bitmap);
1188 	if (ret) {
1189 		*r = 0;
1190 		for_each_set_bit(i, &bitmap, 16) {
1191 			if (!dst[i])
1192 				continue;
1193 			*r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map);
1194 		}
1195 	}
1196 
1197 	rcu_read_unlock();
1198 	return ret;
1199 }
1200 
1201 /*
1202  * This routine tries to handle interrupts in posted mode, here is how
1203  * it deals with different cases:
1204  * - For single-destination interrupts, handle it in posted mode
1205  * - Else if vector hashing is enabled and it is a lowest-priority
1206  *   interrupt, handle it in posted mode and use the following mechanism
1207  *   to find the destination vCPU.
1208  *	1. For lowest-priority interrupts, store all the possible
1209  *	   destination vCPUs in an array.
1210  *	2. Use "guest vector % max number of destination vCPUs" to find
1211  *	   the right destination vCPU in the array for the lowest-priority
1212  *	   interrupt.
1213  * - Otherwise, use remapped mode to inject the interrupt.
1214  */
1215 bool kvm_intr_is_single_vcpu_fast(struct kvm *kvm, struct kvm_lapic_irq *irq,
1216 			struct kvm_vcpu **dest_vcpu)
1217 {
1218 	struct kvm_apic_map *map;
1219 	unsigned long bitmap;
1220 	struct kvm_lapic **dst = NULL;
1221 	bool ret = false;
1222 
1223 	if (irq->shorthand)
1224 		return false;
1225 
1226 	rcu_read_lock();
1227 	map = rcu_dereference(kvm->arch.apic_map);
1228 
1229 	if (kvm_apic_map_get_dest_lapic(kvm, NULL, irq, map, &dst, &bitmap) &&
1230 			hweight16(bitmap) == 1) {
1231 		unsigned long i = find_first_bit(&bitmap, 16);
1232 
1233 		if (dst[i]) {
1234 			*dest_vcpu = dst[i]->vcpu;
1235 			ret = true;
1236 		}
1237 	}
1238 
1239 	rcu_read_unlock();
1240 	return ret;
1241 }
1242 
1243 /*
1244  * Add a pending IRQ into lapic.
1245  * Return 1 if successfully added and 0 if discarded.
1246  */
1247 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
1248 			     int vector, int level, int trig_mode,
1249 			     struct dest_map *dest_map)
1250 {
1251 	int result = 0;
1252 	struct kvm_vcpu *vcpu = apic->vcpu;
1253 
1254 	trace_kvm_apic_accept_irq(vcpu->vcpu_id, delivery_mode,
1255 				  trig_mode, vector);
1256 	switch (delivery_mode) {
1257 	case APIC_DM_LOWEST:
1258 		vcpu->arch.apic_arb_prio++;
1259 		fallthrough;
1260 	case APIC_DM_FIXED:
1261 		if (unlikely(trig_mode && !level))
1262 			break;
1263 
1264 		/* FIXME add logic for vcpu on reset */
1265 		if (unlikely(!apic_enabled(apic)))
1266 			break;
1267 
1268 		result = 1;
1269 
1270 		if (dest_map) {
1271 			__set_bit(vcpu->vcpu_id, dest_map->map);
1272 			dest_map->vectors[vcpu->vcpu_id] = vector;
1273 		}
1274 
1275 		if (apic_test_vector(vector, apic->regs + APIC_TMR) != !!trig_mode) {
1276 			if (trig_mode)
1277 				kvm_lapic_set_vector(vector,
1278 						     apic->regs + APIC_TMR);
1279 			else
1280 				kvm_lapic_clear_vector(vector,
1281 						       apic->regs + APIC_TMR);
1282 		}
1283 
1284 		static_call(kvm_x86_deliver_interrupt)(apic, delivery_mode,
1285 						       trig_mode, vector);
1286 		break;
1287 
1288 	case APIC_DM_REMRD:
1289 		result = 1;
1290 		vcpu->arch.pv.pv_unhalted = 1;
1291 		kvm_make_request(KVM_REQ_EVENT, vcpu);
1292 		kvm_vcpu_kick(vcpu);
1293 		break;
1294 
1295 	case APIC_DM_SMI:
1296 		if (!kvm_inject_smi(vcpu)) {
1297 			kvm_vcpu_kick(vcpu);
1298 			result = 1;
1299 		}
1300 		break;
1301 
1302 	case APIC_DM_NMI:
1303 		result = 1;
1304 		kvm_inject_nmi(vcpu);
1305 		kvm_vcpu_kick(vcpu);
1306 		break;
1307 
1308 	case APIC_DM_INIT:
1309 		if (!trig_mode || level) {
1310 			result = 1;
1311 			/* assumes that there are only KVM_APIC_INIT/SIPI */
1312 			apic->pending_events = (1UL << KVM_APIC_INIT);
1313 			kvm_make_request(KVM_REQ_EVENT, vcpu);
1314 			kvm_vcpu_kick(vcpu);
1315 		}
1316 		break;
1317 
1318 	case APIC_DM_STARTUP:
1319 		result = 1;
1320 		apic->sipi_vector = vector;
1321 		/* make sure sipi_vector is visible for the receiver */
1322 		smp_wmb();
1323 		set_bit(KVM_APIC_SIPI, &apic->pending_events);
1324 		kvm_make_request(KVM_REQ_EVENT, vcpu);
1325 		kvm_vcpu_kick(vcpu);
1326 		break;
1327 
1328 	case APIC_DM_EXTINT:
1329 		/*
1330 		 * Should only be called by kvm_apic_local_deliver() with LVT0,
1331 		 * before NMI watchdog was enabled. Already handled by
1332 		 * kvm_apic_accept_pic_intr().
1333 		 */
1334 		break;
1335 
1336 	default:
1337 		printk(KERN_ERR "TODO: unsupported delivery mode %x\n",
1338 		       delivery_mode);
1339 		break;
1340 	}
1341 	return result;
1342 }
1343 
1344 /*
1345  * This routine identifies the destination vcpus mask meant to receive the
1346  * IOAPIC interrupts. It either uses kvm_apic_map_get_dest_lapic() to find
1347  * out the destination vcpus array and set the bitmap or it traverses to
1348  * each available vcpu to identify the same.
1349  */
1350 void kvm_bitmap_or_dest_vcpus(struct kvm *kvm, struct kvm_lapic_irq *irq,
1351 			      unsigned long *vcpu_bitmap)
1352 {
1353 	struct kvm_lapic **dest_vcpu = NULL;
1354 	struct kvm_lapic *src = NULL;
1355 	struct kvm_apic_map *map;
1356 	struct kvm_vcpu *vcpu;
1357 	unsigned long bitmap, i;
1358 	int vcpu_idx;
1359 	bool ret;
1360 
1361 	rcu_read_lock();
1362 	map = rcu_dereference(kvm->arch.apic_map);
1363 
1364 	ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dest_vcpu,
1365 					  &bitmap);
1366 	if (ret) {
1367 		for_each_set_bit(i, &bitmap, 16) {
1368 			if (!dest_vcpu[i])
1369 				continue;
1370 			vcpu_idx = dest_vcpu[i]->vcpu->vcpu_idx;
1371 			__set_bit(vcpu_idx, vcpu_bitmap);
1372 		}
1373 	} else {
1374 		kvm_for_each_vcpu(i, vcpu, kvm) {
1375 			if (!kvm_apic_present(vcpu))
1376 				continue;
1377 			if (!kvm_apic_match_dest(vcpu, NULL,
1378 						 irq->shorthand,
1379 						 irq->dest_id,
1380 						 irq->dest_mode))
1381 				continue;
1382 			__set_bit(i, vcpu_bitmap);
1383 		}
1384 	}
1385 	rcu_read_unlock();
1386 }
1387 
1388 int kvm_apic_compare_prio(struct kvm_vcpu *vcpu1, struct kvm_vcpu *vcpu2)
1389 {
1390 	return vcpu1->arch.apic_arb_prio - vcpu2->arch.apic_arb_prio;
1391 }
1392 
1393 static bool kvm_ioapic_handles_vector(struct kvm_lapic *apic, int vector)
1394 {
1395 	return test_bit(vector, apic->vcpu->arch.ioapic_handled_vectors);
1396 }
1397 
1398 static void kvm_ioapic_send_eoi(struct kvm_lapic *apic, int vector)
1399 {
1400 	int trigger_mode;
1401 
1402 	/* Eoi the ioapic only if the ioapic doesn't own the vector. */
1403 	if (!kvm_ioapic_handles_vector(apic, vector))
1404 		return;
1405 
1406 	/* Request a KVM exit to inform the userspace IOAPIC. */
1407 	if (irqchip_split(apic->vcpu->kvm)) {
1408 		apic->vcpu->arch.pending_ioapic_eoi = vector;
1409 		kvm_make_request(KVM_REQ_IOAPIC_EOI_EXIT, apic->vcpu);
1410 		return;
1411 	}
1412 
1413 	if (apic_test_vector(vector, apic->regs + APIC_TMR))
1414 		trigger_mode = IOAPIC_LEVEL_TRIG;
1415 	else
1416 		trigger_mode = IOAPIC_EDGE_TRIG;
1417 
1418 	kvm_ioapic_update_eoi(apic->vcpu, vector, trigger_mode);
1419 }
1420 
1421 static int apic_set_eoi(struct kvm_lapic *apic)
1422 {
1423 	int vector = apic_find_highest_isr(apic);
1424 
1425 	trace_kvm_eoi(apic, vector);
1426 
1427 	/*
1428 	 * Not every write EOI will has corresponding ISR,
1429 	 * one example is when Kernel check timer on setup_IO_APIC
1430 	 */
1431 	if (vector == -1)
1432 		return vector;
1433 
1434 	apic_clear_isr(vector, apic);
1435 	apic_update_ppr(apic);
1436 
1437 	if (to_hv_vcpu(apic->vcpu) &&
1438 	    test_bit(vector, to_hv_synic(apic->vcpu)->vec_bitmap))
1439 		kvm_hv_synic_send_eoi(apic->vcpu, vector);
1440 
1441 	kvm_ioapic_send_eoi(apic, vector);
1442 	kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1443 	return vector;
1444 }
1445 
1446 /*
1447  * this interface assumes a trap-like exit, which has already finished
1448  * desired side effect including vISR and vPPR update.
1449  */
1450 void kvm_apic_set_eoi_accelerated(struct kvm_vcpu *vcpu, int vector)
1451 {
1452 	struct kvm_lapic *apic = vcpu->arch.apic;
1453 
1454 	trace_kvm_eoi(apic, vector);
1455 
1456 	kvm_ioapic_send_eoi(apic, vector);
1457 	kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1458 }
1459 EXPORT_SYMBOL_GPL(kvm_apic_set_eoi_accelerated);
1460 
1461 void kvm_apic_send_ipi(struct kvm_lapic *apic, u32 icr_low, u32 icr_high)
1462 {
1463 	struct kvm_lapic_irq irq;
1464 
1465 	/* KVM has no delay and should always clear the BUSY/PENDING flag. */
1466 	WARN_ON_ONCE(icr_low & APIC_ICR_BUSY);
1467 
1468 	irq.vector = icr_low & APIC_VECTOR_MASK;
1469 	irq.delivery_mode = icr_low & APIC_MODE_MASK;
1470 	irq.dest_mode = icr_low & APIC_DEST_MASK;
1471 	irq.level = (icr_low & APIC_INT_ASSERT) != 0;
1472 	irq.trig_mode = icr_low & APIC_INT_LEVELTRIG;
1473 	irq.shorthand = icr_low & APIC_SHORT_MASK;
1474 	irq.msi_redir_hint = false;
1475 	if (apic_x2apic_mode(apic))
1476 		irq.dest_id = icr_high;
1477 	else
1478 		irq.dest_id = GET_XAPIC_DEST_FIELD(icr_high);
1479 
1480 	trace_kvm_apic_ipi(icr_low, irq.dest_id);
1481 
1482 	kvm_irq_delivery_to_apic(apic->vcpu->kvm, apic, &irq, NULL);
1483 }
1484 EXPORT_SYMBOL_GPL(kvm_apic_send_ipi);
1485 
1486 static u32 apic_get_tmcct(struct kvm_lapic *apic)
1487 {
1488 	ktime_t remaining, now;
1489 	s64 ns;
1490 
1491 	ASSERT(apic != NULL);
1492 
1493 	/* if initial count is 0, current count should also be 0 */
1494 	if (kvm_lapic_get_reg(apic, APIC_TMICT) == 0 ||
1495 		apic->lapic_timer.period == 0)
1496 		return 0;
1497 
1498 	now = ktime_get();
1499 	remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1500 	if (ktime_to_ns(remaining) < 0)
1501 		remaining = 0;
1502 
1503 	ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
1504 	return div64_u64(ns, (APIC_BUS_CYCLE_NS * apic->divide_count));
1505 }
1506 
1507 static void __report_tpr_access(struct kvm_lapic *apic, bool write)
1508 {
1509 	struct kvm_vcpu *vcpu = apic->vcpu;
1510 	struct kvm_run *run = vcpu->run;
1511 
1512 	kvm_make_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu);
1513 	run->tpr_access.rip = kvm_rip_read(vcpu);
1514 	run->tpr_access.is_write = write;
1515 }
1516 
1517 static inline void report_tpr_access(struct kvm_lapic *apic, bool write)
1518 {
1519 	if (apic->vcpu->arch.tpr_access_reporting)
1520 		__report_tpr_access(apic, write);
1521 }
1522 
1523 static u32 __apic_read(struct kvm_lapic *apic, unsigned int offset)
1524 {
1525 	u32 val = 0;
1526 
1527 	if (offset >= LAPIC_MMIO_LENGTH)
1528 		return 0;
1529 
1530 	switch (offset) {
1531 	case APIC_ARBPRI:
1532 		break;
1533 
1534 	case APIC_TMCCT:	/* Timer CCR */
1535 		if (apic_lvtt_tscdeadline(apic))
1536 			return 0;
1537 
1538 		val = apic_get_tmcct(apic);
1539 		break;
1540 	case APIC_PROCPRI:
1541 		apic_update_ppr(apic);
1542 		val = kvm_lapic_get_reg(apic, offset);
1543 		break;
1544 	case APIC_TASKPRI:
1545 		report_tpr_access(apic, false);
1546 		fallthrough;
1547 	default:
1548 		val = kvm_lapic_get_reg(apic, offset);
1549 		break;
1550 	}
1551 
1552 	return val;
1553 }
1554 
1555 static inline struct kvm_lapic *to_lapic(struct kvm_io_device *dev)
1556 {
1557 	return container_of(dev, struct kvm_lapic, dev);
1558 }
1559 
1560 #define APIC_REG_MASK(reg)	(1ull << ((reg) >> 4))
1561 #define APIC_REGS_MASK(first, count) \
1562 	(APIC_REG_MASK(first) * ((1ull << (count)) - 1))
1563 
1564 u64 kvm_lapic_readable_reg_mask(struct kvm_lapic *apic)
1565 {
1566 	/* Leave bits '0' for reserved and write-only registers. */
1567 	u64 valid_reg_mask =
1568 		APIC_REG_MASK(APIC_ID) |
1569 		APIC_REG_MASK(APIC_LVR) |
1570 		APIC_REG_MASK(APIC_TASKPRI) |
1571 		APIC_REG_MASK(APIC_PROCPRI) |
1572 		APIC_REG_MASK(APIC_LDR) |
1573 		APIC_REG_MASK(APIC_SPIV) |
1574 		APIC_REGS_MASK(APIC_ISR, APIC_ISR_NR) |
1575 		APIC_REGS_MASK(APIC_TMR, APIC_ISR_NR) |
1576 		APIC_REGS_MASK(APIC_IRR, APIC_ISR_NR) |
1577 		APIC_REG_MASK(APIC_ESR) |
1578 		APIC_REG_MASK(APIC_ICR) |
1579 		APIC_REG_MASK(APIC_LVTT) |
1580 		APIC_REG_MASK(APIC_LVTTHMR) |
1581 		APIC_REG_MASK(APIC_LVTPC) |
1582 		APIC_REG_MASK(APIC_LVT0) |
1583 		APIC_REG_MASK(APIC_LVT1) |
1584 		APIC_REG_MASK(APIC_LVTERR) |
1585 		APIC_REG_MASK(APIC_TMICT) |
1586 		APIC_REG_MASK(APIC_TMCCT) |
1587 		APIC_REG_MASK(APIC_TDCR);
1588 
1589 	if (kvm_lapic_lvt_supported(apic, LVT_CMCI))
1590 		valid_reg_mask |= APIC_REG_MASK(APIC_LVTCMCI);
1591 
1592 	/* ARBPRI, DFR, and ICR2 are not valid in x2APIC mode. */
1593 	if (!apic_x2apic_mode(apic))
1594 		valid_reg_mask |= APIC_REG_MASK(APIC_ARBPRI) |
1595 				  APIC_REG_MASK(APIC_DFR) |
1596 				  APIC_REG_MASK(APIC_ICR2);
1597 
1598 	return valid_reg_mask;
1599 }
1600 EXPORT_SYMBOL_GPL(kvm_lapic_readable_reg_mask);
1601 
1602 static int kvm_lapic_reg_read(struct kvm_lapic *apic, u32 offset, int len,
1603 			      void *data)
1604 {
1605 	unsigned char alignment = offset & 0xf;
1606 	u32 result;
1607 
1608 	/*
1609 	 * WARN if KVM reads ICR in x2APIC mode, as it's an 8-byte register in
1610 	 * x2APIC and needs to be manually handled by the caller.
1611 	 */
1612 	WARN_ON_ONCE(apic_x2apic_mode(apic) && offset == APIC_ICR);
1613 
1614 	if (alignment + len > 4)
1615 		return 1;
1616 
1617 	if (offset > 0x3f0 ||
1618 	    !(kvm_lapic_readable_reg_mask(apic) & APIC_REG_MASK(offset)))
1619 		return 1;
1620 
1621 	result = __apic_read(apic, offset & ~0xf);
1622 
1623 	trace_kvm_apic_read(offset, result);
1624 
1625 	switch (len) {
1626 	case 1:
1627 	case 2:
1628 	case 4:
1629 		memcpy(data, (char *)&result + alignment, len);
1630 		break;
1631 	default:
1632 		printk(KERN_ERR "Local APIC read with len = %x, "
1633 		       "should be 1,2, or 4 instead\n", len);
1634 		break;
1635 	}
1636 	return 0;
1637 }
1638 
1639 static int apic_mmio_in_range(struct kvm_lapic *apic, gpa_t addr)
1640 {
1641 	return addr >= apic->base_address &&
1642 		addr < apic->base_address + LAPIC_MMIO_LENGTH;
1643 }
1644 
1645 static int apic_mmio_read(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
1646 			   gpa_t address, int len, void *data)
1647 {
1648 	struct kvm_lapic *apic = to_lapic(this);
1649 	u32 offset = address - apic->base_address;
1650 
1651 	if (!apic_mmio_in_range(apic, address))
1652 		return -EOPNOTSUPP;
1653 
1654 	if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
1655 		if (!kvm_check_has_quirk(vcpu->kvm,
1656 					 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
1657 			return -EOPNOTSUPP;
1658 
1659 		memset(data, 0xff, len);
1660 		return 0;
1661 	}
1662 
1663 	kvm_lapic_reg_read(apic, offset, len, data);
1664 
1665 	return 0;
1666 }
1667 
1668 static void update_divide_count(struct kvm_lapic *apic)
1669 {
1670 	u32 tmp1, tmp2, tdcr;
1671 
1672 	tdcr = kvm_lapic_get_reg(apic, APIC_TDCR);
1673 	tmp1 = tdcr & 0xf;
1674 	tmp2 = ((tmp1 & 0x3) | ((tmp1 & 0x8) >> 1)) + 1;
1675 	apic->divide_count = 0x1 << (tmp2 & 0x7);
1676 }
1677 
1678 static void limit_periodic_timer_frequency(struct kvm_lapic *apic)
1679 {
1680 	/*
1681 	 * Do not allow the guest to program periodic timers with small
1682 	 * interval, since the hrtimers are not throttled by the host
1683 	 * scheduler.
1684 	 */
1685 	if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
1686 		s64 min_period = min_timer_period_us * 1000LL;
1687 
1688 		if (apic->lapic_timer.period < min_period) {
1689 			pr_info_ratelimited(
1690 			    "vcpu %i: requested %lld ns "
1691 			    "lapic timer period limited to %lld ns\n",
1692 			    apic->vcpu->vcpu_id,
1693 			    apic->lapic_timer.period, min_period);
1694 			apic->lapic_timer.period = min_period;
1695 		}
1696 	}
1697 }
1698 
1699 static void cancel_hv_timer(struct kvm_lapic *apic);
1700 
1701 static void cancel_apic_timer(struct kvm_lapic *apic)
1702 {
1703 	hrtimer_cancel(&apic->lapic_timer.timer);
1704 	preempt_disable();
1705 	if (apic->lapic_timer.hv_timer_in_use)
1706 		cancel_hv_timer(apic);
1707 	preempt_enable();
1708 	atomic_set(&apic->lapic_timer.pending, 0);
1709 }
1710 
1711 static void apic_update_lvtt(struct kvm_lapic *apic)
1712 {
1713 	u32 timer_mode = kvm_lapic_get_reg(apic, APIC_LVTT) &
1714 			apic->lapic_timer.timer_mode_mask;
1715 
1716 	if (apic->lapic_timer.timer_mode != timer_mode) {
1717 		if (apic_lvtt_tscdeadline(apic) != (timer_mode ==
1718 				APIC_LVT_TIMER_TSCDEADLINE)) {
1719 			cancel_apic_timer(apic);
1720 			kvm_lapic_set_reg(apic, APIC_TMICT, 0);
1721 			apic->lapic_timer.period = 0;
1722 			apic->lapic_timer.tscdeadline = 0;
1723 		}
1724 		apic->lapic_timer.timer_mode = timer_mode;
1725 		limit_periodic_timer_frequency(apic);
1726 	}
1727 }
1728 
1729 /*
1730  * On APICv, this test will cause a busy wait
1731  * during a higher-priority task.
1732  */
1733 
1734 static bool lapic_timer_int_injected(struct kvm_vcpu *vcpu)
1735 {
1736 	struct kvm_lapic *apic = vcpu->arch.apic;
1737 	u32 reg = kvm_lapic_get_reg(apic, APIC_LVTT);
1738 
1739 	if (kvm_apic_hw_enabled(apic)) {
1740 		int vec = reg & APIC_VECTOR_MASK;
1741 		void *bitmap = apic->regs + APIC_ISR;
1742 
1743 		if (apic->apicv_active)
1744 			bitmap = apic->regs + APIC_IRR;
1745 
1746 		if (apic_test_vector(vec, bitmap))
1747 			return true;
1748 	}
1749 	return false;
1750 }
1751 
1752 static inline void __wait_lapic_expire(struct kvm_vcpu *vcpu, u64 guest_cycles)
1753 {
1754 	u64 timer_advance_ns = vcpu->arch.apic->lapic_timer.timer_advance_ns;
1755 
1756 	/*
1757 	 * If the guest TSC is running at a different ratio than the host, then
1758 	 * convert the delay to nanoseconds to achieve an accurate delay.  Note
1759 	 * that __delay() uses delay_tsc whenever the hardware has TSC, thus
1760 	 * always for VMX enabled hardware.
1761 	 */
1762 	if (vcpu->arch.tsc_scaling_ratio == kvm_caps.default_tsc_scaling_ratio) {
1763 		__delay(min(guest_cycles,
1764 			nsec_to_cycles(vcpu, timer_advance_ns)));
1765 	} else {
1766 		u64 delay_ns = guest_cycles * 1000000ULL;
1767 		do_div(delay_ns, vcpu->arch.virtual_tsc_khz);
1768 		ndelay(min_t(u32, delay_ns, timer_advance_ns));
1769 	}
1770 }
1771 
1772 static inline void adjust_lapic_timer_advance(struct kvm_vcpu *vcpu,
1773 					      s64 advance_expire_delta)
1774 {
1775 	struct kvm_lapic *apic = vcpu->arch.apic;
1776 	u32 timer_advance_ns = apic->lapic_timer.timer_advance_ns;
1777 	u64 ns;
1778 
1779 	/* Do not adjust for tiny fluctuations or large random spikes. */
1780 	if (abs(advance_expire_delta) > LAPIC_TIMER_ADVANCE_ADJUST_MAX ||
1781 	    abs(advance_expire_delta) < LAPIC_TIMER_ADVANCE_ADJUST_MIN)
1782 		return;
1783 
1784 	/* too early */
1785 	if (advance_expire_delta < 0) {
1786 		ns = -advance_expire_delta * 1000000ULL;
1787 		do_div(ns, vcpu->arch.virtual_tsc_khz);
1788 		timer_advance_ns -= ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
1789 	} else {
1790 	/* too late */
1791 		ns = advance_expire_delta * 1000000ULL;
1792 		do_div(ns, vcpu->arch.virtual_tsc_khz);
1793 		timer_advance_ns += ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
1794 	}
1795 
1796 	if (unlikely(timer_advance_ns > LAPIC_TIMER_ADVANCE_NS_MAX))
1797 		timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
1798 	apic->lapic_timer.timer_advance_ns = timer_advance_ns;
1799 }
1800 
1801 static void __kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
1802 {
1803 	struct kvm_lapic *apic = vcpu->arch.apic;
1804 	u64 guest_tsc, tsc_deadline;
1805 
1806 	tsc_deadline = apic->lapic_timer.expired_tscdeadline;
1807 	apic->lapic_timer.expired_tscdeadline = 0;
1808 	guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1809 	trace_kvm_wait_lapic_expire(vcpu->vcpu_id, guest_tsc - tsc_deadline);
1810 
1811 	if (lapic_timer_advance_dynamic) {
1812 		adjust_lapic_timer_advance(vcpu, guest_tsc - tsc_deadline);
1813 		/*
1814 		 * If the timer fired early, reread the TSC to account for the
1815 		 * overhead of the above adjustment to avoid waiting longer
1816 		 * than is necessary.
1817 		 */
1818 		if (guest_tsc < tsc_deadline)
1819 			guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1820 	}
1821 
1822 	if (guest_tsc < tsc_deadline)
1823 		__wait_lapic_expire(vcpu, tsc_deadline - guest_tsc);
1824 }
1825 
1826 void kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
1827 {
1828 	if (lapic_in_kernel(vcpu) &&
1829 	    vcpu->arch.apic->lapic_timer.expired_tscdeadline &&
1830 	    vcpu->arch.apic->lapic_timer.timer_advance_ns &&
1831 	    lapic_timer_int_injected(vcpu))
1832 		__kvm_wait_lapic_expire(vcpu);
1833 }
1834 EXPORT_SYMBOL_GPL(kvm_wait_lapic_expire);
1835 
1836 static void kvm_apic_inject_pending_timer_irqs(struct kvm_lapic *apic)
1837 {
1838 	struct kvm_timer *ktimer = &apic->lapic_timer;
1839 
1840 	kvm_apic_local_deliver(apic, APIC_LVTT);
1841 	if (apic_lvtt_tscdeadline(apic)) {
1842 		ktimer->tscdeadline = 0;
1843 	} else if (apic_lvtt_oneshot(apic)) {
1844 		ktimer->tscdeadline = 0;
1845 		ktimer->target_expiration = 0;
1846 	}
1847 }
1848 
1849 static void apic_timer_expired(struct kvm_lapic *apic, bool from_timer_fn)
1850 {
1851 	struct kvm_vcpu *vcpu = apic->vcpu;
1852 	struct kvm_timer *ktimer = &apic->lapic_timer;
1853 
1854 	if (atomic_read(&apic->lapic_timer.pending))
1855 		return;
1856 
1857 	if (apic_lvtt_tscdeadline(apic) || ktimer->hv_timer_in_use)
1858 		ktimer->expired_tscdeadline = ktimer->tscdeadline;
1859 
1860 	if (!from_timer_fn && apic->apicv_active) {
1861 		WARN_ON(kvm_get_running_vcpu() != vcpu);
1862 		kvm_apic_inject_pending_timer_irqs(apic);
1863 		return;
1864 	}
1865 
1866 	if (kvm_use_posted_timer_interrupt(apic->vcpu)) {
1867 		/*
1868 		 * Ensure the guest's timer has truly expired before posting an
1869 		 * interrupt.  Open code the relevant checks to avoid querying
1870 		 * lapic_timer_int_injected(), which will be false since the
1871 		 * interrupt isn't yet injected.  Waiting until after injecting
1872 		 * is not an option since that won't help a posted interrupt.
1873 		 */
1874 		if (vcpu->arch.apic->lapic_timer.expired_tscdeadline &&
1875 		    vcpu->arch.apic->lapic_timer.timer_advance_ns)
1876 			__kvm_wait_lapic_expire(vcpu);
1877 		kvm_apic_inject_pending_timer_irqs(apic);
1878 		return;
1879 	}
1880 
1881 	atomic_inc(&apic->lapic_timer.pending);
1882 	kvm_make_request(KVM_REQ_UNBLOCK, vcpu);
1883 	if (from_timer_fn)
1884 		kvm_vcpu_kick(vcpu);
1885 }
1886 
1887 static void start_sw_tscdeadline(struct kvm_lapic *apic)
1888 {
1889 	struct kvm_timer *ktimer = &apic->lapic_timer;
1890 	u64 guest_tsc, tscdeadline = ktimer->tscdeadline;
1891 	u64 ns = 0;
1892 	ktime_t expire;
1893 	struct kvm_vcpu *vcpu = apic->vcpu;
1894 	unsigned long this_tsc_khz = vcpu->arch.virtual_tsc_khz;
1895 	unsigned long flags;
1896 	ktime_t now;
1897 
1898 	if (unlikely(!tscdeadline || !this_tsc_khz))
1899 		return;
1900 
1901 	local_irq_save(flags);
1902 
1903 	now = ktime_get();
1904 	guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1905 
1906 	ns = (tscdeadline - guest_tsc) * 1000000ULL;
1907 	do_div(ns, this_tsc_khz);
1908 
1909 	if (likely(tscdeadline > guest_tsc) &&
1910 	    likely(ns > apic->lapic_timer.timer_advance_ns)) {
1911 		expire = ktime_add_ns(now, ns);
1912 		expire = ktime_sub_ns(expire, ktimer->timer_advance_ns);
1913 		hrtimer_start(&ktimer->timer, expire, HRTIMER_MODE_ABS_HARD);
1914 	} else
1915 		apic_timer_expired(apic, false);
1916 
1917 	local_irq_restore(flags);
1918 }
1919 
1920 static inline u64 tmict_to_ns(struct kvm_lapic *apic, u32 tmict)
1921 {
1922 	return (u64)tmict * APIC_BUS_CYCLE_NS * (u64)apic->divide_count;
1923 }
1924 
1925 static void update_target_expiration(struct kvm_lapic *apic, uint32_t old_divisor)
1926 {
1927 	ktime_t now, remaining;
1928 	u64 ns_remaining_old, ns_remaining_new;
1929 
1930 	apic->lapic_timer.period =
1931 			tmict_to_ns(apic, kvm_lapic_get_reg(apic, APIC_TMICT));
1932 	limit_periodic_timer_frequency(apic);
1933 
1934 	now = ktime_get();
1935 	remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1936 	if (ktime_to_ns(remaining) < 0)
1937 		remaining = 0;
1938 
1939 	ns_remaining_old = ktime_to_ns(remaining);
1940 	ns_remaining_new = mul_u64_u32_div(ns_remaining_old,
1941 	                                   apic->divide_count, old_divisor);
1942 
1943 	apic->lapic_timer.tscdeadline +=
1944 		nsec_to_cycles(apic->vcpu, ns_remaining_new) -
1945 		nsec_to_cycles(apic->vcpu, ns_remaining_old);
1946 	apic->lapic_timer.target_expiration = ktime_add_ns(now, ns_remaining_new);
1947 }
1948 
1949 static bool set_target_expiration(struct kvm_lapic *apic, u32 count_reg)
1950 {
1951 	ktime_t now;
1952 	u64 tscl = rdtsc();
1953 	s64 deadline;
1954 
1955 	now = ktime_get();
1956 	apic->lapic_timer.period =
1957 			tmict_to_ns(apic, kvm_lapic_get_reg(apic, APIC_TMICT));
1958 
1959 	if (!apic->lapic_timer.period) {
1960 		apic->lapic_timer.tscdeadline = 0;
1961 		return false;
1962 	}
1963 
1964 	limit_periodic_timer_frequency(apic);
1965 	deadline = apic->lapic_timer.period;
1966 
1967 	if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic)) {
1968 		if (unlikely(count_reg != APIC_TMICT)) {
1969 			deadline = tmict_to_ns(apic,
1970 				     kvm_lapic_get_reg(apic, count_reg));
1971 			if (unlikely(deadline <= 0)) {
1972 				if (apic_lvtt_period(apic))
1973 					deadline = apic->lapic_timer.period;
1974 				else
1975 					deadline = 0;
1976 			}
1977 			else if (unlikely(deadline > apic->lapic_timer.period)) {
1978 				pr_info_ratelimited(
1979 				    "vcpu %i: requested lapic timer restore with "
1980 				    "starting count register %#x=%u (%lld ns) > initial count (%lld ns). "
1981 				    "Using initial count to start timer.\n",
1982 				    apic->vcpu->vcpu_id,
1983 				    count_reg,
1984 				    kvm_lapic_get_reg(apic, count_reg),
1985 				    deadline, apic->lapic_timer.period);
1986 				kvm_lapic_set_reg(apic, count_reg, 0);
1987 				deadline = apic->lapic_timer.period;
1988 			}
1989 		}
1990 	}
1991 
1992 	apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
1993 		nsec_to_cycles(apic->vcpu, deadline);
1994 	apic->lapic_timer.target_expiration = ktime_add_ns(now, deadline);
1995 
1996 	return true;
1997 }
1998 
1999 static void advance_periodic_target_expiration(struct kvm_lapic *apic)
2000 {
2001 	ktime_t now = ktime_get();
2002 	u64 tscl = rdtsc();
2003 	ktime_t delta;
2004 
2005 	/*
2006 	 * Synchronize both deadlines to the same time source or
2007 	 * differences in the periods (caused by differences in the
2008 	 * underlying clocks or numerical approximation errors) will
2009 	 * cause the two to drift apart over time as the errors
2010 	 * accumulate.
2011 	 */
2012 	apic->lapic_timer.target_expiration =
2013 		ktime_add_ns(apic->lapic_timer.target_expiration,
2014 				apic->lapic_timer.period);
2015 	delta = ktime_sub(apic->lapic_timer.target_expiration, now);
2016 	apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
2017 		nsec_to_cycles(apic->vcpu, delta);
2018 }
2019 
2020 static void start_sw_period(struct kvm_lapic *apic)
2021 {
2022 	if (!apic->lapic_timer.period)
2023 		return;
2024 
2025 	if (ktime_after(ktime_get(),
2026 			apic->lapic_timer.target_expiration)) {
2027 		apic_timer_expired(apic, false);
2028 
2029 		if (apic_lvtt_oneshot(apic))
2030 			return;
2031 
2032 		advance_periodic_target_expiration(apic);
2033 	}
2034 
2035 	hrtimer_start(&apic->lapic_timer.timer,
2036 		apic->lapic_timer.target_expiration,
2037 		HRTIMER_MODE_ABS_HARD);
2038 }
2039 
2040 bool kvm_lapic_hv_timer_in_use(struct kvm_vcpu *vcpu)
2041 {
2042 	if (!lapic_in_kernel(vcpu))
2043 		return false;
2044 
2045 	return vcpu->arch.apic->lapic_timer.hv_timer_in_use;
2046 }
2047 
2048 static void cancel_hv_timer(struct kvm_lapic *apic)
2049 {
2050 	WARN_ON(preemptible());
2051 	WARN_ON(!apic->lapic_timer.hv_timer_in_use);
2052 	static_call(kvm_x86_cancel_hv_timer)(apic->vcpu);
2053 	apic->lapic_timer.hv_timer_in_use = false;
2054 }
2055 
2056 static bool start_hv_timer(struct kvm_lapic *apic)
2057 {
2058 	struct kvm_timer *ktimer = &apic->lapic_timer;
2059 	struct kvm_vcpu *vcpu = apic->vcpu;
2060 	bool expired;
2061 
2062 	WARN_ON(preemptible());
2063 	if (!kvm_can_use_hv_timer(vcpu))
2064 		return false;
2065 
2066 	if (!ktimer->tscdeadline)
2067 		return false;
2068 
2069 	if (static_call(kvm_x86_set_hv_timer)(vcpu, ktimer->tscdeadline, &expired))
2070 		return false;
2071 
2072 	ktimer->hv_timer_in_use = true;
2073 	hrtimer_cancel(&ktimer->timer);
2074 
2075 	/*
2076 	 * To simplify handling the periodic timer, leave the hv timer running
2077 	 * even if the deadline timer has expired, i.e. rely on the resulting
2078 	 * VM-Exit to recompute the periodic timer's target expiration.
2079 	 */
2080 	if (!apic_lvtt_period(apic)) {
2081 		/*
2082 		 * Cancel the hv timer if the sw timer fired while the hv timer
2083 		 * was being programmed, or if the hv timer itself expired.
2084 		 */
2085 		if (atomic_read(&ktimer->pending)) {
2086 			cancel_hv_timer(apic);
2087 		} else if (expired) {
2088 			apic_timer_expired(apic, false);
2089 			cancel_hv_timer(apic);
2090 		}
2091 	}
2092 
2093 	trace_kvm_hv_timer_state(vcpu->vcpu_id, ktimer->hv_timer_in_use);
2094 
2095 	return true;
2096 }
2097 
2098 static void start_sw_timer(struct kvm_lapic *apic)
2099 {
2100 	struct kvm_timer *ktimer = &apic->lapic_timer;
2101 
2102 	WARN_ON(preemptible());
2103 	if (apic->lapic_timer.hv_timer_in_use)
2104 		cancel_hv_timer(apic);
2105 	if (!apic_lvtt_period(apic) && atomic_read(&ktimer->pending))
2106 		return;
2107 
2108 	if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
2109 		start_sw_period(apic);
2110 	else if (apic_lvtt_tscdeadline(apic))
2111 		start_sw_tscdeadline(apic);
2112 	trace_kvm_hv_timer_state(apic->vcpu->vcpu_id, false);
2113 }
2114 
2115 static void restart_apic_timer(struct kvm_lapic *apic)
2116 {
2117 	preempt_disable();
2118 
2119 	if (!apic_lvtt_period(apic) && atomic_read(&apic->lapic_timer.pending))
2120 		goto out;
2121 
2122 	if (!start_hv_timer(apic))
2123 		start_sw_timer(apic);
2124 out:
2125 	preempt_enable();
2126 }
2127 
2128 void kvm_lapic_expired_hv_timer(struct kvm_vcpu *vcpu)
2129 {
2130 	struct kvm_lapic *apic = vcpu->arch.apic;
2131 
2132 	preempt_disable();
2133 	/* If the preempt notifier has already run, it also called apic_timer_expired */
2134 	if (!apic->lapic_timer.hv_timer_in_use)
2135 		goto out;
2136 	WARN_ON(kvm_vcpu_is_blocking(vcpu));
2137 	apic_timer_expired(apic, false);
2138 	cancel_hv_timer(apic);
2139 
2140 	if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
2141 		advance_periodic_target_expiration(apic);
2142 		restart_apic_timer(apic);
2143 	}
2144 out:
2145 	preempt_enable();
2146 }
2147 EXPORT_SYMBOL_GPL(kvm_lapic_expired_hv_timer);
2148 
2149 void kvm_lapic_switch_to_hv_timer(struct kvm_vcpu *vcpu)
2150 {
2151 	restart_apic_timer(vcpu->arch.apic);
2152 }
2153 
2154 void kvm_lapic_switch_to_sw_timer(struct kvm_vcpu *vcpu)
2155 {
2156 	struct kvm_lapic *apic = vcpu->arch.apic;
2157 
2158 	preempt_disable();
2159 	/* Possibly the TSC deadline timer is not enabled yet */
2160 	if (apic->lapic_timer.hv_timer_in_use)
2161 		start_sw_timer(apic);
2162 	preempt_enable();
2163 }
2164 
2165 void kvm_lapic_restart_hv_timer(struct kvm_vcpu *vcpu)
2166 {
2167 	struct kvm_lapic *apic = vcpu->arch.apic;
2168 
2169 	WARN_ON(!apic->lapic_timer.hv_timer_in_use);
2170 	restart_apic_timer(apic);
2171 }
2172 
2173 static void __start_apic_timer(struct kvm_lapic *apic, u32 count_reg)
2174 {
2175 	atomic_set(&apic->lapic_timer.pending, 0);
2176 
2177 	if ((apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
2178 	    && !set_target_expiration(apic, count_reg))
2179 		return;
2180 
2181 	restart_apic_timer(apic);
2182 }
2183 
2184 static void start_apic_timer(struct kvm_lapic *apic)
2185 {
2186 	__start_apic_timer(apic, APIC_TMICT);
2187 }
2188 
2189 static void apic_manage_nmi_watchdog(struct kvm_lapic *apic, u32 lvt0_val)
2190 {
2191 	bool lvt0_in_nmi_mode = apic_lvt_nmi_mode(lvt0_val);
2192 
2193 	if (apic->lvt0_in_nmi_mode != lvt0_in_nmi_mode) {
2194 		apic->lvt0_in_nmi_mode = lvt0_in_nmi_mode;
2195 		if (lvt0_in_nmi_mode) {
2196 			atomic_inc(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
2197 		} else
2198 			atomic_dec(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
2199 	}
2200 }
2201 
2202 static int get_lvt_index(u32 reg)
2203 {
2204 	if (reg == APIC_LVTCMCI)
2205 		return LVT_CMCI;
2206 	if (reg < APIC_LVTT || reg > APIC_LVTERR)
2207 		return -1;
2208 	return array_index_nospec(
2209 			(reg - APIC_LVTT) >> 4, KVM_APIC_MAX_NR_LVT_ENTRIES);
2210 }
2211 
2212 static int kvm_lapic_reg_write(struct kvm_lapic *apic, u32 reg, u32 val)
2213 {
2214 	int ret = 0;
2215 
2216 	trace_kvm_apic_write(reg, val);
2217 
2218 	switch (reg) {
2219 	case APIC_ID:		/* Local APIC ID */
2220 		if (!apic_x2apic_mode(apic)) {
2221 			kvm_apic_set_xapic_id(apic, val >> 24);
2222 		} else {
2223 			ret = 1;
2224 		}
2225 		break;
2226 
2227 	case APIC_TASKPRI:
2228 		report_tpr_access(apic, true);
2229 		apic_set_tpr(apic, val & 0xff);
2230 		break;
2231 
2232 	case APIC_EOI:
2233 		apic_set_eoi(apic);
2234 		break;
2235 
2236 	case APIC_LDR:
2237 		if (!apic_x2apic_mode(apic))
2238 			kvm_apic_set_ldr(apic, val & APIC_LDR_MASK);
2239 		else
2240 			ret = 1;
2241 		break;
2242 
2243 	case APIC_DFR:
2244 		if (!apic_x2apic_mode(apic))
2245 			kvm_apic_set_dfr(apic, val | 0x0FFFFFFF);
2246 		else
2247 			ret = 1;
2248 		break;
2249 
2250 	case APIC_SPIV: {
2251 		u32 mask = 0x3ff;
2252 		if (kvm_lapic_get_reg(apic, APIC_LVR) & APIC_LVR_DIRECTED_EOI)
2253 			mask |= APIC_SPIV_DIRECTED_EOI;
2254 		apic_set_spiv(apic, val & mask);
2255 		if (!(val & APIC_SPIV_APIC_ENABLED)) {
2256 			int i;
2257 
2258 			for (i = 0; i < apic->nr_lvt_entries; i++) {
2259 				kvm_lapic_set_reg(apic, APIC_LVTx(i),
2260 					kvm_lapic_get_reg(apic, APIC_LVTx(i)) | APIC_LVT_MASKED);
2261 			}
2262 			apic_update_lvtt(apic);
2263 			atomic_set(&apic->lapic_timer.pending, 0);
2264 
2265 		}
2266 		break;
2267 	}
2268 	case APIC_ICR:
2269 		WARN_ON_ONCE(apic_x2apic_mode(apic));
2270 
2271 		/* No delay here, so we always clear the pending bit */
2272 		val &= ~APIC_ICR_BUSY;
2273 		kvm_apic_send_ipi(apic, val, kvm_lapic_get_reg(apic, APIC_ICR2));
2274 		kvm_lapic_set_reg(apic, APIC_ICR, val);
2275 		break;
2276 	case APIC_ICR2:
2277 		if (apic_x2apic_mode(apic))
2278 			ret = 1;
2279 		else
2280 			kvm_lapic_set_reg(apic, APIC_ICR2, val & 0xff000000);
2281 		break;
2282 
2283 	case APIC_LVT0:
2284 		apic_manage_nmi_watchdog(apic, val);
2285 		fallthrough;
2286 	case APIC_LVTTHMR:
2287 	case APIC_LVTPC:
2288 	case APIC_LVT1:
2289 	case APIC_LVTERR:
2290 	case APIC_LVTCMCI: {
2291 		u32 index = get_lvt_index(reg);
2292 		if (!kvm_lapic_lvt_supported(apic, index)) {
2293 			ret = 1;
2294 			break;
2295 		}
2296 		if (!kvm_apic_sw_enabled(apic))
2297 			val |= APIC_LVT_MASKED;
2298 		val &= apic_lvt_mask[index];
2299 		kvm_lapic_set_reg(apic, reg, val);
2300 		break;
2301 	}
2302 
2303 	case APIC_LVTT:
2304 		if (!kvm_apic_sw_enabled(apic))
2305 			val |= APIC_LVT_MASKED;
2306 		val &= (apic_lvt_mask[0] | apic->lapic_timer.timer_mode_mask);
2307 		kvm_lapic_set_reg(apic, APIC_LVTT, val);
2308 		apic_update_lvtt(apic);
2309 		break;
2310 
2311 	case APIC_TMICT:
2312 		if (apic_lvtt_tscdeadline(apic))
2313 			break;
2314 
2315 		cancel_apic_timer(apic);
2316 		kvm_lapic_set_reg(apic, APIC_TMICT, val);
2317 		start_apic_timer(apic);
2318 		break;
2319 
2320 	case APIC_TDCR: {
2321 		uint32_t old_divisor = apic->divide_count;
2322 
2323 		kvm_lapic_set_reg(apic, APIC_TDCR, val & 0xb);
2324 		update_divide_count(apic);
2325 		if (apic->divide_count != old_divisor &&
2326 				apic->lapic_timer.period) {
2327 			hrtimer_cancel(&apic->lapic_timer.timer);
2328 			update_target_expiration(apic, old_divisor);
2329 			restart_apic_timer(apic);
2330 		}
2331 		break;
2332 	}
2333 	case APIC_ESR:
2334 		if (apic_x2apic_mode(apic) && val != 0)
2335 			ret = 1;
2336 		break;
2337 
2338 	case APIC_SELF_IPI:
2339 		/*
2340 		 * Self-IPI exists only when x2APIC is enabled.  Bits 7:0 hold
2341 		 * the vector, everything else is reserved.
2342 		 */
2343 		if (!apic_x2apic_mode(apic) || (val & ~APIC_VECTOR_MASK))
2344 			ret = 1;
2345 		else
2346 			kvm_apic_send_ipi(apic, APIC_DEST_SELF | val, 0);
2347 		break;
2348 	default:
2349 		ret = 1;
2350 		break;
2351 	}
2352 
2353 	/*
2354 	 * Recalculate APIC maps if necessary, e.g. if the software enable bit
2355 	 * was toggled, the APIC ID changed, etc...   The maps are marked dirty
2356 	 * on relevant changes, i.e. this is a nop for most writes.
2357 	 */
2358 	kvm_recalculate_apic_map(apic->vcpu->kvm);
2359 
2360 	return ret;
2361 }
2362 
2363 static int apic_mmio_write(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
2364 			    gpa_t address, int len, const void *data)
2365 {
2366 	struct kvm_lapic *apic = to_lapic(this);
2367 	unsigned int offset = address - apic->base_address;
2368 	u32 val;
2369 
2370 	if (!apic_mmio_in_range(apic, address))
2371 		return -EOPNOTSUPP;
2372 
2373 	if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
2374 		if (!kvm_check_has_quirk(vcpu->kvm,
2375 					 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
2376 			return -EOPNOTSUPP;
2377 
2378 		return 0;
2379 	}
2380 
2381 	/*
2382 	 * APIC register must be aligned on 128-bits boundary.
2383 	 * 32/64/128 bits registers must be accessed thru 32 bits.
2384 	 * Refer SDM 8.4.1
2385 	 */
2386 	if (len != 4 || (offset & 0xf))
2387 		return 0;
2388 
2389 	val = *(u32*)data;
2390 
2391 	kvm_lapic_reg_write(apic, offset & 0xff0, val);
2392 
2393 	return 0;
2394 }
2395 
2396 void kvm_lapic_set_eoi(struct kvm_vcpu *vcpu)
2397 {
2398 	kvm_lapic_reg_write(vcpu->arch.apic, APIC_EOI, 0);
2399 }
2400 EXPORT_SYMBOL_GPL(kvm_lapic_set_eoi);
2401 
2402 /* emulate APIC access in a trap manner */
2403 void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset)
2404 {
2405 	struct kvm_lapic *apic = vcpu->arch.apic;
2406 	u64 val;
2407 
2408 	/*
2409 	 * ICR is a single 64-bit register when x2APIC is enabled.  For legacy
2410 	 * xAPIC, ICR writes need to go down the common (slightly slower) path
2411 	 * to get the upper half from ICR2.
2412 	 */
2413 	if (apic_x2apic_mode(apic) && offset == APIC_ICR) {
2414 		val = kvm_lapic_get_reg64(apic, APIC_ICR);
2415 		kvm_apic_send_ipi(apic, (u32)val, (u32)(val >> 32));
2416 		trace_kvm_apic_write(APIC_ICR, val);
2417 	} else {
2418 		/* TODO: optimize to just emulate side effect w/o one more write */
2419 		val = kvm_lapic_get_reg(apic, offset);
2420 		kvm_lapic_reg_write(apic, offset, (u32)val);
2421 	}
2422 }
2423 EXPORT_SYMBOL_GPL(kvm_apic_write_nodecode);
2424 
2425 void kvm_free_lapic(struct kvm_vcpu *vcpu)
2426 {
2427 	struct kvm_lapic *apic = vcpu->arch.apic;
2428 
2429 	if (!vcpu->arch.apic)
2430 		return;
2431 
2432 	hrtimer_cancel(&apic->lapic_timer.timer);
2433 
2434 	if (!(vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE))
2435 		static_branch_slow_dec_deferred(&apic_hw_disabled);
2436 
2437 	if (!apic->sw_enabled)
2438 		static_branch_slow_dec_deferred(&apic_sw_disabled);
2439 
2440 	if (apic->regs)
2441 		free_page((unsigned long)apic->regs);
2442 
2443 	kfree(apic);
2444 }
2445 
2446 /*
2447  *----------------------------------------------------------------------
2448  * LAPIC interface
2449  *----------------------------------------------------------------------
2450  */
2451 u64 kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu)
2452 {
2453 	struct kvm_lapic *apic = vcpu->arch.apic;
2454 
2455 	if (!kvm_apic_present(vcpu) || !apic_lvtt_tscdeadline(apic))
2456 		return 0;
2457 
2458 	return apic->lapic_timer.tscdeadline;
2459 }
2460 
2461 void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data)
2462 {
2463 	struct kvm_lapic *apic = vcpu->arch.apic;
2464 
2465 	if (!kvm_apic_present(vcpu) || !apic_lvtt_tscdeadline(apic))
2466 		return;
2467 
2468 	hrtimer_cancel(&apic->lapic_timer.timer);
2469 	apic->lapic_timer.tscdeadline = data;
2470 	start_apic_timer(apic);
2471 }
2472 
2473 void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8)
2474 {
2475 	apic_set_tpr(vcpu->arch.apic, (cr8 & 0x0f) << 4);
2476 }
2477 
2478 u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
2479 {
2480 	u64 tpr;
2481 
2482 	tpr = (u64) kvm_lapic_get_reg(vcpu->arch.apic, APIC_TASKPRI);
2483 
2484 	return (tpr & 0xf0) >> 4;
2485 }
2486 
2487 void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
2488 {
2489 	u64 old_value = vcpu->arch.apic_base;
2490 	struct kvm_lapic *apic = vcpu->arch.apic;
2491 
2492 	vcpu->arch.apic_base = value;
2493 
2494 	if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE)
2495 		kvm_update_cpuid_runtime(vcpu);
2496 
2497 	if (!apic)
2498 		return;
2499 
2500 	/* update jump label if enable bit changes */
2501 	if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE) {
2502 		if (value & MSR_IA32_APICBASE_ENABLE) {
2503 			kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2504 			static_branch_slow_dec_deferred(&apic_hw_disabled);
2505 			/* Check if there are APF page ready requests pending */
2506 			kvm_make_request(KVM_REQ_APF_READY, vcpu);
2507 		} else {
2508 			static_branch_inc(&apic_hw_disabled.key);
2509 			atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
2510 		}
2511 	}
2512 
2513 	if ((old_value ^ value) & X2APIC_ENABLE) {
2514 		if (value & X2APIC_ENABLE)
2515 			kvm_apic_set_x2apic_id(apic, vcpu->vcpu_id);
2516 		else if (value & MSR_IA32_APICBASE_ENABLE)
2517 			kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2518 	}
2519 
2520 	if ((old_value ^ value) & (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) {
2521 		kvm_make_request(KVM_REQ_APICV_UPDATE, vcpu);
2522 		static_call_cond(kvm_x86_set_virtual_apic_mode)(vcpu);
2523 	}
2524 
2525 	apic->base_address = apic->vcpu->arch.apic_base &
2526 			     MSR_IA32_APICBASE_BASE;
2527 
2528 	if ((value & MSR_IA32_APICBASE_ENABLE) &&
2529 	     apic->base_address != APIC_DEFAULT_PHYS_BASE) {
2530 		kvm_set_apicv_inhibit(apic->vcpu->kvm,
2531 				      APICV_INHIBIT_REASON_APIC_BASE_MODIFIED);
2532 	}
2533 }
2534 
2535 void kvm_apic_update_apicv(struct kvm_vcpu *vcpu)
2536 {
2537 	struct kvm_lapic *apic = vcpu->arch.apic;
2538 
2539 	if (apic->apicv_active) {
2540 		/* irr_pending is always true when apicv is activated. */
2541 		apic->irr_pending = true;
2542 		apic->isr_count = 1;
2543 	} else {
2544 		/*
2545 		 * Don't clear irr_pending, searching the IRR can race with
2546 		 * updates from the CPU as APICv is still active from hardware's
2547 		 * perspective.  The flag will be cleared as appropriate when
2548 		 * KVM injects the interrupt.
2549 		 */
2550 		apic->isr_count = count_vectors(apic->regs + APIC_ISR);
2551 	}
2552 	apic->highest_isr_cache = -1;
2553 }
2554 
2555 int kvm_alloc_apic_access_page(struct kvm *kvm)
2556 {
2557 	struct page *page;
2558 	void __user *hva;
2559 	int ret = 0;
2560 
2561 	mutex_lock(&kvm->slots_lock);
2562 	if (kvm->arch.apic_access_memslot_enabled ||
2563 	    kvm->arch.apic_access_memslot_inhibited)
2564 		goto out;
2565 
2566 	hva = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
2567 				      APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
2568 	if (IS_ERR(hva)) {
2569 		ret = PTR_ERR(hva);
2570 		goto out;
2571 	}
2572 
2573 	page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
2574 	if (is_error_page(page)) {
2575 		ret = -EFAULT;
2576 		goto out;
2577 	}
2578 
2579 	/*
2580 	 * Do not pin the page in memory, so that memory hot-unplug
2581 	 * is able to migrate it.
2582 	 */
2583 	put_page(page);
2584 	kvm->arch.apic_access_memslot_enabled = true;
2585 out:
2586 	mutex_unlock(&kvm->slots_lock);
2587 	return ret;
2588 }
2589 EXPORT_SYMBOL_GPL(kvm_alloc_apic_access_page);
2590 
2591 void kvm_inhibit_apic_access_page(struct kvm_vcpu *vcpu)
2592 {
2593 	struct kvm *kvm = vcpu->kvm;
2594 
2595 	if (!kvm->arch.apic_access_memslot_enabled)
2596 		return;
2597 
2598 	kvm_vcpu_srcu_read_unlock(vcpu);
2599 
2600 	mutex_lock(&kvm->slots_lock);
2601 
2602 	if (kvm->arch.apic_access_memslot_enabled) {
2603 		__x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
2604 		/*
2605 		 * Clear "enabled" after the memslot is deleted so that a
2606 		 * different vCPU doesn't get a false negative when checking
2607 		 * the flag out of slots_lock.  No additional memory barrier is
2608 		 * needed as modifying memslots requires waiting other vCPUs to
2609 		 * drop SRCU (see above), and false positives are ok as the
2610 		 * flag is rechecked after acquiring slots_lock.
2611 		 */
2612 		kvm->arch.apic_access_memslot_enabled = false;
2613 
2614 		/*
2615 		 * Mark the memslot as inhibited to prevent reallocating the
2616 		 * memslot during vCPU creation, e.g. if a vCPU is hotplugged.
2617 		 */
2618 		kvm->arch.apic_access_memslot_inhibited = true;
2619 	}
2620 
2621 	mutex_unlock(&kvm->slots_lock);
2622 
2623 	kvm_vcpu_srcu_read_lock(vcpu);
2624 }
2625 
2626 void kvm_lapic_reset(struct kvm_vcpu *vcpu, bool init_event)
2627 {
2628 	struct kvm_lapic *apic = vcpu->arch.apic;
2629 	u64 msr_val;
2630 	int i;
2631 
2632 	if (!init_event) {
2633 		msr_val = APIC_DEFAULT_PHYS_BASE | MSR_IA32_APICBASE_ENABLE;
2634 		if (kvm_vcpu_is_reset_bsp(vcpu))
2635 			msr_val |= MSR_IA32_APICBASE_BSP;
2636 		kvm_lapic_set_base(vcpu, msr_val);
2637 	}
2638 
2639 	if (!apic)
2640 		return;
2641 
2642 	/* Stop the timer in case it's a reset to an active apic */
2643 	hrtimer_cancel(&apic->lapic_timer.timer);
2644 
2645 	/* The xAPIC ID is set at RESET even if the APIC was already enabled. */
2646 	if (!init_event)
2647 		kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2648 	kvm_apic_set_version(apic->vcpu);
2649 
2650 	for (i = 0; i < apic->nr_lvt_entries; i++)
2651 		kvm_lapic_set_reg(apic, APIC_LVTx(i), APIC_LVT_MASKED);
2652 	apic_update_lvtt(apic);
2653 	if (kvm_vcpu_is_reset_bsp(vcpu) &&
2654 	    kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_LINT0_REENABLED))
2655 		kvm_lapic_set_reg(apic, APIC_LVT0,
2656 			     SET_APIC_DELIVERY_MODE(0, APIC_MODE_EXTINT));
2657 	apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2658 
2659 	kvm_apic_set_dfr(apic, 0xffffffffU);
2660 	apic_set_spiv(apic, 0xff);
2661 	kvm_lapic_set_reg(apic, APIC_TASKPRI, 0);
2662 	if (!apic_x2apic_mode(apic))
2663 		kvm_apic_set_ldr(apic, 0);
2664 	kvm_lapic_set_reg(apic, APIC_ESR, 0);
2665 	if (!apic_x2apic_mode(apic)) {
2666 		kvm_lapic_set_reg(apic, APIC_ICR, 0);
2667 		kvm_lapic_set_reg(apic, APIC_ICR2, 0);
2668 	} else {
2669 		kvm_lapic_set_reg64(apic, APIC_ICR, 0);
2670 	}
2671 	kvm_lapic_set_reg(apic, APIC_TDCR, 0);
2672 	kvm_lapic_set_reg(apic, APIC_TMICT, 0);
2673 	for (i = 0; i < 8; i++) {
2674 		kvm_lapic_set_reg(apic, APIC_IRR + 0x10 * i, 0);
2675 		kvm_lapic_set_reg(apic, APIC_ISR + 0x10 * i, 0);
2676 		kvm_lapic_set_reg(apic, APIC_TMR + 0x10 * i, 0);
2677 	}
2678 	kvm_apic_update_apicv(vcpu);
2679 	update_divide_count(apic);
2680 	atomic_set(&apic->lapic_timer.pending, 0);
2681 
2682 	vcpu->arch.pv_eoi.msr_val = 0;
2683 	apic_update_ppr(apic);
2684 	if (apic->apicv_active) {
2685 		static_call_cond(kvm_x86_apicv_post_state_restore)(vcpu);
2686 		static_call_cond(kvm_x86_hwapic_irr_update)(vcpu, -1);
2687 		static_call_cond(kvm_x86_hwapic_isr_update)(-1);
2688 	}
2689 
2690 	vcpu->arch.apic_arb_prio = 0;
2691 	vcpu->arch.apic_attention = 0;
2692 
2693 	kvm_recalculate_apic_map(vcpu->kvm);
2694 }
2695 
2696 /*
2697  *----------------------------------------------------------------------
2698  * timer interface
2699  *----------------------------------------------------------------------
2700  */
2701 
2702 static bool lapic_is_periodic(struct kvm_lapic *apic)
2703 {
2704 	return apic_lvtt_period(apic);
2705 }
2706 
2707 int apic_has_pending_timer(struct kvm_vcpu *vcpu)
2708 {
2709 	struct kvm_lapic *apic = vcpu->arch.apic;
2710 
2711 	if (apic_enabled(apic) && apic_lvt_enabled(apic, APIC_LVTT))
2712 		return atomic_read(&apic->lapic_timer.pending);
2713 
2714 	return 0;
2715 }
2716 
2717 int kvm_apic_local_deliver(struct kvm_lapic *apic, int lvt_type)
2718 {
2719 	u32 reg = kvm_lapic_get_reg(apic, lvt_type);
2720 	int vector, mode, trig_mode;
2721 
2722 	if (kvm_apic_hw_enabled(apic) && !(reg & APIC_LVT_MASKED)) {
2723 		vector = reg & APIC_VECTOR_MASK;
2724 		mode = reg & APIC_MODE_MASK;
2725 		trig_mode = reg & APIC_LVT_LEVEL_TRIGGER;
2726 		return __apic_accept_irq(apic, mode, vector, 1, trig_mode,
2727 					NULL);
2728 	}
2729 	return 0;
2730 }
2731 
2732 void kvm_apic_nmi_wd_deliver(struct kvm_vcpu *vcpu)
2733 {
2734 	struct kvm_lapic *apic = vcpu->arch.apic;
2735 
2736 	if (apic)
2737 		kvm_apic_local_deliver(apic, APIC_LVT0);
2738 }
2739 
2740 static const struct kvm_io_device_ops apic_mmio_ops = {
2741 	.read     = apic_mmio_read,
2742 	.write    = apic_mmio_write,
2743 };
2744 
2745 static enum hrtimer_restart apic_timer_fn(struct hrtimer *data)
2746 {
2747 	struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
2748 	struct kvm_lapic *apic = container_of(ktimer, struct kvm_lapic, lapic_timer);
2749 
2750 	apic_timer_expired(apic, true);
2751 
2752 	if (lapic_is_periodic(apic)) {
2753 		advance_periodic_target_expiration(apic);
2754 		hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
2755 		return HRTIMER_RESTART;
2756 	} else
2757 		return HRTIMER_NORESTART;
2758 }
2759 
2760 int kvm_create_lapic(struct kvm_vcpu *vcpu, int timer_advance_ns)
2761 {
2762 	struct kvm_lapic *apic;
2763 
2764 	ASSERT(vcpu != NULL);
2765 
2766 	apic = kzalloc(sizeof(*apic), GFP_KERNEL_ACCOUNT);
2767 	if (!apic)
2768 		goto nomem;
2769 
2770 	vcpu->arch.apic = apic;
2771 
2772 	apic->regs = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
2773 	if (!apic->regs) {
2774 		printk(KERN_ERR "malloc apic regs error for vcpu %x\n",
2775 		       vcpu->vcpu_id);
2776 		goto nomem_free_apic;
2777 	}
2778 	apic->vcpu = vcpu;
2779 
2780 	apic->nr_lvt_entries = kvm_apic_calc_nr_lvt_entries(vcpu);
2781 
2782 	hrtimer_init(&apic->lapic_timer.timer, CLOCK_MONOTONIC,
2783 		     HRTIMER_MODE_ABS_HARD);
2784 	apic->lapic_timer.timer.function = apic_timer_fn;
2785 	if (timer_advance_ns == -1) {
2786 		apic->lapic_timer.timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
2787 		lapic_timer_advance_dynamic = true;
2788 	} else {
2789 		apic->lapic_timer.timer_advance_ns = timer_advance_ns;
2790 		lapic_timer_advance_dynamic = false;
2791 	}
2792 
2793 	/*
2794 	 * Stuff the APIC ENABLE bit in lieu of temporarily incrementing
2795 	 * apic_hw_disabled; the full RESET value is set by kvm_lapic_reset().
2796 	 */
2797 	vcpu->arch.apic_base = MSR_IA32_APICBASE_ENABLE;
2798 	static_branch_inc(&apic_sw_disabled.key); /* sw disabled at reset */
2799 	kvm_iodevice_init(&apic->dev, &apic_mmio_ops);
2800 
2801 	return 0;
2802 nomem_free_apic:
2803 	kfree(apic);
2804 	vcpu->arch.apic = NULL;
2805 nomem:
2806 	return -ENOMEM;
2807 }
2808 
2809 int kvm_apic_has_interrupt(struct kvm_vcpu *vcpu)
2810 {
2811 	struct kvm_lapic *apic = vcpu->arch.apic;
2812 	u32 ppr;
2813 
2814 	if (!kvm_apic_present(vcpu))
2815 		return -1;
2816 
2817 	__apic_update_ppr(apic, &ppr);
2818 	return apic_has_interrupt_for_ppr(apic, ppr);
2819 }
2820 EXPORT_SYMBOL_GPL(kvm_apic_has_interrupt);
2821 
2822 int kvm_apic_accept_pic_intr(struct kvm_vcpu *vcpu)
2823 {
2824 	u32 lvt0 = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVT0);
2825 
2826 	if (!kvm_apic_hw_enabled(vcpu->arch.apic))
2827 		return 1;
2828 	if ((lvt0 & APIC_LVT_MASKED) == 0 &&
2829 	    GET_APIC_DELIVERY_MODE(lvt0) == APIC_MODE_EXTINT)
2830 		return 1;
2831 	return 0;
2832 }
2833 
2834 void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu)
2835 {
2836 	struct kvm_lapic *apic = vcpu->arch.apic;
2837 
2838 	if (atomic_read(&apic->lapic_timer.pending) > 0) {
2839 		kvm_apic_inject_pending_timer_irqs(apic);
2840 		atomic_set(&apic->lapic_timer.pending, 0);
2841 	}
2842 }
2843 
2844 int kvm_get_apic_interrupt(struct kvm_vcpu *vcpu)
2845 {
2846 	int vector = kvm_apic_has_interrupt(vcpu);
2847 	struct kvm_lapic *apic = vcpu->arch.apic;
2848 	u32 ppr;
2849 
2850 	if (vector == -1)
2851 		return -1;
2852 
2853 	/*
2854 	 * We get here even with APIC virtualization enabled, if doing
2855 	 * nested virtualization and L1 runs with the "acknowledge interrupt
2856 	 * on exit" mode.  Then we cannot inject the interrupt via RVI,
2857 	 * because the process would deliver it through the IDT.
2858 	 */
2859 
2860 	apic_clear_irr(vector, apic);
2861 	if (to_hv_vcpu(vcpu) && test_bit(vector, to_hv_synic(vcpu)->auto_eoi_bitmap)) {
2862 		/*
2863 		 * For auto-EOI interrupts, there might be another pending
2864 		 * interrupt above PPR, so check whether to raise another
2865 		 * KVM_REQ_EVENT.
2866 		 */
2867 		apic_update_ppr(apic);
2868 	} else {
2869 		/*
2870 		 * For normal interrupts, PPR has been raised and there cannot
2871 		 * be a higher-priority pending interrupt---except if there was
2872 		 * a concurrent interrupt injection, but that would have
2873 		 * triggered KVM_REQ_EVENT already.
2874 		 */
2875 		apic_set_isr(vector, apic);
2876 		__apic_update_ppr(apic, &ppr);
2877 	}
2878 
2879 	return vector;
2880 }
2881 
2882 static int kvm_apic_state_fixup(struct kvm_vcpu *vcpu,
2883 		struct kvm_lapic_state *s, bool set)
2884 {
2885 	if (apic_x2apic_mode(vcpu->arch.apic)) {
2886 		u32 *id = (u32 *)(s->regs + APIC_ID);
2887 		u32 *ldr = (u32 *)(s->regs + APIC_LDR);
2888 		u64 icr;
2889 
2890 		if (vcpu->kvm->arch.x2apic_format) {
2891 			if (*id != vcpu->vcpu_id)
2892 				return -EINVAL;
2893 		} else {
2894 			if (set)
2895 				*id >>= 24;
2896 			else
2897 				*id <<= 24;
2898 		}
2899 
2900 		/*
2901 		 * In x2APIC mode, the LDR is fixed and based on the id.  And
2902 		 * ICR is internally a single 64-bit register, but needs to be
2903 		 * split to ICR+ICR2 in userspace for backwards compatibility.
2904 		 */
2905 		if (set) {
2906 			*ldr = kvm_apic_calc_x2apic_ldr(*id);
2907 
2908 			icr = __kvm_lapic_get_reg(s->regs, APIC_ICR) |
2909 			      (u64)__kvm_lapic_get_reg(s->regs, APIC_ICR2) << 32;
2910 			__kvm_lapic_set_reg64(s->regs, APIC_ICR, icr);
2911 		} else {
2912 			icr = __kvm_lapic_get_reg64(s->regs, APIC_ICR);
2913 			__kvm_lapic_set_reg(s->regs, APIC_ICR2, icr >> 32);
2914 		}
2915 	}
2916 
2917 	return 0;
2918 }
2919 
2920 int kvm_apic_get_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2921 {
2922 	memcpy(s->regs, vcpu->arch.apic->regs, sizeof(*s));
2923 
2924 	/*
2925 	 * Get calculated timer current count for remaining timer period (if
2926 	 * any) and store it in the returned register set.
2927 	 */
2928 	__kvm_lapic_set_reg(s->regs, APIC_TMCCT,
2929 			    __apic_read(vcpu->arch.apic, APIC_TMCCT));
2930 
2931 	return kvm_apic_state_fixup(vcpu, s, false);
2932 }
2933 
2934 int kvm_apic_set_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2935 {
2936 	struct kvm_lapic *apic = vcpu->arch.apic;
2937 	int r;
2938 
2939 	kvm_lapic_set_base(vcpu, vcpu->arch.apic_base);
2940 	/* set SPIV separately to get count of SW disabled APICs right */
2941 	apic_set_spiv(apic, *((u32 *)(s->regs + APIC_SPIV)));
2942 
2943 	r = kvm_apic_state_fixup(vcpu, s, true);
2944 	if (r) {
2945 		kvm_recalculate_apic_map(vcpu->kvm);
2946 		return r;
2947 	}
2948 	memcpy(vcpu->arch.apic->regs, s->regs, sizeof(*s));
2949 
2950 	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
2951 	kvm_recalculate_apic_map(vcpu->kvm);
2952 	kvm_apic_set_version(vcpu);
2953 
2954 	apic_update_ppr(apic);
2955 	cancel_apic_timer(apic);
2956 	apic->lapic_timer.expired_tscdeadline = 0;
2957 	apic_update_lvtt(apic);
2958 	apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2959 	update_divide_count(apic);
2960 	__start_apic_timer(apic, APIC_TMCCT);
2961 	kvm_lapic_set_reg(apic, APIC_TMCCT, 0);
2962 	kvm_apic_update_apicv(vcpu);
2963 	if (apic->apicv_active) {
2964 		static_call_cond(kvm_x86_apicv_post_state_restore)(vcpu);
2965 		static_call_cond(kvm_x86_hwapic_irr_update)(vcpu, apic_find_highest_irr(apic));
2966 		static_call_cond(kvm_x86_hwapic_isr_update)(apic_find_highest_isr(apic));
2967 	}
2968 	kvm_make_request(KVM_REQ_EVENT, vcpu);
2969 	if (ioapic_in_kernel(vcpu->kvm))
2970 		kvm_rtc_eoi_tracking_restore_one(vcpu);
2971 
2972 	vcpu->arch.apic_arb_prio = 0;
2973 
2974 	return 0;
2975 }
2976 
2977 void __kvm_migrate_apic_timer(struct kvm_vcpu *vcpu)
2978 {
2979 	struct hrtimer *timer;
2980 
2981 	if (!lapic_in_kernel(vcpu) ||
2982 		kvm_can_post_timer_interrupt(vcpu))
2983 		return;
2984 
2985 	timer = &vcpu->arch.apic->lapic_timer.timer;
2986 	if (hrtimer_cancel(timer))
2987 		hrtimer_start_expires(timer, HRTIMER_MODE_ABS_HARD);
2988 }
2989 
2990 /*
2991  * apic_sync_pv_eoi_from_guest - called on vmexit or cancel interrupt
2992  *
2993  * Detect whether guest triggered PV EOI since the
2994  * last entry. If yes, set EOI on guests's behalf.
2995  * Clear PV EOI in guest memory in any case.
2996  */
2997 static void apic_sync_pv_eoi_from_guest(struct kvm_vcpu *vcpu,
2998 					struct kvm_lapic *apic)
2999 {
3000 	int vector;
3001 	/*
3002 	 * PV EOI state is derived from KVM_APIC_PV_EOI_PENDING in host
3003 	 * and KVM_PV_EOI_ENABLED in guest memory as follows:
3004 	 *
3005 	 * KVM_APIC_PV_EOI_PENDING is unset:
3006 	 * 	-> host disabled PV EOI.
3007 	 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is set:
3008 	 * 	-> host enabled PV EOI, guest did not execute EOI yet.
3009 	 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is unset:
3010 	 * 	-> host enabled PV EOI, guest executed EOI.
3011 	 */
3012 	BUG_ON(!pv_eoi_enabled(vcpu));
3013 
3014 	if (pv_eoi_test_and_clr_pending(vcpu))
3015 		return;
3016 	vector = apic_set_eoi(apic);
3017 	trace_kvm_pv_eoi(apic, vector);
3018 }
3019 
3020 void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
3021 {
3022 	u32 data;
3023 
3024 	if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
3025 		apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
3026 
3027 	if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
3028 		return;
3029 
3030 	if (kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
3031 				  sizeof(u32)))
3032 		return;
3033 
3034 	apic_set_tpr(vcpu->arch.apic, data & 0xff);
3035 }
3036 
3037 /*
3038  * apic_sync_pv_eoi_to_guest - called before vmentry
3039  *
3040  * Detect whether it's safe to enable PV EOI and
3041  * if yes do so.
3042  */
3043 static void apic_sync_pv_eoi_to_guest(struct kvm_vcpu *vcpu,
3044 					struct kvm_lapic *apic)
3045 {
3046 	if (!pv_eoi_enabled(vcpu) ||
3047 	    /* IRR set or many bits in ISR: could be nested. */
3048 	    apic->irr_pending ||
3049 	    /* Cache not set: could be safe but we don't bother. */
3050 	    apic->highest_isr_cache == -1 ||
3051 	    /* Need EOI to update ioapic. */
3052 	    kvm_ioapic_handles_vector(apic, apic->highest_isr_cache)) {
3053 		/*
3054 		 * PV EOI was disabled by apic_sync_pv_eoi_from_guest
3055 		 * so we need not do anything here.
3056 		 */
3057 		return;
3058 	}
3059 
3060 	pv_eoi_set_pending(apic->vcpu);
3061 }
3062 
3063 void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
3064 {
3065 	u32 data, tpr;
3066 	int max_irr, max_isr;
3067 	struct kvm_lapic *apic = vcpu->arch.apic;
3068 
3069 	apic_sync_pv_eoi_to_guest(vcpu, apic);
3070 
3071 	if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
3072 		return;
3073 
3074 	tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI) & 0xff;
3075 	max_irr = apic_find_highest_irr(apic);
3076 	if (max_irr < 0)
3077 		max_irr = 0;
3078 	max_isr = apic_find_highest_isr(apic);
3079 	if (max_isr < 0)
3080 		max_isr = 0;
3081 	data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
3082 
3083 	kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
3084 				sizeof(u32));
3085 }
3086 
3087 int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
3088 {
3089 	if (vapic_addr) {
3090 		if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
3091 					&vcpu->arch.apic->vapic_cache,
3092 					vapic_addr, sizeof(u32)))
3093 			return -EINVAL;
3094 		__set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
3095 	} else {
3096 		__clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
3097 	}
3098 
3099 	vcpu->arch.apic->vapic_addr = vapic_addr;
3100 	return 0;
3101 }
3102 
3103 int kvm_x2apic_icr_write(struct kvm_lapic *apic, u64 data)
3104 {
3105 	data &= ~APIC_ICR_BUSY;
3106 
3107 	kvm_apic_send_ipi(apic, (u32)data, (u32)(data >> 32));
3108 	kvm_lapic_set_reg64(apic, APIC_ICR, data);
3109 	trace_kvm_apic_write(APIC_ICR, data);
3110 	return 0;
3111 }
3112 
3113 static int kvm_lapic_msr_read(struct kvm_lapic *apic, u32 reg, u64 *data)
3114 {
3115 	u32 low;
3116 
3117 	if (reg == APIC_ICR) {
3118 		*data = kvm_lapic_get_reg64(apic, APIC_ICR);
3119 		return 0;
3120 	}
3121 
3122 	if (kvm_lapic_reg_read(apic, reg, 4, &low))
3123 		return 1;
3124 
3125 	*data = low;
3126 
3127 	return 0;
3128 }
3129 
3130 static int kvm_lapic_msr_write(struct kvm_lapic *apic, u32 reg, u64 data)
3131 {
3132 	/*
3133 	 * ICR is a 64-bit register in x2APIC mode (and Hyper-V PV vAPIC) and
3134 	 * can be written as such, all other registers remain accessible only
3135 	 * through 32-bit reads/writes.
3136 	 */
3137 	if (reg == APIC_ICR)
3138 		return kvm_x2apic_icr_write(apic, data);
3139 
3140 	/* Bits 63:32 are reserved in all other registers. */
3141 	if (data >> 32)
3142 		return 1;
3143 
3144 	return kvm_lapic_reg_write(apic, reg, (u32)data);
3145 }
3146 
3147 int kvm_x2apic_msr_write(struct kvm_vcpu *vcpu, u32 msr, u64 data)
3148 {
3149 	struct kvm_lapic *apic = vcpu->arch.apic;
3150 	u32 reg = (msr - APIC_BASE_MSR) << 4;
3151 
3152 	if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
3153 		return 1;
3154 
3155 	return kvm_lapic_msr_write(apic, reg, data);
3156 }
3157 
3158 int kvm_x2apic_msr_read(struct kvm_vcpu *vcpu, u32 msr, u64 *data)
3159 {
3160 	struct kvm_lapic *apic = vcpu->arch.apic;
3161 	u32 reg = (msr - APIC_BASE_MSR) << 4;
3162 
3163 	if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
3164 		return 1;
3165 
3166 	return kvm_lapic_msr_read(apic, reg, data);
3167 }
3168 
3169 int kvm_hv_vapic_msr_write(struct kvm_vcpu *vcpu, u32 reg, u64 data)
3170 {
3171 	if (!lapic_in_kernel(vcpu))
3172 		return 1;
3173 
3174 	return kvm_lapic_msr_write(vcpu->arch.apic, reg, data);
3175 }
3176 
3177 int kvm_hv_vapic_msr_read(struct kvm_vcpu *vcpu, u32 reg, u64 *data)
3178 {
3179 	if (!lapic_in_kernel(vcpu))
3180 		return 1;
3181 
3182 	return kvm_lapic_msr_read(vcpu->arch.apic, reg, data);
3183 }
3184 
3185 int kvm_lapic_set_pv_eoi(struct kvm_vcpu *vcpu, u64 data, unsigned long len)
3186 {
3187 	u64 addr = data & ~KVM_MSR_ENABLED;
3188 	struct gfn_to_hva_cache *ghc = &vcpu->arch.pv_eoi.data;
3189 	unsigned long new_len;
3190 	int ret;
3191 
3192 	if (!IS_ALIGNED(addr, 4))
3193 		return 1;
3194 
3195 	if (data & KVM_MSR_ENABLED) {
3196 		if (addr == ghc->gpa && len <= ghc->len)
3197 			new_len = ghc->len;
3198 		else
3199 			new_len = len;
3200 
3201 		ret = kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, addr, new_len);
3202 		if (ret)
3203 			return ret;
3204 	}
3205 
3206 	vcpu->arch.pv_eoi.msr_val = data;
3207 
3208 	return 0;
3209 }
3210 
3211 int kvm_apic_accept_events(struct kvm_vcpu *vcpu)
3212 {
3213 	struct kvm_lapic *apic = vcpu->arch.apic;
3214 	u8 sipi_vector;
3215 	int r;
3216 
3217 	if (!kvm_apic_has_pending_init_or_sipi(vcpu))
3218 		return 0;
3219 
3220 	if (is_guest_mode(vcpu)) {
3221 		r = kvm_check_nested_events(vcpu);
3222 		if (r < 0)
3223 			return r == -EBUSY ? 0 : r;
3224 		/*
3225 		 * Continue processing INIT/SIPI even if a nested VM-Exit
3226 		 * occurred, e.g. pending SIPIs should be dropped if INIT+SIPI
3227 		 * are blocked as a result of transitioning to VMX root mode.
3228 		 */
3229 	}
3230 
3231 	/*
3232 	 * INITs are blocked while CPU is in specific states (SMM, VMX root
3233 	 * mode, SVM with GIF=0), while SIPIs are dropped if the CPU isn't in
3234 	 * wait-for-SIPI (WFS).
3235 	 */
3236 	if (!kvm_apic_init_sipi_allowed(vcpu)) {
3237 		WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED);
3238 		clear_bit(KVM_APIC_SIPI, &apic->pending_events);
3239 		return 0;
3240 	}
3241 
3242 	if (test_and_clear_bit(KVM_APIC_INIT, &apic->pending_events)) {
3243 		kvm_vcpu_reset(vcpu, true);
3244 		if (kvm_vcpu_is_bsp(apic->vcpu))
3245 			vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3246 		else
3247 			vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
3248 	}
3249 	if (test_and_clear_bit(KVM_APIC_SIPI, &apic->pending_events)) {
3250 		if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
3251 			/* evaluate pending_events before reading the vector */
3252 			smp_rmb();
3253 			sipi_vector = apic->sipi_vector;
3254 			static_call(kvm_x86_vcpu_deliver_sipi_vector)(vcpu, sipi_vector);
3255 			vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3256 		}
3257 	}
3258 	return 0;
3259 }
3260 
3261 void kvm_lapic_exit(void)
3262 {
3263 	static_key_deferred_flush(&apic_hw_disabled);
3264 	WARN_ON(static_branch_unlikely(&apic_hw_disabled.key));
3265 	static_key_deferred_flush(&apic_sw_disabled);
3266 	WARN_ON(static_branch_unlikely(&apic_sw_disabled.key));
3267 }
3268