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