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