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