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