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