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