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